nika 0.20.0

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
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
# Nika Technical Reference

```
 ███╗   ██╗██╗██╗  ██╗ █████╗
 ████╗  ██║██║██║ ██╔╝██╔══██╗
 ██╔██╗ ██║██║█████╔╝ ███████║
 ██║╚██╗██║██║██╔═██╗ ██╔══██║
 ██║ ╚████║██║██║  ██╗██║  ██║
 ╚═╝  ╚═══╝╚═╝╚═╝  ╚═╝╚═╝  ╚═╝
 Semantic YAML Workflow Engine
```

| | |
|---|---|
| **Version** | 0.5.3 |
| **Updated** | 2026-02-21 |
| **Status** | Production-ready |
| **Tests** | 1200+ passing |
| **Provider** | rig-core v0.31 |
| **MCP** | rmcp v0.16 |

---

## Table of Contents

| Section | Topic | Key Concepts |
|---------|-------|--------------|
| [1]#1-overview | Overview | Philosophy, Features, Brain+Body |
| [2]#2-architecture | Architecture | Modules, Pipeline, Key Types |
| [3]#3-yaml-workflow-schema | YAML Schema | Structure, Versions, Validation |
| [4]#4-the-5-semantic-verbs | 5 Semantic Verbs | infer, exec, fetch, invoke, agent |
| [5]#5-provider-system | Provider System | rig-core, NikaMcpTool |
| [6]#6-mcp-integration | MCP Integration | Zero Cypher Rule, Client |
| [7]#7-data-binding-system | Data Binding | use: block, Templates, JSONPath |
| [8]#8-dag-execution | DAG Execution | Flows, Topological Sort, Cycles |
| [9]#9-event-system | Event System | 16 EventKinds, EventLog |
| [10]#10-observability-and-traces | Observability | NDJSON Traces, TraceWriter |
| [11]#11-for_each-parallelism | for_each Parallelism | Concurrency, JoinSet |
| [12]#12-terminal-ui-tui | Terminal UI | 4-Panel Layout, Keybindings |
| [13]#13-cli-commands | CLI Commands | run, validate, tui, trace |
| [14]#14-error-handling | Error Handling | Error Codes, FixSuggestion |
| [15]#15-architecture-decision-records | ADRs | ADR-001/002/003 |
| [16]#16-development-guide | Development | Setup, TDD, Code Style |
| [17]#17-troubleshooting | Troubleshooting | Common Issues, Debug Tips |
| [18]#18-examples | Examples | UC1, UC2, UC3 |
| [Appendix]#appendix-complete-yaml-schema | YAML Schema | Complete Reference |

---

## Quick Reference Card

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  NIKA CHEAT SHEET                                                           │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  5 SEMANTIC VERBS                                                           │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  infer:  LLM text generation     │  invoke:  MCP tool call         │   │
│  │  exec:   Shell command           │  agent:   Multi-turn loop       │   │
│  │  fetch:  HTTP request            │                                  │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  WORKFLOW STRUCTURE                                                         │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  schema: "nika/workflow@0.4"     # Required                         │   │
│  │  provider: claude                # Default provider                 │   │
│  │  mcp:                            # MCP server configs               │   │
│  │    novanet: { command: ..., args: [...] }                           │   │
│  │  tasks:                          # Task list                        │   │
│  │    - id: task_name               # Unique ID                        │   │
│  │      use: { alias: other_task }  # Data binding                     │   │
│  │      infer: "prompt"             # One verb                         │   │
│  │  flows:                          # DAG edges                        │   │
│  │    - source: a, target: b        # Dependencies                     │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  DATA BINDING                                                               │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  use:                                                                │   │
│  │    data: task_id                 # Entire output                    │   │
│  │    field: task_id.path.to.field  # Nested path                      │   │
│  │    safe: task_id.field ?? "def"  # With default                     │   │
│  │                                                                      │   │
│  │  infer: "Process {{use.data}}"   # Template resolution              │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  CLI COMMANDS                                                               │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  nika run <file>                 # Execute workflow                 │   │
│  │  nika validate <file>            # Parse + validate                 │   │
│  │  nika tui <file>                 # Interactive 4-panel TUI          │   │
│  │  nika trace list                 # List execution traces            │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  for_each PARALLELISM                                                       │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  for_each: ["a", "b", "c"]       # Array to iterate                 │   │
│  │  as: item                        # Loop variable                    │   │
│  │  concurrency: 5                  # Max parallel (default: 1)        │   │
│  │  fail_fast: true                 # Stop on error (default: true)    │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  MCP TOOLS (NovaNet)                                                        │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  novanet_generate   Generate native content with forms              │   │
│  │  novanet_describe   Schema info (nodes, arcs)                       │   │
│  │  novanet_traverse   Graph traversal                                 │   │
│  │  novanet_assemble   Build context                                   │   │
│  │  novanet_search     Entity search                                   │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## 1. Overview

### What is Nika?

Nika is a **semantic YAML workflow engine** for multi-step AI workflows. It serves as the "body" of the supernovae-agi architecture, executing workflows that leverage NovaNet's knowledge graph "brain" via the Model Context Protocol (MCP).

```mermaid
flowchart LR
    subgraph "NIKA WORKFLOW ENGINE"
        direction LR
        YAML["YAML<br/>Workflow"] --> AST["AST<br/>Parser"]
        AST --> DAG["DAG<br/>Builder"]
        DAG --> RT["Runtime<br/>Executor"]
        RT --> OUT["Output"]
    end

    subgraph "Components"
        direction TB
        P["rig-core v0.31"]
        M["rmcp v0.16"]
        E["EventLog"]
    end

    RT --> P
    RT --> M
    RT --> E

    style YAML fill:#0d9488,color:#fff
    style AST fill:#0284c7,color:#fff
    style DAG fill:#7c3aed,color:#fff
    style RT fill:#dc2626,color:#fff
    style OUT fill:#16a34a,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  NIKA WORKFLOW ENGINE                                                       │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│    YAML Workflow          AST            DAG           Runtime              │
│  ┌──────────────┐   ┌──────────┐   ┌──────────┐   ┌──────────────┐         │
│  │ schema: ...  │   │ Workflow │   │ Topo-    │   │ TaskExecutor │         │
│  │ tasks:       │──▶│ Task     │──▶│ logical  │──▶│ + Providers  │──▶ Out  │
│  │   - id: a    │   │ Action   │   │ Sort     │   │ + MCP Client │         │
│  │     infer:   │   │ Binding  │   │ + Deps   │   │ + EventLog   │         │
│  └──────────────┘   └──────────┘   └──────────┘   └──────────────┘         │
│                                                                             │
│  Provider: rig-core v0.31        MCP: rmcp v0.16        Tests: 621+        │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Brain + Body Architecture

```mermaid
flowchart TB
    subgraph BRAIN["NovaNet (Brain)"]
        direction TB
        KG["Knowledge Graph<br/>61 Nodes / 182 Arcs"]
        NEO["Neo4j"]
        MCP_S["MCP Server<br/>7 Tools"]
        KG --> NEO
        NEO --> MCP_S
    end

    subgraph BODY["Nika (Body)"]
        direction TB
        WF["YAML Workflows"]
        ENG["Execution Engine"]
        MCP_C["MCP Client"]
        WF --> ENG
        ENG --> MCP_C
    end

    MCP_C <-->|"MCP Protocol"| MCP_S

    style BRAIN fill:#0d9488,color:#fff
    style BODY fill:#7c3aed,color:#fff
    style MCP_C fill:#0284c7,color:#fff
    style MCP_S fill:#0284c7,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  SUPERNOVAE-AGI ARCHITECTURE                                                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   ┌─────────────────────┐         MCP Protocol        ┌─────────────────┐   │
│   │     NOVANET         │◄──────────────────────────►│      NIKA       │   │
│   │     (Brain)         │                             │     (Body)      │   │
│   ├─────────────────────┤                             ├─────────────────┤   │
│   │ - Knowledge Graph   │    novanet_generate         │ - YAML Workflows│   │
│   │ - Entity Memory     │    novanet_describe         │ - LLM Providers │   │
│   │ - Locale Context    │    novanet_traverse         │ - DAG Execution │   │
│   │ - SEO/GEO Intel     │◄────────────────────────────│ - Tool Calling  │   │
│   │ - 61 Nodes, 182 Arcs│                             │ - State Machine │   │
│   └─────────────────────┘                             └─────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Core Philosophy

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  NIKA PRINCIPLES                                                            │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  1. YAML-FIRST         Workflows are declarative YAML files, not code      │
│  2. 5 SEMANTIC VERBS   infer | exec | fetch | invoke | agent               │
│  3. MCP-ONLY           NovaNet access exclusively via MCP protocol         │
│  4. FULL OBSERVABILITY Every operation emits structured events             │
│  5. PARALLEL EXECUTION First-class for_each with concurrency control       │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

1. **YAML-First**: Workflows are declarative YAML files, not code
2. **5 Semantic Verbs**: `infer:`, `exec:`, `fetch:`, `invoke:`, `agent:`
3. **MCP-Only Integration**: NovaNet access exclusively via MCP protocol
4. **Full Observability**: Every operation emits structured events
5. **Parallel Execution**: First-class `for_each` with concurrency control

### Key Features

| Feature | Description |
|---------|-------------|
| **5 Verbs** | Complete coverage of AI workflow patterns |
| **DAG Execution** | Automatic dependency resolution and topological sort |
| **MCP Integration** | Native connection to NovaNet knowledge graph |
| **rig-core Provider** | 20+ LLM providers via rig-core v0.31 |
| **for_each Parallelism** | Concurrent iteration with configurable limits |
| **Event Sourcing** | 16+ event types for full audit trail |
| **NDJSON Traces** | Persistent execution logs for debugging |
| **Interactive TUI** | Real-time workflow observation |
| **Extended Thinking** | Claude reasoning capture (v0.4+) |

### Version History

| Version | Key Changes |
|---------|-------------|
| **v0.4.1** | Token tracking fix for streaming mode, extended thinking capture |
| **v0.4.0** | rig-core migration, RigAgentLoop, deleted legacy providers (~2,350 lines removed) |
| **v0.3.0** | for_each parallelism, rig-core preparation |
| **v0.2.0** | invoke: and agent: verbs, MCP client |
| **v0.1.0** | Initial release: infer, exec, fetch |

### v0.4.1 Highlights

**Token Tracking Fix:** In v0.4.0, `input_tokens` and `output_tokens` were always 0 when using extended thinking (streaming mode). v0.4.1 extracts token usage from `StreamedAssistantContent::Final` via rig's `GetTokenUsage` trait.

```rust
// Before (v0.4.0) - tokens always 0 in streaming mode
AgentTurnMetadata { input_tokens: 0, output_tokens: 0, thinking: Some("...") }

// After (v0.4.1) - tokens correctly tracked
AgentTurnMetadata { input_tokens: 1234, output_tokens: 567, thinking: Some("...") }
```

**Files Changed:**
- `runtime/rig_agent_loop.rs` - Token extraction from streaming response
- `tests/thinking_capture_test.rs` - Integration tests for token capture

---

## 2. Architecture

### High-Level Architecture (v0.4)

```mermaid
flowchart TB
    subgraph Nika["Nika v0.4.1"]
        YAML[".nika.yaml Workflow"] --> AST["AST Parser<br/>(serde_yaml)"]
        AST --> DAG["DAG Builder<br/>(Kahn's Algorithm)"]
        DAG --> Runtime["Runtime Executor<br/>(tokio)"]

        subgraph Verbs["5 Semantic Verbs"]
            direction LR
            INFER["infer:"]
            EXEC["exec:"]
            FETCH["fetch:"]
            INVOKE["invoke:"]
            AGENT["agent:"]
        end

        Runtime --> Verbs

        subgraph Provider["Provider Layer (rig-core v0.31)"]
            RIG["RigProvider<br/>.claude() | .openai()"]
            LOOP["RigAgentLoop<br/>rig::AgentBuilder"]
        end

        INFER --> RIG
        AGENT --> LOOP

        subgraph Events["Event System"]
            LOG["EventLog<br/>(16 variants)"]
            TRACE["TraceWriter<br/>(.nika/traces/*.ndjson)"]
        end

        Runtime --> LOG
        LOG --> TRACE
    end

    subgraph MCP["MCP Integration (rmcp v0.16)"]
        CLIENT["McpClient"]
        TOOL["NikaMcpTool<br/>implements rig::ToolDyn"]
    end

    INVOKE --> CLIENT
    LOOP --> TOOL
    CLIENT --> NovaNet["NovaNet MCP Server<br/>(7 tools)"]
    NovaNet --> Neo4j["Neo4j<br/>(61 nodes, 182 arcs)"]

    style Nika fill:#0f172a,color:#fff
    style Provider fill:#7c3aed,color:#fff
    style MCP fill:#0284c7,color:#fff
    style NovaNet fill:#0d9488,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  NIKA v0.4.1 ARCHITECTURE                                                   │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐  │
│  │  WORKFLOW PIPELINE                                                    │  │
│  │                                                                       │  │
│  │    .nika.yaml ──▶ AST Parser ──▶ DAG Builder ──▶ Runtime Executor    │  │
│  │                                                                       │  │
│  └──────────────────────────────────────────────────────────────────────┘  │
│                                    │                                        │
│                                    ▼                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐  │
│  │  5 SEMANTIC VERBS                                                     │  │
│  │                                                                       │  │
│  │    infer: ──┐                                                         │  │
│  │             ├──▶ RigProvider (rig-core v0.31)                        │  │
│  │    agent: ──┘    ├── RigProvider::claude()                           │  │
│  │                  └── RigAgentLoop (rig::AgentBuilder)                │  │
│  │                                                                       │  │
│  │    exec:  ──▶ tokio::process::Command                                │  │
│  │    fetch: ──▶ reqwest::Client                                        │  │
│  │    invoke: ──▶ McpClient (rmcp v0.16)                                │  │
│  │                                                                       │  │
│  └──────────────────────────────────────────────────────────────────────┘  │
│                                    │                                        │
│                                    ▼                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐  │
│  │  MCP INTEGRATION                                                      │  │
│  │                                                                       │  │
│  │    McpClient ──▶ NikaMcpTool (rig::ToolDyn) ──▶ NovaNet MCP Server   │  │
│  │                                                                       │  │
│  └──────────────────────────────────────────────────────────────────────┘  │
│                                                                             │
│  STATS: 621+ tests | rig-core v0.31 | rmcp v0.16 | ratatui v0.30          │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Module Structure

```
tools/nika/src/
├── main.rs              # CLI entry point (clap)
├── lib.rs               # Public API exports
├── error.rs             # NikaError with 40+ variants and codes
│
├── ast/                 # YAML → Rust structs
│   ├── mod.rs           # Module exports
│   ├── workflow.rs      # Workflow, Task, Flow, McpConfigInline
│   ├── action.rs        # TaskAction enum (5 variants)
│   ├── agent.rs         # AgentParams with extended_thinking
│   ├── invoke.rs        # InvokeParams for MCP calls
│   └── output.rs        # OutputPolicy and format validation
│
├── binding/             # Data flow between tasks
│   ├── mod.rs           # Module exports
│   ├── entry.rs         # UseEntry, WiringSpec, parse_use_entry
│   ├── resolve.rs       # ResolvedBindings, binding resolution
│   ├── template.rs      # template_resolve() for {{use.alias}}
│   └── validate.rs      # DAG-aware binding validation
│
├── dag/                 # Directed Acyclic Graph
│   ├── mod.rs           # Module exports
│   ├── flow.rs          # Dag, topological sort
│   └── validate.rs      # Cycle detection, dependency validation
│
├── runtime/             # Execution engine
│   ├── mod.rs           # Module exports
│   ├── runner.rs        # Workflow orchestration
│   ├── executor.rs      # TaskExecutor (5 verbs + for_each)
│   ├── output.rs        # Output format handling
│   └── rig_agent_loop.rs # RigAgentLoop with rig::AgentBuilder
│
├── mcp/                 # MCP client (rmcp v0.16)
│   ├── mod.rs           # Module exports
│   ├── client.rs        # McpClient (real + mock modes)
│   ├── types.rs         # McpConfig, ToolDefinition, ToolCallResult
│   ├── protocol.rs      # MCP protocol constants
│   └── rmcp_adapter.rs  # rmcp SDK integration layer
│
├── provider/            # LLM providers (rig-core v0.31)
│   ├── mod.rs           # Provider trait + factory
│   └── rig.rs           # RigProvider + NikaMcpTool
│
├── event/               # Event sourcing
│   ├── mod.rs           # Module exports
│   ├── log.rs           # EventLog, EventKind (16+ variants)
│   ├── emitter.rs       # Event emission helpers
│   └── trace.rs         # NDJSON TraceWriter
│
├── store/               # Runtime data storage
│   ├── mod.rs           # Module exports
│   └── datastore.rs     # Task output storage
│
├── util/                # Utilities
│   ├── mod.rs           # Module exports
│   ├── constants.rs     # Timeouts, limits
│   ├── interner.rs      # String interning for task IDs
│   └── jsonpath.rs      # JSONPath subset implementation
│
└── tui/                 # Terminal UI (feature-gated)
    ├── mod.rs           # TUI entry point
    ├── app.rs           # App state machine
    ├── state.rs         # TUI state management
    ├── theme.rs         # Colors and styling
    ├── panels/          # UI panels
    │   ├── mod.rs
    │   ├── progress.rs  # Progress panel
    │   ├── context.rs   # Context panel
    │   ├── graph.rs     # DAG visualization
    │   └── reasoning.rs # Extended thinking panel
    └── widgets/         # Reusable widgets
        ├── mod.rs
        ├── dag.rs       # DAG widget
        ├── gauge.rs     # Progress gauge
        ├── spinner.rs   # Loading spinner
        ├── timeline.rs  # Event timeline
        ├── mcp_log.rs   # MCP call log
        └── agent_turns.rs # Agent turn display
```

### Data Flow Pipeline

```mermaid
flowchart TB
    subgraph PARSE["1. PARSE (ast/)"]
        direction TB
        Y["YAML File"] --> SY["serde_yaml"]
        SY --> WF["Workflow { tasks, flows, mcp }"]
        WF --> SV["Schema Validation"]
        SV --> TP["Task Parsing"]
        TP --> WS["WiringSpec Parsing"]
    end

    subgraph VALIDATE["2. VALIDATE (dag/, binding/)"]
        direction TB
        FG["Build Dag"] --> CD["Cycle Detection<br/>(Kahn's Algorithm)"]
        CD --> VU["Validate use: refs"]
        VU --> VD["Verify Dependencies"]
    end

    subgraph EXECUTE["3. EXECUTE (runtime/)"]
        direction TB
        RB["Resolve Bindings"] --> RT["Resolve Templates"]
        RT --> TE["TaskExecutor"]
        TE --> DS["Store in DataStore"]
        DS --> EV["Emit Events"]
    end

    subgraph OUTPUT["4. OUTPUT"]
        direction TB
        FO["Final Output"]
        TR["NDJSON Traces"]
        TUI["TUI Streaming"]
    end

    PARSE --> VALIDATE
    VALIDATE --> EXECUTE
    EXECUTE --> OUTPUT

    style PARSE fill:#0d9488,color:#fff
    style VALIDATE fill:#0284c7,color:#fff
    style EXECUTE fill:#7c3aed,color:#fff
    style OUTPUT fill:#16a34a,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  NIKA DATA FLOW PIPELINE                                                    │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  1. PARSE (ast/)                                                            │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  YAML File → serde_yaml → Workflow { tasks, flows, mcp }            │   │
│  │                                                                      │   │
│  │  - Schema validation (nika/workflow@0.1|0.2|0.3)                    │   │
│  │  - Task parsing with TaskAction enum                                 │   │
│  │  - WiringSpec parsing for use: blocks                               │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                     │                                       │
│                                     ▼                                       │
│  2. VALIDATE (dag/, binding/)                                               │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  - Build Dag from tasks + flows                                     │   │
│  │  - Detect cycles (Kahn's algorithm)                                 │   │
│  │  - Validate use: references against DAG                             │   │
│  │  - Ensure all dependencies are upstream                             │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                     │                                       │
│                                     ▼                                       │
│  3. EXECUTE (runtime/)                                                      │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  Runner orchestrates execution:                                      │   │
│  │                                                                      │   │
│  │  for each task in topological_order:                                │   │
│  │    1. Resolve bindings from DataStore                               │   │
│  │    2. Resolve {{use.alias}} templates                               │   │
│  │    3. Execute via TaskExecutor (infer/exec/fetch/invoke/agent)      │   │
│  │    4. Store output in DataStore                                     │   │
│  │    5. Emit events to EventLog                                       │   │
│  │                                                                      │   │
│  │  Parallelism: for_each uses tokio::spawn + JoinSet                  │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                     │                                       │
│                                     ▼                                       │
│  4. OUTPUT                                                                  │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  - Final task output returned                                       │   │
│  │  - NDJSON trace written to .nika/traces/                            │   │
│  │  - Events available for TUI streaming                               │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Key Types

```rust
/// Root workflow structure (src/ast/workflow.rs)
pub struct Workflow {
    pub schema: String,           // "nika/workflow@0.4"
    pub provider: String,         // Default provider ("claude", "openai")
    pub model: Option<String>,    // Default model
    pub mcp: Option<FxHashMap<String, McpConfigInline>>,
    pub tasks: Vec<Arc<Task>>,
    pub flows: Vec<Flow>,
}

/// Individual task (src/ast/workflow.rs)
pub struct Task {
    pub id: String,
    pub use_wiring: Option<WiringSpec>,     // use: block
    pub output: Option<OutputPolicy>,       // output: block
    pub for_each: Option<serde_json::Value>, // Iteration array
    pub for_each_as: Option<String>,        // Loop variable name
    pub concurrency: Option<usize>,         // Parallel limit
    pub fail_fast: Option<bool>,            // Stop on error
    pub action: TaskAction,                 // The verb
}

/// The 5 semantic verbs (src/ast/action.rs)
pub enum TaskAction {
    Infer { infer: InferParams },   // LLM inference
    Exec { exec: ExecParams },      // Shell command
    Fetch { fetch: FetchParams },   // HTTP request
    Invoke { invoke: InvokeParams }, // MCP tool/resource
    Agent { agent: AgentParams },   // Multi-turn agent
}
```

---

## 3. YAML Workflow Schema

### Schema Versions

| Version | Added Features | Status |
|---------|---------------|--------|
| `nika/workflow@0.1` | infer, exec, fetch verbs | Supported |
| `nika/workflow@0.2` | invoke, agent verbs, mcp config | Supported |
| `nika/workflow@0.3` | for_each parallelism | Supported |
| `nika/workflow@0.4` | extended_thinking, thinking_budget, rig-core | **Current** |

### Complete Workflow Structure

```yaml
# Schema version (required)
schema: "nika/workflow@0.4"

# Default LLM provider (optional, defaults to "claude")
provider: claude  # "claude" | "openai" | "mock"

# Default model (optional)
model: claude-sonnet-4-6

# MCP server configurations (optional, v0.2+)
mcp:
  novanet:
    command: cargo
    args:
      - run
      - --manifest-path
      - ../novanet/tools/novanet-mcp/Cargo.toml
    env:
      NEO4J_URI: bolt://localhost:7687
      NEO4J_USER: neo4j
      NEO4J_PASSWORD: password
    cwd: /path/to/working/dir  # Optional

# Task definitions
tasks:
  - id: task_name          # Required, unique identifier

    # Data binding (optional)
    use:
      alias: other_task.path.to.field
      with_default: other_task.field ?? "fallback"

    # Parallel iteration (optional, v0.3+)
    for_each: ["a", "b", "c"]  # Or binding: $other_task
    as: item                    # Loop variable (default: "item")
    concurrency: 5              # Max parallel (default: 1)
    fail_fast: true             # Stop on error (default: true)

    # Output configuration (optional)
    output:
      format: json  # "json" | "text" | "yaml"
      schema:       # JSON Schema for validation
        type: object
        properties:
          field: { type: string }

    # One of the 5 verbs (required)
    infer:
      prompt: "Your prompt with {{use.alias}}"
      provider: claude    # Override default
      model: claude-opus-4-20250514  # Override default

    # OR
    exec:
      command: "echo {{use.alias}}"

    # OR
    fetch:
      url: "https://api.example.com/{{use.alias}}"
      method: GET  # GET | POST | PUT | DELETE
      headers:
        Authorization: "Bearer {{use.token}}"
      body: '{"key": "value"}'  # For POST/PUT

    # OR
    invoke:
      mcp: novanet  # MCP server name
      tool: novanet_generate  # XOR resource
      params:
        entity: "{{use.entity_key}}"
        locale: "fr-FR"

    # OR
    agent:
      prompt: "Your agent goal"
      system: "System prompt (optional)"
      provider: claude
      model: claude-sonnet-4-6
      mcp:
        - novanet  # MCP servers for tools
      max_turns: 10
      token_budget: 100000
      stop_conditions:
        - "GENERATION_COMPLETE"
        - "TASK_DONE"
      extended_thinking: true   # v0.4+
      thinking_budget: 8192     # v0.4+

# Flow definitions (DAG edges)
flows:
  - source: task_a
    target: task_b

  - source: [task_a, task_b]  # Multiple sources
    target: task_c

  - source: task_c
    target: [task_d, task_e]  # Multiple targets
```

### File Naming Convention

All Nika workflow files **MUST** use the `.nika.yaml` extension:

```
workflow.nika.yaml     # Correct
workflow.yaml          # Wrong (ambiguous)
workflow.nika          # Wrong (not YAML)
```

### JSON Schema Validation

Workflows can be validated against `schemas/nika-workflow.schema.json`:

```bash
# VS Code auto-completion via .vscode/settings.json:
{
  "yaml.schemas": {
    "./schemas/nika-workflow.schema.json": "*.nika.yaml"
  }
}
```

---

## 4. The 5 Semantic Verbs

### Overview

```mermaid
flowchart TB
    subgraph VERBS["THE 5 SEMANTIC VERBS"]
        direction TB

        subgraph AI["AI (Non-Deterministic)"]
            INFER["infer:<br/>LLM Inference"]
            AGENT["agent:<br/>Multi-turn Loop"]
        end

        subgraph DET["Deterministic"]
            EXEC["exec:<br/>Shell Command"]
            FETCH["fetch:<br/>HTTP Request"]
        end

        subgraph MCP["MCP Protocol"]
            INVOKE["invoke:<br/>Tool Call"]
        end
    end

    INFER --> |"prompt"| LLM["LLM Provider<br/>(rig-core)"]
    AGENT --> |"tools"| LLM
    EXEC --> |"sh -c"| SHELL["Shell"]
    FETCH --> |"reqwest"| HTTP["HTTP Client"]
    INVOKE --> |"rmcp"| NOVANET["NovaNet MCP"]

    style INFER fill:#7c3aed,color:#fff
    style AGENT fill:#7c3aed,color:#fff
    style EXEC fill:#16a34a,color:#fff
    style FETCH fill:#16a34a,color:#fff
    style INVOKE fill:#0284c7,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  THE 5 SEMANTIC VERBS                                                       │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │   infer:    │  │   exec:     │  │   fetch:    │  │  invoke:    │        │
│  │             │  │             │  │             │  │             │        │
│  │  LLM text   │  │   Shell     │  │    HTTP     │  │  MCP tool   │        │
│  │ generation  │  │  command    │  │  request    │  │    call     │        │
│  │             │  │             │  │             │  │             │        │
│  │    [AI]     │  │   [DET]     │  │    [DET]    │  │   [MCP]     │        │
│  └─────────────┘  └─────────────┘  └─────────────┘  └─────────────┘        │
│                                                                             │
│  ┌───────────────────────────────────────────────────────────────┐         │
│  │                         agent:                                 │         │
│  │                                                                │         │
│  │     Multi-turn agentic loop with tool calling [AI + MCP]      │         │
│  │                                                                │         │
│  └───────────────────────────────────────────────────────────────┘         │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

| Verb | Purpose | Deterministic | Use Case |
|------|---------|---------------|----------|
| `infer:` | LLM inference | No | Text generation, analysis |
| `exec:` | Shell command | Yes | Scripts, system calls |
| `fetch:` | HTTP request | Yes | API calls, data retrieval |
| `invoke:` | MCP tool call | Depends | NovaNet knowledge access |
| `agent:` | Multi-turn loop | No | Complex reasoning with tools |

### 4.1 infer: Verb

One-shot LLM call for text generation.

```yaml
- id: summarize
  use:
    content: fetch_article
  infer:
    prompt: |
      Summarize the following article:

      {{use.content}}

      Provide a 3-sentence summary.
    provider: claude  # Optional override
    model: claude-sonnet-4-6  # Optional override
```

**InferParams Structure:**

```rust
pub struct InferParams {
    pub prompt: String,             // Required: The prompt (supports templates)
    pub provider: Option<String>,   // Override workflow provider
    pub model: Option<String>,      // Override workflow model
}
```

**Events Emitted:**
- `TemplateResolved` - Template variables resolved
- `ProviderCalled` - LLM call initiated
- `ProviderResponded` - Response received

### 4.2 exec: Verb

Shell command execution.

```yaml
- id: build
  exec:
    command: "npm run build && npm test"
```

```yaml
- id: process
  use:
    input: previous_task.filename
  exec:
    command: "python process.py {{use.input}}"
```

**ExecParams Structure:**

```rust
pub struct ExecParams {
    pub command: String,  // Shell command (runs via sh -c)
}
```

**Behavior:**
- Executed via `sh -c` on Unix systems
- Timeout: 120 seconds (configurable via constants)
- Stdout returned as output
- Non-zero exit code = task failure

### 4.3 fetch: Verb

HTTP request with full method support.

```yaml
- id: get_data
  fetch:
    url: "https://api.example.com/data"
    method: GET

- id: post_data
  use:
    payload: prepare_payload
  fetch:
    url: "https://api.example.com/submit"
    method: POST
    headers:
      Content-Type: application/json
      Authorization: "Bearer {{use.token}}"
    body: "{{use.payload}}"
```

**FetchParams Structure:**

```rust
pub struct FetchParams {
    pub url: String,                        // URL (supports templates)
    pub method: String,                     // GET, POST, PUT, DELETE
    pub headers: FxHashMap<String, String>, // Headers (support templates)
    pub body: Option<String>,               // Request body (supports templates)
}
```

**Behavior:**
- Timeout: 30 seconds
- Connection timeout: 10 seconds
- Redirect limit: 10
- User-Agent: `nika-cli/0.1`

### 4.4 invoke: Verb

MCP tool call or resource read.

```yaml
# Tool call
- id: generate_content
  invoke:
    mcp: novanet
    tool: novanet_generate
    params:
      entity: "qr-code"
      locale: "fr-FR"
      forms: ["text", "title", "abbrev"]

# Resource read
- id: read_entity
  invoke:
    mcp: novanet
    resource: "neo4j://entity/qr-code"
```

**InvokeParams Structure:**

```rust
pub struct InvokeParams {
    pub mcp: String,              // MCP server name (from workflow mcp: config)
    pub tool: Option<String>,     // Tool name (XOR with resource)
    pub params: Option<Value>,    // Tool parameters (JSON)
    pub resource: Option<String>, // Resource URI (XOR with tool)
}
```

**Validation Rules:**
- `tool` and `resource` are mutually exclusive
- One of `tool` or `resource` must be set
- `mcp` must reference a configured server

**Events Emitted:**
- `McpInvoke` - MCP call initiated
- `McpResponse` - Response received (with duration, cached status)

### 4.5 agent: Verb

Multi-turn agentic execution with tool calling.

```yaml
- id: research_agent
  agent:
    prompt: |
      Research the competitive landscape for QR code generators.
      Use the novanet tools to gather entity information.
      When complete, output "RESEARCH_COMPLETE".

    system: "You are a market research analyst."

    provider: claude
    model: claude-sonnet-4-6

    mcp:
      - novanet

    max_turns: 10
    token_budget: 100000

    stop_conditions:
      - "RESEARCH_COMPLETE"
      - "TASK_DONE"

    # v0.4+ Extended Thinking
    extended_thinking: true
    thinking_budget: 8192
```

**AgentParams Structure:**

```rust
pub struct AgentParams {
    pub prompt: String,                    // User prompt
    pub system: Option<String>,            // System prompt
    pub provider: Option<String>,          // Provider override
    pub model: Option<String>,             // Model override
    pub mcp: Vec<String>,                  // MCP servers for tools
    pub max_turns: Option<u32>,            // Max iterations (default: 10, max: 100)
    pub token_budget: Option<u32>,         // Token limit
    pub stop_conditions: Vec<String>,      // Early termination strings
    pub scope: Option<String>,             // Scope preset
    pub extended_thinking: Option<bool>,   // Enable reasoning capture (v0.4+)
    pub thinking_budget: Option<u64>,      // Thinking token budget (default: 4096)
}
```

**Agent Loop Execution:**

```mermaid
stateDiagram-v2
    [*] --> Initialize: AgentBuilder + Tools

    Initialize --> SendPrompt: Start Turn

    SendPrompt --> CheckResponse: LLM Response

    CheckResponse --> ExecuteTool: tool_use
    CheckResponse --> CheckStop: text_response

    ExecuteTool --> AppendResult: Tool Result
    AppendResult --> IncrementTurn: Continue

    IncrementTurn --> CheckMaxTurns: turn++
    CheckMaxTurns --> SendPrompt: turns < max
    CheckMaxTurns --> MaxTurnsReached: turns >= max

    CheckStop --> StopConditionMet: stop_condition found
    CheckStop --> NaturalCompletion: no tool calls

    NaturalCompletion --> [*]
    StopConditionMet --> [*]
    MaxTurnsReached --> [*]
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  AGENT LOOP STATE MACHINE (RigAgentLoop)                                    │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│    ┌──────────────┐                                                         │
│    │  Initialize  │ rig::AgentBuilder + prompt + tools                      │
│    └──────┬───────┘                                                         │
│           │                                                                 │
│           ▼                                                                 │
│    ┌──────────────┐         ┌──────────────┐         ┌──────────────┐      │
│    │ Send Prompt  │────────▶│ Check Resp.  │────────▶│ Execute Tool │      │
│    └──────────────┘         └──────┬───────┘         └──────┬───────┘      │
│           ▲                        │                        │               │
│           │                        │                        │               │
│           │              ┌─────────┴─────────┐              │               │
│           │              │                   │              │               │
│           │              ▼                   ▼              │               │
│           │       ┌────────────┐      ┌────────────┐       │               │
│           │       │ Check Stop │      │ No Tools   │       │               │
│           │       └──────┬─────┘      └─────┬──────┘       │               │
│           │              │                  │               │               │
│           │              ▼                  ▼               │               │
│           │       ┌────────────┐      ┌────────────┐       │               │
│           │       │ STOP MET   │      │ NATURAL    │       │               │
│           │       │ COMPLETION │      │ COMPLETION │       │               │
│           │       └────────────┘      └────────────┘       │               │
│           │                                                 │               │
│           └────────────◄────────────────────────────────────┘               │
│                   (if turns < max_turns)                                    │
│                                                                             │
│  EXIT STATES:                                                               │
│  - NaturalCompletion:  No tool calls in response                           │
│  - StopConditionMet:   Stop keyword found in text                          │
│  - MaxTurnsReached:    Turn limit exceeded                                  │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

**Events Emitted:**
- `AgentStart` - Loop initiated
- `AgentTurn` (for each turn) - With optional metadata including thinking
- `AgentComplete` - Loop finished

**Extended Thinking (v0.4+):**

When `extended_thinking: true`, Claude's reasoning process is captured:

```rust
pub struct AgentTurnMetadata {
    pub thinking: Option<String>,  // Claude's reasoning (if streaming)
    pub response_text: String,     // Main response
    pub input_tokens: u32,
    pub output_tokens: u32,
    pub cache_read_tokens: u32,
    pub stop_reason: String,       // "end_turn", "tool_use", "max_tokens"
}
```

---

## 5. Provider System

### rig-core Integration (v0.4)

Nika uses [rig-core](https://github.com/0xPlaygrounds/rig) v0.31 for LLM providers:

```rust
// RigProvider wraps rig-core clients
pub enum RigProvider {
    Claude(anthropic::Client),
    OpenAI(openai::Client),
}

impl RigProvider {
    pub fn claude() -> Self { ... }    // From ANTHROPIC_API_KEY
    pub fn openai() -> Self { ... }    // From OPENAI_API_KEY

    pub async fn infer(&self, prompt: &str, model: Option<&str>) -> Result<String> {
        // Uses rig-core's completion API
    }
}
```

### Provider Configuration

**Environment Variables:**

| Provider | Variable | Description |
|----------|----------|-------------|
| Claude | `ANTHROPIC_API_KEY` | Anthropic API key |
| OpenAI | `OPENAI_API_KEY` | OpenAI API key |

**Workflow Override:**

```yaml
provider: claude          # Workflow default
model: claude-sonnet-4-6

tasks:
  - id: premium_task
    infer:
      prompt: "Complex task"
      provider: claude    # Task override
      model: claude-opus-4-20250514  # Use premium model
```

### NikaMcpTool

MCP tools are exposed to rig agents via `NikaMcpTool`:

```rust
/// Wraps MCP tool for rig's ToolDyn trait
pub struct NikaMcpTool {
    def: NikaMcpToolDef,
    client: Arc<McpClient>,
}

impl ToolDyn for NikaMcpTool {
    fn name(&self) -> String { ... }
    fn definition(&self) -> ToolDefinition { ... }
    async fn call(&self, input: Value) -> Result<Value> {
        // Delegates to McpClient.call_tool()
    }
}
```

### v0.4 Migration: Removed Legacy Code

The following files were **permanently deleted** in v0.4 (replaced by rig-core):

| Removed File | Lines | Replacement |
|--------------|-------|-------------|
| `provider/claude.rs` | ~400 | `RigProvider::claude()` |
| `provider/openai.rs` | ~350 | `RigProvider::openai()` |
| `provider/types.rs` | ~200 | rig::completion types in `mod.rs` |
| `runtime/agent_loop.rs` | ~600 | `RigAgentLoop` in `rig_agent_loop.rs` |
| `resilience/` module (4 files) | ~800 | rig-core built-in retry |

**Total removed:** ~2,350 lines of code

**Why rig-core?**
- Native `rmcp` v0.16 integration via `.rmcp_tools()`
- 20+ built-in LLM providers (Anthropic, OpenAI, Cohere, Mistral, etc.)
- Built-in retry, streaming, and agent workflows
- Active maintenance and community support

**Migration for existing code:**

```rust
// Before (v0.3)
use nika::provider::ClaudeProvider;
let provider = ClaudeProvider::new()?;
let result = provider.generate("prompt", None).await?;

// After (v0.4)
use nika::provider::rig::RigProvider;
let provider = RigProvider::claude()?;
let result = provider.infer("prompt", None).await?;
```

---

## 6. MCP Integration

### Zero Cypher Rule (ADR-003)

Nika connects to NovaNet **exclusively via MCP**. No direct Neo4j access.

```mermaid
sequenceDiagram
    participant W as Nika Workflow
    participant E as TaskExecutor
    participant MC as McpClient
    participant MS as NovaNet MCP Server
    participant N as Neo4j

    W->>E: invoke: novanet_generate
    E->>MC: call_tool("novanet_generate", params)
    MC->>MS: MCP Protocol Request
    MS->>N: Cypher Query
    N-->>MS: Graph Data
    MS-->>MC: MCP Response
    MC-->>E: ToolCallResult
    E-->>W: Task Output

    Note over W,N: Zero Cypher Rule: Nika never touches Neo4j directly
```

```
┌──────────┐     MCP Protocol     ┌──────────────┐     Cypher     ┌────────┐
│   Nika   │ ──────────────────► │ NovaNet MCP  │ ─────────────► │ Neo4j  │
│ (Client) │                      │   (Server)   │                │   DB   │
└──────────┘                      └──────────────┘                └────────┘
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  MCP INTEGRATION FLOW                                                       │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  1. Workflow defines MCP server config                                      │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  mcp:                                                                │   │
│  │    novanet:                                                          │   │
│  │      command: cargo run -p novanet-mcp                               │   │
│  │      env: { NEO4J_URI: bolt://localhost:7687 }                       │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  2. McpClient spawns server process on first use                           │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  McpClient::new(config) → connect() → list_tools()                   │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  3. invoke: verb calls MCP tools                                            │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  TaskExecutor → McpClient.call_tool(name, params) → Response         │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  4. agent: verb exposes tools via NikaMcpTool                              │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  RigAgentLoop → rig::AgentBuilder.tools([NikaMcpTool]) → Agent       │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### McpClient

```rust
pub struct McpClient {
    name: String,
    connected: AtomicBool,
    is_mock: bool,
    adapter: Option<RmcpClientAdapter>,
}

impl McpClient {
    // Create from config
    pub fn new(config: McpConfig) -> Result<Self>;

    // Testing
    pub fn mock(name: &str) -> Self;

    // Operations
    pub async fn connect(&self) -> Result<()>;
    pub async fn call_tool(&self, name: &str, params: Value) -> Result<ToolCallResult>;
    pub async fn read_resource(&self, uri: &str) -> Result<ResourceContent>;
    pub async fn list_tools(&self) -> Result<Vec<ToolDefinition>>;

    // Retry logic with reconnection
    pub async fn reconnect(&self) -> Result<()>;
}
```

### MCP Configuration

```yaml
mcp:
  novanet:
    command: cargo
    args:
      - run
      - --manifest-path
      - ../novanet/tools/novanet-mcp/Cargo.toml
    env:
      NEO4J_URI: bolt://localhost:7687
      NEO4J_USER: neo4j
      NEO4J_PASSWORD: novanetpassword
    cwd: /optional/working/dir
```

### Available NovaNet MCP Tools

| Tool | Purpose |
|------|---------|
| `novanet_describe` | Describe schema (nodes, arcs) |
| `novanet_generate` | Generate native content |
| `novanet_traverse` | Graph traversal |
| `novanet_assemble` | Build context |
| `novanet_atoms` | Knowledge atoms |
| `novanet_search` | Entity search |
| `novanet_query` | Advanced queries |

### Mock Mode

For testing without NovaNet:

```rust
// Create mock client
let client = McpClient::mock("novanet");
assert!(client.is_connected());

// Mock responses
// - novanet_describe: {"nodes": 61, "arcs": 182, ...}
// - novanet_generate: Entity context with locale
// - Other tools: Generic success response
```

---

## 7. Data Binding System

### use: Block Syntax

Data flows between tasks via the `use:` block:

```yaml
tasks:
  - id: fetch_data
    fetch:
      url: "https://api.example.com/data"
    output:
      format: json

  - id: process
    use:
      data: fetch_data                     # Entire output
      name: fetch_data.user.name           # Nested path
      score: fetch_data.score ?? 0         # With default
      tags: 'fetch_data.tags ?? ["default"]'  # Complex default
    infer:
      prompt: |
        Process user {{use.name}} with score {{use.score}}.
        Tags: {{use.tags}}

flows:
  - source: fetch_data
    target: process
```

### UseEntry Parsing

```rust
pub struct UseEntry {
    pub path: String,           // "task.field.subfield"
    pub default: Option<Value>, // Fallback value
}

// Parsing rules:
// "task.path"           -> UseEntry { path: "task.path", default: None }
// "task.path ?? 0"      -> UseEntry { path: "task.path", default: Some(0) }
// 'task.path ?? "str"'  -> UseEntry { path: "task.path", default: Some("str") }
// 'task ?? {"a": 1}'    -> UseEntry { path: "task", default: Some({"a": 1}) }
```

### Template Resolution

Templates `{{use.alias}}` are resolved at execution time:

```rust
pub fn template_resolve(
    template: &str,
    bindings: &ResolvedBindings,
) -> Result<Cow<str>, NikaError>;

// Example:
// Template: "Hello {{use.name}}, score: {{use.score}}"
// Bindings: { "name": "Alice", "score": 95 }
// Result: "Hello Alice, score: 95"
```

### JSONPath Support

Limited JSONPath subset for nested access:

```yaml
use:
  title: fetch_data.response.items[0].title
  count: fetch_data.$.data.count  # $ prefix optional
```

Supported patterns:
- `task` - Entire output
- `task.field` - Object field
- `task.field.nested` - Nested field
- `task.array[0]` - Array index
- `task.array[0].field` - Combined

---

## 8. DAG Execution

### DAG Overview

```mermaid
flowchart TB
    subgraph DAG["DAG EXECUTION"]
        direction TB

        A["Task A<br/>(fetch)"] --> B["Task B<br/>(infer)"]
        A --> C["Task C<br/>(invoke)"]
        B --> D["Task D<br/>(agent)"]
        C --> D
    end

    subgraph TOPO["Topological Sort"]
        direction LR
        O1["1. A"] --> O2["2. B, C"] --> O3["3. D"]
    end

    DAG --> TOPO

    style A fill:#0d9488,color:#fff
    style B fill:#7c3aed,color:#fff
    style C fill:#0284c7,color:#fff
    style D fill:#dc2626,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  DAG EXECUTION MODEL                                                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  WORKFLOW DEFINITION:                                                       │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  flows:                                                              │   │
│  │    - source: task_a                                                  │   │
│  │      target: [task_b, task_c]    # Fan-out                          │   │
│  │    - source: [task_b, task_c]                                        │   │
│  │      target: task_d              # Fan-in                            │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  VISUAL REPRESENTATION:                                                     │
│                                                                             │
│               task_a                                                        │
│              /      \                                                       │
│             ▼        ▼                                                      │
│         task_b    task_c                                                    │
│             \      /                                                        │
│              ▼    ▼                                                         │
│               task_d                                                        │
│                                                                             │
│  TOPOLOGICAL ORDER: [task_a, task_b, task_c, task_d]                       │
│  (task_b and task_c can execute in parallel after task_a)                  │
│                                                                             │
│  CYCLE DETECTION: Kahn's Algorithm (O(V + E))                              │
│  - Remove nodes with no incoming edges                                      │
│  - Repeat until graph is empty (success) or stuck (cycle)                  │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Flow Definition

```yaml
flows:
  # Simple edge
  - source: task_a
    target: task_b

  # Fan-out
  - source: task_a
    target: [task_b, task_c, task_d]

  # Fan-in
  - source: [task_b, task_c, task_d]
    target: task_e
```

### Topological Sort

Tasks are executed in topological order:

```
Given: A → B → C
       A → D → C

Execution order: A, B, D, C (or A, D, B, C)
```

### Cycle Detection

Cycles are detected during validation:

```yaml
# ERROR: Cycle detected
flows:
  - source: task_a
    target: task_b
  - source: task_b
    target: task_c
  - source: task_c
    target: task_a  # Creates cycle!
```

Error: `[NIKA-020] Cycle detected in DAG: task_a -> task_b -> task_c -> task_a`

### Dependency Validation

Use block references are validated against the DAG:

```yaml
tasks:
  - id: task_a
    exec: { command: "echo a" }

  - id: task_b
    use:
      data: task_c  # ERROR: task_c is not upstream of task_b
    exec: { command: "echo {{use.data}}" }

  - id: task_c
    exec: { command: "echo c" }

flows:
  - source: task_a
    target: task_b
  - source: task_b
    target: task_c
```

Error: `[NIKA-081] use.data.from='task_c' is not upstream of task 'task_b'`

---

## 9. Event System

### Event Flow Overview

```mermaid
flowchart TB
    subgraph SOURCES["Event Sources"]
        WF["Workflow<br/>Started/Completed/Failed"]
        TK["Task<br/>Scheduled/Started/Completed/Failed"]
        PR["Provider<br/>Called/Responded"]
        MC["MCP<br/>Invoke/Response"]
        AG["Agent<br/>Start/Turn/Complete"]
    end

    subgraph LOG["EventLog"]
        direction TB
        EV["events: Vec&lt;Event&gt;"]
        BC["broadcast_tx"]
    end

    subgraph CONSUMERS["Consumers"]
        TR["TraceWriter<br/>.nika/traces/*.ndjson"]
        TUI["TUI Panels<br/>Real-time Updates"]
        API["Runner<br/>Progress Tracking"]
    end

    WF --> LOG
    TK --> LOG
    PR --> LOG
    MC --> LOG
    AG --> LOG

    LOG --> TR
    LOG --> TUI
    LOG --> API

    style LOG fill:#7c3aed,color:#fff
    style SOURCES fill:#0d9488,color:#fff
    style CONSUMERS fill:#16a34a,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  EVENT SYSTEM ARCHITECTURE                                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  SOURCES                         EVENTLOG                    CONSUMERS      │
│  ┌─────────┐                                                                │
│  │Workflow │──┐                ┌─────────────┐          ┌─────────────┐    │
│  │ Events  │  │                │             │          │ TraceWriter │    │
│  └─────────┘  │   emit()       │  EventLog   │  recv()  │   (NDJSON)  │    │
│  ┌─────────┐  │ ─────────────▶ │             │ ───────▶ └─────────────┘    │
│  │  Task   │──┤                │  - events   │          ┌─────────────┐    │
│  │ Events  │  │                │  - broadcast│  recv()  │     TUI     │    │
│  └─────────┘  │                │             │ ───────▶ │   (panels)  │    │
│  ┌─────────┐  │                └─────────────┘          └─────────────┘    │
│  │Provider │──┤                                         ┌─────────────┐    │
│  │ Events  │  │                                  recv() │   Runner    │    │
│  └─────────┘  │                               ───────▶  │  (progress) │    │
│  ┌─────────┐  │                                         └─────────────┘    │
│  │  MCP    │──┤                                                             │
│  │ Events  │  │                                                             │
│  └─────────┘  │                                                             │
│  ┌─────────┐  │                                                             │
│  │ Agent   │──┘                                                             │
│  │ Events  │                                                                │
│  └─────────┘                                                                │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### EventKind Variants (16+)

```rust
pub enum EventKind {
    // Workflow Level (3)
    WorkflowStarted { task_count, generation_id, workflow_hash, nika_version },
    WorkflowCompleted { final_output, total_duration_ms },
    WorkflowFailed { error, failed_task },

    // Task Level (4)
    TaskScheduled { task_id, dependencies },
    TaskStarted { task_id, inputs },
    TaskCompleted { task_id, output, duration_ms },
    TaskFailed { task_id, error, duration_ms },

    // Fine-Grained (3)
    TemplateResolved { task_id, template, result },
    ProviderCalled { task_id, provider, model, prompt_len },
    ProviderResponded { task_id, request_id, input_tokens, output_tokens, ... },

    // Context Assembly (1)
    ContextAssembled { task_id, sources, excluded, total_tokens, budget_used_pct, truncated },

    // MCP Events (2)
    McpInvoke { task_id, call_id, mcp_server, tool, resource },
    McpResponse { task_id, call_id, output_len, duration_ms, cached, is_error },

    // Agent Events (3)
    AgentStart { task_id, max_turns, mcp_servers },
    AgentTurn { task_id, turn_index, kind, metadata },  // v0.4.1: includes thinking
    AgentComplete { task_id, turns, stop_reason },
}
```

### EventLog

Thread-safe, append-only event log:

```rust
pub struct EventLog {
    events: Arc<RwLock<Vec<Event>>>,
    start_time: Instant,
    next_id: Arc<AtomicU64>,
    broadcast_tx: Option<broadcast::Sender<Event>>,
}

impl EventLog {
    pub fn new() -> Self;
    pub fn new_with_broadcast() -> (Self, broadcast::Receiver<Event>);

    pub fn emit(&self, kind: EventKind) -> u64;
    pub fn events(&self) -> Vec<Event>;
    pub fn filter_task(&self, task_id: &str) -> Vec<Event>;
    pub fn workflow_events(&self) -> Vec<Event>;
}
```

### Event Structure

```rust
pub struct Event {
    pub id: u64,              // Monotonic sequence ID
    pub timestamp_ms: u64,    // Time since workflow start
    pub kind: EventKind,      // Event type and data
}
```

---

## 10. Observability and Traces

### NDJSON Trace Files

Execution traces are written to `.nika/traces/`:

```
.nika/
└── traces/
    ├── 2026-02-19T14-30-45-a1b2.ndjson
    ├── 2026-02-19T14-25-12-c3d4.ndjson
    └── ...
```

### Trace Format

Each line is a JSON event:

```json
{"id":0,"timestamp_ms":0,"kind":{"type":"workflow_started","task_count":3,"generation_id":"2026-02-19T14-30-45-a1b2","workflow_hash":"xxh3:abc123...","nika_version":"0.4.1"}}
{"id":1,"timestamp_ms":5,"kind":{"type":"task_started","task_id":"fetch_context","inputs":{}}}
{"id":2,"timestamp_ms":150,"kind":{"type":"mcp_invoke","task_id":"fetch_context","call_id":"uuid-1234","mcp_server":"novanet","tool":"novanet_generate"}}
{"id":3,"timestamp_ms":500,"kind":{"type":"mcp_response","task_id":"fetch_context","call_id":"uuid-1234","output_len":1234,"duration_ms":345,"cached":false,"is_error":false}}
{"id":4,"timestamp_ms":510,"kind":{"type":"task_completed","task_id":"fetch_context","output":{...},"duration_ms":505}}
...
```

### TraceWriter

```rust
pub struct TraceWriter {
    writer: Arc<Mutex<BufWriter<File>>>,
    path: PathBuf,
}

impl TraceWriter {
    pub fn new(generation_id: &str) -> Result<Self>;
    pub fn write_event(&self, event: &Event) -> Result<()>;
    pub fn write_all(&self, event_log: &EventLog) -> Result<()>;
}

pub fn generate_generation_id() -> String;
// Format: "YYYY-MM-DDTHH-MM-SS-XXXX" (random hex suffix)

pub fn calculate_workflow_hash(yaml: &str) -> String;
// Format: "xxh3:XXXXXXXXXXXXXXXX"
```

### Trace Commands

```bash
# List all traces
nika trace list
nika trace list --limit 5

# Show trace details
nika trace show 2026-02-19T14-30-45-a1b2

# Export trace
nika trace export 2026-02-19T14-30-45 --format json --output trace.json
nika trace export 2026-02-19T14-30-45 --format yaml

# Clean old traces
nika trace clean --keep 10
```

---

## 11. for_each Parallelism

### Parallel Execution Overview

```mermaid
flowchart TB
    subgraph FOREACH["for_each: [A, B, C, D]"]
        direction TB
        FE["for_each Parser"]
    end

    subgraph POOL["Semaphore Pool (concurrency: 2)"]
        direction LR
        S1["Slot 1"]
        S2["Slot 2"]
    end

    subgraph JOINSET["tokio JoinSet"]
        direction TB
        T1["Task A"]
        T2["Task B"]
        T3["Task C"]
        T4["Task D"]
    end

    subgraph RESULTS["Results (ordered)"]
        R["[A_result, B_result, C_result, D_result]"]
    end

    FE --> POOL
    POOL --> JOINSET
    JOINSET --> RESULTS

    style FOREACH fill:#0d9488,color:#fff
    style POOL fill:#7c3aed,color:#fff
    style JOINSET fill:#0284c7,color:#fff
    style RESULTS fill:#16a34a,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  for_each PARALLEL EXECUTION                                                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  INPUT: for_each: ["A", "B", "C", "D"]                                      │
│         concurrency: 2                                                      │
│                                                                             │
│  TIME ──────────────────────────────────────────────────────────────────▶   │
│                                                                             │
│  Slot 1:  ┌──────────┐          ┌──────────┐                               │
│           │  Task A  │          │  Task C  │                               │
│           └──────────┘          └──────────┘                               │
│                                                                             │
│  Slot 2:  ┌──────────┐          ┌──────────┐                               │
│           │  Task B  │          │  Task D  │                               │
│           └──────────┘          └──────────┘                               │
│                                                                             │
│  RESULT: [A_result, B_result, C_result, D_result]  (original order)        │
│                                                                             │
│  ─────────────────────────────────────────────────────────────────────────  │
│                                                                             │
│  COMPARISON:                                                                │
│                                                                             │
│  concurrency=1 (sequential):                                                │
│    [A]───▶[B]───▶[C]───▶[D]                      Total: 4 * avg_time       │
│                                                                             │
│  concurrency=2:                                                             │
│    [A]   [C]                                                                │
│    [B]───▶[D]                                     Total: 2 * avg_time       │
│                                                                             │
│  concurrency=4 (all parallel):                                              │
│    [A]                                                                      │
│    [B]                                            Total: 1 * max_time       │
│    [C]                                                                      │
│    [D]                                                                      │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Basic Syntax (Flat Format)

```yaml
tasks:
  - id: process_locales
    for_each: ["en-US", "fr-FR", "de-DE", "ja-JP"]  # Array or binding
    as: locale                                        # Loop variable name
    concurrency: 4                                    # Max parallel
    fail_fast: true                                   # Stop on error
    infer:
      prompt: "Generate content for {{use.locale}}"
```

### Binding Expressions

```yaml
tasks:
  - id: fetch_entities
    invoke:
      mcp: novanet
      tool: novanet_search
      params:
        category: "products"

  - id: process_entities
    use:
      entities: fetch_entities.results
    for_each: "$entities"           # Binding syntax 1
    # for_each: "{{use.entities}}"  # Binding syntax 2 (also works)
    as: entity
    concurrency: 5
    fail_fast: false
    invoke:
      mcp: novanet
      tool: novanet_generate
      params:
        entity: "{{use.entity.key}}"
        locale: "en-US"

flows:
  - source: fetch_entities
    target: process_entities
```

### Configuration Options

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `for_each` | array/binding | required | Array literal or binding expression |
| `as` | string | `"item"` | Loop variable name |
| `concurrency` | integer | `1` | Max parallel tasks |
| `fail_fast` | boolean | `true` | Stop on first error |

> **Note:** Binding expressions are resolved at runtime. Use `$name` or `{{use.name}}`.

### Implementation

Uses `tokio::spawn` with `JoinSet` for true concurrent execution:

```rust
// Simplified executor logic
let mut join_set = JoinSet::new();
let semaphore = Arc::new(Semaphore::new(concurrency));

for item in items {
    let permit = semaphore.clone().acquire_owned().await?;
    join_set.spawn(async move {
        let result = execute_task(item).await;
        drop(permit);
        result
    });
}

// Collect results in order
let results = join_set.join_all().await;
```

### Execution Patterns

```
concurrency=1 (sequential):
  [Item 1] → [Item 2] → [Item 3] → [Item 4]

concurrency=2:
  [Item 1]   [Item 3]
  [Item 2] → [Item 4]

concurrency=4 (all parallel):
  [Item 1]
  [Item 2]
  [Item 3]
  [Item 4]
```

---

## 12. Terminal UI (TUI)

### Launching TUI

```bash
cargo run -- tui workflow.nika.yaml
```

### 4-Panel Layout

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  NIKA TUI v0.4.1                                    [?] Help  [q] Quit     │
├───────────────────────────────────┬─────────────────────────────────────────┤
│                                   │                                         │
│  PROGRESS (33%)                   │  CONTEXT                                │
│  ━━━━━━━━━░░░░░░░░░░░░░░░░░      │                                         │
│                                   │  task: generate_content                 │
│  Tasks:                           │  entity: qr-code                        │
│  ✓ fetch_context     [2.1s]      │  locale: fr-FR                          │
│  ● polish_content    [running]    │                                         │
│  ○ validate_quality  [pending]    │  MCP Calls:                             │
│                                   │  └─ novanet_generate (345ms)            │
│                                   │                                         │
├───────────────────────────────────┼─────────────────────────────────────────┤
│                                   │                                         │
│  DAG                              │  REASONING                              │
│                                   │                                         │
│  fetch_context ─────┐             │  <thinking>                             │
│                     ├──▶ polish   │  Let me analyze the entity context...   │
│  (MCP: novanet)     │    content  │  The denomination_forms provide:        │
│                     │             │  - text: "code QR"                      │
│  validate_quality ◀─┘             │  - title: "Code QR"                     │
│  (waiting)                        │  </thinking>                            │
│                                   │                                         │
└───────────────────────────────────┴─────────────────────────────────────────┘
```

### Keybindings

| Key | Action |
|-----|--------|
| `q` / `Esc` | Quit |
| `?` / `h` | Toggle help |
| `Tab` | Cycle panels |
| `` / `` | Scroll within panel |
| `` / `` | Navigate timeline |
| `Enter` | Expand/collapse item |
| `r` | Restart workflow |

### Real-Time Event Streaming

TUI subscribes to EventLog broadcasts:

```rust
let (event_log, rx) = EventLog::new_with_broadcast();

// TUI receives events via rx
tokio::spawn(async move {
    while let Ok(event) = rx.recv().await {
        update_ui(event);
    }
});
```

---

## 13. CLI Commands

### Quick Reference

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  NIKA CLI COMMANDS                                                          │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  EXECUTION                                                                  │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  nika run <file>            Execute workflow                        │   │
│  │  nika run <file> --provider Execute with specific provider          │   │
│  │  nika run <file> --model    Execute with specific model             │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  VALIDATION                                                                 │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  nika validate <file>       Parse and validate workflow             │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  INTERACTIVE                                                                │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  nika tui <file>            Launch 4-panel TUI                      │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  TRACES                                                                     │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  nika trace list            List all traces                         │   │
│  │  nika trace show <id>       Display trace events                    │   │
│  │  nika trace export <id>     Export trace to file                    │   │
│  │  nika trace clean           Remove old traces                       │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Command Reference

| Command | Description | Options |
|---------|-------------|---------|
| `nika run <file>` | Execute workflow | `--provider`, `--model` |
| `nika validate <file>` | Parse and validate | none |
| `nika tui <file>` | Launch interactive TUI | none |
| `nika trace list` | List all traces | `--limit <n>` |
| `nika trace show <id>` | Display trace events | none |
| `nika trace export <id>` | Export trace | `--format`, `--output` |
| `nika trace clean` | Remove old traces | `--keep <n>` |

```bash
# Run workflow
nika run <file> [--provider <p>] [--model <m>]

# Validate workflow (parse only)
nika validate <file>

# Interactive TUI
nika tui <file>

# Trace management
nika trace list [--limit <n>]
nika trace show <id>
nika trace export <id> [--format json|yaml] [--output <file>]
nika trace clean [--keep <n>]
```

### Examples

```bash
# Run with default provider
cargo run -- run examples/uc1-entity-generation.nika.yaml

# Run with mock provider (no API calls)
cargo run -- run examples/uc1-entity-generation.nika.yaml --provider mock

# Run with specific model
cargo run -- run workflow.nika.yaml --provider claude --model claude-opus-4-20250514

# Validate before running
cargo run -- validate examples/uc1-entity-generation.nika.yaml

# Launch TUI
cargo run -- tui examples/uc1-entity-generation.nika.yaml

# List recent traces
cargo run -- trace list --limit 5

# Show trace events
cargo run -- trace show 2026-02-19T14-30-45-a1b2

# Export to JSON
cargo run -- trace export 2026-02-19T14-30-45 --format json --output trace.json
```

---

## 14. Error Handling

### Error Architecture

```mermaid
flowchart TB
    subgraph ERRORS["NikaError (40+ variants)"]
        direction TB

        subgraph WF["Workflow (000-009)"]
            W1["ParseError"]
            W2["ValidationError"]
        end

        subgraph DAG_E["DAG (020-029)"]
            D1["CycleDetected"]
            D2["MissingDependency"]
        end

        subgraph PROV["Provider (030-039)"]
            P1["MissingApiKey"]
            P2["ProviderError"]
        end

        subgraph MCP_E["MCP (100-109)"]
            M1["McpNotConnected"]
            M2["McpNotConfigured"]
        end

        subgraph AGENT_E["Agent (110-119)"]
            A1["MaxTurnsExceeded"]
            A2["AgentFailed"]
        end
    end

    ERRORS --> FIX["FixSuggestion Trait"]
    FIX --> CLI["CLI Display"]

    style WF fill:#0d9488,color:#fff
    style DAG_E fill:#0284c7,color:#fff
    style PROV fill:#7c3aed,color:#fff
    style MCP_E fill:#dc2626,color:#fff
    style AGENT_E fill:#ea580c,color:#fff
```

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  ERROR CODE ARCHITECTURE                                                    │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌────────────┐   ┌────────────┐   ┌────────────┐   ┌────────────┐        │
│  │  000-009   │   │  010-019   │   │  020-029   │   │  030-039   │        │
│  │  Workflow  │   │   Schema   │   │    DAG     │   │  Provider  │        │
│  └────────────┘   └────────────┘   └────────────┘   └────────────┘        │
│                                                                             │
│  ┌────────────┐   ┌────────────┐   ┌────────────┐   ┌────────────┐        │
│  │  040-049   │   │  050-059   │   │  060-069   │   │  070-079   │        │
│  │  Template  │   │   Path     │   │   Output   │   │ Use Block  │        │
│  └────────────┘   └────────────┘   └────────────┘   └────────────┘        │
│                                                                             │
│  ┌────────────┐   ┌────────────┐   ┌────────────┐   ┌────────────┐        │
│  │  080-089   │   │  090-099   │   │  100-109   │   │  110-119   │        │
│  │ DAG Valid. │   │  JSONPath  │   │    MCP     │   │   Agent    │        │
│  └────────────┘   └────────────┘   └────────────┘   └────────────┘        │
│                                                                             │
│  ┌────────────┐   ┌────────────┐                                           │
│  │  120-129   │   │  130-139   │                                           │
│  │ (Reserved) │   │    TUI     │                                           │
│  └────────────┘   └────────────┘                                           │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Error Code Ranges

| Range | Category | Key Errors |
|-------|----------|------------|
| `NIKA-000-009` | Workflow errors | ParseError, WorkflowFailed |
| `NIKA-010-019` | Schema/validation errors | InvalidSchema, UnsupportedVersion |
| `NIKA-020-029` | DAG errors | CycleDetected, InvalidFlow |
| `NIKA-030-039` | Provider errors | MissingApiKey, ProviderError |
| `NIKA-040-049` | Template/binding errors | TemplateError, InvalidBinding |
| `NIKA-050-059` | Path/task errors | TaskNotFound, PathResolution |
| `NIKA-060-069` | Output errors | InvalidFormat, SchemaValidation |
| `NIKA-070-079` | Use block validation | UnknownAlias, InvalidPath |
| `NIKA-080-089` | DAG validation | NotUpstream, MissingDependency |
| `NIKA-090-099` | JSONPath/IO errors | JSONPathError, IOError |
| `NIKA-100-109` | MCP errors | McpNotConnected, McpNotConfigured |
| `NIKA-110-119` | Agent errors | MaxTurnsExceeded, AgentFailed |
| `NIKA-120-129` | (Reserved) | Unused - resilience module removed in v0.4 |
| `NIKA-130-139` | TUI errors | RenderError, InputError |

### Common Errors

| Code | Error | Fix |
|------|-------|-----|
| `NIKA-001` | Parse error | Check YAML syntax |
| `NIKA-010` | Invalid schema | Use `nika/workflow@0.4` (or 0.1-0.3 for older features) |
| `NIKA-020` | Cycle detected | Remove circular dependencies |
| `NIKA-032` | Missing API key | Set `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` |
| `NIKA-071` | Unknown alias | Declare alias in `use:` block |
| `NIKA-100` | MCP not connected | Check MCP server config |
| `NIKA-105` | MCP not configured | Add server to workflow `mcp:` |
| `NIKA-110` | Max turns exceeded | Increase `max_turns` or simplify task |

### FixSuggestion Trait

```rust
impl FixSuggestion for NikaError {
    fn fix_suggestion(&self) -> Option<&str> {
        match self {
            Self::MissingApiKey { .. } =>
                Some("Set the API key env var (ANTHROPIC_API_KEY or OPENAI_API_KEY)"),
            Self::CycleDetected { .. } =>
                Some("Remove circular dependencies from your workflow"),
            // ...
        }
    }
}
```

CLI displays suggestions:

```
Error: [NIKA-032] Missing API key for provider 'claude'
  Fix: Set the API key env var (ANTHROPIC_API_KEY or OPENAI_API_KEY)
```

---

## 15. Architecture Decision Records

### Core ADRs

| ADR | Title | Key Decision |
|-----|-------|--------------|
| **ADR-001** | 5 Semantic Verbs | Exactly 5 verbs: infer, exec, fetch, invoke, agent |
| **ADR-002** | YAML-First | Workflows as YAML files, not code |
| **ADR-003** | MCP-Only | Zero Cypher Rule - NovaNet via MCP only |

### ADR-001: 5 Semantic Verbs

**Decision:** Nika uses exactly 5 semantic verbs.

**Rationale:**
- Balance simplicity (few verbs) with completeness (all AI patterns)
- Each verb is irreducible:
  - `infer:` - Non-deterministic AI capability
  - `exec:` - Deterministic system integration
  - `fetch:` - HTTP with built-in semantics
  - `invoke:` - MCP protocol, tool-based AI
  - `agent:` - Multi-turn loops with tools

**Rejected alternatives:**
- `transform:` - Use `infer:` with transformation prompt
- `validate:` - Use `exec:` with validation script
- `loop:` - Use `for_each:` modifier instead

### ADR-002: YAML-First

**Decision:** Workflows are defined in YAML files.

**Why YAML over alternatives:**
| Factor | YAML | JSON | TOML | DSL |
|--------|------|------|------|-----|
| Multi-line strings | Excellent | Poor | OK | Excellent |
| Comments | Yes | No | Yes | Yes |
| Industry standard | Yes (K8s, CI) | Yes | Less | No |
| IDE support | Excellent | Excellent | Limited | None |

**Benefits:**
- Static analysis before execution
- DAG visualization from file
- Git-friendly diffs
- Non-programmers can edit

### ADR-003: MCP-Only Integration

**Decision:** Zero Cypher Rule - all NovaNet access via MCP.

**Rationale:**
| Factor | Direct Neo4j | MCP-Only |
|--------|--------------|----------|
| Coupling | Tight | Loose |
| Schema changes | Break Nika | Transparent |
| Security | Cypher injection risk | Validated tools |
| Caching | Manual | MCP server handles |

**Compliance check:**
```yaml
# WRONG - direct Cypher
- exec:
    command: "cypher-shell 'MATCH (e:Entity) RETURN e'"

# RIGHT - semantic MCP tool
- invoke:
    mcp: novanet
    tool: novanet_describe
```

---

## 16. Development Guide

### Setup

```bash
# Clone and enter directory
cd nika-dev/tools/nika

# Install dependencies
cargo build

# Run tests
cargo test

# Run with coverage
cargo llvm-cov nextest
```

### Testing Strategy

1. **Unit tests:** In-file `#[cfg(test)]` modules
2. **Integration tests:** `tests/` directory
3. **Snapshot tests:** `insta` for YAML/JSON outputs
4. **Property tests:** `proptest` for parser fuzzing

### TDD Workflow

```rust
// 1. Write failing test
#[test]
fn test_parse_workflow_with_for_each() {
    let yaml = r#"
schema: "nika/workflow@0.4"
tasks:
  - id: test
    for_each: ["a", "b"]
    exec: { command: "echo {{use.item}}" }
"#;
    let workflow: Workflow = serde_yaml::from_str(yaml).unwrap();
    assert!(workflow.tasks[0].for_each.is_some());
}

// 2. Run test (fails)
// 3. Implement feature
// 4. Run test (passes)
// 5. Refactor
```

### Code Style

```rust
// Imports: group by std, external, internal
use std::sync::Arc;

use serde::Deserialize;
use tokio::sync::OnceCell;

use crate::error::NikaError;
use crate::event::EventLog;

// Error handling: use NikaError with codes
fn parse_workflow(yaml: &str) -> Result<Workflow, NikaError> {
    serde_yaml::from_str(yaml)
        .map_err(|e| NikaError::ParseError { details: e.to_string() })
}

// Logging: use tracing macros
tracing::info!(task_id = %task_id, "Task completed");
tracing::debug!(provider = %name, model = %model, "Provider called");
```

### Commit Conventions

```
type(scope): description

feat(agent): add extended_thinking support
fix(mcp): handle reconnection on broken pipe
test(binding): add property tests for template resolution
docs(book): add complete YAML schema reference
```

---

## 17. Troubleshooting

### Common Issues

#### "MCP server not configured"

```
Error: [NIKA-105] MCP server 'novanet' not configured in workflow
```

**Solution:** Add MCP configuration to workflow:

```yaml
mcp:
  novanet:
    command: cargo
    args: [run, -p, novanet-mcp]
```

#### "Missing API key"

```
Error: [NIKA-032] Missing API key for provider 'claude'
```

**Solution:** Set environment variable:

```bash
export ANTHROPIC_API_KEY=sk-ant-...
# or
export OPENAI_API_KEY=sk-...
```

#### "Cycle detected in DAG"

```
Error: [NIKA-020] Cycle detected in DAG: a -> b -> c -> a
```

**Solution:** Review flows and remove circular dependencies.

#### "Unknown alias"

```
Error: [NIKA-071] Unknown alias '{{use.data}}' - not declared in use: block
```

**Solution:** Declare the alias:

```yaml
use:
  data: previous_task
infer:
  prompt: "Process {{use.data}}"
```

#### "use.X is not upstream"

```
Error: [NIKA-081] use.data.from='task_c' is not upstream of task 'task_b'
```

**Solution:** Add missing flow:

```yaml
flows:
  - source: task_c
    target: task_b
```

### Debug Tips

1. **Enable verbose logging:**
   ```bash
   RUST_LOG=debug cargo run -- run workflow.nika.yaml
   ```

2. **Use mock provider for testing:**
   ```bash
   cargo run -- run workflow.nika.yaml --provider mock
   ```

3. **Validate before running:**
   ```bash
   cargo run -- validate workflow.nika.yaml
   ```

4. **Check trace files:**
   ```bash
   cargo run -- trace list
   cargo run -- trace show <id>
   ```

5. **Use TUI for real-time observation:**
   ```bash
   cargo run -- tui workflow.nika.yaml
   ```

---

## 18. Examples

### UC1: Entity Generation

```yaml
# examples/uc1-entity-generation.nika.yaml
schema: "nika/workflow@0.4"
provider: claude

mcp:
  novanet:
    command: cargo
    args: [run, -p, novanet-mcp]
    env:
      NEO4J_URI: bolt://localhost:7687

tasks:
  - id: fetch_context
    invoke:
      mcp: novanet
      tool: novanet_generate
      params:
        entity: "qr-code"
        locale: "fr-FR"
        forms: ["text", "title", "abbrev", "url"]
    output:
      format: json

  - id: polish_content
    use:
      ctx: fetch_context
    infer:
      prompt: |
        You are a native French content specialist.

        ENTITY: {{use.ctx.entity}}
        DENOMINATION FORMS: {{use.ctx.denomination_forms}}

        Generate polished EntityNative content in JSON.
    output:
      format: json

  - id: validate_quality
    use:
      original: fetch_context
      polished: polish_content
    infer:
      prompt: |
        Validate the polished content against original forms.

        ORIGINAL: {{use.original.denomination_forms}}
        POLISHED: {{use.polished}}

        Return {"is_valid": true/false, "issues": [], "score": 0-100}
    output:
      format: json

flows:
  - source: fetch_context
    target: polish_content
  - source: fetch_context
    target: validate_quality
  - source: polish_content
    target: validate_quality
```

### UC2: Multi-Locale Generation with for_each

```yaml
# examples/uc2-multi-locale-generation.nika.yaml
schema: "nika/workflow@0.4"
provider: claude

mcp:
  novanet:
    command: cargo
    args: [run, -p, novanet-mcp]

tasks:
  - id: generate_all_locales
    for_each: ["en-US", "fr-FR", "de-DE", "ja-JP", "es-ES"]
    as: locale
    concurrency: 3
    invoke:
      mcp: novanet
      tool: novanet_generate
      params:
        entity: "qr-code"
        locale: "{{use.locale}}"
        forms: ["text", "title"]
    output:
      format: json
```

### UC3: Research Agent with Extended Thinking (v0.4)

```yaml
# examples/v04-reasoning-capture.nika.yaml
schema: "nika/workflow@0.4"
provider: claude

tasks:
  - id: analyze_with_reasoning
    agent:
      prompt: |
        Analyze why QR codes are effective for marketing.
        Think through this step by step before answering.
      extended_thinking: true
      thinking_budget: 8192  # v0.4: configurable (default: 4096)
      model: claude-sonnet-4-6
      max_turns: 1
    output:
      format: text

  - id: summarize
    use:
      analysis: analyze_with_reasoning
    infer:
      prompt: |
        Summarize this analysis in 2 sentences:
        {{use.analysis}}
      model: claude-haiku-4-20250514
    output:
      format: text

flows:
  - source: analyze_with_reasoning
    target: summarize
```

**Extended Thinking Metadata (v0.4.1):**

When `extended_thinking: true`, the agent's reasoning is captured in traces:

```rust
pub struct AgentTurnMetadata {
    pub thinking: Option<String>,  // Claude's <thinking> content
    pub response_text: String,     // Main response
    pub input_tokens: u32,         // v0.4.1: Now correctly tracked
    pub output_tokens: u32,        // v0.4.1: Now correctly tracked
    pub cache_read_tokens: u32,
    pub stop_reason: String,
}
```

---

## Appendix: Complete YAML Schema

```yaml
# Complete Nika Workflow Schema Reference
# Version: nika/workflow@0.4

# ============================================================================
# ROOT STRUCTURE
# ============================================================================

schema: "nika/workflow@0.4"  # Required: Schema version

provider: claude             # Optional: Default provider (claude|openai|mock)
model: claude-sonnet-4-6  # Optional: Default model

# ============================================================================
# MCP SERVER CONFIGURATION
# ============================================================================

mcp:                         # Optional: MCP server definitions
  server_name:               # Server name (used in invoke.mcp)
    command: string          # Required: Command to run
    args:                    # Optional: Command arguments
      - string
    env:                     # Optional: Environment variables
      KEY: value
    cwd: string              # Optional: Working directory

# ============================================================================
# TASKS
# ============================================================================

tasks:                       # Required: Task list
  - id: string               # Required: Unique task identifier

    # Data Binding
    use:                     # Optional: Data binding from other tasks
      alias: task.path                    # Simple path
      alias2: task.path ?? default        # With default value
      alias3: 'task.path ?? {"key": 1}'   # Complex default (quoted)

    # Parallel Iteration (v0.3+)
    for_each: [a, b, c]      # Optional: Array to iterate
    as: item                 # Optional: Loop variable (default: "item")
    concurrency: 5           # Optional: Max parallel (default: 1)
    fail_fast: true          # Optional: Stop on error (default: true)

    # Output Configuration
    output:                  # Optional: Output handling
      format: json           # json | text | yaml
      schema:                # Optional: JSON Schema validation
        type: object
        properties: {}

    # ========================================================================
    # VERBS (exactly one required)
    # ========================================================================

    # infer: LLM Inference
    infer:
      prompt: string         # Required: Prompt with {{use.alias}} templates
      provider: string       # Optional: Override provider
      model: string          # Optional: Override model

    # exec: Shell Command
    exec:
      command: string        # Required: Shell command

    # fetch: HTTP Request
    fetch:
      url: string            # Required: URL with templates
      method: GET            # Optional: GET|POST|PUT|DELETE
      headers:               # Optional: HTTP headers
        Header-Name: value
      body: string           # Optional: Request body

    # invoke: MCP Tool Call
    invoke:
      mcp: string            # Required: MCP server name
      tool: string           # XOR: Tool name
      resource: string       # XOR: Resource URI
      params:                # Optional: Tool parameters (JSON)
        key: value

    # agent: Agentic Execution
    agent:
      prompt: string         # Required: Agent goal
      system: string         # Optional: System prompt
      provider: string       # Optional: Override provider
      model: string          # Optional: Override model
      mcp:                   # Optional: MCP servers for tools
        - server_name
      max_turns: 10          # Optional: Max iterations (1-100)
      token_budget: 100000   # Optional: Token limit
      stop_conditions:       # Optional: Early termination
        - "COMPLETE"
      extended_thinking: true  # Optional: Enable reasoning (v0.4+)
      thinking_budget: 8192    # Optional: Thinking tokens (v0.4+)

# ============================================================================
# FLOWS (DAG EDGES)
# ============================================================================

flows:                       # Optional: Task dependencies
  - source: task_a           # Single or [multiple] sources
    target: task_b           # Single or [multiple] targets
```

---

## References

- **Repository:** `nika-dev/tools/nika/`
- **CLAUDE.md:** `nika-dev/tools/nika/CLAUDE.md`
- **ADRs:** `nika-dev/tools/nika/.claude/rules/adr/`
- **Examples:** `nika-dev/tools/nika/examples/`
- **rig-core:** https://github.com/0xPlaygrounds/rig
- **rmcp:** https://crates.io/crates/rmcp
- **MCP Spec:** https://spec.modelcontextprotocol.io/

---

*This document is the authoritative technical reference for Nika v0.4.1.*