nika 0.35.4

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
Documentation
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
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
// The #[error] attribute from thiserror uses struct fields via string interpolation,
// but Rust's unused_assignments lint doesn't recognize this.
#![allow(unused_assignments)]

//! Nika Error Types with Error Codes
//!
//! Error code ranges:
//! - NIKA-000-009: Workflow errors
//! - NIKA-010-019: Schema/validation errors
//! - NIKA-020-029: DAG errors
//! - NIKA-030-039: Provider errors
//! - NIKA-040-049: Template/binding errors
//! - NIKA-050-059: Path/task/security errors
//! - NIKA-060-069: Output errors
//! - NIKA-070-079: With block validation errors
//! - NIKA-080-089: DAG validation errors
//! - NIKA-090-099: JSONPath/IO errors (+NIKA-096 Execution catch-all)
//! - NIKA-100-109: MCP errors
//! - NIKA-110-119: Agent errors
//! - NIKA-120-129: Resilience errors
//! - NIKA-130-139: TUI errors
//! - NIKA-140-151: AST analysis errors (Phase 2 analyzer)
//! - NIKA-160-164: Parse errors (Phase 1 parser — ParseErrorKind)
//! - NIKA-165-166: Policy/Boot errors (renumbered to avoid 160/161 collision)
//!
//! Extended ranges:
//! - NIKA-200-209: File Tool errors (ToolErrorCode in src/tools/mod.rs)
//! - NIKA-210-219: Builtin tool errors
//! - NIKA-220-229: Reserved (DAG Panel - not implemented)
//! - NIKA-230-239: Reserved (Session persistence - not implemented)
//! - NIKA-240-249: Reserved (Animation/Export - not implemented)
//! - NIKA-251-259: Media pipeline errors (MIME, CAS, base64, budget — src/media/error.rs)
//! - NIKA-260-269: Package URI errors
//! - NIKA-270-279: Skill errors
//! - NIKA-280-285: Artifact/media errors (path validation, write, size, integrity, cleanup, lock)
//! - NIKA-290-297: Media tool errors (tool, format, deps, timeout, args, pipeline, security)
//! - NIKA-300-309: Structured Output errors (JSON Schema validation, extraction, repair)

use crate::mcp::types::McpErrorCode;
use crate::serde_yaml;
use miette::Diagnostic;
use thiserror::Error;

pub type Result<T> = std::result::Result<T, NikaError>;

/// Format schema validation errors for display
fn format_schema_errors(errors: &[crate::ast::schema_validator::SchemaError]) -> String {
    if errors.is_empty() {
        return "no errors".to_string();
    }
    if errors.len() == 1 {
        return errors[0].message.clone();
    }
    format!(
        "{} errors: {}",
        errors.len(),
        errors
            .iter()
            .map(|e| format!("[{}] {}", e.path, e.message))
            .collect::<Vec<_>>()
            .join("; ")
    )
}

/// Format structured output validation errors for display
fn format_validation_errors_short(errors: &[String]) -> String {
    if errors.is_empty() {
        return "no errors".to_string();
    }
    if errors.len() == 1 {
        return errors[0].clone();
    }
    format!("{} errors: {}", errors.len(), errors.join("; "))
}

/// Trait for errors that provide fix suggestions
pub trait FixSuggestion {
    fn fix_suggestion(&self) -> Option<&str>;
}

/// All error variants are part of the public API.
///
/// Implements both `thiserror::Error` for std error compatibility
/// and `miette::Diagnostic` for fancy terminal error display.
#[derive(Error, Debug, Diagnostic)]
#[diagnostic(url(docsrs))]
pub enum NikaError {
    // ═══════════════════════════════════════════
    // WORKFLOW ERRORS (000-009)
    // ═══════════════════════════════════════════
    #[error("[NIKA-001] Failed to parse workflow: {details}")]
    #[diagnostic(
        code(nika::parse_error),
        help("Check YAML syntax: indentation and quoting")
    )]
    ParseError { details: String },

    #[error("[NIKA-002] Invalid schema version: {version}")]
    #[diagnostic(
        code(nika::invalid_schema_version),
        help("Use 'nika/workflow@0.12' as the schema version")
    )]
    InvalidSchemaVersion { version: String },

    #[error("[NIKA-003] Workflow file not found: {path}")]
    #[diagnostic(code(nika::workflow_not_found), help("Check the file path exists"))]
    WorkflowNotFound { path: String },

    #[error("[NIKA-004] Workflow validation failed: {reason}")]
    #[diagnostic(
        code(nika::validation_error),
        help("Check workflow structure matches schema")
    )]
    ValidationError { reason: String },

    #[error("[NIKA-005] Schema validation failed: {}", format_schema_errors(.errors))]
    #[diagnostic(
        code(nika::schema_validation_failed),
        help("Check YAML against schemas/nika-workflow.schema.json")
    )]
    SchemaValidationFailed {
        errors: Vec<crate::ast::schema_validator::SchemaError>,
    },

    #[error("[NIKA-006] Could not determine home directory")]
    #[diagnostic(
        code(nika::home_directory_not_found),
        help("Set the NIKA_HOME environment variable to specify the Nika home directory")
    )]
    HomeDirectoryNotFound,

    // ═══════════════════════════════════════════
    // SCHEMA ERRORS (010-019)
    // ═══════════════════════════════════════════
    #[error("[NIKA-013] Schema file not found for task '{task_id}': {path}")]
    #[diagnostic(
        code(nika::schema_file_not_found),
        help("Ensure the schema file exists relative to the workflow file")
    )]
    SchemaFileNotFound { task_id: String, path: String },

    #[error("[NIKA-014] Invalid JSON in schema file for task '{task_id}': {path}: {reason}")]
    #[diagnostic(
        code(nika::schema_file_invalid),
        help("Ensure the schema file contains valid JSON")
    )]
    SchemaFileInvalid {
        task_id: String,
        path: String,
        reason: String,
    },

    // ═══════════════════════════════════════════
    // DAG ERRORS (020-029)
    // ═══════════════════════════════════════════
    #[error("[NIKA-020] Cycle detected in DAG: {cycle}")]
    CycleDetected { cycle: String },

    #[error("[NIKA-021] Missing dependency: task '{task_id}' depends on unknown '{dep_id}'")]
    MissingDependency { task_id: String, dep_id: String },

    #[error("[NIKA-022] Duplicate task ID: '{task_id}' appears multiple times in workflow")]
    #[diagnostic(
        code(nika::duplicate_task_id),
        help("Each task must have a unique ID. Rename one of the duplicate tasks.")
    )]
    DuplicateTaskId { task_id: String },

    #[error("[NIKA-026] Dependency chain failed: {count} task(s) blocked by failed dependencies")]
    #[diagnostic(
        code(nika::dependency_chain_failed),
        help("One or more upstream tasks failed, blocking downstream tasks. Fix the failing tasks first.")
    )]
    DependencyChainFailed {
        /// Number of tasks blocked
        count: usize,
        /// List of blocked task IDs
        blocked_tasks: Vec<String>,
        /// The root failure that caused the chain
        root_failure: Option<String>,
    },

    #[error("[NIKA-027] Task '{task_id}' was cancelled due to fail_fast")]
    #[diagnostic(
        code(nika::task_cancelled),
        help("Another task in the for_each batch failed with fail_fast=true, causing remaining tasks to be cancelled.")
    )]
    TaskCancelled { task_id: String, reason: String },

    // ═══════════════════════════════════════════
    // PROVIDER ERRORS (030-039)
    // ═══════════════════════════════════════════
    #[error("[NIKA-030] Provider '{provider}' not configured")]
    ProviderNotConfigured { provider: String },

    #[error("[NIKA-031] Provider API error: {message}")]
    ProviderApiError { message: String },

    #[error("[NIKA-032] Missing API key for provider '{provider}'")]
    MissingApiKey { provider: String },

    #[error("[NIKA-033] Invalid configuration: {message}")]
    InvalidConfig { message: String },

    // ═══════════════════════════════════════════
    // TEMPLATE/BINDING ERRORS (040-049)
    // ═══════════════════════════════════════════
    /// Simple execution error
    /// Note: Widely used - consider structured variant for new code
    #[error("[NIKA-096] Execution error: {0}")]
    Execution(String),

    #[error("[NIKA-041] Template error in '{template}': {reason}")]
    TemplateError { template: String, reason: String },

    #[error("[NIKA-042] Binding '{alias}' not found")]
    BindingNotFound { alias: String },

    #[error("[NIKA-043] Binding type mismatch at '{path}': expected {expected}, got {actual}")]
    BindingTypeMismatch {
        expected: String,
        actual: String,
        path: String,
    },

    // ═══════════════════════════════════════════
    // PATH/TASK ERRORS (050-059)
    // ═══════════════════════════════════════════
    #[error("[NIKA-050] Invalid path syntax: {path}")]
    InvalidPath { path: String },

    #[error("[NIKA-052] Path '{path}' not found (task may not have JSON output)")]
    PathNotFound { path: String },

    #[error("[NIKA-053] Command blocked: '{command}' - {reason}")]
    #[diagnostic(
        code(nika::blocked_command),
        help("Use shell: true to opt-in to shell execution, or use a different command")
    )]
    BlockedCommand { command: String, reason: String },

    #[error("[NIKA-055] Invalid task ID '{id}': {reason}")]
    InvalidTaskId { id: String, reason: String },

    #[error("[NIKA-056] Invalid default value '{raw}': {reason}")]
    InvalidDefault { raw: String, reason: String },

    // ═══════════════════════════════════════════
    // OUTPUT ERRORS (060-069)
    // ═══════════════════════════════════════════
    #[error("[NIKA-060] Invalid JSON output: {details}")]
    InvalidJson { details: String },

    #[error("[NIKA-061] Schema validation failed: {details}")]
    SchemaFailed { details: String },

    #[error("[NIKA-062] Serialization error: {details}")]
    SerializationError { details: String },

    // ═══════════════════════════════════════════
    // BINDING VALIDATION (070-079)
    // ═══════════════════════════════════════════
    #[error("[NIKA-071] Unknown alias '{{{{with.{alias}}}}}' - not declared in with: block")]
    UnknownAlias { alias: String, task_id: String },

    #[error("[NIKA-072] Null value at path '{path}' (strict mode)")]
    NullValue { path: String, alias: String },

    #[error("[NIKA-073] Cannot traverse '{segment}' on {value_type} (expected object/array)")]
    InvalidTraversal {
        segment: String,
        value_type: String,
        full_path: String,
    },

    #[error("[NIKA-074] Template parse error at position {position}: {details}")]
    TemplateParse { position: usize, details: String },

    // ═══════════════════════════════════════════
    // DAG VALIDATION (080-089)
    // ═══════════════════════════════════════════
    #[error("[NIKA-080] with.{alias} references unknown task '{from_task}'")]
    WithUnknownTask {
        alias: String,
        from_task: String,
        task_id: String,
    },

    #[error("[NIKA-081] with.{alias}='{from_task}' is not upstream of task '{task_id}'")]
    WithNotUpstream {
        alias: String,
        from_task: String,
        task_id: String,
    },

    #[error("[NIKA-082] with.{alias}='{from_task}' creates circular dependency with '{task_id}'")]
    WithCircularDep {
        alias: String,
        from_task: String,
        task_id: String,
    },

    // ═══════════════════════════════════════════
    // JSONPATH / IO ERRORS (090-099)
    // ═══════════════════════════════════════════
    #[error("[NIKA-090] JSONPath '{path}' is not supported in v0.1 (use $.a.b or $.a[0].b)")]
    JsonPathUnsupported { path: String },

    #[error("[NIKA-093] IO error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("[NIKA-094] JSON error: {0}")]
    JsonError(#[from] serde_json::Error),

    #[error("[NIKA-095] YAML parse error: {0}")]
    #[diagnostic(
        code(nika::yaml_parse),
        help(
            "Check YAML syntax: indentation must be consistent, strings with special chars need quoting"
        )
    )]
    YamlParse(#[from] serde_yaml::Error),

    // ═══════════════════════════════════════════
    // MCP ERRORS (100-109)
    // ═══════════════════════════════════════════
    #[error("[NIKA-100] MCP server '{name}' not connected")]
    #[diagnostic(
        code(nika::mcp_not_connected),
        help("Check MCP server is running and configured correctly")
    )]
    McpNotConnected { name: String },

    #[error("[NIKA-101] MCP server '{name}' failed to start: {reason}")]
    #[diagnostic(
        code(nika::mcp_start_error),
        help("Check MCP command and args in workflow config")
    )]
    McpStartError { name: String, reason: String },

    #[error("[NIKA-102] MCP tool '{tool}' call failed{}: {reason}", error_code.map(|c| format!(" ({})", c)).unwrap_or_default())]
    #[diagnostic(
        code(nika::mcp_tool_error),
        help("Check tool parameters and MCP server logs")
    )]
    McpToolError {
        tool: String,
        reason: String,
        /// JSON-RPC error code from MCP server
        error_code: Option<McpErrorCode>,
    },

    #[error("[NIKA-103] MCP resource '{uri}' not found")]
    McpResourceNotFound { uri: String },

    #[error("[NIKA-104] MCP protocol error: {reason}")]
    McpProtocolError { reason: String },

    #[error("[NIKA-105] MCP server '{name}' not configured in workflow")]
    McpNotConfigured { name: String },

    #[error("[NIKA-106] MCP tool '{tool}' returned invalid response: {reason}")]
    McpInvalidResponse { tool: String, reason: String },

    #[error("[NIKA-107] MCP parameter validation failed for '{tool}': {details}")]
    McpValidationFailed {
        tool: String,
        details: String,
        /// Required fields that are missing
        missing: Vec<String>,
        /// Suggested corrections
        suggestions: Vec<String>,
    },

    #[error("[NIKA-108] MCP schema error for '{tool}': {reason}")]
    McpSchemaError { tool: String, reason: String },

    #[error(
        "[NIKA-109] MCP operation timed out for '{name}' ({operation}): exceeded {timeout_secs}s"
    )]
    McpTimeout {
        name: String,
        operation: String,
        timeout_secs: u64,
    },

    // ═══════════════════════════════════════════
    // AGENT ERRORS (110-119)
    // ═══════════════════════════════════════════
    #[error("[NIKA-113] Agent validation failed: {reason}")]
    AgentValidationError { reason: String },

    #[error("[NIKA-115] Agent execution failed for task '{task_id}': {reason}")]
    AgentExecutionError { task_id: String, reason: String },

    #[error("[NIKA-116] Extended thinking capture failed: {reason}")]
    ThinkingCaptureFailed { reason: String },

    #[error("[NIKA-112] Guardrail violation in task '{task_id}': {}", violations.join(", "))]
    GuardrailViolation {
        task_id: String,
        violations: Vec<String>,
    },

    // ═══════════════════════════════════════════
    // RESILIENCE ERRORS (120-129)
    // ═══════════════════════════════════════════
    #[error("[NIKA-121] Operation '{operation}' timed out after {duration_ms}ms")]
    Timeout { operation: String, duration_ms: u64 },

    #[error("[NIKA-125] MCP tool call '{tool}' failed: {reason}")]
    McpToolCallFailed { tool: String, reason: String },

    // ═══════════════════════════════════════════
    // TUI ERRORS (130-139)
    // ═══════════════════════════════════════════
    #[error("[NIKA-130] TUI error: {reason}")]
    TuiError { reason: String },

    // ═══════════════════════════════════════════
    // CONFIG ERRORS (135-139) - Range reassigned to avoid NIKA-140 collision
    // Note: NIKA-140-149 is reserved for AST analyzer errors (see ast/analyzer/errors.rs)
    // ═══════════════════════════════════════════
    #[error("[NIKA-135] Config error: {reason}")]
    ConfigError { reason: String },

    // ═══════════════════════════════════════════
    // STARTUP ERRORS (150-159)
    // ═══════════════════════════════════════════
    #[error("[NIKA-150] Startup verification failed in '{phase}': {reason}")]
    StartupError { phase: String, reason: String },

    // ═══════════════════════════════════════════
    // POLICY ERRORS (165-166)
    // Renumbered from 160-161 to avoid collision with ParseErrorKind::Syntax (NIKA-160)
    // and ParseErrorKind::MissingField (NIKA-161) in src/ast/raw/parser.rs
    // ═══════════════════════════════════════════
    #[error("[NIKA-165] Policy violation: {reason}")]
    #[diagnostic(
        code(nika::policy_violation),
        help("Check .nika/config.toml [policy] section or use --allow flag")
    )]
    PolicyViolation { reason: String },

    #[error("[NIKA-166] Boot sequence failed in phase '{phase}': {reason}")]
    #[diagnostic(
        code(nika::boot_failed),
        help("Run 'nika doctor' to diagnose boot issues")
    )]
    BootFailed { phase: String, reason: String },

    // ═══════════════════════════════════════════
    // RUNTIME ERRORS (170-179)
    // ═══════════════════════════════════════════
    #[error(
        "[NIKA-171] Decompose expansion timed out for task '{task_id}': exceeded {timeout_secs}s"
    )]
    #[diagnostic(
        code(nika::decompose_timeout),
        help("The decompose operation took too long. Consider reducing max_depth or max_items, or check MCP server performance.")
    )]
    DecomposeTimeout { task_id: String, timeout_secs: u64 },

    // ═══════════════════════════════════════════
    // TOOL ERRORS (200-209)
    // ═══════════════════════════════════════════
    #[error("[{code}] {message}")]
    ToolError { code: String, message: String },

    // ═══════════════════════════════════════════
    // BUILTIN TOOL ERRORS (210-219)
    // ═══════════════════════════════════════════
    #[error("[NIKA-210] Builtin tool '{tool}' error: {reason}")]
    #[diagnostic(
        code(nika::builtin_tool_error),
        help("Check builtin tool parameters and configuration")
    )]
    BuiltinToolError { tool: String, reason: String },

    #[error("[NIKA-212] Builtin tool '{tool}' invalid parameters: {reason}")]
    #[diagnostic(
        code(nika::builtin_invalid_params),
        help("Check the parameter format matches the expected JSON schema")
    )]
    BuiltinInvalidParams { tool: String, reason: String },

    #[error("[NIKA-213] Assertion failed in nika:assert: {message}")]
    #[diagnostic(code(nika::assertion_failed), help("The condition evaluated to false"))]
    AssertionFailed { message: String, condition: String },

    // ═══════════════════════════════════════════
    // CONTEXT ERROR (250)
    // ═══════════════════════════════════════════
    #[error("[NIKA-250] Failed to load context file '{alias}' from '{path}': {reason}")]
    #[diagnostic(
        code(nika::context_load_error),
        help("Check the file path exists and is readable")
    )]
    ContextLoadError {
        alias: String,
        path: String,
        reason: String,
    },

    // ═══════════════════════════════════════════
    // MEDIA ERRORS (251-259)
    // ═══════════════════════════════════════════
    /// Media pipeline error (NIKA-251..259)
    /// Note: miette diagnostic codes are forwarded via MediaError's own Diagnostic derive.
    #[error(transparent)]
    MediaError(#[from] crate::media::error::MediaError),

    // ═══════════════════════════════════════════
    // PKG URI ERRORS (260-269)
    // ═══════════════════════════════════════════
    #[error("[NIKA-260] Invalid pkg: URI '{uri}': {reason}")]
    #[diagnostic(
        code(nika::invalid_pkg_uri),
        help("Format: pkg:@scope/name@version/path or pkg:@scope/name/path")
    )]
    InvalidPkgUri { uri: String, reason: String },

    #[error("[NIKA-261] Package '{name}@{version}' not found in registry")]
    #[diagnostic(
        code(nika::package_not_found),
        help("Install the package with: nika pkg install {name}@{version}")
    )]
    PackageNotFound { name: String, version: String },

    // ═══════════════════════════════════════════
    // SKILL ERRORS (270-279)
    // ═══════════════════════════════════════════
    #[error("[NIKA-270] Failed to load skill '{skill}': {reason}")]
    #[diagnostic(
        code(nika::skill_load_error),
        help("Ensure skill file exists and is readable. Check pkg: URI format if using packages.")
    )]
    SkillLoadError { skill: String, reason: String },

    // ═══════════════════════════════════════════
    // ARTIFACT ERRORS (280-289)
    // ═══════════════════════════════════════════
    #[error("[NIKA-280] Artifact path error for '{path}': {reason}")]
    #[diagnostic(
        code(nika::artifact_path_error),
        help("Check the artifact path is within the workflow directory and does not contain path traversal patterns")
    )]
    ArtifactPathError { path: String, reason: String },

    #[error("[NIKA-281] Artifact write failed for '{path}': {reason}")]
    #[diagnostic(
        code(nika::artifact_write_error),
        help("Check file permissions and disk space")
    )]
    ArtifactWriteError { path: String, reason: String },

    #[error("[NIKA-282] Artifact size exceeds limit: {size} bytes > {max_size} bytes")]
    #[diagnostic(
        code(nika::artifact_size_exceeded),
        help("Increase artifacts.max_size in workflow or reduce output size")
    )]
    ArtifactSizeExceeded {
        path: String,
        size: u64,
        max_size: u64,
    },

    #[error("[NIKA-283] Media integrity warning: {reason}")]
    #[diagnostic(
        code(nika::media_integrity_warning),
        help("CAS file may have been deleted or corrupted during workflow execution")
    )]
    MediaIntegrityWarning { reason: String },

    #[error("[NIKA-284] Media cleanup failed: {reason}")]
    #[diagnostic(
        code(nika::media_cleanup_error),
        help("Check file permissions and disk space in .nika/media/store/")
    )]
    MediaCleanupError { reason: String },

    #[error("[NIKA-285] Media store is locked: {reason}")]
    #[diagnostic(
        code(nika::media_store_locked),
        help("A workflow is currently running. Use --force to override or wait for completion")
    )]
    MediaStoreLocked { reason: String },

    // ═══════════════════════════════════════════
    // STRUCTURED OUTPUT ERRORS (300-309)
    // ═══════════════════════════════════════════
    #[error(
        "[NIKA-300] Structured output extraction failed for task '{task_id}' at {layer}: {reason}"
    )]
    #[diagnostic(
        code(nika::structured_output_extraction_failed),
        help("Check the LLM response format matches the expected JSON Schema")
    )]
    StructuredOutputExtractionFailed {
        task_id: String,
        layer: String,
        reason: String,
    },

    #[error("[NIKA-301] Structured output validation failed for task '{task_id}' at {layer} (attempt {attempt}): {}", format_validation_errors_short(.errors))]
    #[diagnostic(
        code(nika::structured_output_validation_failed),
        help("Fix JSON output to match the declared schema")
    )]
    StructuredOutputValidationFailed {
        task_id: String,
        layer: String,
        attempt: u32,
        errors: Vec<String>,
    },

    #[error("[NIKA-302] Structured output repair failed for task '{task_id}': original errors: {original_errors:?}, repair errors: {repair_errors:?}")]
    #[diagnostic(
        code(nika::structured_output_repair_failed),
        help("The LLM could not repair the output. Consider simplifying the schema or providing more context.")
    )]
    StructuredOutputRepairFailed {
        task_id: String,
        original_errors: Vec<String>,
        repair_errors: Vec<String>,
    },

    #[error("[NIKA-303] Structured output failed after all {attempts} attempts for task '{task_id}': {}", format_validation_errors_short(.final_errors))]
    #[diagnostic(
        code(nika::structured_output_all_layers_failed),
        help("All validation layers failed. Check your schema is valid and the prompt provides enough context for the LLM to generate conforming output.")
    )]
    StructuredOutputAllLayersFailed {
        task_id: String,
        attempts: u32,
        final_errors: Vec<String>,
    },
}

impl NikaError {
    /// Get the error code (e.g., "NIKA-001")
    pub fn code(&self) -> &'static str {
        match self {
            // Workflow errors
            Self::ParseError { .. } => "NIKA-001",
            Self::InvalidSchemaVersion { .. } => "NIKA-002",
            Self::WorkflowNotFound { .. } => "NIKA-003",
            Self::ValidationError { .. } => "NIKA-004",
            Self::SchemaValidationFailed { .. } => "NIKA-005",
            Self::HomeDirectoryNotFound => "NIKA-006",
            // Schema errors
            Self::SchemaFileNotFound { .. } => "NIKA-013",
            Self::SchemaFileInvalid { .. } => "NIKA-014",
            // DAG errors
            Self::CycleDetected { .. } => "NIKA-020",
            Self::MissingDependency { .. } => "NIKA-021",
            Self::DuplicateTaskId { .. } => "NIKA-022",
            Self::DependencyChainFailed { .. } => "NIKA-026",
            Self::TaskCancelled { .. } => "NIKA-027",
            // Provider errors
            Self::ProviderNotConfigured { .. } => "NIKA-030",
            Self::ProviderApiError { .. } => "NIKA-031",
            Self::MissingApiKey { .. } => "NIKA-032",
            Self::InvalidConfig { .. } => "NIKA-033",
            // Binding/Template errors
            Self::Execution(_) => "NIKA-096",
            Self::TemplateError { .. } => "NIKA-041",
            Self::BindingNotFound { .. } => "NIKA-042",
            Self::BindingTypeMismatch { .. } => "NIKA-043",
            // Path/Task errors
            Self::InvalidPath { .. } => "NIKA-050",
            Self::PathNotFound { .. } => "NIKA-052",
            Self::BlockedCommand { .. } => "NIKA-053",
            Self::InvalidTaskId { .. } => "NIKA-055",
            Self::InvalidDefault { .. } => "NIKA-056",
            // Output errors
            Self::InvalidJson { .. } => "NIKA-060",
            Self::SchemaFailed { .. } => "NIKA-061",
            Self::SerializationError { .. } => "NIKA-062",
            // With block errors
            Self::UnknownAlias { .. } => "NIKA-071",
            Self::NullValue { .. } => "NIKA-072",
            Self::InvalidTraversal { .. } => "NIKA-073",
            Self::TemplateParse { .. } => "NIKA-074",
            // DAG validation errors
            Self::WithUnknownTask { .. } => "NIKA-080",
            Self::WithNotUpstream { .. } => "NIKA-081",
            Self::WithCircularDep { .. } => "NIKA-082",
            // JSONPath/IO errors
            Self::JsonPathUnsupported { .. } => "NIKA-090",
            Self::IoError(_) => "NIKA-093",
            Self::JsonError(_) => "NIKA-094",
            Self::YamlParse(_) => "NIKA-095",
            // MCP errors
            Self::McpNotConnected { .. } => "NIKA-100",
            Self::McpStartError { .. } => "NIKA-101",
            Self::McpToolError { .. } => "NIKA-102",
            Self::McpResourceNotFound { .. } => "NIKA-103",
            Self::McpProtocolError { .. } => "NIKA-104",
            Self::McpNotConfigured { .. } => "NIKA-105",
            Self::McpInvalidResponse { .. } => "NIKA-106",
            Self::McpValidationFailed { .. } => "NIKA-107",
            Self::McpSchemaError { .. } => "NIKA-108",
            Self::McpTimeout { .. } => "NIKA-109",
            // Agent errors
            Self::AgentValidationError { .. } => "NIKA-113",
            Self::AgentExecutionError { .. } => "NIKA-115",
            Self::ThinkingCaptureFailed { .. } => "NIKA-116",
            Self::GuardrailViolation { .. } => "NIKA-112",
            // Resilience errors
            Self::Timeout { .. } => "NIKA-121",
            Self::McpToolCallFailed { .. } => "NIKA-125",
            // TUI errors
            Self::TuiError { .. } => "NIKA-130",
            // Config errors
            Self::ConfigError { .. } => "NIKA-135",
            // Startup errors
            Self::StartupError { .. } => "NIKA-150",
            // Tool errors (code is dynamic)
            Self::ToolError { .. } => "NIKA-2XX",
            // Builtin tool errors
            Self::BuiltinToolError { .. } => "NIKA-210",
            Self::BuiltinInvalidParams { .. } => "NIKA-212",
            Self::AssertionFailed { .. } => "NIKA-213",
            // Context errors
            Self::ContextLoadError { .. } => "NIKA-250",
            // Media errors
            Self::MediaError(e) => e.code(),
            // Pkg URI errors
            Self::InvalidPkgUri { .. } => "NIKA-260",
            // Package errors
            Self::PackageNotFound { .. } => "NIKA-261",

            // Skill errors
            Self::SkillLoadError { .. } => "NIKA-270",
            // Artifact errors
            Self::ArtifactPathError { .. } => "NIKA-280",
            Self::ArtifactWriteError { .. } => "NIKA-281",
            Self::ArtifactSizeExceeded { .. } => "NIKA-282",
            Self::MediaIntegrityWarning { .. } => "NIKA-283",
            Self::MediaCleanupError { .. } => "NIKA-284",
            Self::MediaStoreLocked { .. } => "NIKA-285",
            // Structured Output errors
            Self::StructuredOutputExtractionFailed { .. } => "NIKA-300",
            Self::StructuredOutputValidationFailed { .. } => "NIKA-301",
            Self::StructuredOutputRepairFailed { .. } => "NIKA-302",
            Self::StructuredOutputAllLayersFailed { .. } => "NIKA-303",
            // Policy errors (renumbered from 160/161 to avoid ParseErrorKind collision)
            Self::PolicyViolation { .. } => "NIKA-165",
            Self::BootFailed { .. } => "NIKA-166",
            // Runtime errors
            Self::DecomposeTimeout { .. } => "NIKA-171",
        }
    }

    /// Check if error is recoverable (can be retried)
    pub fn is_recoverable(&self) -> bool {
        match self {
            Self::McpNotConnected { .. }
            | Self::ProviderApiError { .. }
            | Self::McpToolError { .. }
            | Self::Timeout { .. }
            | Self::McpTimeout { .. }
            | Self::McpToolCallFailed { .. }
            // Structured output errors that can be retried
            | Self::StructuredOutputExtractionFailed { .. }
            | Self::StructuredOutputValidationFailed { .. }
            | Self::StructuredOutputRepairFailed { .. } => true,
            // Delegate to MediaError's own is_recoverable (only I/O errors)
            Self::MediaError(e) => e.is_recoverable(),
            _ => false,
        }
    }
}

impl FixSuggestion for NikaError {
    fn fix_suggestion(&self) -> Option<&str> {
        match self {
            NikaError::ParseError { .. } => Some("Check YAML syntax: indentation and quoting"),
            NikaError::InvalidSchemaVersion { .. } => {
                Some("Use 'nika/workflow@0.12' as the schema version")
            }
            NikaError::WorkflowNotFound { .. } => Some("Check the file path exists"),
            NikaError::ValidationError { .. } => Some("Check workflow structure matches schema"),
            NikaError::SchemaValidationFailed { .. } => {
                Some("Check YAML against schemas/nika-workflow.schema.json")
            }
            NikaError::HomeDirectoryNotFound => {
                Some("Set NIKA_HOME environment variable to specify Nika home directory")
            }
            NikaError::YamlParse(_) => Some("Check YAML syntax: indentation and quoting"),
            NikaError::SchemaFileNotFound { .. } => {
                Some("Check the schema file path is correct relative to the workflow file")
            }
            NikaError::SchemaFileInvalid { .. } => {
                Some("Ensure the schema file contains valid JSON (not YAML)")
            }
            NikaError::CycleDetected { .. } => {
                Some("Remove circular dependencies from your workflow")
            }
            NikaError::MissingDependency { .. } => {
                Some("Add the missing task or fix the dependency reference")
            }
            NikaError::ProviderNotConfigured { .. } => {
                Some("Add provider configuration to your workflow")
            }
            NikaError::ProviderApiError { .. } => Some("Check API key and provider availability"),
            NikaError::MissingApiKey { .. } => {
                Some("Set the API key env var (ANTHROPIC_API_KEY or OPENAI_API_KEY)")
            }
            NikaError::InvalidConfig { .. } => Some("Check configuration value is valid"),
            NikaError::Execution(_) => Some("Check command/URL is valid"),
            NikaError::TemplateError { .. } => Some("Use {{with.alias}} format with with: block"),
            NikaError::InvalidPath { .. } => Some("Use format: task_id.field.subfield"),
            NikaError::PathNotFound { .. } => Some("Add '?? default' or ensure task outputs JSON"),
            NikaError::BlockedCommand { .. } => {
                Some("Use shell: true to opt-in to shell execution, or use a different command")
            }
            NikaError::InvalidTaskId { .. } => {
                Some("Task IDs must be snake_case: lowercase letters, digits, underscores")
            }
            NikaError::InvalidDefault { .. } => {
                Some("Default values must be valid JSON. Strings must be quoted.")
            }
            NikaError::InvalidJson { .. } => Some("Ensure output is valid JSON"),
            NikaError::SchemaFailed { .. } => Some("Fix output to match declared schema"),
            NikaError::SerializationError { .. } => Some("Check data structure is serializable"),
            NikaError::UnknownAlias { .. } => {
                Some("Declare the alias in with: block before referencing")
            }
            NikaError::NullValue { .. } => {
                Some("Provide a default value or ensure non-null output")
            }
            NikaError::InvalidTraversal { .. } => {
                Some("Check the path - accessing field on non-object")
            }
            NikaError::TemplateParse { .. } => Some("Check template syntax: {{with.alias}}"),
            NikaError::WithUnknownTask { .. } => Some("Verify the task_id exists in your workflow"),
            NikaError::WithNotUpstream { .. } => {
                Some("Add depends_on: [source_task] to this task")
            }
            NikaError::WithCircularDep { .. } => Some("Remove the circular dependency"),
            NikaError::JsonPathUnsupported { .. } => Some("Use simple paths like $.field.subfield"),
            NikaError::IoError(_) => Some("Check file path and permissions"),
            NikaError::JsonError(_) => Some("Check JSON syntax"),
            // MCP errors
            NikaError::McpNotConnected { .. } => {
                Some("Check MCP server is running and configured correctly")
            }
            NikaError::McpStartError { .. } => {
                Some("Check MCP command and args in workflow config")
            }
            NikaError::McpToolError { .. } => Some("Check tool parameters and MCP server logs"),
            NikaError::McpResourceNotFound { .. } => Some("Verify the resource URI exists"),
            NikaError::McpProtocolError { .. } => Some("Check MCP server compatibility"),
            NikaError::McpNotConfigured { .. } => {
                Some("Add MCP server config to workflow 'mcp:' section")
            }
            NikaError::McpInvalidResponse { .. } => {
                Some("Check MCP server is returning valid JSON responses")
            }
            NikaError::McpValidationFailed {
                missing,
                suggestions,
                ..
            } => {
                if !missing.is_empty() {
                    Some("Add the required fields to your params")
                } else if !suggestions.is_empty() {
                    Some("Check spelling of field names")
                } else {
                    Some("Review the tool's parameter schema")
                }
            }
            NikaError::McpSchemaError { .. } => Some("Check MCP server's tool schema definitions"),
            // Binding errors (decompose)
            NikaError::BindingNotFound { .. } => {
                Some("Verify the binding alias exists in with: block or task outputs")
            }
            NikaError::BindingTypeMismatch { .. } => {
                Some("Check binding value type matches expected type")
            }
            // Agent errors
            NikaError::AgentValidationError { .. } => {
                Some("Check agent prompt is not empty and max_turns is valid (1-100)")
            }
            NikaError::AgentExecutionError { .. } => {
                Some("Check LLM provider API key and network connectivity")
            }
            NikaError::ThinkingCaptureFailed { .. } => {
                Some("Check Claude API response and streaming connection")
            }
            NikaError::GuardrailViolation { .. } => {
                Some("One or more guardrails failed. Check guardrail config or adjust on_failure action")
            }
            // Resilience errors
            NikaError::Timeout { .. } => Some("Increase timeout or check for slow operations"),
            NikaError::McpTimeout { .. } => {
                Some("MCP server is slow or unresponsive. Check network and server health.")
            }
            NikaError::McpToolCallFailed { .. } => {
                Some("Check MCP tool parameters and server logs")
            }
            // TUI errors
            NikaError::TuiError { .. } => Some("Check terminal compatibility and size"),
            // Config errors
            NikaError::ConfigError { .. } => {
                Some("Check ~/.config/nika/config.toml for syntax errors")
            }
            // Startup errors
            NikaError::StartupError { .. } => Some(
                "Check directory permissions and run 'nika init' to create required directories",
            ),
            // Tool errors
            NikaError::ToolError { .. } => {
                Some("Check file path and permissions. Use Read before Edit.")
            }
            // Builtin tool errors
            NikaError::BuiltinToolError { .. } => {
                Some("Check builtin tool parameters and configuration")
            }
            NikaError::BuiltinInvalidParams { .. } => {
                Some("Check the parameter format matches the expected JSON schema")
            }
            NikaError::AssertionFailed { .. } => Some("The condition evaluated to false"),
            // Context errors
            NikaError::ContextLoadError { .. } => {
                Some("Check the file path exists and is readable")
            }
            // Media errors
            NikaError::MediaError(_) => {
                Some("Check media content and CAS store configuration")
            }
            // Pkg URI errors
            NikaError::InvalidPkgUri { .. } => Some(
                "Use format: pkg:@scope/name@version/path (e.g., pkg:@supernovae/skills@1.0.0/rust.md)",
            ),
            // Package errors
            NikaError::PackageNotFound { .. } => Some(
                "Check package name and version. Run 'nika pkg list' to see installed packages.",
            ),
            // Policy errors
            NikaError::PolicyViolation { .. } => Some(
                "This action was blocked by security policy. Check .nika/config.toml policy section.",
            ),
            NikaError::BootFailed { .. } => {
                Some("Boot sequence failed. Run 'nika doctor' to diagnose.")
            }
            // Skill errors
            NikaError::SkillLoadError { .. } => {
                Some("Ensure skill file exists and is readable. Check pkg: URI format if using packages.")
            }
            // Decompose timeout
            NikaError::DecomposeTimeout { .. } => {
                Some("Decompose expansion timed out. Try reducing max_items or check MCP server performance.")
            }
            // Artifact errors
            NikaError::ArtifactPathError { .. } => {
                Some("Check the artifact path is within the workflow directory and does not contain path traversal patterns")
            }
            NikaError::ArtifactWriteError { .. } => {
                Some("Check file permissions and disk space")
            }
            NikaError::ArtifactSizeExceeded { .. } => {
                Some("Increase artifacts.max_size in workflow or reduce output size")
            }
            NikaError::MediaIntegrityWarning { .. } => {
                Some("CAS file may have been deleted or corrupted during workflow execution")
            }
            NikaError::MediaCleanupError { .. } => {
                Some("Check file permissions and disk space in .nika/media/store/")
            }
            NikaError::MediaStoreLocked { .. } => {
                Some("A workflow is currently running. Use --force to override or wait for completion")
            }
            // Structured Output errors
            NikaError::StructuredOutputExtractionFailed { .. } => {
                Some("Check the LLM response format matches the expected JSON Schema")
            }
            NikaError::StructuredOutputValidationFailed { .. } => {
                Some("Fix JSON output to match the declared schema. Check required fields and types.")
            }
            NikaError::StructuredOutputRepairFailed { .. } => {
                Some("The LLM could not repair the output. Consider simplifying the schema or providing more context.")
            }
            NikaError::StructuredOutputAllLayersFailed { .. } => {
                Some("All validation layers failed. Check your schema is valid and the prompt provides enough context for the LLM to generate conforming output.")
            }
            // Task dependency/lifecycle errors
            NikaError::DependencyChainFailed { .. } => {
                Some("Dependency chain failed. Fix upstream task errors first.")
            }
            NikaError::TaskCancelled { .. } => {
                Some("Task was cancelled. Check workflow execution logs.")
            }
            // Duplicate task ID
            NikaError::DuplicateTaskId { .. } => {
                Some("Each task must have a unique ID. Rename one of the duplicate tasks.")
            }
        }
    }
}

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

    // ═══════════════════════════════════════════════════════════════════════════
    // WORKFLOW ERRORS (000-009)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_parse_error_code_and_display() {
        let err = NikaError::ParseError {
            details: "unexpected token at line 5".to_string(),
        };
        assert_eq!(err.code(), "NIKA-001");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-001]"));
        assert!(msg.contains("unexpected token"));
    }

    #[test]
    fn test_parse_error_fix_suggestion() {
        let err = NikaError::ParseError {
            details: "bad yaml".to_string(),
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("YAML syntax"));
    }

    #[test]
    fn test_invalid_schema_version_error() {
        let err = NikaError::InvalidSchemaVersion {
            version: "0.1".to_string(),
        };
        assert_eq!(err.code(), "NIKA-002");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-002]"));
        assert!(msg.contains("0.1"));
    }

    #[test]
    fn test_workflow_not_found_error() {
        let err = NikaError::WorkflowNotFound {
            path: "/path/to/missing.yaml".to_string(),
        };
        assert_eq!(err.code(), "NIKA-003");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-003]"));
        assert!(msg.contains("missing.yaml"));
    }

    #[test]
    fn test_validation_error() {
        let err = NikaError::ValidationError {
            reason: "missing required field 'tasks'".to_string(),
        };
        assert_eq!(err.code(), "NIKA-004");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-004]"));
    }

    #[test]
    fn test_schema_validation_failed_error_empty() {
        let err = NikaError::SchemaValidationFailed { errors: vec![] };
        assert_eq!(err.code(), "NIKA-005");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-005]"));
        assert!(msg.contains("no errors"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // SCHEMA ERRORS (010-019)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_schema_file_not_found_error() {
        let err = NikaError::SchemaFileNotFound {
            task_id: "extract".to_string(),
            path: "./schemas/user.json".to_string(),
        };
        assert_eq!(err.code(), "NIKA-013");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-013]"));
        assert!(msg.contains("extract"));
        assert!(msg.contains("./schemas/user.json"));
    }

    #[test]
    fn test_schema_file_invalid_error() {
        let err = NikaError::SchemaFileInvalid {
            task_id: "generate".to_string(),
            path: "./schemas/broken.json".to_string(),
            reason: "expected value at line 1".to_string(),
        };
        assert_eq!(err.code(), "NIKA-014");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-014]"));
        assert!(msg.contains("generate"));
        assert!(msg.contains("broken.json"));
        assert!(msg.contains("expected value"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // DAG ERRORS (020-029)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_cycle_detected_error() {
        let err = NikaError::CycleDetected {
            cycle: "task1 -> task2 -> task1".to_string(),
        };
        assert_eq!(err.code(), "NIKA-020");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-020]"));
        assert!(msg.contains("task1"));
    }

    #[test]
    fn test_missing_dependency_error() {
        let err = NikaError::MissingDependency {
            task_id: "step2".to_string(),
            dep_id: "step1".to_string(),
        };
        assert_eq!(err.code(), "NIKA-021");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-021]"));
        assert!(msg.contains("step2"));
        assert!(msg.contains("step1"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // PROVIDER ERRORS (030-039)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_provider_not_configured_error() {
        let err = NikaError::ProviderNotConfigured {
            provider: "openai".to_string(),
        };
        assert_eq!(err.code(), "NIKA-030");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-030]"));
    }

    #[test]
    fn test_provider_api_error() {
        let err = NikaError::ProviderApiError {
            message: "Rate limit exceeded".to_string(),
        };
        assert_eq!(err.code(), "NIKA-031");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-031]"));
    }

    #[test]
    fn test_missing_api_key_error() {
        let err = NikaError::MissingApiKey {
            provider: "anthropic".to_string(),
        };
        assert_eq!(err.code(), "NIKA-032");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-032]"));
        assert!(msg.contains("anthropic"));
    }

    #[test]
    fn test_invalid_config_error() {
        let err = NikaError::InvalidConfig {
            message: "port must be > 0".to_string(),
        };
        assert_eq!(err.code(), "NIKA-033");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-033]"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // TEMPLATE/BINDING ERRORS (040-049)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_execution_error() {
        let err = NikaError::Execution("command not found".to_string());
        assert_eq!(err.code(), "NIKA-096");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-096]"));
        assert!(msg.contains("Execution error"));
    }

    #[test]
    fn test_template_error_with_path() {
        let err = NikaError::TemplateError {
            template: "{{with.result}}".to_string(),
            reason: "alias not in with block".to_string(),
        };
        assert_eq!(err.code(), "NIKA-041");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-041]"));
        assert!(msg.contains("result"));
    }

    #[test]
    fn test_binding_not_found_error() {
        let err = NikaError::BindingNotFound {
            alias: "entity_data".to_string(),
        };
        assert_eq!(err.code(), "NIKA-042");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-042]"));
        assert!(msg.contains("entity_data"));
    }

    #[test]
    fn test_binding_type_mismatch_error() {
        let err = NikaError::BindingTypeMismatch {
            expected: "string".to_string(),
            actual: "array".to_string(),
            path: "use.field.subfield".to_string(),
        };
        assert_eq!(err.code(), "NIKA-043");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-043]"));
        assert!(msg.contains("string"));
        assert!(msg.contains("array"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // PATH/TASK ERRORS (050-059)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_invalid_path_error() {
        let err = NikaError::InvalidPath {
            path: "task1..field".to_string(),
        };
        assert_eq!(err.code(), "NIKA-050");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-050]"));
    }

    #[test]
    fn test_path_not_found_error() {
        let err = NikaError::PathNotFound {
            path: "task.deeply.nested.field".to_string(),
        };
        assert_eq!(err.code(), "NIKA-052");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-052]"));
    }

    #[test]
    fn test_invalid_task_id_error() {
        let err = NikaError::InvalidTaskId {
            id: "Invalid-Task-ID".to_string(),
            reason: "contains uppercase or hyphens".to_string(),
        };
        assert_eq!(err.code(), "NIKA-055");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-055]"));
    }

    #[test]
    fn test_invalid_default_error() {
        let err = NikaError::InvalidDefault {
            raw: "not_quoted_string".to_string(),
            reason: "strings must be quoted".to_string(),
        };
        assert_eq!(err.code(), "NIKA-056");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-056]"));
    }

    #[test]
    fn test_blocked_command_error() {
        let err = NikaError::BlockedCommand {
            command: "rm -rf /".to_string(),
            reason: "Destructive command blocked by security policy".to_string(),
        };
        assert_eq!(err.code(), "NIKA-053");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-053]"));
        assert!(msg.contains("rm -rf /"));
        assert!(msg.contains("blocked"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // OUTPUT ERRORS (060-069)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_invalid_json_error() {
        let err = NikaError::InvalidJson {
            details: "trailing comma in object".to_string(),
        };
        assert_eq!(err.code(), "NIKA-060");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-060]"));
    }

    #[test]
    fn test_schema_failed_error() {
        let err = NikaError::SchemaFailed {
            details: "missing required property 'id'".to_string(),
        };
        assert_eq!(err.code(), "NIKA-061");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-061]"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // WITH BLOCK VALIDATION (070-079)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_unknown_alias_error() {
        let err = NikaError::UnknownAlias {
            alias: "undefined".to_string(),
            task_id: "current_task".to_string(),
        };
        assert_eq!(err.code(), "NIKA-071");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-071]"));
        assert!(msg.contains("undefined"));
    }

    #[test]
    fn test_null_value_error() {
        let err = NikaError::NullValue {
            path: "task.field".to_string(),
            alias: "myalias".to_string(),
        };
        assert_eq!(err.code(), "NIKA-072");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-072]"));
    }

    #[test]
    fn test_invalid_traversal_error() {
        let err = NikaError::InvalidTraversal {
            segment: "field".to_string(),
            value_type: "string".to_string(),
            full_path: "task.value.field".to_string(),
        };
        assert_eq!(err.code(), "NIKA-073");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-073]"));
        assert!(msg.contains("string"));
    }

    #[test]
    fn test_template_parse_error() {
        let err = NikaError::TemplateParse {
            position: 10,
            details: "unexpected closing brace".to_string(),
        };
        assert_eq!(err.code(), "NIKA-074");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-074]"));
        assert!(msg.contains("10"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // DAG VALIDATION (080-089)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_with_unknown_task_error() {
        let err = NikaError::WithUnknownTask {
            alias: "ctx".to_string(),
            from_task: "undefined".to_string(),
            task_id: "current".to_string(),
        };
        assert_eq!(err.code(), "NIKA-080");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-080]"));
        assert!(msg.contains("undefined"));
    }

    #[test]
    fn test_with_not_upstream_error() {
        let err = NikaError::WithNotUpstream {
            alias: "ctx".to_string(),
            from_task: "task2".to_string(),
            task_id: "task1".to_string(),
        };
        assert_eq!(err.code(), "NIKA-081");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-081]"));
    }

    #[test]
    fn test_with_circular_dep_error() {
        let err = NikaError::WithCircularDep {
            alias: "ctx".to_string(),
            from_task: "task1".to_string(),
            task_id: "task2".to_string(),
        };
        assert_eq!(err.code(), "NIKA-082");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-082]"));
        assert!(msg.contains("circular"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // JSONPATH / IO ERRORS (090-099)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_jsonpath_unsupported_error() {
        let err = NikaError::JsonPathUnsupported {
            path: "$.deeply[*].nested.path".to_string(),
        };
        assert_eq!(err.code(), "NIKA-090");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-090]"));
    }

    #[test]
    fn test_io_error_from_std() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
        let err: NikaError = io_err.into();
        assert_eq!(err.code(), "NIKA-093");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-093]"));
    }

    #[test]
    fn test_json_error_from_serde() {
        let json_str = "{invalid json";
        let json_err: serde_json::Result<serde_json::Value> = serde_json::from_str(json_str);
        if let Err(e) = json_err {
            let err: NikaError = e.into();
            assert_eq!(err.code(), "NIKA-094");
            let msg = err.to_string();
            assert!(msg.contains("[NIKA-094]"));
        }
    }

    #[test]
    fn test_yaml_parse_error_from_serde() {
        let yaml_str = "invalid: yaml: syntax:";
        // Use serde_json::Value as target since serde-saphyr doesn't export Value type
        let yaml_err = serde_yaml::from_str::<serde_json::Value>(yaml_str);
        if let Err(e) = yaml_err {
            let err: NikaError = e.into();
            assert_eq!(err.code(), "NIKA-095");
            let msg = err.to_string();
            assert!(msg.contains("[NIKA-095]"));
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // MCP ERRORS (100-109)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_mcp_not_connected_error() {
        let err = NikaError::McpNotConnected {
            name: "novanet".to_string(),
        };
        assert_eq!(err.code(), "NIKA-100");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-100]"));
        assert!(msg.contains("novanet"));
    }

    #[test]
    fn test_mcp_start_error() {
        let err = NikaError::McpStartError {
            name: "novanet".to_string(),
            reason: "port already in use".to_string(),
        };
        assert_eq!(err.code(), "NIKA-101");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-101]"));
    }

    #[test]
    fn test_mcp_tool_error_without_code() {
        let err = NikaError::McpToolError {
            tool: "novanet_context".to_string(),
            reason: "invalid parameters".to_string(),
            error_code: None,
        };
        assert_eq!(err.code(), "NIKA-102");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-102]"));
        assert!(msg.contains("novanet_context"));
    }

    #[test]
    fn test_mcp_tool_error_with_code() {
        let err = NikaError::McpToolError {
            tool: "novanet_describe".to_string(),
            reason: "entity not found".to_string(),
            error_code: Some(McpErrorCode::InvalidRequest),
        };
        assert_eq!(err.code(), "NIKA-102");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-102]"));
        // Error code description should be included in display
        // McpErrorCode::InvalidRequest displays as "The JSON sent is not a valid Request object (-32600)"
        assert!(msg.contains("Request") || msg.contains("-32600"));
    }

    #[test]
    fn test_mcp_resource_not_found_error() {
        let err = NikaError::McpResourceNotFound {
            uri: "novanet://entity/qr-code".to_string(),
        };
        assert_eq!(err.code(), "NIKA-103");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-103]"));
    }

    #[test]
    fn test_mcp_protocol_error() {
        let err = NikaError::McpProtocolError {
            reason: "JSON-RPC version mismatch".to_string(),
        };
        assert_eq!(err.code(), "NIKA-104");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-104]"));
    }

    #[test]
    fn test_mcp_not_configured_error() {
        let err = NikaError::McpNotConfigured {
            name: "novanet".to_string(),
        };
        assert_eq!(err.code(), "NIKA-105");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-105]"));
    }

    #[test]
    fn test_mcp_invalid_response_error() {
        let err = NikaError::McpInvalidResponse {
            tool: "novanet_search".to_string(),
            reason: "missing 'result' field".to_string(),
        };
        assert_eq!(err.code(), "NIKA-106");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-106]"));
    }

    #[test]
    fn test_mcp_validation_failed_error() {
        let err = NikaError::McpValidationFailed {
            tool: "novanet_context".to_string(),
            details: "parameter validation failed".to_string(),
            missing: vec!["focus_key".to_string(), "locale".to_string()],
            suggestions: vec!["Check parameter names".to_string()],
        };
        assert_eq!(err.code(), "NIKA-107");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-107]"));
    }

    #[test]
    fn test_mcp_schema_error() {
        let err = NikaError::McpSchemaError {
            tool: "novanet_context".to_string(),
            reason: "invalid property type in schema".to_string(),
        };
        assert_eq!(err.code(), "NIKA-108");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-108]"));
    }

    #[test]
    fn test_mcp_timeout_error() {
        let err = NikaError::McpTimeout {
            name: "novanet".to_string(),
            operation: "novanet_context".to_string(),
            timeout_secs: 30,
        };
        assert_eq!(err.code(), "NIKA-109");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-109]"));
        assert!(msg.contains("30"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // AGENT ERRORS (110-119)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_agent_validation_error() {
        let err = NikaError::AgentValidationError {
            reason: "empty prompt".to_string(),
        };
        assert_eq!(err.code(), "NIKA-113");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-113]"));
    }

    #[test]
    fn test_agent_execution_error() {
        let err = NikaError::AgentExecutionError {
            task_id: "agent_task".to_string(),
            reason: "provider unreachable".to_string(),
        };
        assert_eq!(err.code(), "NIKA-115");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-115]"));
    }

    #[test]
    fn test_thinking_capture_failed_error() {
        let err = NikaError::ThinkingCaptureFailed {
            reason: "streaming connection lost".to_string(),
        };
        assert_eq!(err.code(), "NIKA-116");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-116]"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // RESILIENCE ERRORS (120-129)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_timeout_error() {
        let err = NikaError::Timeout {
            operation: "fetch_data".to_string(),
            duration_ms: 5000,
        };
        assert_eq!(err.code(), "NIKA-121");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-121]"));
        assert!(msg.contains("5000"));
    }

    #[test]
    fn test_mcp_tool_call_failed_error() {
        let err = NikaError::McpToolCallFailed {
            tool: "novanet_audit".to_string(),
            reason: "malformed response".to_string(),
        };
        assert_eq!(err.code(), "NIKA-125");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-125]"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // TUI ERRORS (130-139)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_tui_error() {
        let err = NikaError::TuiError {
            reason: "terminal size too small".to_string(),
        };
        assert_eq!(err.code(), "NIKA-130");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-130]"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // CONFIG ERRORS (135-139)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_config_error() {
        let err = NikaError::ConfigError {
            reason: "invalid TOML syntax".to_string(),
        };
        assert_eq!(err.code(), "NIKA-135");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-135]"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // TOOL ERRORS (200-219)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_tool_error() {
        let err = NikaError::ToolError {
            code: "TOOL-001".to_string(),
            message: "File not found".to_string(),
        };
        assert_eq!(err.code(), "NIKA-2XX");
        let msg = err.to_string();
        assert!(msg.contains("TOOL-001"));
        assert!(msg.contains("File not found"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // FIX SUGGESTION TRAIT TESTS
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_fix_suggestion_for_all_recoverable_errors() {
        let err = NikaError::Timeout {
            operation: "slow_op".to_string(),
            duration_ms: 5000,
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("timeout"));
    }

    #[test]
    fn test_fix_suggestion_for_mcp_validation_with_missing_fields() {
        let err = NikaError::McpValidationFailed {
            tool: "test_tool".to_string(),
            details: "missing required fields".to_string(),
            missing: vec!["field1".to_string()],
            suggestions: vec![],
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("required fields"));
    }

    #[test]
    fn test_fix_suggestion_for_mcp_validation_with_suggestions() {
        let err = NikaError::McpValidationFailed {
            tool: "test_tool".to_string(),
            details: "field mismatch".to_string(),
            missing: vec![],
            suggestions: vec!["Did you mean 'entity'?".to_string()],
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("spelling"));
    }

    #[test]
    fn test_fix_suggestion_for_mcp_validation_default() {
        let err = NikaError::McpValidationFailed {
            tool: "test_tool".to_string(),
            details: "unknown issue".to_string(),
            missing: vec![],
            suggestions: vec![],
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("parameter schema"));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // IS_RECOVERABLE TESTS
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_is_recoverable_mcp_not_connected() {
        let err = NikaError::McpNotConnected { name: "x".into() };
        assert!(err.is_recoverable());
    }

    #[test]
    fn test_is_recoverable_provider_api_error() {
        let err = NikaError::ProviderApiError {
            message: "x".into(),
        };
        assert!(err.is_recoverable());
    }

    #[test]
    fn test_is_recoverable_mcp_tool_error() {
        let err = NikaError::McpToolError {
            tool: "x".into(),
            reason: "y".into(),
            error_code: None,
        };
        assert!(err.is_recoverable());
    }

    #[test]
    fn test_is_recoverable_timeout() {
        let err = NikaError::Timeout {
            operation: "x".into(),
            duration_ms: 1000,
        };
        assert!(err.is_recoverable());
    }

    #[test]
    fn test_is_recoverable_mcp_timeout() {
        let err = NikaError::McpTimeout {
            name: "x".into(),
            operation: "y".into(),
            timeout_secs: 30,
        };
        assert!(err.is_recoverable());
    }

    #[test]
    fn test_is_recoverable_mcp_tool_call_failed() {
        let err = NikaError::McpToolCallFailed {
            tool: "x".into(),
            reason: "y".into(),
        };
        assert!(err.is_recoverable());
    }

    #[test]
    fn test_is_not_recoverable_parse_error() {
        let err = NikaError::ParseError {
            details: "x".into(),
        };
        assert!(!err.is_recoverable());
    }

    #[test]
    fn test_is_not_recoverable_validation_error() {
        let err = NikaError::ValidationError { reason: "x".into() };
        assert!(!err.is_recoverable());
    }

    #[test]
    fn test_is_not_recoverable_cycle_detected() {
        let err = NikaError::CycleDetected { cycle: "x".into() };
        assert!(!err.is_recoverable());
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // ERROR CODE CONSISTENCY TESTS
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_all_workflow_errors_have_correct_codes() {
        assert_eq!(
            NikaError::ParseError {
                details: "x".into()
            }
            .code(),
            "NIKA-001"
        );
        assert_eq!(
            NikaError::InvalidSchemaVersion {
                version: "x".into()
            }
            .code(),
            "NIKA-002"
        );
        assert_eq!(
            NikaError::WorkflowNotFound { path: "x".into() }.code(),
            "NIKA-003"
        );
        assert_eq!(
            NikaError::ValidationError { reason: "x".into() }.code(),
            "NIKA-004"
        );
    }

    #[test]
    fn test_all_dag_errors_have_correct_codes() {
        assert_eq!(
            NikaError::CycleDetected { cycle: "x".into() }.code(),
            "NIKA-020"
        );
        assert_eq!(
            NikaError::MissingDependency {
                task_id: "x".into(),
                dep_id: "y".into()
            }
            .code(),
            "NIKA-021"
        );
    }

    #[test]
    fn test_all_provider_errors_have_correct_codes() {
        assert_eq!(
            NikaError::ProviderNotConfigured {
                provider: "x".into()
            }
            .code(),
            "NIKA-030"
        );
        assert_eq!(
            NikaError::ProviderApiError {
                message: "x".into()
            }
            .code(),
            "NIKA-031"
        );
        assert_eq!(
            NikaError::MissingApiKey {
                provider: "x".into()
            }
            .code(),
            "NIKA-032"
        );
    }

    #[test]
    fn test_all_binding_errors_have_correct_codes() {
        assert_eq!(
            NikaError::BindingNotFound { alias: "x".into() }.code(),
            "NIKA-042"
        );
        assert_eq!(
            NikaError::BindingTypeMismatch {
                expected: "x".into(),
                actual: "y".into(),
                path: "z".into()
            }
            .code(),
            "NIKA-043"
        );
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // STRUCTURED OUTPUT ERRORS (300-309)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_structured_output_extraction_failed_error() {
        let err = NikaError::StructuredOutputExtractionFailed {
            task_id: "generate_json".to_string(),
            layer: "rig_extractor".to_string(),
            reason: "Failed to parse JSON from response".to_string(),
        };
        assert_eq!(err.code(), "NIKA-300");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-300]"));
        assert!(msg.contains("generate_json"));
        assert!(msg.contains("rig_extractor"));
        assert!(msg.contains("Failed to parse JSON"));
    }

    #[test]
    fn test_structured_output_validation_failed_error() {
        let err = NikaError::StructuredOutputValidationFailed {
            task_id: "validate_output".to_string(),
            layer: "extract_validate".to_string(),
            attempt: 2,
            errors: vec![
                "missing required field 'id'".to_string(),
                "invalid type for 'count': expected integer".to_string(),
            ],
        };
        assert_eq!(err.code(), "NIKA-301");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-301]"));
        assert!(msg.contains("validate_output"));
        assert!(msg.contains("extract_validate"));
        assert!(msg.contains("attempt 2"));
        assert!(msg.contains("2 errors"));
    }

    #[test]
    fn test_structured_output_validation_failed_single_error() {
        let err = NikaError::StructuredOutputValidationFailed {
            task_id: "single_error".to_string(),
            layer: "retry_with_feedback".to_string(),
            attempt: 1,
            errors: vec!["missing required field 'name'".to_string()],
        };
        assert_eq!(err.code(), "NIKA-301");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-301]"));
        assert!(msg.contains("missing required field 'name'"));
        // Should not contain "errors:" prefix for single error
        assert!(!msg.contains("1 errors:"));
    }

    #[test]
    fn test_structured_output_repair_failed_error() {
        let err = NikaError::StructuredOutputRepairFailed {
            task_id: "repair_task".to_string(),
            original_errors: vec!["invalid JSON syntax".to_string()],
            repair_errors: vec!["repair produced invalid output".to_string()],
        };
        assert_eq!(err.code(), "NIKA-302");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-302]"));
        assert!(msg.contains("repair_task"));
        assert!(msg.contains("original errors"));
        assert!(msg.contains("repair errors"));
    }

    #[test]
    fn test_structured_output_all_layers_failed_error() {
        let err = NikaError::StructuredOutputAllLayersFailed {
            task_id: "final_failure".to_string(),
            attempts: 4,
            final_errors: vec!["schema validation failed".to_string()],
        };
        assert_eq!(err.code(), "NIKA-303");
        let msg = err.to_string();
        assert!(msg.contains("[NIKA-303]"));
        assert!(msg.contains("final_failure"));
        assert!(msg.contains("4 attempts"));
    }

    #[test]
    fn test_all_structured_output_errors_have_correct_codes() {
        assert_eq!(
            NikaError::StructuredOutputExtractionFailed {
                task_id: "x".into(),
                layer: "y".into(),
                reason: "z".into()
            }
            .code(),
            "NIKA-300"
        );
        assert_eq!(
            NikaError::StructuredOutputValidationFailed {
                task_id: "x".into(),
                layer: "y".into(),
                attempt: 1,
                errors: vec![]
            }
            .code(),
            "NIKA-301"
        );
        assert_eq!(
            NikaError::StructuredOutputRepairFailed {
                task_id: "x".into(),
                original_errors: vec![],
                repair_errors: vec![]
            }
            .code(),
            "NIKA-302"
        );
        assert_eq!(
            NikaError::StructuredOutputAllLayersFailed {
                task_id: "x".into(),
                attempts: 1,
                final_errors: vec![]
            }
            .code(),
            "NIKA-303"
        );
    }

    #[test]
    fn test_structured_output_errors_fix_suggestions() {
        let extraction_err = NikaError::StructuredOutputExtractionFailed {
            task_id: "t".into(),
            layer: "l".into(),
            reason: "r".into(),
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&extraction_err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("JSON Schema"));

        let validation_err = NikaError::StructuredOutputValidationFailed {
            task_id: "t".into(),
            layer: "l".into(),
            attempt: 1,
            errors: vec![],
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&validation_err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("schema"));

        let repair_err = NikaError::StructuredOutputRepairFailed {
            task_id: "t".into(),
            original_errors: vec![],
            repair_errors: vec![],
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&repair_err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("simplifying"));

        let all_failed_err = NikaError::StructuredOutputAllLayersFailed {
            task_id: "t".into(),
            attempts: 1,
            final_errors: vec![],
        };
        let suggestion = <NikaError as FixSuggestion>::fix_suggestion(&all_failed_err);
        assert!(suggestion.is_some());
        assert!(suggestion.unwrap().contains("validation layers"));
    }

    #[test]
    fn test_structured_output_is_recoverable() {
        // Extraction, validation, and repair errors are recoverable
        let extraction = NikaError::StructuredOutputExtractionFailed {
            task_id: "x".into(),
            layer: "y".into(),
            reason: "z".into(),
        };
        assert!(extraction.is_recoverable());

        let validation = NikaError::StructuredOutputValidationFailed {
            task_id: "x".into(),
            layer: "y".into(),
            attempt: 1,
            errors: vec![],
        };
        assert!(validation.is_recoverable());

        let repair = NikaError::StructuredOutputRepairFailed {
            task_id: "x".into(),
            original_errors: vec![],
            repair_errors: vec![],
        };
        assert!(repair.is_recoverable());

        // All layers failed is NOT recoverable (final failure)
        let all_failed = NikaError::StructuredOutputAllLayersFailed {
            task_id: "x".into(),
            attempts: 4,
            final_errors: vec![],
        };
        assert!(!all_failed.is_recoverable());
    }

    #[test]
    fn test_format_validation_errors_short_empty() {
        let result = format_validation_errors_short(&[]);
        assert_eq!(result, "no errors");
    }

    #[test]
    fn test_format_validation_errors_short_single() {
        let result = format_validation_errors_short(&["missing field".to_string()]);
        assert_eq!(result, "missing field");
    }

    #[test]
    fn test_format_validation_errors_short_multiple() {
        let result = format_validation_errors_short(&[
            "error 1".to_string(),
            "error 2".to_string(),
            "error 3".to_string(),
        ]);
        assert!(result.contains("3 errors:"));
        assert!(result.contains("error 1"));
        assert!(result.contains("error 2"));
        assert!(result.contains("error 3"));
    }
}