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
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
use std::collections::HashSet;
use std::fs;
use std::path::Path;

use serde::{Deserialize, Serialize};
use serde_yaml::Value;
use tracing::{debug, info, warn};

use crate::error::{OrchestratorError, Result};
use crate::task_parser;
use crate::tui::log_deduplicator;

/// Represents allowed proposal priority values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProposalPriority {
    High,
    Medium,
    Low,
}

/// Machine-readable metadata extracted from `proposal.md` frontmatter.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProposalMetadata {
    pub change_type: Option<String>,
    pub priority: Option<ProposalPriority>,
    pub dependencies: Vec<String>,
    pub references: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub verifications: Vec<VerificationDeclaration>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerificationDeclaration {
    pub id: Option<String>,
    pub requirement: Option<String>,
    pub phase: Option<String>,
    pub owner: Option<String>,
    pub trigger: Option<String>,
    pub automation: Option<String>,
    pub evidence: Option<String>,
    pub rerun: Option<String>,
    pub prerequisites: Option<Vec<String>>,
    /// Where the verification actually executes. Optional during migration.
    pub execution_class: Option<String>,
    /// Whether the verification may block Conflux completion. Optional during migration.
    pub completion_role: Option<String>,
}

/// Execution environment for a structured verification declaration.
///
/// Only `RepositoryLocal` evidence can be produced offline from the repository
/// before integration, so only that class may hold a change-blocking role.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerificationExecutionClass {
    RepositoryLocal,
    RepositoryAutomation,
    DeployedService,
    PhysicalDevice,
    ExternalApproval,
    CredentialedExternal,
}

impl VerificationExecutionClass {
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim() {
            "repository-local" => Some(Self::RepositoryLocal),
            "repository-automation" => Some(Self::RepositoryAutomation),
            "deployed-service" => Some(Self::DeployedService),
            "physical-device" => Some(Self::PhysicalDevice),
            "external-approval" => Some(Self::ExternalApproval),
            "credentialed-external" => Some(Self::CredentialedExternal),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::RepositoryLocal => "repository-local",
            Self::RepositoryAutomation => "repository-automation",
            Self::DeployedService => "deployed-service",
            Self::PhysicalDevice => "physical-device",
            Self::ExternalApproval => "external-approval",
            Self::CredentialedExternal => "credentialed-external",
        }
    }

    /// Whether evidence for this class is produced from the repository itself.
    pub fn is_repository_local(self) -> bool {
        matches!(self, Self::RepositoryLocal)
    }
}

/// Whether a structured verification may keep a Conflux change incomplete.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerificationCompletionRole {
    ChangeBlocking,
    OperationalObservation,
}

impl VerificationCompletionRole {
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim() {
            "change-blocking" => Some(Self::ChangeBlocking),
            "operational-observation" => Some(Self::OperationalObservation),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::ChangeBlocking => "change-blocking",
            Self::OperationalObservation => "operational-observation",
        }
    }
}

/// Structural problem found in a single verification declaration's role metadata.
///
/// Message rendering belongs to the validator so the owning change ID stays with
/// the caller; this enum only carries the deterministic classification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerificationRoleIssue {
    UnknownExecutionClass(String),
    UnknownCompletionRole(String),
    /// Exactly one of the two role fields is present.
    IncompleteRoleMetadata,
    /// `change-blocking` declared on a non-`pre-integration` phase.
    PostIntegrationChangeBlocking(String),
    /// `change-blocking` declared on a non-`repository-local` execution class.
    NonLocalChangeBlocking(VerificationExecutionClass),
    /// Neither role field is declared yet (migration warning, not an error).
    LegacyRoleMetadataMissing,
}

impl VerificationRoleIssue {
    /// Migration gaps are advisory; every other issue is a hard failure.
    pub fn is_warning(&self) -> bool {
        matches!(self, Self::LegacyRoleMetadataMissing)
    }
}

impl VerificationDeclaration {
    pub fn execution_class(&self) -> Option<VerificationExecutionClass> {
        self.execution_class
            .as_deref()
            .and_then(VerificationExecutionClass::parse)
    }

    pub fn completion_role(&self) -> Option<VerificationCompletionRole> {
        self.completion_role
            .as_deref()
            .and_then(VerificationCompletionRole::parse)
    }

    /// Whether this declaration participates in the new role model at all.
    pub fn declares_role_metadata(&self) -> bool {
        non_empty(self.execution_class.as_deref()).is_some()
            || non_empty(self.completion_role.as_deref()).is_some()
    }

    /// Whether this declaration is a valid repository-local completion gate.
    pub fn is_change_blocking(&self) -> bool {
        self.completion_role() == Some(VerificationCompletionRole::ChangeBlocking)
    }

    /// Whether a change-blocking role is declared on non-local evidence.
    ///
    /// This is the hazardous composition that turns operational release
    /// acceptance into a graph-wide implementation stop.
    pub fn is_non_local_change_blocker(&self) -> bool {
        self.is_change_blocking()
            && (self.phase.as_deref() != Some("pre-integration")
                || !self
                    .execution_class()
                    .is_some_and(VerificationExecutionClass::is_repository_local))
    }
}

fn non_empty(value: Option<&str>) -> Option<&str> {
    value.map(str::trim).filter(|value| !value.is_empty())
}

/// Evaluate role metadata for one declaration without touching the filesystem.
pub fn evaluate_verification_role(
    declaration: &VerificationDeclaration,
) -> Vec<VerificationRoleIssue> {
    let mut issues = Vec::new();
    let execution_class = non_empty(declaration.execution_class.as_deref());
    let completion_role = non_empty(declaration.completion_role.as_deref());

    match (execution_class, completion_role) {
        (None, None) => return vec![VerificationRoleIssue::LegacyRoleMetadataMissing],
        (Some(_), None) | (None, Some(_)) => {
            issues.push(VerificationRoleIssue::IncompleteRoleMetadata)
        }
        (Some(_), Some(_)) => {}
    }

    let parsed_class =
        execution_class.map(|value| (value, VerificationExecutionClass::parse(value)));
    if let Some((raw, None)) = parsed_class {
        issues.push(VerificationRoleIssue::UnknownExecutionClass(
            raw.to_string(),
        ));
    }
    let parsed_role =
        completion_role.map(|value| (value, VerificationCompletionRole::parse(value)));
    if let Some((raw, None)) = parsed_role {
        issues.push(VerificationRoleIssue::UnknownCompletionRole(
            raw.to_string(),
        ));
    }

    if matches!(
        parsed_role,
        Some((_, Some(VerificationCompletionRole::ChangeBlocking)))
    ) {
        match declaration.phase.as_deref() {
            Some("pre-integration") => {}
            Some(phase) => issues.push(VerificationRoleIssue::PostIntegrationChangeBlocking(
                phase.to_string(),
            )),
            None => issues.push(VerificationRoleIssue::PostIntegrationChangeBlocking(
                "<missing phase>".to_string(),
            )),
        }
        if let Some((_, Some(class))) = parsed_class {
            if !class.is_repository_local() {
                issues.push(VerificationRoleIssue::NonLocalChangeBlocking(class));
            }
        }
    }

    issues
}

/// Collect declaration IDs that are valid repository-local completion gates.
pub fn change_blocking_verification_ids(declarations: &[VerificationDeclaration]) -> Vec<String> {
    declarations
        .iter()
        .filter(|declaration| {
            declaration.is_change_blocking() && !declaration.is_non_local_change_blocker()
        })
        .filter_map(|declaration| non_empty(declaration.id.as_deref()).map(str::to_string))
        .collect()
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProposalFrontmatterParse {
    pub metadata: Option<ProposalFrontmatterMetadata>,
    pub diagnostics: Vec<String>,
}

fn proposal_priority_label(priority: ProposalPriority) -> String {
    match priority {
        ProposalPriority::High => "high",
        ProposalPriority::Medium => "medium",
        ProposalPriority::Low => "low",
    }
    .to_string()
}

fn warnings_to_strings(warnings: &[ProposalFrontmatterWarning]) -> Vec<String> {
    warnings
        .iter()
        .map(|warning| warning.message.clone())
        .collect()
}

fn frontmatter_metadata_to_metadata(metadata: ProposalFrontmatterMetadata) -> ProposalMetadata {
    ProposalMetadata {
        change_type: metadata.change_type,
        priority: metadata
            .priority
            .as_deref()
            .and_then(|priority| match priority {
                "high" => Some(ProposalPriority::High),
                "medium" => Some(ProposalPriority::Medium),
                "low" => Some(ProposalPriority::Low),
                _ => None,
            }),
        dependencies: metadata.dependencies.unwrap_or_default(),
        references: metadata.references,
        verifications: metadata.verifications,
        warnings: warnings_to_strings(&metadata.warnings),
    }
}

fn read_proposal_from_path(path: &Path) -> ProposalReadResult {
    let content = match fs::read_to_string(path) {
        Ok(content) => content,
        Err(error) => {
            debug!(proposal = %path.display(), error = %error, "Failed to read proposal metadata source");
            return ProposalReadResult {
                metadata: None,
                body_dependencies: Vec::new(),
            };
        }
    };

    let (frontmatter, body) = split_frontmatter(&content);
    let metadata =
        frontmatter.and_then(|frontmatter| parse_frontmatter_metadata(frontmatter, path));
    let body_dependencies = parse_body_dependencies(body, path);

    ProposalReadResult {
        metadata,
        body_dependencies,
    }
}

pub fn read_proposal(change_id: &str) -> ProposalReadResult {
    let proposal_path = Path::new("openspec/changes")
        .join(change_id)
        .join("proposal.md");
    read_proposal_from_path(&proposal_path)
}

/// Parse proposal metadata from a `proposal.md` file.
///
/// Supports optional YAML frontmatter. Dependencies in frontmatter take precedence,
/// but the legacy `## Dependencies` section remains supported as a fallback.
pub fn parse_proposal_metadata_from_file(path: &Path) -> ProposalMetadata {
    let proposal = read_proposal_from_path(path);

    if let Some(metadata) = proposal.metadata {
        let mut parsed = frontmatter_metadata_to_metadata(metadata);
        if parsed.dependencies.is_empty() {
            parsed.dependencies = proposal.body_dependencies;
        }
        parsed
    } else {
        ProposalMetadata {
            change_type: None,
            priority: None,
            dependencies: proposal.body_dependencies,
            references: Vec::new(),
            verifications: Vec::new(),
            warnings: Vec::new(),
        }
    }
}

/// Read proposal dependencies for scheduler dispatch gates.
///
/// Unlike the display-oriented metadata parser, this fails when proposal metadata
/// cannot be read or decoded. Dispatch must not treat unavailable dependency
/// declarations as an empty dependency list.
pub fn parse_proposal_dependencies_strict_from_file(path: &Path) -> Result<Vec<String>> {
    let content = fs::read_to_string(path)?;
    let (frontmatter, body) = split_frontmatter(&content);
    if content.starts_with("---\n") && frontmatter.is_none() {
        return Err(OrchestratorError::Parse(format!(
            "Failed to find closing frontmatter delimiter in {}",
            path.display()
        )));
    }

    let mut dependencies = match frontmatter {
        Some(frontmatter) => {
            let parsed = parse_frontmatter_metadata_strict(frontmatter, path);
            if !parsed.diagnostics.is_empty() {
                return Err(OrchestratorError::Parse(parsed.diagnostics.join("; ")));
            }
            parsed
                .metadata
                .and_then(|metadata| metadata.dependencies)
                .unwrap_or_default()
        }
        None => Vec::new(),
    };
    if dependencies.is_empty() {
        dependencies = parse_body_dependencies(body, path);
    }
    Ok(dependencies)
}

#[cfg_attr(not(test), allow(dead_code))]
fn parse_proposal_metadata(content: &str, path: &Path) -> ProposalMetadata {
    let (frontmatter, body) = split_frontmatter(content);
    let mut metadata = frontmatter
        .and_then(|frontmatter| parse_frontmatter_metadata(frontmatter, path))
        .map(frontmatter_metadata_to_metadata)
        .unwrap_or_default();

    if metadata.dependencies.is_empty() {
        metadata.dependencies = parse_body_dependencies(body, path);
    }

    metadata
}

fn split_frontmatter(content: &str) -> (Option<&str>, &str) {
    if !content.starts_with("---\n") {
        return (None, content);
    }

    let remainder = &content[4..];
    if let Some(end) = remainder.find("\n---\n") {
        let frontmatter = &remainder[..end];
        let body = &remainder[end + 5..];
        return (Some(frontmatter), body);
    }

    (None, content)
}

fn parse_frontmatter_metadata(
    frontmatter: &str,
    path: &Path,
) -> Option<ProposalFrontmatterMetadata> {
    let parsed = parse_frontmatter_metadata_strict(frontmatter, path);
    parsed.metadata
}

pub fn parse_proposal_frontmatter_strict(content: &str, path: &Path) -> ProposalFrontmatterParse {
    split_frontmatter(content)
        .0
        .map(|frontmatter| parse_frontmatter_metadata_strict(frontmatter, path))
        .unwrap_or_default()
}

pub fn parse_frontmatter_metadata_strict(
    frontmatter: &str,
    path: &Path,
) -> ProposalFrontmatterParse {
    let value: Value = match serde_yaml::from_str(frontmatter) {
        Ok(value) => value,
        Err(error) => {
            let diagnostic = format!("Failed to parse proposal frontmatter YAML: {error}");
            warn!(proposal = %path.display(), error = %error, "Failed to parse proposal frontmatter YAML");
            return ProposalFrontmatterParse {
                metadata: None,
                diagnostics: vec![diagnostic],
            };
        }
    };

    let mut warnings = Vec::new();
    let mut diagnostics = Vec::new();
    if let Value::Mapping(mapping) = &value {
        let known_keys: HashSet<&str> = [
            "change_type",
            "priority",
            "dependencies",
            "references",
            "verifications",
        ]
        .into_iter()
        .collect();

        for key in mapping.keys() {
            if let Some(key) = key.as_str() {
                if !known_keys.contains(key) {
                    let warning = format!("Unknown proposal frontmatter key: {}", key);
                    warn!(proposal = %path.display(), key = key, warning = %warning, "Unknown proposal frontmatter key detected");
                    warnings.push(ProposalFrontmatterWarning {
                        key: key.to_string(),
                        message: warning,
                    });
                }
            }
        }

        if let Some(Value::Sequence(verifications)) =
            mapping.get(Value::String("verifications".to_string()))
        {
            let known_verification_keys: HashSet<&str> = [
                "id",
                "requirement",
                "phase",
                "owner",
                "trigger",
                "automation",
                "evidence",
                "rerun",
                "prerequisites",
                "execution_class",
                "completion_role",
            ]
            .into_iter()
            .collect();
            for (index, verification) in verifications.iter().enumerate() {
                if let Value::Mapping(verification) = verification {
                    for key in verification.keys() {
                        if let Some(key) = key.as_str() {
                            if !known_verification_keys.contains(key) {
                                diagnostics.push(format!(
                                    "Unknown verification declaration key at index {}: {}",
                                    index, key
                                ));
                            }
                        }
                    }
                }
            }
        }
    }

    let raw: RawProposalFrontmatter = match serde_yaml::from_value(value) {
        Ok(raw) => raw,
        Err(error) => {
            let diagnostic = format!("Failed to decode proposal frontmatter fields: {error}");
            warn!(proposal = %path.display(), error = %error, "Failed to decode proposal frontmatter fields");
            return ProposalFrontmatterParse {
                metadata: None,
                diagnostics: vec![diagnostic],
            };
        }
    };

    let mut dependencies = Vec::new();
    if let Some(items) = raw.dependencies {
        for item in items {
            let dep_id = extract_dependency_id(item.trim());
            if !dep_id.is_empty() {
                dependencies.push(dep_id);
            }
        }
    }

    let metadata = ProposalFrontmatterMetadata {
        change_type: raw.change_type,
        priority: raw.priority.map(proposal_priority_label),
        dependencies: (!dependencies.is_empty()).then_some(dependencies),
        references: raw.references.unwrap_or_default(),
        verifications: raw.verifications.unwrap_or_default(),
        warnings,
    };

    ProposalFrontmatterParse {
        metadata: (!metadata.is_empty()).then_some(metadata),
        diagnostics,
    }
}

/// Represents a change from openspec list
#[derive(Debug, Clone, PartialEq)]
pub struct Change {
    pub id: String,
    pub completed_tasks: u32,
    pub total_tasks: u32,
    #[allow(dead_code)]
    pub last_modified: String,
    /// Dependencies on other changes (parsed from proposal.md)
    pub dependencies: Vec<String>,
    /// Optional proposal metadata from `proposal.md` frontmatter.
    pub metadata: ProposalMetadata,
}

impl Change {
    /// Calculate progress percentage
    pub fn progress_percent(&self) -> f32 {
        if self.total_tasks == 0 {
            return 0.0;
        }
        (self.completed_tasks as f32 / self.total_tasks as f32) * 100.0
    }

    /// Check if all tasks are completed
    pub fn is_complete(&self) -> bool {
        self.completed_tasks == self.total_tasks && self.total_tasks > 0
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProposalFrontmatterWarning {
    pub key: String,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProposalFrontmatterMetadata {
    pub change_type: Option<String>,
    pub priority: Option<String>,
    pub dependencies: Option<Vec<String>>,
    pub references: Vec<String>,
    pub verifications: Vec<VerificationDeclaration>,
    pub warnings: Vec<ProposalFrontmatterWarning>,
}

impl ProposalFrontmatterMetadata {
    fn is_empty(&self) -> bool {
        self.change_type.is_none()
            && self.priority.is_none()
            && self.dependencies.is_none()
            && self.references.is_empty()
            && self.verifications.is_empty()
            && self.warnings.is_empty()
    }
}

#[derive(Debug, Default, Deserialize)]
struct RawProposalFrontmatter {
    change_type: Option<String>,
    priority: Option<ProposalPriority>,
    dependencies: Option<Vec<String>>,
    references: Option<Vec<String>>,
    verifications: Option<Vec<VerificationDeclaration>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProposalReadResult {
    pub metadata: Option<ProposalFrontmatterMetadata>,
    pub body_dependencies: Vec<String>,
}

impl ProposalReadResult {
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn dependencies_for_analysis(&self) -> Vec<String> {
        self.metadata
            .as_ref()
            .and_then(|metadata| metadata.dependencies.clone())
            .unwrap_or_else(|| self.body_dependencies.clone())
    }
}

/// Parse dependencies from the legacy body `## Dependencies` section.
///
/// Supports formats like:
/// - `- feature-base`
/// - `- [feature-base](../feature-base/proposal.md)`
/// - `- feature-base: description`
fn parse_body_dependencies(content: &str, path: &Path) -> Vec<String> {
    let mut dependencies = Vec::new();
    let mut in_deps_section = false;

    for line in content.lines() {
        let trimmed = line.trim();

        // Check for Dependencies section header
        if trimmed.starts_with("## Dependencies") {
            in_deps_section = true;
            continue;
        }

        // Exit section on next header
        if in_deps_section && trimmed.starts_with("## ") {
            break;
        }

        // Parse bullet points in Dependencies section
        if in_deps_section && trimmed.starts_with("- ") {
            let item = trimmed.trim_start_matches("- ").trim();

            // Skip "None" or empty items
            if item.is_empty() || item.eq_ignore_ascii_case("none") {
                continue;
            }

            // Extract change ID from various formats
            let dep_id = extract_dependency_id(item);
            if !dep_id.is_empty() {
                dependencies.push(dep_id);
            }
        }
    }

    if !dependencies.is_empty() {
        info!(proposal = %path.display(), dependencies = ?dependencies, "Parsed proposal dependencies from body section");
    }

    dependencies
}

fn parse_dependencies_from_base(base_path: &Path, change_id: &str) -> ProposalMetadata {
    let proposal_path = base_path
        .join("openspec/changes")
        .join(change_id)
        .join("proposal.md");

    let mut metadata = parse_proposal_metadata_from_file(&proposal_path);
    metadata
        .dependencies
        .retain(|dependency| dependency != change_id);
    metadata
}

/// Extract a dependency ID from a bullet point item.
///
/// Handles formats like:
/// - `feature-base` -> `feature-base`
/// - `[feature-base](../feature-base/proposal.md)` -> `feature-base`
/// - `feature-base: some description` -> `feature-base`
/// - `feature-base (optional)` -> `feature-base`
fn extract_dependency_id(item: &str) -> String {
    // Handle markdown link format: [id](path)
    if item.starts_with('[') {
        if let Some(end) = item.find(']') {
            return item[1..end].trim().to_string();
        }
    }

    // Handle inline code format: `id`
    if let Some(stripped) = item.strip_prefix('`') {
        if let Some(end) = stripped.find('`') {
            return stripped[..end].trim().to_string();
        }
    }

    // Handle plain text with optional suffix (colon, parenthesis)
    // Note: Don't split on '-' as it's common in change IDs like "feature-base"
    item.split(&[':', '('][..])
        .next()
        .unwrap_or(item)
        .trim()
        .to_string()
}

/// Read one change entry's task progress through the shared task-file contract.
///
/// `Ok(None)` means the entry declares no task artifact at all; an ambiguous or
/// invalid artifact is an error rather than a silent zero.
fn read_entry_task_progress(
    entry_dir: &Path,
    change_id: &str,
) -> Result<Option<task_parser::TaskProgress>> {
    match crate::task_file::find_in_entry(entry_dir)? {
        Some(file) => Ok(Some(crate::task_file::read_progress(
            &file,
            Some(change_id),
        )?)),
        None => Ok(None),
    }
}

/// List changes by directly reading the openspec/changes directory.
///
/// This is the native implementation that avoids calling the external
/// `openspec list --json` command. It reads the directory structure and
/// reads each change's own task artifact to get accurate task progress.
pub fn list_changes_native() -> Result<Vec<Change>> {
    list_changes_native_from(Path::new("."))
}

pub fn list_changes_native_from(base_path: &Path) -> Result<Vec<Change>> {
    let changes_dir = base_path.join("openspec/changes");

    if !changes_dir.exists() {
        debug!("Changes directory does not exist: {:?}", changes_dir);
        return Ok(Vec::new());
    }

    let entries = fs::read_dir(changes_dir).map_err(|e| {
        OrchestratorError::ConfigLoad(format!("Failed to read changes directory: {}", e))
    })?;

    let mut changes = Vec::new();

    for entry in entries {
        let entry = entry.map_err(|e| {
            OrchestratorError::ConfigLoad(format!("Failed to read directory entry: {}", e))
        })?;

        let path = entry.path();

        // Skip non-directories
        if !path.is_dir() {
            continue;
        }

        // Skip special directories like 'archive'
        let dir_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();

        if dir_name == "archive" || dir_name.starts_with('.') {
            continue;
        }

        // Skip changes without proposal.md
        let proposal_path = path.join("proposal.md");
        if !proposal_path.exists() {
            debug!("Skipping change '{}' - no proposal.md found", dir_name);
            continue;
        }

        // Rejected marker committed on base means this change is terminal and must
        // not be re-queued in subsequent runs.
        if path.join("REJECTED.md").exists() {
            debug!(
                "Skipping change '{}' from active list - REJECTED.md marker exists",
                dir_name
            );
            continue;
        }

        // Read the change's own task artifact, in whichever format it declares
        let (completed_tasks, total_tasks) = match read_entry_task_progress(&path, dir_name) {
            Ok(Some(progress)) => (progress.completed, progress.total),
            Ok(None) | Err(_) => {
                // A missing, ambiguous, or unreadable artifact projects 0/0 for
                // this read-only listing; every gating path fails closed instead.
                debug!("Could not parse tasks for change '{}', using 0/0", dir_name);
                (0, 0)
            }
        };

        // Parse dependencies and metadata from proposal.md
        let metadata = parse_dependencies_from_base(base_path, dir_name);
        let dependencies = metadata.dependencies.clone();

        changes.push(Change {
            id: dir_name.to_string(),
            completed_tasks,
            total_tasks,
            last_modified: String::new(), // Not used in native implementation
            dependencies,
            metadata,
        });
    }

    // Sort by id for consistent ordering
    changes.sort_by(|a, b| a.id.cmp(&b.id));

    if log_deduplicator::should_log_change_count(changes.len()) {
        debug!("Found {} changes via native parsing", changes.len());
    }
    Ok(changes)
}

/// List change directories that are marked as rejected (`REJECTED.md`) for
/// read-only UI surfaces.
///
/// Unlike [`list_changes_native`], this function intentionally returns only
/// marker-bearing rows and is not used for execution candidate discovery.
pub fn list_rejected_changes_native_from(base_path: &Path) -> Result<Vec<Change>> {
    let changes_dir = base_path.join("openspec/changes");

    if !changes_dir.exists() {
        debug!("Changes directory does not exist: {:?}", changes_dir);
        return Ok(Vec::new());
    }

    let entries = fs::read_dir(changes_dir).map_err(|e| {
        OrchestratorError::ConfigLoad(format!("Failed to read changes directory: {}", e))
    })?;

    let mut changes = Vec::new();

    for entry in entries {
        let entry = entry.map_err(|e| {
            OrchestratorError::ConfigLoad(format!("Failed to read directory entry: {}", e))
        })?;

        let path = entry.path();
        if !path.is_dir() {
            continue;
        }

        let dir_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();

        if dir_name == "archive" || dir_name.starts_with('.') {
            continue;
        }

        if !path.join("proposal.md").exists() || !path.join("REJECTED.md").exists() {
            continue;
        }

        let (completed_tasks, total_tasks) = match read_entry_task_progress(&path, dir_name) {
            Ok(Some(progress)) => (progress.completed, progress.total),
            Ok(None) | Err(_) => {
                debug!(
                    "Could not parse tasks for rejected change '{}', using 0/0",
                    dir_name
                );
                (0, 0)
            }
        };

        let metadata = parse_dependencies_from_base(base_path, dir_name);
        let dependencies = metadata.dependencies.clone();

        changes.push(Change {
            id: dir_name.to_string(),
            completed_tasks,
            total_tasks,
            last_modified: String::new(),
            dependencies,
            metadata,
        });
    }

    changes.sort_by(|a, b| a.id.cmp(&b.id));
    Ok(changes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::LoggingConfig;
    use crate::tui::log_deduplicator;
    use std::env;
    use std::fs;
    use std::io::Write;
    use std::sync::{Mutex, OnceLock};
    use tempfile::TempDir;

    static LOG_TEST_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();

    #[test]
    fn test_change_progress() {
        let change = Change {
            id: "test".to_string(),
            completed_tasks: 0,
            total_tasks: 0,
            last_modified: "now".to_string(),
            dependencies: Vec::new(),
            metadata: ProposalMetadata::default(),
        };
        assert_eq!(change.progress_percent(), 0.0);
        assert!(!change.is_complete());
    }

    #[test]
    fn test_change_is_complete() {
        let change = Change {
            id: "test".to_string(),
            completed_tasks: 5,
            total_tasks: 5,
            last_modified: "now".to_string(),
            dependencies: Vec::new(),
            metadata: ProposalMetadata::default(),
        };
        assert_eq!(change.progress_percent(), 100.0);
        assert!(change.is_complete());
    }

    // ====================
    // list_changes_native tests
    // ====================

    // Note: These tests run in the actual project directory which has openspec/changes
    // The function relies on relative paths, so these tests validate real behavior

    #[test]
    fn test_list_changes_native_returns_ok() {
        // Test that the function returns Ok when run in a valid openspec project
        // This test verifies the basic functionality works in the real project structure
        let result = list_changes_native();
        // The function should always return Ok (empty vec if dir doesn't exist)
        assert!(result.is_ok());
    }

    #[test]
    fn test_list_changes_native_excludes_archive() {
        // The result should not include "archive" as a change ID
        let result = list_changes_native().unwrap();
        assert!(
            !result.iter().any(|c| c.id == "archive"),
            "archive directory should be excluded"
        );
    }

    #[test]
    fn test_list_changes_native_excludes_hidden() {
        // The result should not include any hidden directories (starting with .)
        let result = list_changes_native().unwrap();
        assert!(
            !result.iter().any(|c| c.id.starts_with('.')),
            "hidden directories should be excluded"
        );
    }

    #[test]
    fn test_list_changes_native_sorted_by_id() {
        // The result should be sorted by change ID
        let result = list_changes_native().unwrap();
        if result.len() > 1 {
            let mut sorted = result.clone();
            sorted.sort_by(|a, b| a.id.cmp(&b.id));
            assert_eq!(result, sorted, "changes should be sorted by ID");
        }
    }

    #[test]
    fn test_list_changes_native_parses_task_counts() {
        // If there are any changes, verify they have valid task counts
        let result = list_changes_native().unwrap();
        for change in &result {
            // completed_tasks should never exceed total_tasks
            assert!(
                change.completed_tasks <= change.total_tasks,
                "completed_tasks ({}) should not exceed total_tasks ({}) for change '{}'",
                change.completed_tasks,
                change.total_tasks,
                change.id
            );
        }
    }

    #[test]
    fn test_list_changes_native_integration() {
        // Integration test: verify the function works with the actual project structure
        // This test runs in the project root where openspec/changes exists
        let result = list_changes_native();
        assert!(result.is_ok(), "list_changes_native should succeed");

        let changes = result.unwrap();
        // Verify each change has a non-empty ID
        for change in &changes {
            assert!(!change.id.is_empty(), "change ID should not be empty");
        }
    }

    #[test]
    fn test_list_changes_native_excludes_rejected_marker_changes() {
        let _lock = crate::test_support::cwd_lock().lock().unwrap();
        let temp_dir = TempDir::new().unwrap();
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("change-rejected");
        fs::create_dir_all(&change_dir).unwrap();
        fs::write(change_dir.join("proposal.md"), "# proposal").unwrap();
        fs::write(change_dir.join("tasks.md"), "- [ ] pending task").unwrap();
        fs::write(
            change_dir.join("REJECTED.md"),
            "# REJECTED\n\n- reason: blocked\n",
        )
        .unwrap();

        let original_dir = env::current_dir().unwrap();
        env::set_current_dir(temp_dir.path()).unwrap();

        let result = list_changes_native().unwrap();

        env::set_current_dir(original_dir).unwrap();

        assert!(
            result.iter().all(|change| change.id != "change-rejected"),
            "changes with REJECTED.md marker must be excluded from active change list"
        );
    }

    #[test]
    fn test_list_changes_and_rejected_native_from_use_explicit_base_when_cwd_differs() {
        let _lock = crate::test_support::cwd_lock().lock().unwrap();
        let repo_dir = TempDir::new().unwrap();
        let other_dir = TempDir::new().unwrap();
        let base = repo_dir.path().join("openspec").join("changes");

        let active_dir = base.join("change-active");
        fs::create_dir_all(&active_dir).unwrap();
        fs::write(active_dir.join("proposal.md"), "# proposal").unwrap();
        fs::write(active_dir.join("tasks.md"), "- [ ] active task").unwrap();

        let rejected_dir = base.join("change-rejected");
        fs::create_dir_all(&rejected_dir).unwrap();
        fs::write(rejected_dir.join("proposal.md"), "# proposal").unwrap();
        fs::write(rejected_dir.join("tasks.md"), "- [x] rejected task").unwrap();
        fs::write(rejected_dir.join("REJECTED.md"), "# REJECTED").unwrap();

        let original_dir = env::current_dir().unwrap();
        env::set_current_dir(other_dir.path()).unwrap();

        let active = list_changes_native_from(repo_dir.path()).unwrap();
        let rejected = list_rejected_changes_native_from(repo_dir.path()).unwrap();

        env::set_current_dir(original_dir).unwrap();

        assert_eq!(
            active.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(),
            vec!["change-active"]
        );
        assert_eq!(
            rejected.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(),
            vec!["change-rejected"]
        );
        assert_eq!(
            (rejected[0].completed_tasks, rejected[0].total_tasks),
            (1, 1)
        );
    }

    #[test]
    fn test_list_rejected_changes_native_returns_only_marker_rows() {
        let _lock = crate::test_support::cwd_lock().lock().unwrap();
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path().join("openspec").join("changes");

        let rejected_dir = base.join("change-rejected");
        fs::create_dir_all(&rejected_dir).unwrap();
        fs::write(rejected_dir.join("proposal.md"), "# proposal").unwrap();
        fs::write(rejected_dir.join("tasks.md"), "- [ ] pending task").unwrap();
        fs::write(rejected_dir.join("REJECTED.md"), "# REJECTED").unwrap();

        let active_dir = base.join("change-active");
        fs::create_dir_all(&active_dir).unwrap();
        fs::write(active_dir.join("proposal.md"), "# proposal").unwrap();
        fs::write(active_dir.join("tasks.md"), "- [ ] pending task").unwrap();

        let result = list_rejected_changes_native_from(temp_dir.path()).unwrap();

        assert_eq!(result.len(), 1, "only rejected rows should be returned");
        assert_eq!(result[0].id, "change-rejected");
    }

    #[test]
    fn test_read_proposal_prefers_frontmatter_dependencies() {
        let _lock = crate::test_support::cwd_lock().lock().unwrap();
        let temp_dir = TempDir::new().unwrap();
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("change-a");
        fs::create_dir_all(&change_dir).unwrap();
        fs::write(
            change_dir.join("proposal.md"),
            "---\ndependencies:\n  - frontmatter-dep\npriority: high\nreferences:\n  - src/analyzer.rs\n---\n# Change: Sample\n\n## Dependencies\n\n- body-dep\n",
        )
        .unwrap();

        let original_dir = env::current_dir().unwrap();
        env::set_current_dir(temp_dir.path()).unwrap();

        let proposal = read_proposal("change-a");

        env::set_current_dir(original_dir).unwrap();

        let metadata = proposal
            .metadata
            .as_ref()
            .expect("metadata should be present");
        assert_eq!(metadata.priority.as_deref(), Some("high"));
        assert_eq!(
            metadata.dependencies,
            Some(vec!["frontmatter-dep".to_string()])
        );
        assert_eq!(metadata.references, vec!["src/analyzer.rs".to_string()]);
        assert!(metadata.warnings.is_empty());
        assert_eq!(proposal.body_dependencies, vec!["body-dep".to_string()]);
        assert_eq!(
            proposal.dependencies_for_analysis(),
            vec!["frontmatter-dep".to_string()]
        );
    }

    #[test]
    fn test_read_proposal_falls_back_to_body_dependencies_without_frontmatter_field() {
        let _lock = crate::test_support::cwd_lock().lock().unwrap();
        let temp_dir = TempDir::new().unwrap();
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("change-a");
        fs::create_dir_all(&change_dir).unwrap();
        fs::write(
            change_dir.join("proposal.md"),
            "---\npriority: low\n---\n# Change: Sample\n\n## Dependencies\n\n- body-dep\n",
        )
        .unwrap();

        let original_dir = env::current_dir().unwrap();
        env::set_current_dir(temp_dir.path()).unwrap();

        let proposal = read_proposal("change-a");

        env::set_current_dir(original_dir).unwrap();

        let metadata = proposal
            .metadata
            .as_ref()
            .expect("metadata should be present");
        assert_eq!(metadata.priority.as_deref(), Some("low"));
        assert_eq!(metadata.dependencies, None);
        assert_eq!(
            proposal.dependencies_for_analysis(),
            vec!["body-dep".to_string()]
        );
    }

    #[test]
    fn test_strict_dependency_metadata_rejects_unreadable_or_invalid_frontmatter() {
        let temp_dir = TempDir::new().unwrap();
        let missing = temp_dir.path().join("missing.md");
        assert!(parse_proposal_dependencies_strict_from_file(&missing).is_err());

        let invalid = temp_dir.path().join("invalid.md");
        fs::write(&invalid, "---\ndependencies: [broken\n---\n# Change\n").unwrap();
        assert!(parse_proposal_dependencies_strict_from_file(&invalid).is_err());
    }

    #[test]
    fn test_read_proposal_warns_on_unknown_frontmatter_keys() {
        let _lock = crate::test_support::cwd_lock().lock().unwrap();
        let temp_dir = TempDir::new().unwrap();
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("change-a");
        fs::create_dir_all(&change_dir).unwrap();
        fs::write(
            change_dir.join("proposal.md"),
            "---\ndependencies:\n  - frontmatter-dep\nowner: tumf\n---\n# Change: Sample\n",
        )
        .unwrap();

        let original_dir = env::current_dir().unwrap();
        env::set_current_dir(temp_dir.path()).unwrap();

        let proposal = read_proposal("change-a");

        env::set_current_dir(original_dir).unwrap();

        let metadata = proposal
            .metadata
            .as_ref()
            .expect("metadata should be present");
        assert_eq!(
            metadata.dependencies,
            Some(vec!["frontmatter-dep".to_string()])
        );
        assert_eq!(metadata.warnings.len(), 1);
        assert_eq!(metadata.warnings[0].key, "owner");
        assert!(metadata.warnings[0]
            .message
            .contains("Unknown proposal frontmatter key: owner"));
        assert_eq!(
            proposal.dependencies_for_analysis(),
            vec!["frontmatter-dep".to_string()]
        );
    }

    #[test]
    fn test_list_changes_native_excludes_without_proposal() {
        let _lock = crate::test_support::cwd_lock().lock().unwrap();
        // Test that changes without proposal.md are excluded
        let temp_dir = TempDir::new().unwrap();
        let changes_dir = temp_dir.path().join("openspec").join("changes");
        fs::create_dir_all(&changes_dir).unwrap();

        // Create change-a WITH proposal.md
        let change_a_dir = changes_dir.join("change-a");
        fs::create_dir_all(&change_a_dir).unwrap();
        fs::File::create(change_a_dir.join("proposal.md")).unwrap();
        let mut tasks_a = fs::File::create(change_a_dir.join("tasks.md")).unwrap();
        writeln!(tasks_a, "- [x] Task 1\n- [ ] Task 2").unwrap();

        // Create change-b WITHOUT proposal.md
        let change_b_dir = changes_dir.join("change-b");
        fs::create_dir_all(&change_b_dir).unwrap();
        let mut tasks_b = fs::File::create(change_b_dir.join("tasks.md")).unwrap();
        writeln!(tasks_b, "- [ ] Task 1").unwrap();

        let original_dir = env::current_dir().unwrap();
        env::set_current_dir(temp_dir.path()).unwrap();

        let result = list_changes_native().unwrap();

        env::set_current_dir(original_dir).unwrap();

        // Should only include change-a (has proposal.md), not change-b (no proposal.md)
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "change-a");
        assert_eq!(result[0].completed_tasks, 1);
        assert_eq!(result[0].total_tasks, 2);
    }

    #[test]
    fn test_parse_proposal_metadata_prefers_frontmatter_dependencies() {
        let proposal = r#"---
change_type: hybrid
priority: high
dependencies:
  - frontmatter-change
references:
  - src/openspec.rs
---

# Change: Example

## Dependencies
- body-change
"#;

        let metadata = parse_proposal_metadata(proposal, Path::new("proposal.md"));

        assert_eq!(metadata.priority, Some(ProposalPriority::High));
        assert_eq!(
            metadata.dependencies,
            vec!["frontmatter-change".to_string()]
        );
        assert_eq!(metadata.references, vec!["src/openspec.rs".to_string()]);
        assert!(metadata.warnings.is_empty());
    }

    #[test]
    fn test_parse_verification_declarations_and_strict_diagnostics() {
        let proposal = r#"---
change_type: implementation
verifications:
  - id: local
    requirement: parser behavior
    phase: pre-integration
    owner: conflux-acceptance
    trigger: pull request
    automation: Cargo.toml
    evidence: cargo test
    rerun: cargo test
    prerequisites: []
  - id: deployed
    requirement: deployment behavior
    phase: post-integration
    owner: repository-automation
    trigger: default branch integration
    automation: Cargo.toml
    evidence: CI result
    rerun: rerun CI
    prerequisites:
      - deployment approval
---
# Change: Example
"#;
        let parsed = parse_proposal_frontmatter_strict(proposal, Path::new("proposal.md"));
        assert!(parsed.diagnostics.is_empty());
        let metadata = parsed.metadata.expect("metadata");
        assert_eq!(metadata.verifications.len(), 2);
        assert!(metadata.warnings.is_empty());
        assert_eq!(metadata.verifications[0].id.as_deref(), Some("local"));
        assert_eq!(
            metadata.verifications[1].prerequisites,
            Some(vec!["deployment approval".to_string()])
        );

        let malformed = parse_proposal_frontmatter_strict(
            "---\nverifications: [\n---\n# Change",
            Path::new("proposal.md"),
        );
        assert!(malformed.metadata.is_none());
        assert!(!malformed.diagnostics.is_empty());

        let unknown_nested = parse_proposal_frontmatter_strict(
            "---\nverifications:\n  - id: local\n    unexpected: value\n---\n# Change",
            Path::new("proposal.md"),
        );
        assert_eq!(unknown_nested.metadata.unwrap().verifications.len(), 1);
        assert_eq!(
            unknown_nested.diagnostics,
            vec!["Unknown verification declaration key at index 0: unexpected"]
        );
    }

    #[test]
    fn test_parse_verification_declarations_preserves_duplicate_invalid_and_empty_values() {
        let parsed = parse_proposal_frontmatter_strict(
            "---\nverifications:\n  - id: duplicate\n    phase: invalid\n    prerequisites: []\n  - id: duplicate\n    phase: pre-integration\n    prerequisites: []\n---\n# Change",
            Path::new("proposal.md"),
        );

        assert!(parsed.diagnostics.is_empty());
        let declarations = &parsed.metadata.unwrap().verifications;
        assert_eq!(declarations.len(), 2);
        assert_eq!(declarations[0].id.as_deref(), Some("duplicate"));
        assert_eq!(declarations[0].phase.as_deref(), Some("invalid"));
        assert_eq!(declarations[0].prerequisites, Some(Vec::new()));
        assert_eq!(declarations[1].id.as_deref(), Some("duplicate"));
    }

    fn declaration(
        phase: &str,
        execution_class: &str,
        completion_role: &str,
    ) -> VerificationDeclaration {
        VerificationDeclaration {
            id: Some("check".to_string()),
            phase: (!phase.is_empty()).then(|| phase.to_string()),
            execution_class: (!execution_class.is_empty()).then(|| execution_class.to_string()),
            completion_role: (!completion_role.is_empty()).then(|| completion_role.to_string()),
            ..Default::default()
        }
    }

    #[test]
    fn test_parse_verification_role_fields_from_frontmatter() {
        let parsed = parse_proposal_frontmatter_strict(
            "---\nverifications:\n  - id: local\n    phase: pre-integration\n    execution_class: repository-local\n    completion_role: change-blocking\n    prerequisites: []\n---\n# Change",
            Path::new("proposal.md"),
        );

        assert!(parsed.diagnostics.is_empty());
        let declarations = parsed.metadata.unwrap().verifications;
        assert_eq!(
            declarations[0].execution_class(),
            Some(VerificationExecutionClass::RepositoryLocal)
        );
        assert_eq!(
            declarations[0].completion_role(),
            Some(VerificationCompletionRole::ChangeBlocking)
        );
        assert!(declarations[0].is_change_blocking());
        assert!(!declarations[0].is_non_local_change_blocker());
        assert_eq!(
            change_blocking_verification_ids(&declarations),
            vec!["local".to_string()]
        );
    }

    #[test]
    fn test_legacy_verification_declaration_reports_migration_issue_only() {
        let legacy = declaration("pre-integration", "", "");

        assert!(!legacy.declares_role_metadata());
        let issues = evaluate_verification_role(&legacy);
        assert_eq!(
            issues,
            vec![VerificationRoleIssue::LegacyRoleMetadataMissing]
        );
        assert!(issues.iter().all(VerificationRoleIssue::is_warning));
        assert!(change_blocking_verification_ids(&[legacy]).is_empty());
    }

    #[test]
    fn test_evaluate_verification_role_rejects_inconsistent_combinations() {
        assert_eq!(
            evaluate_verification_role(&declaration(
                "post-integration",
                "repository-automation",
                "change-blocking"
            )),
            vec![
                VerificationRoleIssue::PostIntegrationChangeBlocking(
                    "post-integration".to_string()
                ),
                VerificationRoleIssue::NonLocalChangeBlocking(
                    VerificationExecutionClass::RepositoryAutomation
                )
            ]
        );
        assert_eq!(
            evaluate_verification_role(&declaration(
                "pre-integration",
                "physical-device",
                "change-blocking"
            )),
            vec![VerificationRoleIssue::NonLocalChangeBlocking(
                VerificationExecutionClass::PhysicalDevice
            )]
        );
        assert_eq!(
            evaluate_verification_role(&declaration("pre-integration", "repository-local", "")),
            vec![VerificationRoleIssue::IncompleteRoleMetadata]
        );
        assert_eq!(
            evaluate_verification_role(&declaration("pre-integration", "on-my-laptop", "blocking")),
            vec![
                VerificationRoleIssue::UnknownExecutionClass("on-my-laptop".to_string()),
                VerificationRoleIssue::UnknownCompletionRole("blocking".to_string()),
            ]
        );
    }

    #[test]
    fn test_operational_observation_declarations_are_never_change_blocking() {
        for class in [
            "repository-automation",
            "deployed-service",
            "physical-device",
            "external-approval",
            "credentialed-external",
        ] {
            let observation = declaration("post-integration", class, "operational-observation");
            assert!(
                evaluate_verification_role(&observation).is_empty(),
                "{class}"
            );
            assert!(!observation.is_change_blocking());
            assert!(!observation.is_non_local_change_blocker());
        }
    }

    #[test]
    fn test_non_local_change_blocker_detection_covers_missing_phase_and_class() {
        assert!(
            declaration("", "repository-local", "change-blocking").is_non_local_change_blocker()
        );
        assert!(declaration("pre-integration", "", "change-blocking").is_non_local_change_blocker());
        assert!(
            declaration("pre-integration", "deployed-service", "change-blocking")
                .is_non_local_change_blocker()
        );
    }

    #[test]
    fn test_parse_proposal_metadata_falls_back_to_body_dependencies() {
        let proposal = r#"---
change_type: implementation
priority: medium
references:
  - tests/test_demo.py
---

# Change: Example

## Dependencies
- [body-change](../body-change/proposal.md)
- another-change: note
"#;

        let metadata = parse_proposal_metadata(proposal, Path::new("proposal.md"));

        assert_eq!(metadata.priority, Some(ProposalPriority::Medium));
        assert_eq!(
            metadata.dependencies,
            vec!["body-change".to_string(), "another-change".to_string()]
        );
        assert_eq!(metadata.references, vec!["tests/test_demo.py".to_string()]);
    }

    #[test]
    fn test_parse_proposal_metadata_warns_on_unknown_frontmatter_keys() {
        let proposal = r#"---
change_type: spec-only
priority: low
owner: tumf
references: []
---

# Change: Example
"#;

        let metadata = parse_proposal_metadata(proposal, Path::new("proposal.md"));

        assert_eq!(metadata.priority, Some(ProposalPriority::Low));
        assert_eq!(metadata.warnings.len(), 1);
        assert!(metadata.warnings[0].contains("owner"));
    }

    #[test]
    fn test_list_changes_native_suppresses_repetitive_logs() {
        let _cwd_lock = crate::test_support::cwd_lock().lock().unwrap();
        let log_lock = LOG_TEST_MUTEX.get_or_init(|| Mutex::new(()));
        let _guard = log_lock.lock().expect("log mutex poisoned");

        let temp_dir = TempDir::new().unwrap();
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("sample-change");
        fs::create_dir_all(&change_dir).unwrap();
        // Create proposal.md (required for change to be included)
        fs::File::create(change_dir.join("proposal.md")).unwrap();
        let mut tasks_file = fs::File::create(change_dir.join("tasks.md")).unwrap();
        writeln!(tasks_file, "- [ ] Task 1").unwrap();

        let original_dir = env::current_dir().unwrap();
        env::set_current_dir(temp_dir.path()).unwrap();

        log_deduplicator::configure_logging(LoggingConfig {
            suppress_repetitive_debug: true,
            summary_interval_secs: 0,
        });

        let _ = list_changes_native();
        let _ = list_changes_native();

        let should_log_progress = log_deduplicator::should_log_task_progress("sample-change", 0, 1);
        let should_log_count = log_deduplicator::should_log_change_count(1);

        env::set_current_dir(original_dir).unwrap();

        assert!(!should_log_progress);
        assert!(!should_log_count);
    }
}