terraphim_orchestrator 1.16.34

AI Dark Factory orchestrator wiring spawner, router, supervisor into a reconciliation loop
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
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

/// Strategy for gating agent spawns.
/// All strategies fail-open: if the check itself fails, the agent spawns anyway.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum PreCheckStrategy {
    /// Always spawn the agent. No gating.
    Always,
    /// Check git diff between last recorded commit and HEAD.
    /// Only spawn if changed files match watch_paths prefixes.
    GitDiff { watch_paths: Vec<String> },
    /// Query latest comments on a Gitea issue. Skip if PASS verdict
    /// and no new commits since.
    GiteaIssue { issue_number: u64 },
    /// Run an arbitrary shell command via sh -c.
    /// Exit 0 + non-empty stdout = Findings; Exit 0 + empty stdout = NoFindings;
    /// Non-zero exit or timeout = Failed (fail-open).
    Shell {
        script: String,
        #[serde(default = "default_pre_check_timeout")]
        timeout_secs: u64,
    },
}

fn default_pre_check_timeout() -> u64 {
    60
}

/// Top-level orchestrator configuration (parsed from TOML).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrchestratorConfig {
    /// Working directory for all agents.
    pub working_dir: PathBuf,
    /// Nightwatch configuration.
    pub nightwatch: NightwatchConfig,
    /// Compound review configuration.
    pub compound_review: CompoundReviewConfig,
    /// Optional workflow configuration for issue-driven mode.
    #[serde(default)]
    pub workflow: Option<WorkflowConfig>,
    /// Agent definitions.
    pub agents: Vec<AgentDefinition>,
    /// Seconds to wait before restarting a Safety agent after it exits.
    #[serde(default = "default_restart_cooldown")]
    pub restart_cooldown_secs: u64,
    /// Maximum number of restarts per Safety agent before giving up.
    #[serde(default = "default_max_restart_count")]
    pub max_restart_count: u32,
    /// Time window for restart budget accounting for Safety agents.
    /// Restart counts older than this window are ignored.
    #[serde(default = "default_restart_budget_window")]
    pub restart_budget_window_secs: u64,
    /// Disk usage percentage threshold (0-100) above which agent spawning is refused.
    /// Set to 100 to disable the guard. Default: 90.
    #[serde(default = "default_disk_usage_threshold")]
    pub disk_usage_threshold: u8,
    /// Reconciliation tick interval in seconds.
    #[serde(default = "default_tick_interval")]
    pub tick_interval_secs: u64,
    /// Default TTL in seconds for handoff buffer entries (None = 86400).
    #[serde(default)]
    pub handoff_buffer_ttl_secs: Option<u64>,
    /// Directory for persona data and configuration files.
    #[serde(default)]
    pub persona_data_dir: Option<PathBuf>,
    /// Directory containing skill definitions (SKILL.md files in subdirectories).
    /// Used to inject skill_chain content into agent prompts.
    #[serde(default)]
    pub skill_data_dir: Option<PathBuf>,
    /// Flow DAG definitions for multi-step workflows.
    #[serde(default)]
    pub flows: Vec<crate::flow::config::FlowDefinition>,
    /// Directory for flow run state persistence.
    #[serde(default)]
    pub flow_state_dir: Option<PathBuf>,
    /// Gitea configuration for posting agent output to issues.
    #[serde(default)]
    pub gitea: Option<GiteaOutputConfig>,
    /// Mention-driven dispatch configuration.
    #[serde(default)]
    pub mentions: Option<MentionConfig>,
    /// Webhook configuration for real-time mention dispatch.
    #[serde(default)]
    pub webhook: Option<WebhookConfig>,
    /// Path to persona role configuration JSON for terraphim-agent.
    #[serde(default)]
    pub role_config_path: Option<PathBuf>,
    /// KG-driven model routing configuration.
    #[serde(default)]
    pub routing: Option<RoutingConfig>,
    /// Quickwit log shipping configuration (only available with quickwit feature).
    #[cfg(feature = "quickwit")]
    #[serde(default)]
    pub quickwit: Option<QuickwitConfig>,
}

/// Configuration for KG-driven model routing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingConfig {
    /// Path to directory containing KG routing rule markdown files.
    pub taxonomy_path: PathBuf,
    /// Provider probe TTL in seconds (default: 300 = 5 minutes).
    #[serde(default = "default_probe_ttl")]
    pub probe_ttl_secs: u64,
    /// Directory for saving probe results JSON (default: ~/.terraphim/benchmark-results).
    #[serde(default)]
    pub probe_results_dir: Option<PathBuf>,
    /// Run provider probes on startup (default: true).
    #[serde(default = "default_true_routing")]
    pub probe_on_startup: bool,
    /// Use RoutingDecisionEngine instead of inline model selection.
    ///
    /// When enabled, `spawn_agent()` delegates model selection to the
    /// control-plane routing engine which combines KG routing, keyword
    /// routing, provider health, budget pressure, and live telemetry
    /// signals (throughput, latency, subscription limits).
    ///
    /// Telemetry data is persisted across restarts and restored on startup.
    ///
    /// Default: `false` (uses inline model selection logic).
    #[serde(default)]
    pub use_routing_engine: bool,
}

fn default_probe_ttl() -> u64 {
    300
}

fn default_true_routing() -> bool {
    true
}

/// Configuration for posting agent output to Gitea issues.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GiteaOutputConfig {
    pub base_url: String,
    pub token: String,
    pub owner: String,
    pub repo: String,
    /// Path to JSON file mapping agent names to Gitea API tokens.
    /// When present, agents post comments under their own Gitea user.
    #[serde(default)]
    pub agent_tokens_path: Option<PathBuf>,
}

/// Configuration for mention-driven dispatch.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MentionConfig {
    /// Poll every N reconciliation ticks (default 2).
    #[serde(default = "default_poll_modulo")]
    pub poll_modulo: u64,
    /// Max mentions to dispatch per poll tick (default 3).
    #[serde(default = "default_max_dispatches_per_tick")]
    pub max_dispatches_per_tick: u32,
    /// Max concurrent mention-spawned agents (default 5).
    #[serde(default = "default_max_concurrent_mention_agents")]
    pub max_concurrent_mention_agents: u32,
}

fn default_poll_modulo() -> u64 {
    2
}

fn default_max_dispatches_per_tick() -> u32 {
    3
}

fn default_max_concurrent_mention_agents() -> u32 {
    5
}

/// Configuration for the webhook server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookConfig {
    /// Bind address for the webhook server (default "127.0.0.1:9090").
    /// Use 127.0.0.1 (localhost) to avoid exposing the webhook endpoint to all network interfaces.
    /// Set to "0.0.0.0:9090" explicitly if external access is required.
    #[serde(default = "default_webhook_bind")]
    pub bind: String,
    /// Shared secret for HMAC signature verification.
    /// Must match the secret configured in Gitea webhook settings.
    pub secret: Option<String>,
}

fn default_webhook_bind() -> String {
    "127.0.0.1:9090".to_string()
}

/// Quickwit log shipping configuration.
#[cfg(feature = "quickwit")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuickwitConfig {
    /// Whether Quickwit logging is enabled.
    #[serde(default = "default_quickwit_enabled")]
    pub enabled: bool,
    /// Quickwit API endpoint.
    #[serde(default = "default_quickwit_endpoint")]
    pub endpoint: String,
    /// Index ID for log ingestion.
    #[serde(default = "default_quickwit_index_id")]
    pub index_id: String,
    /// Maximum documents per batch.
    #[serde(default = "default_quickwit_batch_size")]
    pub batch_size: usize,
    /// Seconds between forced flushes.
    #[serde(default = "default_quickwit_flush_interval_secs")]
    pub flush_interval_secs: u64,
}

#[cfg(feature = "quickwit")]
impl Default for QuickwitConfig {
    fn default() -> Self {
        Self {
            enabled: default_quickwit_enabled(),
            endpoint: default_quickwit_endpoint(),
            index_id: default_quickwit_index_id(),
            batch_size: default_quickwit_batch_size(),
            flush_interval_secs: default_quickwit_flush_interval_secs(),
        }
    }
}

#[cfg(feature = "quickwit")]
fn default_quickwit_enabled() -> bool {
    false
}

#[cfg(feature = "quickwit")]
fn default_quickwit_endpoint() -> String {
    "http://127.0.0.1:7280".to_string()
}

#[cfg(feature = "quickwit")]
fn default_quickwit_index_id() -> String {
    "adf-logs".to_string()
}

#[cfg(feature = "quickwit")]
fn default_quickwit_batch_size() -> usize {
    100
}

#[cfg(feature = "quickwit")]
fn default_quickwit_flush_interval_secs() -> u64 {
    5
}

/// Lightweight reference to an SFIA skill code and level.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SfiaSkillRef {
    pub code: String,
    pub level: u8,
}

/// Definition of a single agent in the fleet.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentDefinition {
    /// Unique name (e.g., "security-sentinel").
    pub name: String,
    /// Which layer: Safety, Core, Growth.
    pub layer: AgentLayer,
    /// CLI tool to use (maps to Provider).
    pub cli_tool: String,
    /// Task/prompt to give the agent on spawn.
    pub task: String,
    /// Cron schedule (None = always running for Safety, or on-demand for Growth).
    pub schedule: Option<String>,
    /// Model to use with the CLI tool (e.g., "o3" for codex, "sonnet" for claude).
    pub model: Option<String>,
    /// Capabilities this agent provides.
    #[serde(default)]
    pub capabilities: Vec<String>,
    /// Maximum memory in bytes (optional resource limit).
    pub max_memory_bytes: Option<u64>,
    /// Monthly USD budget in cents (e.g., 5000 = $50.00).
    /// None means unlimited (subscription model).
    #[serde(default)]
    pub budget_monthly_cents: Option<u64>,
    /// LLM provider for this agent (e.g., "openai", "anthropic", "openrouter").
    #[serde(default)]
    pub provider: Option<String>,
    /// Persona name for this agent (e.g., "Security Analyst", "Code Reviewer").
    #[serde(default)]
    pub persona: Option<String>,
    /// Terraphim role identifier (e.g., "Terraphim Engineer", "Terraphim Designer").
    #[serde(default)]
    pub terraphim_role: Option<String>,
    /// Chain of skills to invoke for this agent.
    #[serde(default)]
    pub skill_chain: Vec<String>,
    /// SFIA skills with proficiency levels.
    #[serde(default)]
    pub sfia_skills: Vec<SfiaSkillRef>,
    /// Fallback LLM provider if primary fails.
    #[serde(default)]
    pub fallback_provider: Option<String>,
    /// Fallback model if primary fails.
    #[serde(default)]
    pub fallback_model: Option<String>,
    /// Grace period in seconds before killing an unresponsive agent.
    #[serde(default)]
    pub grace_period_secs: Option<u64>,
    /// Maximum CPU seconds allowed per agent execution.
    #[serde(default)]
    pub max_cpu_seconds: Option<u64>,
    /// Optional pre-check strategy to gate agent spawns.
    /// If None, the agent always spawns (equivalent to Always).
    #[serde(default)]
    pub pre_check: Option<PreCheckStrategy>,

    /// Gitea issue number to post output to (optional).
    #[serde(default)]
    pub gitea_issue: Option<u64>,
}

/// Agent layer in the dark factory hierarchy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AgentLayer {
    /// Always running, auto-restart on failure.
    Safety,
    /// Cron-scheduled or event-triggered.
    Core,
    /// On-demand, spawned when needed.
    Growth,
}

/// Nightwatch drift detection thresholds.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NightwatchConfig {
    /// How often to evaluate drift (seconds).
    #[serde(default = "default_eval_interval")]
    pub eval_interval_secs: u64,
    /// Drift percentage threshold for Minor correction.
    #[serde(default = "default_minor_threshold")]
    pub minor_threshold: f64,
    /// Drift percentage threshold for Moderate correction.
    #[serde(default = "default_moderate_threshold")]
    pub moderate_threshold: f64,
    /// Drift percentage threshold for Severe correction.
    #[serde(default = "default_severe_threshold")]
    pub severe_threshold: f64,
    /// Drift percentage threshold for Critical correction.
    #[serde(default = "default_critical_threshold")]
    pub critical_threshold: f64,
    /// Hour (0-23) when nightwatch evaluation starts. Default: 0 (midnight).
    #[serde(default)]
    pub active_start_hour: u8,
    /// Hour (0-23) when nightwatch evaluation ends. Default: 24 (always active).
    #[serde(default = "default_active_end_hour")]
    pub active_end_hour: u8,
    /// Weight for error rate in drift calculation (default: 0.35).
    #[serde(default = "default_error_weight")]
    pub error_weight: f64,
    /// Weight for command success rate in drift calculation (default: 0.25).
    #[serde(default = "default_success_weight")]
    pub success_weight: f64,
    /// Weight for health score in drift calculation (default: 0.20).
    #[serde(default = "default_health_weight")]
    pub health_weight: f64,
    /// Weight for budget exhaustion in drift calculation (default: 0.20).
    #[serde(default = "default_budget_weight")]
    pub budget_weight: f64,
}

impl Default for NightwatchConfig {
    fn default() -> Self {
        Self {
            eval_interval_secs: default_eval_interval(),
            minor_threshold: default_minor_threshold(),
            moderate_threshold: default_moderate_threshold(),
            severe_threshold: default_severe_threshold(),
            critical_threshold: default_critical_threshold(),
            active_start_hour: 0,
            active_end_hour: default_active_end_hour(),
            error_weight: default_error_weight(),
            success_weight: default_success_weight(),
            health_weight: default_health_weight(),
            budget_weight: default_budget_weight(),
        }
    }
}

fn default_eval_interval() -> u64 {
    300
}
fn default_minor_threshold() -> f64 {
    0.10
}
fn default_moderate_threshold() -> f64 {
    0.20
}
fn default_severe_threshold() -> f64 {
    0.40
}
fn default_critical_threshold() -> f64 {
    0.70
}
fn default_active_end_hour() -> u8 {
    24
}
fn default_error_weight() -> f64 {
    0.35
}
fn default_success_weight() -> f64 {
    0.25
}
fn default_health_weight() -> f64 {
    0.20
}
fn default_budget_weight() -> f64 {
    0.20
}

/// Compound review settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompoundReviewConfig {
    /// Cron schedule for compound review (e.g., "0 2 * * *").
    pub schedule: String,
    /// Maximum duration in seconds.
    #[serde(default = "default_max_duration")]
    pub max_duration_secs: u64,
    /// Git repository path.
    pub repo_path: PathBuf,
    /// Whether to create PRs (false = dry run).
    #[serde(default)]
    pub create_prs: bool,
    /// Root directory for worktrees.
    #[serde(default = "default_worktree_root")]
    pub worktree_root: PathBuf,
    /// Base branch for comparison.
    #[serde(default = "default_base_branch")]
    pub base_branch: String,
    /// Maximum number of concurrent agents.
    #[serde(default = "default_max_concurrent_agents")]
    pub max_concurrent_agents: usize,
    /// CLI tool override for compound review agents.
    #[serde(default)]
    pub cli_tool: Option<String>,
    /// LLM provider for compound review agents.
    #[serde(default)]
    pub provider: Option<String>,
    /// Model override for compound review agents.
    #[serde(default)]
    pub model: Option<String>,
    /// Gitea issue number to post compound review summaries.
    #[serde(default)]
    pub gitea_issue: Option<u64>,
    /// Auto-file Gitea issues for CRITICAL and HIGH severity findings.
    #[serde(default)]
    pub auto_file_issues: bool,
    /// Spawn remediation agents for CRITICAL findings.
    #[serde(default)]
    pub auto_remediate: bool,
    /// Map of finding categories to remediation agent names.
    #[serde(default)]
    pub remediation_agents: std::collections::HashMap<String, String>,
}

fn default_max_duration() -> u64 {
    1800
}

fn default_worktree_root() -> PathBuf {
    PathBuf::from(".worktrees")
}

fn default_base_branch() -> String {
    "main".to_string()
}

fn default_max_concurrent_agents() -> usize {
    3
}

impl Default for CompoundReviewConfig {
    fn default() -> Self {
        Self {
            schedule: "0 2 * * *".to_string(),
            max_duration_secs: default_max_duration(),
            repo_path: PathBuf::from("."),
            create_prs: false,
            worktree_root: default_worktree_root(),
            base_branch: default_base_branch(),
            max_concurrent_agents: default_max_concurrent_agents(),
            cli_tool: None,
            provider: None,
            model: None,
            gitea_issue: None,
            auto_file_issues: false,
            auto_remediate: false,
            remediation_agents: std::collections::HashMap::new(),
        }
    }
}

/// Workflow configuration for issue-driven mode.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowConfig {
    /// Whether issue-driven mode is enabled.
    pub enabled: bool,
    /// Poll interval in seconds.
    #[serde(default = "default_poll_interval")]
    pub poll_interval_secs: u64,
    /// Path to WORKFLOW.md file.
    pub workflow_file: PathBuf,
    /// Tracker configuration.
    pub tracker: TrackerConfig,
    /// Concurrency configuration.
    #[serde(default)]
    pub concurrency: ConcurrencyConfig,
}

/// Tracker configuration for issue-driven mode.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackerConfig {
    /// Tracker kind: "gitea" or "linear".
    pub kind: String,
    /// API endpoint URL.
    pub endpoint: String,
    /// API key (supports env var substitution like "${GITEA_TOKEN}").
    pub api_key: String,
    /// Repository owner (for Gitea).
    pub owner: String,
    /// Repository name (for Gitea).
    pub repo: String,
    /// Project slug for Linear (optional, Linear-specific).
    #[serde(default)]
    pub project_slug: Option<String>,
    /// Whether to use gitea-robot PageRank API.
    #[serde(default)]
    pub use_robot_api: bool,
    /// State configuration.
    #[serde(default)]
    pub states: TrackerStates,
}

/// Tracker state configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackerStates {
    /// Active states that trigger agent dispatch.
    #[serde(default = "default_active_states")]
    pub active: Vec<String>,
    /// Terminal states that trigger workspace cleanup.
    #[serde(default = "default_terminal_states")]
    pub terminal: Vec<String>,
}

impl Default for TrackerStates {
    fn default() -> Self {
        Self {
            active: default_active_states(),
            terminal: default_terminal_states(),
        }
    }
}

/// Concurrency configuration for issue-driven mode.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConcurrencyConfig {
    /// Global maximum concurrent agents (both modes combined).
    #[serde(default = "default_global_max")]
    pub global_max: usize,
    /// Maximum issue-driven agents.
    #[serde(default = "default_issue_max")]
    pub issue_max: usize,
    /// Fairness strategy: "round_robin", "priority", "proportional".
    #[serde(default = "default_fairness")]
    pub fairness: String,
}

impl Default for ConcurrencyConfig {
    fn default() -> Self {
        Self {
            global_max: default_global_max(),
            issue_max: default_issue_max(),
            fairness: default_fairness(),
        }
    }
}

fn default_poll_interval() -> u64 {
    120 // 2 minutes
}

fn default_active_states() -> Vec<String> {
    vec!["Todo".into(), "In Progress".into()]
}

fn default_terminal_states() -> Vec<String> {
    vec!["Done".into(), "Closed".into(), "Cancelled".into()]
}

fn default_global_max() -> usize {
    5
}

fn default_issue_max() -> usize {
    3
}

fn default_fairness() -> String {
    "round_robin".into()
}

fn default_restart_cooldown() -> u64 {
    60
}

fn default_max_restart_count() -> u32 {
    10
}

fn default_restart_budget_window() -> u64 {
    43_200
}

fn default_disk_usage_threshold() -> u8 {
    90
}

fn default_tick_interval() -> u64 {
    30
}

impl OrchestratorConfig {
    /// Parse an OrchestratorConfig from a TOML string.
    pub fn from_toml(toml_str: &str) -> Result<Self, crate::error::OrchestratorError> {
        toml::from_str(toml_str).map_err(|e| crate::error::OrchestratorError::Config(e.to_string()))
    }

    /// Load an OrchestratorConfig from a TOML file.
    pub fn from_file(
        path: impl AsRef<std::path::Path>,
    ) -> Result<Self, crate::error::OrchestratorError> {
        let content = std::fs::read_to_string(path.as_ref())?;
        Self::from_toml(&content)
    }

    /// Substitute environment variables in workflow config.
    /// Replaces ${VAR} or $VAR with the value of the environment variable.
    pub fn substitute_env_vars(&mut self) {
        if let Some(ref mut workflow) = self.workflow {
            workflow.tracker.api_key = substitute_env(&workflow.tracker.api_key);
        }
    }

    /// Validate the configuration.
    pub fn validate(&self) -> Result<(), crate::error::OrchestratorError> {
        // Validate workflow config if present
        if let Some(ref workflow) = self.workflow {
            if workflow.enabled {
                if workflow.tracker.api_key.is_empty() {
                    return Err(crate::error::OrchestratorError::Config(
                        "workflow.tracker.api_key is required when workflow is enabled".into(),
                    ));
                }
                if workflow.tracker.endpoint.is_empty() {
                    return Err(crate::error::OrchestratorError::Config(
                        "workflow.tracker.endpoint is required when workflow is enabled".into(),
                    ));
                }
            }
        }

        // Validate pre-check strategies
        for agent in &self.agents {
            if let Some(PreCheckStrategy::GiteaIssue { .. }) = &agent.pre_check {
                if self.workflow.is_none() {
                    return Err(crate::error::OrchestratorError::PreCheckConfig {
                        agent: agent.name.clone(),
                        reason: "gitea-issue strategy requires [workflow] config section".into(),
                    });
                }
            }
        }

        Ok(())
    }
}

/// Substitute environment variables in a string.
/// Supports ${VAR} syntax. Bare $VAR syntax is not implemented.
fn substitute_env(s: &str) -> String {
    let mut result = s.to_string();

    // Handle ${VAR} syntax
    while let Some(start) = result.find("${") {
        if let Some(end) = result[start..].find('}') {
            let var_name = &result[start + 2..start + end];
            let var_value = std::env::var(var_name).unwrap_or_default();
            result.replace_range(start..start + end + 1, &var_value);
        } else {
            break;
        }
    }

    result
}

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

    #[test]
    fn test_config_parse_minimal() {
        let toml_str = r#"
working_dir = "/tmp/terraphim"

[nightwatch]

[compound_review]
schedule = "0 2 * * *"
repo_path = "/tmp/repo"

[[agents]]
name = "test-agent"
layer = "Safety"
cli_tool = "codex"
task = "Run tests"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents.len(), 1);
        assert_eq!(config.agents[0].name, "test-agent");
        assert_eq!(config.agents[0].layer, AgentLayer::Safety);
        assert!(config.agents[0].schedule.is_none());
        assert!(config.agents[0].capabilities.is_empty());
    }

    #[test]
    fn test_config_parse_full() {
        let toml_str = r#"
working_dir = "/Users/alex/projects/terraphim/terraphim-ai"

[nightwatch]
eval_interval_secs = 300
minor_threshold = 0.10
moderate_threshold = 0.20
severe_threshold = 0.40
critical_threshold = 0.70

[compound_review]
schedule = "0 2 * * *"
max_duration_secs = 1800
repo_path = "/Users/alex/projects/terraphim/terraphim-ai"
create_prs = false

[[agents]]
name = "security-sentinel"
layer = "Safety"
cli_tool = "codex"
task = "Scan for CVEs"
capabilities = ["security", "vulnerability-scanning"]
max_memory_bytes = 2147483648

[[agents]]
name = "upstream-synchronizer"
layer = "Core"
cli_tool = "codex"
task = "Sync upstream"
schedule = "0 3 * * *"
capabilities = ["sync"]

[[agents]]
name = "code-reviewer"
layer = "Growth"
cli_tool = "claude"
task = "Review PRs"
capabilities = ["code-review", "architecture"]
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents.len(), 3);

        // Safety agent
        assert_eq!(config.agents[0].name, "security-sentinel");
        assert_eq!(config.agents[0].layer, AgentLayer::Safety);
        assert!(config.agents[0].schedule.is_none());
        assert_eq!(config.agents[0].max_memory_bytes, Some(2_147_483_648));

        // Core agent with schedule
        assert_eq!(config.agents[1].name, "upstream-synchronizer");
        assert_eq!(config.agents[1].layer, AgentLayer::Core);
        assert_eq!(config.agents[1].schedule.as_deref(), Some("0 3 * * *"));

        // Growth agent
        assert_eq!(config.agents[2].name, "code-reviewer");
        assert_eq!(config.agents[2].layer, AgentLayer::Growth);
        assert!(config.agents[2].schedule.is_none());
        assert_eq!(
            config.agents[2].capabilities,
            vec!["code-review", "architecture"]
        );

        // Nightwatch config
        assert_eq!(config.nightwatch.eval_interval_secs, 300);
        assert!((config.nightwatch.minor_threshold - 0.10).abs() < f64::EPSILON);
        assert!((config.nightwatch.critical_threshold - 0.70).abs() < f64::EPSILON);

        // Compound review config
        assert_eq!(config.compound_review.schedule, "0 2 * * *");
        assert_eq!(config.compound_review.max_duration_secs, 1800);
        assert!(!config.compound_review.create_prs);
    }

    #[test]
    fn test_config_defaults() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "codex"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();

        // Nightwatch defaults
        assert_eq!(config.nightwatch.eval_interval_secs, 300);
        assert!((config.nightwatch.minor_threshold - 0.10).abs() < f64::EPSILON);
        assert!((config.nightwatch.moderate_threshold - 0.20).abs() < f64::EPSILON);
        assert!((config.nightwatch.severe_threshold - 0.40).abs() < f64::EPSILON);
        assert!((config.nightwatch.critical_threshold - 0.70).abs() < f64::EPSILON);

        // Compound review defaults
        assert_eq!(config.compound_review.max_duration_secs, 1800);
        assert!(!config.compound_review.create_prs);

        // Agent defaults
        assert!(config.agents[0].capabilities.is_empty());
        assert!(config.agents[0].max_memory_bytes.is_none());
        assert!(config.agents[0].schedule.is_none());
    }

    #[test]
    fn test_config_restart_defaults() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.restart_cooldown_secs, 60);
        assert_eq!(config.max_restart_count, 10);
        assert_eq!(config.restart_budget_window_secs, 43_200);
        assert_eq!(config.tick_interval_secs, 30);
    }

    #[test]
    fn test_config_restart_custom() {
        let toml_str = r#"
working_dir = "/tmp"
restart_cooldown_secs = 120
max_restart_count = 5
restart_budget_window_secs = 3600
tick_interval_secs = 15

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.restart_cooldown_secs, 120);
        assert_eq!(config.max_restart_count, 5);
        assert_eq!(config.restart_budget_window_secs, 3600);
        assert_eq!(config.tick_interval_secs, 15);
    }

    #[test]
    fn test_example_config_parses() {
        let example_path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("orchestrator.example.toml");
        let config = OrchestratorConfig::from_file(&example_path).unwrap();
        assert_eq!(config.agents.len(), 16);
        assert_eq!(config.agents[0].layer, AgentLayer::Safety);
        assert_eq!(config.agents[1].layer, AgentLayer::Safety);
        assert_eq!(config.agents[2].layer, AgentLayer::Core);
        assert!(config.agents[2].schedule.is_some());
    }

    #[test]
    fn test_config_backward_compatible_without_workflow() {
        // Old config without workflow section should still parse
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert!(config.workflow.is_none());
    }

    #[test]
    fn test_config_with_workflow_section() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[workflow]
enabled = true
poll_interval_secs = 120
workflow_file = "./WORKFLOW.md"

[workflow.tracker]
kind = "gitea"
endpoint = "https://git.terraphim.cloud"
api_key = "..."
owner = "terraphim"
repo = "terraphim-ai"
use_robot_api = true

[workflow.tracker.states]
active = ["Todo", "In Progress"]
terminal = ["Done", "Closed"]

[workflow.concurrency]
global_max = 5
issue_max = 3
fairness = "round_robin"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();

        let workflow = config.workflow.expect("workflow config should exist");
        assert!(workflow.enabled);
        assert_eq!(workflow.poll_interval_secs, 120);
        assert_eq!(
            workflow.workflow_file,
            std::path::PathBuf::from("./WORKFLOW.md")
        );

        assert_eq!(workflow.tracker.kind, "gitea");
        assert_eq!(workflow.tracker.endpoint, "https://git.terraphim.cloud");
        assert_eq!(workflow.tracker.owner, "terraphim");
        assert!(workflow.tracker.use_robot_api);

        assert_eq!(workflow.tracker.states.active.len(), 2);
        assert_eq!(workflow.tracker.states.terminal.len(), 2);

        assert_eq!(workflow.concurrency.global_max, 5);
        assert_eq!(workflow.concurrency.issue_max, 3);
        assert_eq!(workflow.concurrency.fairness, "round_robin");
    }

    #[test]
    fn test_workflow_defaults() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[workflow]
enabled = true
workflow_file = "./WORKFLOW.md"

[workflow.tracker]
kind = "gitea"
endpoint = "https://git.example.com"
api_key = "..."
owner = "owner"
repo = "repo"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        let workflow = config.workflow.expect("workflow config should exist");

        // Check defaults
        assert_eq!(workflow.poll_interval_secs, 120);
        assert!(!workflow.tracker.use_robot_api);
        assert_eq!(workflow.concurrency.global_max, 5);
        assert_eq!(workflow.concurrency.issue_max, 3);
        assert_eq!(workflow.concurrency.fairness, "round_robin");
    }

    #[test]
    fn test_validate_workflow_missing_api_key() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[workflow]
enabled = true
workflow_file = "./WORKFLOW.md"

[workflow.tracker]
kind = "gitea"
endpoint = "https://git.example.com"
api_key = ""
owner = "owner"
repo = "repo"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_parse_with_budget() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
budget_monthly_cents = 5000
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents.len(), 1);
        assert_eq!(config.agents[0].budget_monthly_cents, Some(5000));
    }

    #[test]
    fn test_config_parse_without_budget() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents.len(), 1);
        assert!(config.agents[0].budget_monthly_cents.is_none());
    }

    #[test]
    fn test_config_parse_with_persona_fields() {
        let toml_str = r#"
working_dir = "/tmp"
persona_data_dir = "/tmp/personas"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "test-agent"
layer = "Safety"
cli_tool = "codex"
task = "Test task"
provider = "openai"
persona = "Security Analyst"
terraphim_role = "Terraphim Engineer"
skill_chain = ["security", "analysis"]
sfia_skills = [{code = "SCTY", level = 5}, {code = "PROG", level = 4}]
fallback_provider = "anthropic"
fallback_model = "claude-sonnet"
grace_period_secs = 30
max_cpu_seconds = 300
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents.len(), 1);
        let agent = &config.agents[0];
        assert_eq!(agent.provider, Some("openai".to_string()));
        assert_eq!(agent.persona, Some("Security Analyst".to_string()));
        assert_eq!(agent.terraphim_role, Some("Terraphim Engineer".to_string()));
        assert_eq!(agent.skill_chain, vec!["security", "analysis"]);
        assert_eq!(agent.sfia_skills.len(), 2);
        assert_eq!(agent.sfia_skills[0].code, "SCTY");
        assert_eq!(agent.sfia_skills[0].level, 5);
        assert_eq!(agent.sfia_skills[1].code, "PROG");
        assert_eq!(agent.sfia_skills[1].level, 4);
        assert_eq!(agent.fallback_provider, Some("anthropic".to_string()));
        assert_eq!(agent.fallback_model, Some("claude-sonnet".to_string()));
        assert_eq!(agent.grace_period_secs, Some(30));
        assert_eq!(agent.max_cpu_seconds, Some(300));
        assert_eq!(
            config.persona_data_dir,
            Some(PathBuf::from("/tmp/personas"))
        );
    }

    #[test]
    fn test_config_parse_without_persona_fields() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "test-agent"
layer = "Safety"
cli_tool = "codex"
task = "Test task"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents.len(), 1);
        let agent = &config.agents[0];
        assert!(agent.provider.is_none());
        assert!(agent.persona.is_none());
        assert!(agent.terraphim_role.is_none());
        assert!(agent.skill_chain.is_empty());
        assert!(agent.sfia_skills.is_empty());
        assert!(agent.fallback_provider.is_none());
        assert!(agent.fallback_model.is_none());
        assert!(agent.grace_period_secs.is_none());
        assert!(agent.max_cpu_seconds.is_none());
        assert!(config.persona_data_dir.is_none());
    }

    #[test]
    fn test_config_persona_defaults() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        let agent = &config.agents[0];
        assert!(agent.provider.is_none());
        assert!(agent.persona.is_none());
        assert!(agent.terraphim_role.is_none());
        assert!(agent.skill_chain.is_empty());
        assert!(agent.sfia_skills.is_empty());
        assert!(agent.fallback_provider.is_none());
        assert!(agent.fallback_model.is_none());
        assert!(agent.grace_period_secs.is_none());
        assert!(agent.max_cpu_seconds.is_none());
    }

    #[test]
    fn test_config_sfia_skills_parse() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
sfia_skills = [{code = "SCTY", level = 5}]
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents[0].sfia_skills.len(), 1);
        assert_eq!(config.agents[0].sfia_skills[0].code, "SCTY");
        assert_eq!(config.agents[0].sfia_skills[0].level, 5);
    }

    #[test]
    fn test_config_skill_chain_parse() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
skill_chain = ["a", "b"]
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents[0].skill_chain, vec!["a", "b"]);
    }

    #[test]
    fn test_config_persona_data_dir() {
        let toml_str = r#"
working_dir = "/tmp"
persona_data_dir = "/tmp/personas"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(
            config.persona_data_dir,
            Some(PathBuf::from("/tmp/personas"))
        );
    }

    #[test]
    fn test_config_persona_data_dir_default() {
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert!(config.persona_data_dir.is_none());
    }

    #[test]
    fn test_example_config_parses_with_persona() {
        let example_path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("orchestrator.example.toml");
        if example_path.exists() {
            let config = OrchestratorConfig::from_file(&example_path).unwrap();
            assert!(config.agents.len() >= 3);
        }
    }

    #[test]
    fn test_config_parse_pre_check_always() {
        let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"
[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
[agents.pre_check]
kind = "always"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert_eq!(config.agents[0].pre_check, Some(PreCheckStrategy::Always));
    }

    #[test]
    fn test_config_parse_pre_check_git_diff() {
        let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"
[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
[agents.pre_check]
kind = "git-diff"
watch_paths = ["crates/", "Cargo.toml"]
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        match &config.agents[0].pre_check {
            Some(PreCheckStrategy::GitDiff { watch_paths }) => {
                assert_eq!(
                    watch_paths,
                    &vec!["crates/".to_string(), "Cargo.toml".to_string()]
                );
            }
            other => panic!("expected GitDiff, got {:?}", other),
        }
    }

    #[test]
    fn test_config_parse_pre_check_gitea_issue() {
        let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"
[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
[agents.pre_check]
kind = "gitea-issue"
issue_number = 637
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        match &config.agents[0].pre_check {
            Some(PreCheckStrategy::GiteaIssue { issue_number }) => {
                assert_eq!(*issue_number, 637);
            }
            other => panic!("expected GiteaIssue, got {:?}", other),
        }
    }

    #[test]
    fn test_config_parse_pre_check_shell() {
        let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"
[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
[agents.pre_check]
kind = "shell"
script = "echo hello"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        match &config.agents[0].pre_check {
            Some(PreCheckStrategy::Shell {
                script,
                timeout_secs,
            }) => {
                assert_eq!(script, "echo hello");
                assert_eq!(*timeout_secs, 60); // default
            }
            other => panic!("expected Shell, got {:?}", other),
        }
    }

    #[test]
    fn test_config_parse_pre_check_shell_custom_timeout() {
        let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"
[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
[agents.pre_check]
kind = "shell"
script = "test -f /tmp/flag"
timeout_secs = 10
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        match &config.agents[0].pre_check {
            Some(PreCheckStrategy::Shell {
                script,
                timeout_secs,
            }) => {
                assert_eq!(script, "test -f /tmp/flag");
                assert_eq!(*timeout_secs, 10);
            }
            other => panic!("expected Shell, got {:?}", other),
        }
    }

    #[test]
    fn test_config_parse_no_pre_check() {
        let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"
[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert!(config.agents[0].pre_check.is_none());
    }

    #[test]
    fn test_config_validate_gitea_issue_requires_workflow() {
        let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"
[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
[agents.pre_check]
kind = "gitea-issue"
issue_number = 42
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        let result = config.validate();
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("gitea-issue"),
            "error should mention gitea-issue: {}",
            err
        );
    }

    #[test]
    fn test_config_validate_gitea_issue_with_workflow_ok() {
        let toml_str = r#"
working_dir = "/tmp"
[nightwatch]
[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"
[workflow]
enabled = true
workflow_file = "./WORKFLOW.md"
[workflow.tracker]
kind = "gitea"
endpoint = "https://git.example.com"
api_key = "token123"
owner = "owner"
repo = "repo"
[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
[agents.pre_check]
kind = "gitea-issue"
issue_number = 42
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_config_with_flows() {
        let toml_str = r#"
working_dir = "/tmp"
flow_state_dir = "/tmp/flow-states"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"

[[flows]]
name = "test-flow"
repo_path = "/home/user/project"

[[flows.steps]]
name = "build"
kind = "action"
command = "cargo build"

[[flows.steps]]
name = "test"
kind = "action"
command = "cargo test"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();

        // Check flows parsed correctly
        assert_eq!(config.flows.len(), 1);
        assert_eq!(config.flows[0].name, "test-flow");
        assert_eq!(config.flows[0].repo_path, "/home/user/project");
        assert_eq!(config.flows[0].steps.len(), 2);

        // Check step data
        assert_eq!(config.flows[0].steps[0].name, "build");
        assert_eq!(
            config.flows[0].steps[0].kind,
            crate::flow::config::StepKind::Action
        );
        assert_eq!(
            config.flows[0].steps[0].command,
            Some("cargo build".to_string())
        );

        assert_eq!(config.flows[0].steps[1].name, "test");
        assert_eq!(
            config.flows[0].steps[1].command,
            Some("cargo test".to_string())
        );

        // Check flow_state_dir
        assert_eq!(
            config.flow_state_dir,
            Some(PathBuf::from("/tmp/flow-states"))
        );
    }

    #[test]
    fn test_config_without_flows() {
        // Existing config without flows section should still parse
        let toml_str = r#"
working_dir = "/tmp"

[nightwatch]

[compound_review]
schedule = "0 0 * * *"
repo_path = "/tmp"

[[agents]]
name = "a"
layer = "Safety"
cli_tool = "echo"
task = "t"
"#;
        let config = OrchestratorConfig::from_toml(toml_str).unwrap();

        // Flows should be empty by default
        assert!(config.flows.is_empty());
        assert!(config.flow_state_dir.is_none());
    }
}