cflx 0.6.322

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
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
//! Workspace state detection module for OpenSpec Orchestrator.
//!
//! This module provides state detection logic for workspace resume operations,
//! enabling idempotent parallel execution. It detects the current state of a
//! workspace and determines the appropriate action to take during resume.
//!
//! # Workspace States
//!
//! 1. **Created**: Workspace created, no apply commits → Start apply
//! 2. **Applying**: WIP commits exist, apply in progress → Resume apply (next iteration)
//! 3. **Applied**: Apply complete, archive not complete → Resume decision is delegated to worktree routing (non-terminal resumes go to apply or acceptance, never direct archive)
//! 4. **Archiving**: Archive files moved, commit not complete → Resume archive to finish in-progress archive step (this state occurs only after acceptance has already handed off to archive)
//! 5. **Archived**: Archive complete, not merged to main → Merge only
//! 6. **Merged**: Merged to main → Skip & Cleanup
//!
//! # Example
//!
//! ```ignore
//! use crate::execution::state::{detect_workspace_state, WorkspaceState};
//!
//! let state = detect_workspace_state("add-feature", &workspace_path).await?;
//! match state {
//!     WorkspaceState::Created => { /* start apply */ }
//!     WorkspaceState::Applying { iteration } => { /* resume from iteration */ }
//!     WorkspaceState::Blocked => { /* wait for unblock/resume */ }
//!     WorkspaceState::Rejecting => { /* run rejecting review */ }
//!     WorkspaceState::Applied => { /* defer to resume-action router (apply or acceptance) */ }
//!     WorkspaceState::Archiving => { /* resume archive loop after acceptance handoff */ }
//!     WorkspaceState::Archived => { /* merge only */ }
//!     WorkspaceState::Merged => { /* skip & cleanup */ }
//! }
//! ```

use std::path::Path;
use tokio::process::Command;
use tracing::debug;

use crate::bounded_git::{run_git, GitDeadline, GitOutcome};

use crate::error::{OrchestratorError, Result};
use crate::execution::archive::is_archive_commit_complete;
use crate::parallel::acceptance_state::{
    parse_blocked_marker, repository_identity, worktree_identity, WorkspaceFacts,
};
use crate::vcs::git::commands::status_policy::{read_only_status_argv, PORCELAIN_STATUS_ARGS};

/// Workspace state for resume detection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WorkspaceState {
    /// Workspace created, no apply commits yet.
    Created,
    /// Apply in progress, WIP commits exist.
    /// The iteration number indicates the next iteration to resume from.
    Applying { iteration: u32 },
    /// Apply-generated blocker marker exists and change should remain blocked.
    Blocked,
    /// Rejection proposal exists and requires rejection review.
    Rejecting,
    /// Apply complete, archive not complete.
    Applied,
    /// Archive files moved but commit not complete.
    Archiving,
    /// Archive complete, not merged to main.
    Archived,
    /// Merged to main.
    Merged,
}

/// Why base-completion evidence could not be read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BaseEvidenceErrorKind {
    /// The base branch could not be resolved in the repository.
    MissingBranch,
    /// A Git command could not be executed.
    CommandFailure,
}

/// Typed repository-tree evidence for base-integrated completion.
///
/// This is the only accepted proof that a change is already completed: the base
/// branch HEAD tree. Commit subjects, logs, events, and server state are never
/// consulted, so the classification stays derivable from repository files alone.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BaseCompletionEvidence {
    /// A matching archive entry exists in the base tree and the active change
    /// directory is absent from it.
    Completed,
    /// No matching archive entry exists in the base tree.
    NotCompleted,
    /// The base tree contains both an archive entry and the active change
    /// directory, so completion cannot be proven.
    Contradictory { detail: String },
    /// The base branch or its tree could not be read.
    EvidenceError {
        kind: BaseEvidenceErrorKind,
        detail: String,
    },
}

impl BaseCompletionEvidence {
    /// Whether the evidence proves base-integrated completion.
    #[allow(dead_code)] // Boolean projection used by evidence consumers/tests.
    pub fn is_completed(&self) -> bool {
        matches!(self, Self::Completed)
    }

    /// Human-facing description used in target diagnostics.
    pub fn describe(&self) -> String {
        match self {
            Self::Completed => {
                "archive entry present in base tree and change directory absent".to_string()
            }
            Self::NotCompleted => "no archive entry in base tree".to_string(),
            Self::Contradictory { detail } => detail.clone(),
            Self::EvidenceError { detail, .. } => detail.clone(),
        }
    }
}

/// Classify base-integrated completion from the base branch HEAD tree.
///
/// The four results are mutually exclusive so contradictions and Git read
/// failures cannot collapse into "not completed" or "unknown":
///
/// * [`BaseCompletionEvidence::Completed`] - archive entry present, change directory absent
/// * [`BaseCompletionEvidence::NotCompleted`] - no archive entry for the change
/// * [`BaseCompletionEvidence::Contradictory`] - archive entry AND change directory present
/// * [`BaseCompletionEvidence::EvidenceError`] - base branch missing or Git command failure
///
/// Only the base branch tree is read, so uncommitted working-copy archives and
/// archive-shaped commit subjects can never pass as completed.
pub async fn classify_base_completion(
    change_id: &str,
    repo_root: &Path,
    base_branch: &str,
) -> BaseCompletionEvidence {
    // No deadline, so expiry is unreachable and the fallback is unobservable.
    classify_base_completion_within(change_id, repo_root, base_branch, GitDeadline::Unbounded)
        .await
        .unwrap_or(BaseCompletionEvidence::NotCompleted)
}

/// [`classify_base_completion`], bounded by a caller's [`GitDeadline`].
///
/// `None` means a Git child hit that bound before the evidence was established.
/// It is deliberately not an [`BaseCompletionEvidence::EvidenceError`]: a
/// classification that ran out of time says nothing about the repository, and
/// reporting broken evidence would send an operator to look at a repository that
/// is fine. What the expiry *means* is the caller's to decide — the whole
/// operation ran out under [`GitDeadline::Operation`], one attempt gave up under
/// [`GitDeadline::PerChild`].
///
/// Every Git child is spawned through [`run_git`], so an expiry terminates and
/// reaps the classification's own subprocess instead of orphaning it.
pub async fn classify_base_completion_within(
    change_id: &str,
    repo_root: &Path,
    base_branch: &str,
    deadline: GitDeadline,
) -> Option<BaseCompletionEvidence> {
    let failed = |detail: String| {
        Some(BaseCompletionEvidence::EvidenceError {
            kind: BaseEvidenceErrorKind::CommandFailure,
            detail,
        })
    };

    // Check if base branch exists
    let rev_parse_output =
        match run_git(repo_root, &["rev-parse", "--verify", base_branch], deadline).await {
            Ok(GitOutcome::Finished(output)) => output,
            Ok(GitOutcome::DeadlineExpired) => return None,
            Err(e) => return failed(format!("Failed to verify base branch: {}", e)),
        };

    if !rev_parse_output.status.success() {
        debug!(
            base_branch = %base_branch,
            "classify_base_completion: base branch does not exist"
        );
        return Some(BaseCompletionEvidence::EvidenceError {
            kind: BaseEvidenceErrorKind::MissingBranch,
            detail: format!("base branch '{}' does not exist", base_branch),
        });
    }

    // Check if archive entry exists in base branch HEAD tree
    let archive_path = format!("{}:openspec/changes/archive/", base_branch);
    let ls_tree_output = match run_git(repo_root, &["ls-tree", "-d", &archive_path], deadline).await
    {
        Ok(GitOutcome::Finished(output)) => output,
        Ok(GitOutcome::DeadlineExpired) => return None,
        Err(e) => return failed(format!("Failed to list archive tree: {}", e)),
    };

    if !ls_tree_output.status.success() {
        // Archive directory doesn't exist in base branch
        debug!(
            base_branch = %base_branch,
            "classify_base_completion: archive directory does not exist in base branch"
        );
        return Some(BaseCompletionEvidence::NotCompleted);
    }

    // Parse ls-tree output to find matching archive entries
    let output = String::from_utf8_lossy(&ls_tree_output.stdout);
    let archive_entry_exists = output.lines().any(|line| {
        // Parse line format: "040000 tree <hash>\t<name>"
        if let Some(name) = line.split('\t').nth(1) {
            name == change_id || name.ends_with(&format!("-{}", change_id))
        } else {
            false
        }
    });

    if !archive_entry_exists {
        debug!(
            change_id = %change_id,
            base_branch = %base_branch,
            "classify_base_completion: no archive entry in base branch tree"
        );
        return Some(BaseCompletionEvidence::NotCompleted);
    }

    // Check if the active change directory still exists in base branch HEAD tree.
    //
    // The parent directory is listed rather than the change directory itself:
    // `git ls-tree -d <branch>:openspec/changes/<id>` lists that directory's
    // *subdirectories*, so a change directory holding only files would look
    // absent and an archive-plus-active contradiction would read as completed.
    let changes_path = format!("{}:openspec/changes/", base_branch);
    let changes_ls_tree =
        match run_git(repo_root, &["ls-tree", "-d", &changes_path], deadline).await {
            Ok(GitOutcome::Finished(output)) => output,
            Ok(GitOutcome::DeadlineExpired) => return None,
            Err(e) => return failed(format!("Failed to check change tree: {}", e)),
        };

    let change_dir_exists = changes_ls_tree.status.success()
        && String::from_utf8_lossy(&changes_ls_tree.stdout)
            .lines()
            .any(|line| line.split('\t').nth(1) == Some(change_id));

    debug!(
        change_id = %change_id,
        base_branch = %base_branch,
        archive_entry_exists = archive_entry_exists,
        change_dir_exists = change_dir_exists,
        "classify_base_completion: checking base branch HEAD tree file state"
    );

    if change_dir_exists {
        return Some(BaseCompletionEvidence::Contradictory {
            detail: format!(
                "archive entry and active change directory both exist for '{}' in base branch '{}'",
                change_id, base_branch
            ),
        });
    }

    Some(BaseCompletionEvidence::Completed)
}

/// Check if a change has been merged to the base branch.
///
/// This function checks if the archive entry exists and the change directory
/// has been removed in the base branch's HEAD tree. It uses file state only
/// and does NOT check commit messages.
///
/// It is a Boolean projection of [`classify_base_completion`]: only
/// [`BaseCompletionEvidence::Completed`] maps to `true`, while contradictory
/// evidence and a missing base branch map to `false` and a Git command failure
/// is an error.
///
/// # Arguments
///
/// * `change_id` - The change ID to check
/// * `repo_root` - The repository root path
/// * `base_branch` - The base branch to check against
///
/// # Returns
///
/// * `Ok(true)` - Archive entry exists in base branch HEAD tree and change directory is gone
/// * `Ok(false)` - Archive entry does not exist or change directory still exists in base branch
/// * `Err` - Failed to check merge status
pub async fn is_merged_to_base(
    change_id: &str,
    repo_root: &Path,
    base_branch: &str,
) -> Result<bool> {
    match classify_base_completion(change_id, repo_root, base_branch).await {
        BaseCompletionEvidence::Completed => Ok(true),
        BaseCompletionEvidence::NotCompleted => Ok(false),
        BaseCompletionEvidence::Contradictory { .. } => {
            tracing::warn!(
                change_id = %change_id,
                base_branch = %base_branch,
                "Archive entry found in base branch but change directory still exists in base branch tree"
            );
            Ok(false)
        }
        BaseCompletionEvidence::EvidenceError {
            kind: BaseEvidenceErrorKind::MissingBranch,
            ..
        } => Ok(false),
        BaseCompletionEvidence::EvidenceError {
            kind: BaseEvidenceErrorKind::CommandFailure,
            detail,
        } => Err(OrchestratorError::GitCommand(detail)),
    }
}

/// Get the latest WIP snapshot iteration number.
///
/// This function searches for WIP commit messages in the format
/// `WIP(apply): <change_id> (iteration N/M)` and returns the highest
/// iteration number found.
///
/// # Arguments
///
/// * `change_id` - The change ID to check
/// * `repo_root` - The repository root path
///
/// # Returns
///
/// * `Ok(Some(n))` - WIP commits exist, highest iteration is n
/// * `Ok(None)` - No WIP commits found
/// * `Err` - Failed to check WIP commits
pub async fn get_latest_wip_snapshot(change_id: &str, repo_root: &Path) -> Result<Option<u32>> {
    let wip_prefix = format!("WIP(apply): {}", change_id);

    let log_output = Command::new("git")
        .args(["log", "--format=%s", "--grep", &wip_prefix, "--all-match"])
        .current_dir(repo_root)
        .output()
        .await
        .map_err(|e| OrchestratorError::GitCommand(format!("Failed to read git log: {}", e)))?;

    if !log_output.status.success() {
        let stderr = String::from_utf8_lossy(&log_output.stderr);
        return Err(OrchestratorError::GitCommand(format!(
            "Failed to read git log: {}",
            stderr
        )));
    }

    let commits = String::from_utf8_lossy(&log_output.stdout);
    let mut max_iteration = None;

    // Parse WIP commit messages: "WIP(apply): <change_id> (iteration N/M)"
    for line in commits.lines() {
        if let Some(iteration_part) = line.strip_prefix(&wip_prefix) {
            // Extract iteration number from "(iteration N/M)"
            if let Some(captures) = iteration_part
                .trim()
                .strip_prefix("(iteration ")
                .and_then(|s| s.split_once('/'))
            {
                if let Ok(iteration) = captures.0.trim().parse::<u32>() {
                    max_iteration =
                        Some(max_iteration.map_or(iteration, |m: u32| m.max(iteration)));
                }
            }
        }
    }

    debug!(
        change_id = %change_id,
        max_iteration = ?max_iteration,
        "get_latest_wip_snapshot: found WIP commits"
    );

    Ok(max_iteration)
}

/// Check if the workspace is in the "archiving" state.
///
/// The archiving state occurs when files have been moved to the archive directory
/// but the commit is not yet complete (working tree is dirty).
///
/// This function checks if:
/// 1. The worktree is dirty (has uncommitted changes)
/// 2. The change directory does NOT exist in `openspec/changes/<change_id>`
/// 3. An archive entry exists in `openspec/changes/archive/`
///
/// # Arguments
///
/// * `change_id` - The change ID to check
/// * `repo_root` - The repository root path (workspace path)
///
/// # Returns
///
/// * `Ok(true)` - In archiving state (dirty, change gone, archive exists)
/// * `Ok(false)` - Not in archiving state
/// * `Err` - Failed to check archiving state
pub async fn has_archive_files(change_id: &str, repo_root: &Path) -> Result<bool> {
    // Check if working tree is dirty
    let status_output = Command::new("git")
        .args(read_only_status_argv(PORCELAIN_STATUS_ARGS))
        .current_dir(repo_root)
        .output()
        .await
        .map_err(|e| OrchestratorError::GitCommand(format!("Failed to check git status: {}", e)))?;

    if !status_output.status.success() {
        let stderr = String::from_utf8_lossy(&status_output.stderr);
        return Err(OrchestratorError::GitCommand(format!(
            "Failed to check git status: {}",
            stderr
        )));
    }

    let is_dirty = !String::from_utf8_lossy(&status_output.stdout)
        .trim()
        .is_empty();

    // Check if change directory exists (should NOT exist for archiving state)
    let change_path = repo_root.join("openspec/changes").join(change_id);
    let change_exists = change_path.exists();

    // Check for archive directory (supports both formats)
    // 1. openspec/changes/archive/{change_id}
    // 2. openspec/changes/archive/{date}-{change_id}
    let archive_base = repo_root.join("openspec/changes/archive");
    let mut archive_entry_exists = false;

    if archive_base.exists() {
        // Check for exact match first
        let exact_match = archive_base.join(change_id);
        if exact_match.exists() && exact_match.is_dir() {
            archive_entry_exists = true;
        } else {
            // Check for date-prefixed match
            if let Ok(entries) = std::fs::read_dir(&archive_base) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let name = entry.file_name();
                    let name_str = name.to_string_lossy();

                    // Check if it ends with "-{change_id}" and is a directory
                    if name_str.ends_with(&format!("-{}", change_id)) && entry.path().is_dir() {
                        archive_entry_exists = true;
                        break;
                    }
                }
            }
        }
    }

    debug!(
        change_id = %change_id,
        is_dirty = is_dirty,
        change_exists = change_exists,
        archive_entry_exists = archive_entry_exists,
        "has_archive_files: checking archiving state (dirty={}, change_gone={}, archive_exists={})",
        is_dirty,
        !change_exists,
        archive_entry_exists
    );

    // Archiving state requires:
    // 1. Worktree is dirty
    // 2. Change directory is gone
    // 3. Archive entry exists
    Ok(is_dirty && !change_exists && archive_entry_exists)
}

/// Check if an apply commit exists for a change.
///
/// An apply commit is a non-WIP commit that indicates apply completion.
/// This function checks for commits with the message `Apply: <change_id>`.
///
/// # Arguments
///
/// * `change_id` - The change ID to check
/// * `repo_root` - The repository root path
///
/// # Returns
///
/// * `Ok(true)` - Apply commit exists
/// * `Ok(false)` - Apply commit does not exist
/// * `Err` - Failed to check apply commit
pub async fn has_apply_commit(change_id: &str, repo_root: &Path) -> Result<bool> {
    let expected_subject = format!("Apply: {}", change_id);

    let log_output = Command::new("git")
        .args([
            "log",
            "--format=%s",
            "--grep",
            &expected_subject,
            "--all-match",
        ])
        .current_dir(repo_root)
        .output()
        .await
        .map_err(|e| OrchestratorError::GitCommand(format!("Failed to read git log: {}", e)))?;

    if !log_output.status.success() {
        let stderr = String::from_utf8_lossy(&log_output.stderr);
        return Err(OrchestratorError::GitCommand(format!(
            "Failed to read git log: {}",
            stderr
        )));
    }

    let commits = String::from_utf8_lossy(&log_output.stdout);
    let found = commits.lines().any(|line| line.trim() == expected_subject);

    debug!(
        change_id = %change_id,
        expected_subject = %expected_subject,
        found = found,
        "has_apply_commit: checking apply commit"
    );

    Ok(found)
}

/// Detect the current state of a workspace.
///
/// This function analyzes the workspace's git history and filesystem to determine
/// the current state for resume operations.
///
/// # State Detection Logic
///
/// 1. Check if merged to base branch → `Merged`
/// 2. Check if archive commit complete → `Archived`
/// 3. Check if archive files exist (but commit incomplete) → `Archiving`
///    - This only resumes an archive step that was already started after acceptance handoff.
/// 4. Check if worktree-local apply blocker marker exists → `Blocked`
///    - Apply-generated blockers resume as blocked, not rejecting.
/// 5. Check if worktree-local `REJECTED.md` exists → `Rejecting`
///    - Terminal rejection proposals resume into dedicated rejecting review.
/// 6. Check if apply commit exists → `Applied`
///    - Resume router decides apply vs acceptance from worktree task progress; no direct archive jump for non-terminal resumes.
/// 6. Check for WIP commits → `Applying { iteration }`
/// 7. Otherwise → `Created`
///
/// # Arguments
///
/// * `change_id` - The change ID to check
/// * `repo_root` - The repository root path (workspace path)
/// * `base_branch` - The base branch to check against
///
/// # Returns
///
/// * `Ok(WorkspaceState)` - Detected workspace state
/// * `Err` - Failed to detect state
pub async fn detect_workspace_state(
    change_id: &str,
    repo_root: &Path,
    base_branch: &str,
) -> Result<WorkspaceState> {
    // 1. Check if merged to base branch
    if is_merged_to_base(change_id, repo_root, base_branch).await? {
        debug!(change_id = %change_id, "State: Merged");
        return Ok(WorkspaceState::Merged);
    }

    // 2. Check if archive commit is complete
    if is_archive_commit_complete(change_id, Some(repo_root)).await? {
        debug!(change_id = %change_id, "State: Archived");
        return Ok(WorkspaceState::Archived);
    }

    // 3. Check if archive files exist (but commit incomplete) → Archiving
    if has_archive_files(change_id, repo_root).await? {
        debug!(change_id = %change_id, "State: Archiving (files moved, commit incomplete)");
        return Ok(WorkspaceState::Archiving);
    }

    // 4. Check if apply-blocked marker exists in workspace
    let blocked_marker_path = repo_root
        .join("openspec")
        .join("changes")
        .join(change_id)
        .join("APPLY_BLOCKED")
        .join("marker.md");
    if blocked_marker_path.exists() {
        parse_blocked_marker(repo_root, change_id)?;
        debug!(
            change_id = %change_id,
            blocked_marker_path = %blocked_marker_path.display(),
            "State: Blocked"
        );
        return Ok(WorkspaceState::Blocked);
    }

    // 5. Check if rejection proposal exists in workspace
    let rejected_path = repo_root
        .join("openspec")
        .join("changes")
        .join(change_id)
        .join("REJECTED.md");
    if rejected_path.exists() {
        debug!(
            change_id = %change_id,
            rejected_path = %rejected_path.display(),
            "State: Rejecting"
        );
        return Ok(WorkspaceState::Rejecting);
    }

    // 6. Check if apply commit exists
    if has_apply_commit(change_id, repo_root).await? {
        debug!(change_id = %change_id, "State: Applied");
        return Ok(WorkspaceState::Applied);
    }

    // 6. Check for WIP commits
    if let Some(iteration) = get_latest_wip_snapshot(change_id, repo_root).await? {
        debug!(change_id = %change_id, iteration = iteration, "State: Applying");
        return Ok(WorkspaceState::Applying {
            iteration: iteration + 1,
        });
    }

    // 6. No commits found - workspace just created
    debug!(change_id = %change_id, "State: Created");
    Ok(WorkspaceState::Created)
}

/// Gather the current repository/worktree facts that an acceptance stall record
/// must reconcile against before it may control any routing.
///
/// Every value here is read from git and the filesystem right now. The stall
/// record contributes only the `apply_revision` being checked, so a stale or
/// forged record cannot make its own binding look valid.
///
/// Retired along with the stall record itself: no production path calls this any
/// more. Kept for one release cycle, then removed with
/// [`crate::parallel::acceptance_state::AcceptanceStallRecord`].
#[allow(dead_code)] // Retired disk persistence; kept for one release cycle.
pub async fn gather_workspace_facts(
    repo_root: &Path,
    workspace_path: &Path,
    change_id: &str,
    apply_revision: &str,
    base_branch: &str,
) -> Result<WorkspaceFacts> {
    let merged = is_merged_to_base(change_id, workspace_path, base_branch)
        .await
        .unwrap_or(false);
    let archived = is_archive_commit_complete(change_id, Some(workspace_path))
        .await
        .unwrap_or(false);

    let apply_revision_exists = revision_exists(workspace_path, apply_revision).await;
    let head_descends_from_apply_revision = apply_revision_exists
        && crate::vcs::git::commands::is_ancestor(workspace_path, apply_revision, "HEAD")
            .await
            .unwrap_or(false);

    Ok(WorkspaceFacts {
        repository_id: repository_identity(repo_root),
        change_id: change_id.to_string(),
        worktree_id: worktree_identity(workspace_path),
        worktree_path: canonical_path_string(workspace_path),
        branch: crate::vcs::git::commands::get_current_branch(workspace_path)
            .await
            .ok()
            .flatten(),
        apply_revision_exists,
        head_descends_from_apply_revision,
        change_active: !merged && !archived,
    })
}

/// Canonical string form of a worktree path, so equivalent paths compare equal
/// across symlinked and relative spellings.
#[allow(dead_code)] // Retired disk persistence; kept for one release cycle.
pub fn canonical_path_string(path: &Path) -> String {
    std::fs::canonicalize(path)
        .unwrap_or_else(|_| path.to_path_buf())
        .to_string_lossy()
        .to_string()
}

/// Whether `revision` resolves to an existing commit object in `workspace_path`.
#[allow(dead_code)] // Retired disk persistence; kept for one release cycle.
async fn revision_exists(workspace_path: &Path, revision: &str) -> bool {
    if revision.trim().is_empty() {
        return false;
    }
    Command::new("git")
        .args(["cat-file", "-e", &format!("{revision}^{{commit}}")])
        .current_dir(workspace_path)
        .output()
        .await
        .map(|output| output.status.success())
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::process::Command as StdCommand;
    use tempfile::TempDir;

    fn init_git_repo(repo_root: &Path) {
        StdCommand::new("git")
            .args(["init", "-b", "main"])
            .current_dir(repo_root)
            .output()
            .unwrap();
        StdCommand::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(repo_root)
            .output()
            .unwrap();
        StdCommand::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(repo_root)
            .output()
            .unwrap();
    }

    fn commit(repo_root: &Path, message: &str) {
        fs::write(repo_root.join("test.txt"), message).unwrap();
        StdCommand::new("git")
            .args(["add", "-A"])
            .current_dir(repo_root)
            .output()
            .unwrap();
        StdCommand::new("git")
            .args(["commit", "-m", message])
            .current_dir(repo_root)
            .output()
            .unwrap();
    }

    use crate::acceptance::AcceptanceBlocker;
    use crate::parallel::acceptance_state::{
        migrate_legacy_acceptance_marker, write_legacy_acceptance_marker, AcceptanceRetryContext,
        AcceptanceStallStore, BlockedMarkerOrigin, MarkerMigration,
    };

    fn head_revision(repo_root: &Path) -> String {
        let output = StdCommand::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(repo_root)
            .output()
            .unwrap();
        String::from_utf8(output.stdout).unwrap().trim().to_string()
    }

    fn porcelain_status(repo_root: &Path) -> String {
        let output = StdCommand::new("git")
            .args(["status", "--porcelain"])
            .current_dir(repo_root)
            .output()
            .unwrap();
        String::from_utf8(output.stdout).unwrap()
    }

    fn external_blocker() -> AcceptanceBlocker {
        AcceptanceBlocker {
            category: "credential".to_string(),
            evidence: vec!["STAGING_API_KEY is unset in the verification environment".to_string()],
            unblock_condition: "STAGING_API_KEY is present in the verification environment"
                .to_string(),
            next_action: "provision STAGING_API_KEY then retry acceptance".to_string(),
            resumable: true,
            prerequisite_owner: Some("platform".to_string()),
            evidence_ids: Vec::new(),
        }
    }

    /// Losing (or never having) runtime stall state must fail safe to
    /// acceptance, never to an inferred PASS or an archive jump. This is the
    /// restart contract now that no stall record exists on disk at all.
    #[tokio::test]
    async fn missing_runtime_state_leaves_a_complete_apply_routed_to_acceptance() {
        let repo = TempDir::new().unwrap();
        init_git_repo(repo.path());
        commit(repo.path(), "Apply: test-change");

        let state = detect_workspace_state("test-change", repo.path(), "main")
            .await
            .unwrap();
        assert_eq!(
            state,
            WorkspaceState::Applied,
            "a complete unarchived apply must route to acceptance, not archive"
        );
    }

    /// A validated blocker projects to the operator-facing view without any
    /// store, file, or revision binding: the whole hold is in memory.
    #[test]
    fn validated_blocker_projects_to_the_external_blocked_presentation() {
        let blocker = external_blocker().to_stalled_blocker();

        assert_eq!(blocker.category, "credential");
        assert_eq!(blocker.phase, "acceptance");
        assert_eq!(blocker.gate, "acceptance");
        assert_eq!(
            blocker.unblock_condition.as_deref(),
            Some("STAGING_API_KEY is present in the verification environment")
        );
        assert_eq!(blocker.prerequisite_owner.as_deref(), Some("platform"));
        assert_eq!(
            blocker.next_action,
            "provision STAGING_API_KEY then retry acceptance"
        );
        assert!(blocker.resumable);
        assert!(blocker.worktree_preserved);
        assert_eq!(
            blocker.evidence,
            vec!["STAGING_API_KEY is unset in the verification environment".to_string()]
        );

        // The orchestrator, not the reporter, turns these facts into `blocked`.
        match crate::orchestration::blocker_classification::classify_reported_facts(&blocker) {
            crate::orchestration::blocker_classification::LifecycleClassification::ExternalBlocked(
                info,
            ) => {
                assert_eq!(info.category, "credential");
                assert_eq!(
                    info.origin,
                    crate::runtime::proposal::BlockerOrigin::Acceptance
                );
            }
            other => panic!("expected external blocked, got {other:?}"),
        }
    }

    /// Constitutional restart contract: a validated external blocked hold has no
    /// durable backing, so deleting or never having runtime state cannot change
    /// the next action for identical workspace contents, and stale blocked
    /// metadata can never authorize acceptance PASS, archive, or merge.
    #[tokio::test]
    async fn external_blocked_runtime_state_has_no_restart_routing_authority() {
        use crate::events::ExecutionEvent;
        use crate::orchestration::state::{BlockerKind, OrchestratorState, TerminalState};

        let repo = TempDir::new().unwrap();
        init_git_repo(repo.path());
        commit(repo.path(), "Apply: test-change");

        // Workspace evidence before any runtime state exists.
        let routed_without_runtime_state =
            detect_workspace_state("test-change", repo.path(), "main")
                .await
                .unwrap();

        let mut held = OrchestratorState::new(vec!["test-change".to_string()], 1);
        held.apply_execution_event(&ExecutionEvent::AcceptanceGated {
            change_id: "test-change".to_string(),
            blocker: external_blocker().to_stalled_blocker(),
        });
        let runtime = held.change_runtime("test-change").expect("runtime entry");
        assert_eq!(held.display_status("test-change"), "blocked");
        assert_eq!(runtime.blocker_kind(), BlockerKind::External);
        // The hold proves nothing about completion or archive readiness.
        assert!(matches!(runtime.terminal, TerminalState::None));

        // Identical workspace contents route identically while the hold exists.
        let routed_with_runtime_state = detect_workspace_state("test-change", repo.path(), "main")
            .await
            .unwrap();
        assert_eq!(routed_with_runtime_state, routed_without_runtime_state);

        // A restart is a fresh reducer: the hold simply does not exist, and the
        // complete unarchived apply revision returns to acceptance.
        let restarted = OrchestratorState::new(vec!["test-change".to_string()], 1);
        assert!(restarted.externally_blocked_change_ids().is_empty());
        assert!(restarted.all_blocker_views().is_empty());
        assert_eq!(
            detect_workspace_state("test-change", repo.path(), "main")
                .await
                .unwrap(),
            WorkspaceState::Applied,
            "a complete unarchived apply must return to acceptance after restart"
        );
        assert_eq!(
            porcelain_status(repo.path()),
            "",
            "the worktree stays clean"
        );
    }

    /// Legacy acceptance-origin markers migrate once, leave no residue, and are
    /// idempotent across restarts.
    #[tokio::test]
    async fn acceptance_marker_migration_converts_and_cleans_up() {
        let repo = TempDir::new().unwrap();
        let state_root = TempDir::new().unwrap();
        init_git_repo(repo.path());
        commit(repo.path(), "Apply: test-change");
        let apply_revision = head_revision(repo.path());

        write_legacy_acceptance_marker(
            repo.path(),
            "test-change",
            "acceptance_gated",
            &["managed verification job 42 is still running".to_string()],
            &AcceptanceRetryContext {
                finding_identities: vec!["external|job 42|verification".to_string()],
                semantic_fingerprint: Some("baseline".to_string()),
                cycle_count: 3,
                ..AcceptanceRetryContext::default()
            },
            "no_semantic_progress",
            &["verification job 42".to_string()],
            true,
            "wait for job 42 then retry acceptance",
        )
        .unwrap();
        assert_ne!(porcelain_status(repo.path()), "", "fixture must be dirty");

        let store = AcceptanceStallStore::new(state_root.path());
        let facts = gather_workspace_facts(
            repo.path(),
            repo.path(),
            "test-change",
            &apply_revision,
            "main",
        )
        .await
        .unwrap();

        assert_eq!(
            migrate_legacy_acceptance_marker(&store, repo.path(), &facts, &apply_revision).unwrap(),
            MarkerMigration::Migrated {
                category: "pending_verification".to_string()
            }
        );

        // The generated marker and its directory are gone, and the worktree is
        // clean again.
        assert!(!repo
            .path()
            .join("openspec/changes/test-change/APPLY_BLOCKED")
            .exists());
        assert_eq!(porcelain_status(repo.path()), "");
        assert_eq!(head_revision(repo.path()), apply_revision);

        let record = store
            .load(&repository_identity(repo.path()), "test-change")
            .unwrap()
            .expect("migration must produce a usable record");
        assert_eq!(record.retry_count, 3);
        assert_eq!(record.apply_revision, apply_revision);
        assert!(record.resumable);
        assert_eq!(record.next_action, "wait for job 42 then retry acceptance");
        assert!(record
            .evidence
            .iter()
            .any(|entry| entry.contains("job 42 is still running")));

        // Idempotent: a second pass finds nothing left to migrate and leaves the
        // existing hold alone.
        assert_eq!(
            migrate_legacy_acceptance_marker(&store, repo.path(), &facts, &apply_revision).unwrap(),
            MarkerMigration::NotApplicable
        );
        assert_eq!(
            store
                .load(&repository_identity(repo.path()), "test-change")
                .unwrap(),
            Some(record)
        );
    }

    /// A git-tracked marker is committed repository content, not generated
    /// residue. Removing it would dirty the managed worktree, so migration must
    /// refuse and leave both the file and the worktree exactly as they were.
    #[tokio::test]
    async fn acceptance_marker_migration_preserves_tracked_markers() {
        let repo = TempDir::new().unwrap();
        let state_root = TempDir::new().unwrap();
        init_git_repo(repo.path());
        commit(repo.path(), "Apply: test-change");

        write_legacy_acceptance_marker(
            repo.path(),
            "test-change",
            "acceptance_gated",
            &["managed verification job 42 is still running".to_string()],
            &AcceptanceRetryContext {
                finding_identities: vec!["external|job 42|verification".to_string()],
                semantic_fingerprint: Some("baseline".to_string()),
                cycle_count: 3,
                ..AcceptanceRetryContext::default()
            },
            "no_semantic_progress",
            &["verification job 42".to_string()],
            true,
            "wait for job 42 then retry acceptance",
        )
        .unwrap();

        // Commit the marker so git tracks it, exactly like a legacy run that
        // captured the marker into the apply commit.
        StdCommand::new("git")
            .args(["add", "-A"])
            .current_dir(repo.path())
            .output()
            .unwrap();
        StdCommand::new("git")
            .args(["commit", "-m", "legacy tracked marker"])
            .current_dir(repo.path())
            .output()
            .unwrap();
        let apply_revision = head_revision(repo.path());
        assert_eq!(
            porcelain_status(repo.path()),
            "",
            "fixture must start from a clean tracked state"
        );

        let marker_path = repo
            .path()
            .join("openspec/changes/test-change/APPLY_BLOCKED/marker.md");
        let before = std::fs::read(&marker_path).unwrap();

        let store = AcceptanceStallStore::new(state_root.path());
        let facts = gather_workspace_facts(
            repo.path(),
            repo.path(),
            "test-change",
            &apply_revision,
            "main",
        )
        .await
        .unwrap();

        let migration =
            migrate_legacy_acceptance_marker(&store, repo.path(), &facts, &apply_revision).unwrap();
        match migration {
            MarkerMigration::Preserved { reason } => {
                assert!(
                    reason.contains("tracked"),
                    "tracked markers must be preserved for tracked-ness, got: {reason}"
                );
            }
            other => panic!("tracked marker must be preserved, got {other:?}"),
        }

        // Neither the marker nor the worktree changed, and no hold was invented.
        assert_eq!(std::fs::read(&marker_path).unwrap(), before);
        assert_eq!(porcelain_status(repo.path()), "");
        assert_eq!(head_revision(repo.path()), apply_revision);
        assert_eq!(
            store
                .load(&repository_identity(repo.path()), "test-change")
                .unwrap(),
            None,
            "a preserved marker must not create a migrated record"
        );
    }

    /// Migration must never delete evidence it cannot prove is acceptance-owned.
    #[tokio::test]
    async fn acceptance_marker_migration_preserves_foreign_and_malformed_markers() {
        let repo = TempDir::new().unwrap();
        init_git_repo(repo.path());
        commit(repo.path(), "Apply: test-change");
        let apply_revision = head_revision(repo.path());
        let marker_path = repo
            .path()
            .join("openspec/changes/test-change/APPLY_BLOCKED/marker.md");

        let facts = gather_workspace_facts(
            repo.path(),
            repo.path(),
            "test-change",
            &apply_revision,
            "main",
        )
        .await
        .unwrap();

        // Each fixture must survive migration untouched.
        type WriteFixture = Box<dyn Fn()>;
        let fixtures: [(&str, WriteFixture); 5] = [
            (
                "apply-origin",
                Box::new({
                    let marker_path = marker_path.clone();
                    move || {
                        std::fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
                        std::fs::write(&marker_path, "origin: apply\nreason: blocked\n").unwrap();
                    }
                }),
            ),
            (
                "unknown-origin",
                Box::new({
                    let marker_path = marker_path.clone();
                    move || {
                        std::fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
                        std::fs::write(&marker_path, "reason: something happened\n").unwrap();
                    }
                }),
            ),
            (
                "malformed",
                Box::new({
                    let marker_path = marker_path.clone();
                    move || {
                        std::fs::create_dir_all(marker_path.parent().unwrap()).unwrap();
                        std::fs::write(&marker_path, "{ malformed").unwrap();
                    }
                }),
            ),
            (
                "non-resumable acceptance",
                Box::new({
                    let repo_path = repo.path().to_path_buf();
                    move || {
                        write_legacy_acceptance_marker(
                            &repo_path,
                            "test-change",
                            "acceptance_gated",
                            &["evidence".to_string()],
                            &AcceptanceRetryContext::default(),
                            "no_semantic_progress",
                            &[],
                            false,
                            "inspect evidence",
                        )
                        .unwrap();
                    }
                }),
            ),
            (
                "acceptance without evidence",
                Box::new({
                    let repo_path = repo.path().to_path_buf();
                    move || {
                        write_legacy_acceptance_marker(
                            &repo_path,
                            "test-change",
                            "acceptance_gated",
                            &[],
                            &AcceptanceRetryContext::default(),
                            "no_semantic_progress",
                            &[],
                            true,
                            "explicit retry",
                        )
                        .unwrap();
                    }
                }),
            ),
        ];

        for (label, write_fixture) in fixtures {
            let state_root = TempDir::new().unwrap();
            let store = AcceptanceStallStore::new(state_root.path());
            let _ = std::fs::remove_dir_all(marker_path.parent().unwrap());
            write_fixture();
            let before = std::fs::read(&marker_path).unwrap();

            let outcome =
                migrate_legacy_acceptance_marker(&store, repo.path(), &facts, &apply_revision)
                    .unwrap();
            assert!(
                matches!(outcome, MarkerMigration::Preserved { .. }),
                "{label} marker must be preserved, got {outcome:?}"
            );
            assert_eq!(
                std::fs::read(&marker_path).unwrap(),
                before,
                "{label} marker must be left byte-identical"
            );
            assert!(
                store
                    .load(&repository_identity(repo.path()), "test-change")
                    .unwrap()
                    .is_none(),
                "{label} marker must not create a migrated record"
            );
        }

        // Apply-origin markers keep their existing conservative blocked routing.
        std::fs::write(&marker_path, "origin: apply\nreason: blocked\n").unwrap();
        assert_eq!(
            detect_workspace_state("test-change", repo.path(), "main")
                .await
                .unwrap(),
            WorkspaceState::Blocked
        );
        assert_eq!(
            parse_blocked_marker(repo.path(), "test-change")
                .unwrap()
                .unwrap()
                .origin,
            BlockedMarkerOrigin::Apply
        );
    }

    #[tokio::test]
    async fn test_detect_workspace_state_rejects_malformed_marker_without_consuming_it() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");
        let path = repo_root.join("openspec/changes/test-change/APPLY_BLOCKED/marker.md");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "{ malformed").unwrap();

        assert!(detect_workspace_state("test-change", repo_root, "main")
            .await
            .is_err());
        assert!(path.exists());
    }

    #[tokio::test]
    async fn test_detect_workspace_state_created() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        let state = detect_workspace_state("test-change", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Created);
    }

    #[tokio::test]
    async fn test_detect_workspace_state_applying() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");
        commit(repo_root, "WIP(apply): test-change (iteration 1/5)");

        let state = detect_workspace_state("test-change", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Applying { iteration: 2 });
    }

    #[tokio::test]
    async fn test_detect_workspace_state_applied() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");
        commit(repo_root, "Apply: test-change");

        let state = detect_workspace_state("test-change", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Applied);
    }

    #[tokio::test]
    async fn test_detect_workspace_state_archived() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create a branch to simulate workspace
        StdCommand::new("git")
            .args(["checkout", "-b", "workspace-test-change"])
            .current_dir(repo_root)
            .output()
            .unwrap();

        // Create archive directory (change moved to archive)
        let archive_dir = repo_root.join("openspec/changes/archive/test-change");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# Test").unwrap();

        commit(repo_root, "Archive: test-change");

        let state = detect_workspace_state("test-change", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Archived);
    }

    #[tokio::test]
    async fn test_detect_workspace_state_merged() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create archive directory (change moved to archive)
        let archive_dir = repo_root.join("openspec/changes/archive/test-change");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# Test").unwrap();

        commit(repo_root, "Archive: test-change");

        // We're on main, so the archive commit is in main
        // State should be Merged when change directory is gone
        let state = detect_workspace_state("test-change", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Merged);
    }

    #[tokio::test]
    async fn test_detect_workspace_state_merged_with_remaining_changes() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create changes directory before archiving
        let changes_dir = repo_root.join("openspec/changes/test-change");
        fs::create_dir_all(&changes_dir).unwrap();
        fs::write(changes_dir.join("proposal.md"), "# Test Change").unwrap();

        commit(repo_root, "Archive: test-change");

        // Archive commit exists in main, but change directory still exists
        // With the new guardrails, this should NOT be considered Archived
        // because the archive is incomplete (change directory still exists)
        let state = detect_workspace_state("test-change", repo_root, "main")
            .await
            .unwrap();

        // Should be Created state (archive incomplete, no apply commit, no WIP)
        assert_eq!(state, WorkspaceState::Created);
    }

    #[tokio::test]
    async fn test_get_latest_wip_snapshot_multiple() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");
        commit(repo_root, "WIP(apply): test-change (iteration 1/5)");
        commit(repo_root, "WIP(apply): test-change (iteration 2/5)");
        commit(repo_root, "WIP(apply): test-change (iteration 3/5)");

        let iteration = get_latest_wip_snapshot("test-change", repo_root)
            .await
            .unwrap();
        assert_eq!(iteration, Some(3));
    }

    #[tokio::test]
    async fn test_get_latest_wip_snapshot_none() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        let iteration = get_latest_wip_snapshot("test-change", repo_root)
            .await
            .unwrap();
        assert_eq!(iteration, None);
    }

    #[tokio::test]
    async fn test_has_apply_commit_true() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");
        commit(repo_root, "Apply: test-change");

        let result = has_apply_commit("test-change", repo_root).await.unwrap();
        assert!(result);
    }

    #[tokio::test]
    async fn test_has_apply_commit_false() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        let result = has_apply_commit("test-change", repo_root).await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_is_merged_to_base_true() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create archive directory (change moved to archive)
        let archive_dir = repo_root.join("openspec/changes/archive/test-change");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# Test").unwrap();

        commit(repo_root, "Archive: test-change");

        let result = is_merged_to_base("test-change", repo_root, "main")
            .await
            .unwrap();
        assert!(result);
    }

    #[tokio::test]
    async fn test_is_merged_to_base_false_on_branch() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create a branch
        StdCommand::new("git")
            .args(["checkout", "-b", "feature-branch"])
            .current_dir(repo_root)
            .output()
            .unwrap();

        // Create archive directory in feature branch
        let archive_dir = repo_root.join("openspec/changes/archive/test-change");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# Test").unwrap();

        commit(repo_root, "Archive: test-change");

        // Archive is in feature branch, not in main
        let result = is_merged_to_base("test-change", repo_root, "main")
            .await
            .unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_has_archive_files_exact_match() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create archive directory (exact match) with uncommitted changes (dirty)
        let archive_dir = repo_root.join("openspec/changes/archive/test-archiving");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# Test").unwrap();

        // Archiving state requires dirty worktree (uncommitted archive files)
        let result = has_archive_files("test-archiving", repo_root)
            .await
            .unwrap();
        assert!(result);
    }

    #[tokio::test]
    async fn test_has_archive_files_date_prefixed() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create archive directory (date-prefixed) with uncommitted changes (dirty)
        let archive_dir = repo_root.join("openspec/changes/archive/2024-01-15-test-archiving");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# Test").unwrap();

        // Archiving state requires dirty worktree (uncommitted archive files)
        let result = has_archive_files("test-archiving", repo_root)
            .await
            .unwrap();
        assert!(result);
    }

    #[tokio::test]
    async fn test_has_archive_files_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        let result = has_archive_files("nonexistent", repo_root).await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_detect_workspace_state_archiving() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create a branch to simulate workspace
        StdCommand::new("git")
            .args(["checkout", "-b", "workspace-test-archiving"])
            .current_dir(repo_root)
            .output()
            .unwrap();

        // Add apply commit
        commit(repo_root, "Apply: test-archiving");

        // Create archive directory (files moved but no Archive commit yet)
        let archive_dir = repo_root.join("openspec/changes/archive/test-archiving");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# Test").unwrap();

        let state = detect_workspace_state("test-archiving", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Archiving);
    }

    #[tokio::test]
    async fn test_detect_workspace_state_archiving_date_prefixed() {
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create a branch to simulate workspace
        StdCommand::new("git")
            .args(["checkout", "-b", "workspace-test-date-arch"])
            .current_dir(repo_root)
            .output()
            .unwrap();

        // Add apply commit
        commit(repo_root, "Apply: test-date-arch");

        // Create date-prefixed archive directory (files moved but no Archive commit yet)
        let archive_dir = repo_root.join("openspec/changes/archive/2024-01-15-test-date-arch");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# Test").unwrap();

        let state = detect_workspace_state("test-date-arch", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Archiving);
    }

    #[tokio::test]
    async fn test_detect_workspace_state_archived_file_state_only() {
        // Test that archive detection uses file state only, not commit messages
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create a branch to simulate workspace
        StdCommand::new("git")
            .args(["checkout", "-b", "workspace-file-state-test"])
            .current_dir(repo_root)
            .output()
            .unwrap();

        // Create archive directory (change moved to archive)
        let archive_dir = repo_root.join("openspec/changes/archive/file-state-test");
        fs::create_dir_all(&archive_dir).unwrap();
        fs::write(archive_dir.join("proposal.md"), "# File State Test").unwrap();

        // Commit with ANY message (not necessarily "Archive: ...")
        // This tests that we don't rely on commit message matching
        commit(repo_root, "Some other commit message");

        // State should be Archived because:
        // 1. Working tree is clean (committed)
        // 2. Change directory does not exist in openspec/changes/
        // 3. Archive entry exists in openspec/changes/archive/
        let state = detect_workspace_state("file-state-test", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Archived);
    }

    #[tokio::test]
    async fn test_detect_workspace_state_not_archived_without_archive_entry() {
        // Test that archived state requires archive entry existence
        let temp_dir = TempDir::new().unwrap();
        let repo_root = temp_dir.path();
        init_git_repo(repo_root);
        commit(repo_root, "Initial commit");

        // Create a branch
        StdCommand::new("git")
            .args(["checkout", "-b", "workspace-no-archive-entry"])
            .current_dir(repo_root)
            .output()
            .unwrap();

        // Commit with "Archive: ..." message but NO archive directory
        // This tests that commit message alone is not sufficient
        commit(repo_root, "Archive: no-archive-entry");

        // State should NOT be Archived because archive entry does not exist
        // Should fall back to Created (no apply commit, no WIP)
        let state = detect_workspace_state("no-archive-entry", repo_root, "main")
            .await
            .unwrap();
        assert_eq!(state, WorkspaceState::Created);
    }
}