apollo-agent 0.3.0

Local-first Rust AI agent runtime — Telegram-first, trait-driven, SurrealDB + RocksDB state layer.
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
//! apollo — Lightweight agent runtime CLI
//! Successor to OpenClaw. Best-of-breed from ZeroClaw, NanoClaw, HiClaw.

use std::path::PathBuf;
use std::sync::Arc;

use clap::{Parser, Subcommand};

use apollo::agent::hooks::PermissionHook;
use apollo::agent::{agent_mode_from_permission_profile, AgentRunner};
use apollo::autonomous::{AutonomousConfig, AutonomousLoop};
use apollo::bootstrap::{
    build_base_tools, build_embedding_provider, build_memory_backend, build_provider, load_config,
    require_config_file,
};
#[cfg(feature = "channel-cli")]
use apollo::channels::cli::CliChannel;
#[cfg(feature = "channel-discord")]
use apollo::channels::discord::DiscordChannel;
use apollo::config::{apply_permission_profile, Config};
use apollo::cron_scheduler::CronScheduler;
use apollo::diagnostics::{collect_doctor_report, render_doctor_report, render_findings};
use apollo::heartbeat::{self, HeartbeatConfig};
use apollo::policy::ExecutionPolicy;
use apollo::prompt;
use apollo::self_update::{SelfUpdater, UpdateOutcome};
use apollo::skills;
use apollo::telegram_runtime::{run_telegram_chat, TelegramChatRun};

#[derive(Parser)]
#[command(name = "apollo", about = "Local-first AI agent runtime", version)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Start interactive agent chat
    Chat {
        /// Configuration file path
        #[arg(short, long, default_value = "apollo.json")]
        config: String,

        /// Override the model
        #[arg(short, long)]
        model: Option<String>,

        /// Workspace directory
        #[arg(short, long)]
        workspace: Option<PathBuf>,

        /// Channel: cli, telegram, discord
        #[arg(long, default_value = "cli")]
        channel: String,

        /// Telegram bot token (required for --channel telegram)
        #[arg(long)]
        telegram_token: Option<String>,

        /// Telegram chat ID (required for --channel telegram)
        #[arg(long)]
        telegram_chat_id: Option<i64>,

        /// Discord bot token (required for --channel discord)
        #[arg(long)]
        discord_token: Option<String>,

        /// Discord channel ID (required for --channel discord)
        #[arg(long)]
        discord_channel_id: Option<String>,
    },

    /// Send a one-shot message
    Ask {
        /// The message to send
        message: String,

        /// Configuration file path
        #[arg(short, long, default_value = "apollo.json")]
        config: String,

        /// Override the model
        #[arg(short, long)]
        model: Option<String>,
    },

    /// Run system diagnostics and config validation
    Doctor {
        /// Configuration file path
        #[arg(short, long, default_value = "apollo.json")]
        config: String,

        /// Show more dependency checks
        #[arg(short, long, default_value_t = false)]
        verbose: bool,

        /// Output JSON
        #[arg(long, default_value_t = false)]
        json: bool,
    },

    /// Run a focused security/config audit
    Audit {
        /// Configuration file path
        #[arg(short, long, default_value = "apollo.json")]
        config: String,

        /// Output JSON
        #[arg(long, default_value_t = false)]
        json: bool,
    },

    /// Show runtime status
    Status,

    /// Run as an MCP server (stdio or HTTP for Cloudflare Container)
    Mcp {
        /// Configuration file path
        #[arg(short, long, default_value = "apollo.json")]
        config: String,

        /// Workspace directory
        #[arg(short, long)]
        workspace: Option<PathBuf>,

        /// Override the model
        #[arg(short, long)]
        model: Option<String>,

        /// Run in HTTP mode on this port (default: stdio mode)
        #[arg(long)]
        port: Option<u16>,
    },

    /// Run one self-update cycle against the current repo
    SelfUpdate {
        /// Configuration file path
        #[arg(short, long, default_value = "apollo.json")]
        config: String,

        /// Workspace directory
        #[arg(short, long)]
        workspace: Option<PathBuf>,
    },

    /// Initialize configuration (interactive wizard or one-command setup)
    #[command(alias = "setup")]
    Init {
        /// Provider (omit to pick from compiled-in list with type-to-filter)
        #[arg(short, long)]
        provider: Option<String>,

        /// API key
        #[arg(short = 'k', long)]
        api_key: Option<String>,

        /// Channel (telegram, discord, cli)
        #[arg(long)]
        channel: Option<String>,

        /// Telegram bot token
        #[arg(long)]
        telegram_token: Option<String>,

        /// Telegram chat ID
        #[arg(long)]
        telegram_chat_id: Option<String>,

        /// Discord bot token
        #[arg(long)]
        discord_token: Option<String>,

        /// Discord channel ID
        #[arg(long)]
        discord_channel_id: Option<String>,

        /// Model to use
        #[arg(short, long)]
        model: Option<String>,

        /// Start the bot after init
        #[arg(long, default_value_t = false)]
        start: bool,

        /// Workspace directory
        #[arg(short, long)]
        workspace: Option<PathBuf>,

        /// Permission profile: full | auto | prompt | tools_only
        #[arg(long)]
        permission_profile: Option<String>,
    },

    /// Send a message to the running apollo bot via Telegram
    #[command(alias = "msg")]
    Message {
        /// Message text
        message: String,

        /// Chat ID (defaults to APOLLO_CHAT_ID from .env)
        #[arg(long)]
        chat_id: Option<String>,

        /// Workspace directory (to find .env)
        #[arg(short, long)]
        workspace: Option<PathBuf>,
    },

    /// Manage cron jobs
    Cron {
        #[command(subcommand)]
        action: CronAction,

        /// Configuration file path
        #[arg(short, long, default_value = "apollo.json")]
        config: String,

        /// Workspace directory
        #[arg(short, long)]
        workspace: Option<PathBuf>,
    },

    /// Run autonomous TODO.md-driven coding loop
    Autonomous {
        /// Configuration file path
        #[arg(short, long, default_value = "apollo.json")]
        config: String,

        /// Workspace directory
        #[arg(short, long)]
        workspace: Option<PathBuf>,

        /// Check cycle interval in seconds
        #[arg(long)]
        interval: Option<u64>,

        /// Reset autonomous status and start fresh
        #[arg(long, default_value_t = false)]
        start: bool,

        /// Clear paused state and continue
        #[arg(long, default_value_t = false)]
        resume: bool,
    },

    /// Swarm commands (multi-agent coordination)
    Swarm {
        #[command(subcommand)]
        action: SwarmAction,

        /// Workspace directory
        #[arg(short, long)]
        workspace: Option<PathBuf>,
    },

    /// Launch the desktop UI (apollo-ui)
    Ui,
}

#[derive(Subcommand)]
enum CronAction {
    /// Add a new cron job
    Add {
        /// Job name
        #[arg(short, long)]
        name: String,

        /// Cron expression (e.g. "0 0 9 * * * *")
        #[arg(short, long)]
        schedule: String,

        /// Task prompt text
        #[arg(short, long)]
        task: String,

        /// Channel (default: cli)
        #[arg(long, default_value = "cli")]
        channel: String,

        #[arg(long, default_value = "cli")]
        chat_id: String,

        /// Model override
        #[arg(long, default_value = "")]
        model: String,
    },

    /// List all cron jobs
    List,

    /// Remove a cron job by ID or name
    Remove {
        /// Job ID or name
        id_or_name: String,
    },

    /// Enable a cron job
    Enable {
        /// Job ID or name
        id_or_name: String,
    },

    /// Disable a cron job
    Disable {
        /// Job ID or name
        id_or_name: String,
    },
}

#[derive(Subcommand)]
enum SwarmAction {
    /// Start swarm coordinator
    Start {
        /// SurrealDB path
        #[arg(long, default_value = ".apollo/state.surreal")]
        surreal_path: String,

        /// RocksDB cache path
        #[arg(long, default_value = ".apollo/cache")]
        cache_path: String,
    },

    /// Register a named agent
    AgentCreate {
        /// Agent name (unique)
        name: String,

        /// LLM model
        #[arg(long, default_value = "claude-sonnet-4-5")]
        model: String,

        /// Capabilities (comma-separated: coding,research,review,testing,documentation,design,devops,security)
        #[arg(long, default_value = "coding")]
        capabilities: String,

        /// Tools (comma-separated)
        #[arg(long)]
        tools: Option<String>,

        /// Max concurrent incoming delegations
        #[arg(long, default_value = "5")]
        max_concurrent: i32,
    },

    /// Create a delegation link between agents
    AgentLink {
        /// Source agent name
        source: String,

        /// Target agent name
        target: String,

        /// Direction: outbound, inbound, bidirectional
        #[arg(long, default_value = "outbound")]
        direction: String,

        /// Max concurrent delegations on this link
        #[arg(long, default_value = "3")]
        max_concurrent: u32,
    },

    /// Create a team
    TeamCreate {
        /// Team name
        name: String,

        /// Lead agent name
        #[arg(long)]
        lead: String,
    },

    /// Add a task to a team's board
    TeamTaskAdd {
        /// Team name
        team: String,

        /// Task subject
        subject: String,

        /// Priority (0-10)
        #[arg(short, long, default_value = "0")]
        priority: i32,

        /// Blocked by task IDs (comma-separated)
        #[arg(long)]
        blocked_by: Option<String>,
    },

    /// List active agents
    Agents,

    /// List pending tasks
    Tasks,

    /// List teams
    Teams,

    /// List delegations for an agent
    Delegations {
        /// Agent name
        agent: String,
    },

    /// Submit a task to the swarm
    Task {
        /// Task description
        description: String,

        /// Priority (low, medium, high, critical)
        #[arg(short, long, default_value = "medium")]
        priority: String,

        /// Title (defaults to first line of description)
        #[arg(short, long)]
        title: Option<String>,
    },

    /// Queue a message (steering)
    Queue {
        /// Message to queue
        message: String,
    },

    /// Show scheduler status
    Status,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Load .env if present — allows running without manually exporting env vars
    let _ = dotenvy::dotenv();

    let cli = Cli::parse();
    let tracing_cfg = config_path_for_cli(&cli)
        .and_then(|path| Config::load(&path).ok())
        .map(|cfg| cfg.observability)
        .unwrap_or_default();
    init_tracing(&tracing_cfg)?;

    // Hermes-style: bare `apollo` starts interactive chat.
    let command = cli.command.unwrap_or(Commands::Chat {
        config: "apollo.json".into(),
        model: None,
        workspace: None,
        channel: "cli".into(),
        telegram_token: None,
        telegram_chat_id: None,
        discord_token: None,
        discord_channel_id: None,
    });

    match command {
        Commands::Chat {
            config,
            model,
            workspace,
            channel,
            telegram_token,
            telegram_chat_id,
            discord_token: _discord_token,
            discord_channel_id: _discord_channel_id,
        } => {
            require_config_file(&config)?;
            let workspace = workspace.unwrap_or_else(|| load_config(&config).workspace.clone());
            let cfg = apollo::bootstrap::load_config_workspace(&config, Some(&workspace));
            let model = model.unwrap_or(cfg.model.clone());
            let _ = apollo::workspace_init::ensure_workspace_kit(&workspace);

            let provider = build_provider(&cfg);
            let policy = Arc::new(ExecutionPolicy::from_config(&cfg.policy));
            let memory = build_memory_backend(&workspace, &cfg).await?;
            let embedding_provider = build_embedding_provider(&cfg)?;
            let self_updater = SelfUpdater::new(workspace.clone(), cfg.runtime.self_update.clone());

            // Build system prompt from workspace context files
            let system_prompt = prompt::build_system_prompt(&workspace).await;

            // Discover skills
            let discovered_skills = skills::discover_skills_for_workspace(Some(&workspace));
            if !discovered_skills.is_empty() {
                tracing::info!("Discovered {} skills", discovered_skills.len());
            }

            // Build shared zkr memory store (used by both the zkr tool and the runner)
            #[cfg(feature = "zkr-memory")]
            let zkr_store = apollo::bootstrap::build_zkr_store(&workspace, &cfg)
                .ok()
                .flatten();

            // Register tools (including memory search/get)
            #[cfg(feature = "zkr-memory")]
            let mut tools = build_base_tools(
                &workspace,
                Arc::clone(&policy),
                memory.clone(),
                embedding_provider,
                Arc::clone(&provider),
                &cfg,
                zkr_store.clone(),
            );
            #[cfg(not(feature = "zkr-memory"))]
            let mut tools = build_base_tools(
                &workspace,
                Arc::clone(&policy),
                memory.clone(),
                embedding_provider,
                Arc::clone(&provider),
                &cfg,
            );

            // Load any previously created dynamic tools
            let dynamic_tools = apollo::tools::dynamic::DynamicTool::load_all(Arc::clone(&policy));
            let dynamic_count = dynamic_tools.len();
            for dt in dynamic_tools {
                tools.push(Arc::new(dt));
            }
            if dynamic_count > 0 {
                println!("   Loaded {} custom tool(s)", dynamic_count);
            }

            // Start swarm coordinator if requested
            #[cfg(feature = "swarm")]
            let coordinator = {
                let storage: Arc<dyn apollo::swarm::SwarmStorage> = Arc::new(
                    apollo::swarm::SurrealBackend::new(&workspace.join(".apollo/swarm.surreal"))
                        .await?,
                );
                let coord = Arc::new(apollo::swarm::SwarmCoordinator::new(storage));
                coord.init().await?;
                Some(coord)
            };

            #[cfg_attr(not(feature = "swarm"), allow(unused_mut))]
            let mut runner =
                AgentRunner::new(provider, tools, memory.clone(), &system_prompt, model)
                    .with_config(cfg.agent.clone())
                    .with_mode(agent_mode_from_permission_profile(
                        &cfg.agent.permission_profile,
                    ))
                    .with_workspace(workspace.clone())
                    .with_memory_ideas(cfg.memory.clone())
                    .with_group_chat(cfg.group_chat.clone())
                    .with_skills(discovered_skills.clone())
                    .await;
            #[cfg(feature = "zkr-memory")]
            {
                runner = runner.with_zkr(zkr_store.clone(), cfg.zkr.clone());
            }

            {
                let mut host_reg = apollo::plugin::PluginRegistry::new();
                host_reg.ingest_host_plugins(&workspace, &cfg.plugin_layer.host_plugin_roots);
                runner = runner.with_plugin_registry(host_reg).await;
            }

            #[cfg(feature = "swarm")]
            if let Some(coord) = coordinator {
                runner = runner.with_swarm(coord);
            }

            let runner_arc = Arc::new(runner);

            if std::env::var("APOLLO_HTTP")
                .map(|v| v != "0")
                .unwrap_or(true)
            {
                apollo::agent_http::spawn_http_server(Arc::clone(&runner_arc));
            }

            runner_arc.add_hook(Arc::new(PermissionHook::new(
                cfg.agent.permissions.deny.clone(),
                cfg.agent.permissions.allow.clone(),
            )));

            #[cfg(feature = "swarm")]
            runner_arc
                .add_tool(Arc::new(apollo::tools::CodingSwarmTool::new(
                    runner_arc.clone(),
                    3,
                )))
                .await;
            runner_arc
                .add_tool(Arc::new(apollo::tools::tool_search::ToolSearchTool::new(
                    runner_arc.tools.clone(),
                )))
                .await;
            runner_arc
                .add_tool(Arc::new(apollo::tools::mode_switch::ModeSwitchTool::new(
                    runner_arc.mode_handle(),
                )))
                .await;

            // Add claude_usage tool (needs cost tracker reference)
            runner_arc
                .add_tool(Arc::new(apollo::tools::claude_usage::ClaudeUsageTool::new(
                    runner_arc.cost_tracker(),
                )))
                .await;

            // Start cron scheduler background task and add tool
            let scheduled_chat_id = match channel.as_str() {
                "telegram" => telegram_chat_id
                    .map(|id| id.to_string())
                    .unwrap_or_default(),
                "discord" => _discord_channel_id.clone().unwrap_or_default(),
                _ => "cli".to_string(),
            };
            let mut cron_runtime = None;
            if let Some(surreal_mem) = memory
                .as_any()
                .downcast_ref::<apollo::memory::surreal::SurrealMemory>()
            {
                let cron_sched = Arc::new(CronScheduler::new(Arc::new(surreal_mem.clone())));
                let (cron_rx, cron_shutdown) =
                    apollo::cron_scheduler::start_cron_ticker(cron_sched.clone(), channel.clone());

                runner_arc
                    .add_tool(Arc::new(apollo::tools::cron_tool::CronTool::new(
                        cron_sched.clone(),
                        channel.clone(),
                        scheduled_chat_id.clone(),
                        cfg.model.clone(),
                    )))
                    .await;
                cron_runtime = Some((cron_rx, cron_shutdown, cron_sched));
            }

            let _self_update_handle = self_updater.start();

            match channel.as_str() {
                #[cfg(feature = "channel-cli")]
                "cli" => {
                    println!(
                        "apollo v{}{} via {}",
                        env!("CARGO_PKG_VERSION"),
                        cfg.model,
                        cfg.provider.name
                    );
                    println!("   Workspace: {}", workspace.display());
                    println!("   Channel: CLI");
                    println!("   Type /quit to exit");
                    println!(
                        "   Agent HTTP: http://{}/v1/chat (APOLLO_HTTP_PORT)",
                        apollo::agent_http::http_listen_addr()
                    );
                    println!();

                    // Start heartbeat background task
                    let heartbeat_cfg = HeartbeatConfig {
                        workspace: workspace.clone(),
                        deliver_chat_id: cfg.memory.heartbeat_chat_id.clone(),
                        ..Default::default()
                    };
                    let (hb_tx, hb_rx) = tokio::sync::mpsc::channel(16);
                    let _heartbeat_handle = heartbeat::start_heartbeat(heartbeat_cfg, hb_tx);

                    let mut ch = CliChannel::new();
                    if let Some((cron_rx, cron_shutdown, cron_sched)) = cron_runtime.take() {
                        runner_arc
                            .run_with_runtime_rx(&mut ch, hb_rx, cron_rx, cron_sched)
                            .await?;
                        cron_shutdown.notify_waiters();
                    } else {
                        runner_arc.run_with_extra_rx(&mut ch, hb_rx).await?;
                    }
                }
                #[cfg(feature = "channel-telegram")]
                "telegram" => {
                    let token = telegram_token
                        .ok_or_else(|| anyhow::anyhow!("--telegram-token required"))?;
                    let chat_id = telegram_chat_id
                        .ok_or_else(|| anyhow::anyhow!("--telegram-chat-id required"))?;
                    run_telegram_chat(TelegramChatRun {
                        runner: runner_arc,
                        memory,
                        token,
                        chat_id,
                        model: cfg.model.clone(),
                        skills_count: discovered_skills.len(),
                        workspace: workspace.clone(),
                        channel_cfg: &cfg.channel,
                        cron_runtime: cron_runtime.take(),
                    })
                    .await?;
                }
                #[cfg(feature = "channel-discord")]
                "discord" => {
                    let token = _discord_token
                        .ok_or_else(|| anyhow::anyhow!("--discord-token required"))?;
                    let channel_id = _discord_channel_id
                        .ok_or_else(|| anyhow::anyhow!("--discord-channel-id required"))?;

                    println!("apollo — {} via Discord", cfg.model);
                    println!("   Channel ID: {}", channel_id);
                    println!("   Listening for messages...");

                    let mut ch = DiscordChannel::new(token, channel_id);
                    if let Some((cron_rx, cron_shutdown, cron_sched)) = cron_runtime.take() {
                        let (_extra_tx, extra_rx) = tokio::sync::mpsc::channel(1);
                        runner_arc
                            .run_with_runtime_rx(&mut ch, extra_rx, cron_rx, cron_sched)
                            .await?;
                        cron_shutdown.notify_waiters();
                    } else {
                        runner_arc.run(&mut ch).await?;
                    }
                }
                other => {
                    anyhow::bail!(
                        "Unknown channel: {} (supported: cli, telegram, discord)",
                        other
                    );
                }
            }
        }

        Commands::Ask {
            message,
            config,
            model,
        } => {
            require_config_file(&config)?;
            let cfg = load_config(&config);
            let model = model.unwrap_or(cfg.model.clone());
            let provider = build_provider(&cfg);

            let response = provider.simple_chat(&message, &model).await?;
            println!("{}", response);
        }

        Commands::Doctor {
            config,
            verbose,
            json,
        } => {
            let cfg = load_config(&config);
            let report = collect_doctor_report(Some(&cfg), Some(&config), verbose).await;
            if json {
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                println!("{}", render_doctor_report(&report));
            }
        }

        Commands::Audit { config, json } => {
            let cfg = load_config(&config);
            let findings = apollo::diagnostics::audit_config(&cfg);
            if json {
                println!("{}", serde_json::to_string_pretty(&findings)?);
            } else {
                println!("{}", render_findings(&findings));
            }
        }

        Commands::Status => {
            println!("apollo v{}", env!("CARGO_PKG_VERSION"));
            println!("Status: OK");
            println!(
                "Commands: chat, ask, doctor, audit, status, mcp, self-update, init, cron, autonomous, swarm"
            );
        }

        Commands::Mcp {
            config,
            workspace,
            model,
            port,
        } => {
            let cfg = load_config(&config);
            let model = model.unwrap_or(cfg.model.clone());
            let workspace = workspace.unwrap_or(cfg.workspace.clone());

            let provider = build_provider(&cfg);
            let policy = Arc::new(ExecutionPolicy::from_config(&cfg.policy));
            let memory = build_memory_backend(&workspace, &cfg).await?;
            let embedding_provider = build_embedding_provider(&cfg)?;

            #[cfg(feature = "zkr-memory")]
            let zkr_store = apollo::bootstrap::build_zkr_store(&workspace, &cfg)
                .ok()
                .flatten();
            #[cfg(feature = "zkr-memory")]
            let tools = build_base_tools(
                &workspace,
                Arc::clone(&policy),
                Arc::clone(&memory),
                embedding_provider,
                Arc::clone(&provider),
                &cfg,
                zkr_store.clone(),
            );
            #[cfg(not(feature = "zkr-memory"))]
            let tools = build_base_tools(
                &workspace,
                Arc::clone(&policy),
                Arc::clone(&memory),
                embedding_provider,
                Arc::clone(&provider),
                &cfg,
            );

            if let Some(port) = port {
                let system_prompt = cfg.system_prompt.clone();
                let mut runner = apollo::agent::loop_runner::AgentRunner::new(
                    Arc::clone(&provider),
                    tools.clone(),
                    Arc::clone(&memory),
                    system_prompt,
                    model.clone(),
                )
                .with_config(cfg.agent.clone())
                .with_mode(agent_mode_from_permission_profile(
                    &cfg.agent.permission_profile,
                ));
                #[cfg(feature = "zkr-memory")]
                {
                    runner = runner.with_zkr(zkr_store.clone(), cfg.zkr.clone());
                }
                let runner = Arc::new(runner);
                runner.add_hook(Arc::new(PermissionHook::new(
                    cfg.agent.permissions.deny.clone(),
                    cfg.agent.permissions.allow.clone(),
                )));
                eprintln!(
                    "apollo v{} — MCP HTTP server on port {} ({})",
                    env!("CARGO_PKG_VERSION"),
                    port,
                    model
                );
                apollo::mcp_server::run_mcp_server_http(
                    tools,
                    Some(provider),
                    Some(model),
                    Some(runner),
                    port,
                )
                .await?;
            } else {
                eprintln!(
                    "apollo v{} — MCP server mode ({})",
                    env!("CARGO_PKG_VERSION"),
                    model
                );
                apollo::mcp_server::run_mcp_server(tools, Some(provider), Some(model)).await?;
            }
        }

        Commands::SelfUpdate { config, workspace } => {
            let cfg = load_config(&config);
            let workspace = workspace.unwrap_or(cfg.workspace.clone());
            let updater = SelfUpdater::new(workspace, cfg.runtime.self_update.clone());
            match updater.run_once().await? {
                UpdateOutcome::NoRepo => println!("Not a git repo. Nothing to update."),
                UpdateOutcome::Disabled => println!("Self-update is disabled in config."),
                UpdateOutcome::DirtyWorktree => {
                    println!("Skipped self-update because the worktree is dirty.");
                }
                UpdateOutcome::AlreadyCurrent => println!("Already up to date."),
                UpdateOutcome::Updated { restarted } => {
                    if restarted {
                        println!("Updated, rebuilt, and restarted service.");
                    } else {
                        println!("Updated and rebuilt. Restart the process or service if needed.");
                    }
                }
            }
        }

        Commands::Init {
            provider,
            api_key,
            channel,
            telegram_token,
            telegram_chat_id,
            discord_token,
            discord_channel_id,
            model,
            start,
            workspace,
            permission_profile,
        } => {
            let workspace = workspace.unwrap_or_else(|| PathBuf::from("."));
            println!("🐾 apollo setup\n");

            // === Resolve values (flags or interactive prompts) ===
            let provider = match provider {
                Some(p) if !p.trim().is_empty() => p.trim().to_string(),
                Some(_) | None => prompt_provider_interactive()?,
            };

            let api_key = match api_key {
                Some(k) => k,
                None => {
                    if provider == "ollama" {
                        String::new()
                    } else {
                        eprint!("  API key ({}): ", provider);
                        let mut buf = String::new();
                        std::io::stdin().read_line(&mut buf)?;
                        let k = buf.trim().to_string();
                        if k.is_empty() {
                            anyhow::bail!("API key required (omit only for ollama)");
                        }
                        k
                    }
                }
            };

            let channel = match channel {
                Some(c) => c,
                None => {
                    eprint!("  Channel (telegram/discord/cli) [telegram]: ");
                    let mut buf = String::new();
                    std::io::stdin().read_line(&mut buf)?;
                    let c = buf.trim().to_string();
                    if c.is_empty() {
                        "telegram".to_string()
                    } else {
                        c
                    }
                }
            };

            let model = model.unwrap_or_else(|| "claude-sonnet-4-5".to_string());

            // Channel-specific tokens
            let tg_token = if channel == "telegram" {
                match telegram_token {
                    Some(t) => Some(t),
                    None => {
                        eprint!("  Telegram bot token: ");
                        let mut buf = String::new();
                        std::io::stdin().read_line(&mut buf)?;
                        let t = buf.trim().to_string();
                        if t.is_empty() {
                            None
                        } else {
                            Some(t)
                        }
                    }
                }
            } else {
                telegram_token
            };

            let tg_chat_id = if channel == "telegram" {
                match telegram_chat_id {
                    Some(c) => Some(c),
                    None => {
                        eprint!("  Telegram chat ID: ");
                        let mut buf = String::new();
                        std::io::stdin().read_line(&mut buf)?;
                        let c = buf.trim().to_string();
                        if c.is_empty() {
                            None
                        } else {
                            Some(c)
                        }
                    }
                }
            } else {
                telegram_chat_id
            };

            let dc_token = if channel == "discord" {
                discord_token
            } else {
                None
            };
            let dc_channel = if channel == "discord" {
                discord_channel_id
            } else {
                None
            };

            if channel == "telegram" && tg_token.is_none() {
                anyhow::bail!("Telegram channel requires a bot token (use --telegram-token or enter it when prompted)");
            }

            let permission_profile = match permission_profile {
                Some(p) if !p.trim().is_empty() => p.trim().to_string(),
                Some(_) | None => prompt_permission_profile_interactive()?,
            };

            // === Validate ===
            let client = reqwest::Client::new();
            match provider.as_str() {
                "ollama" => {
                    print!("\n  Validating Ollama... ");
                    let base_url = "http://localhost:11434";
                    let resp = client.get(format!("{}/api/tags", base_url)).send().await;
                    match resp {
                        Ok(r) if r.status().is_success() => println!(""),
                        Ok(r) => println!("⚠️  HTTP {} from local Ollama", r.status()),
                        Err(e) => println!("{}", e),
                    }
                }
                "anthropic" | "claude" => {
                    print!("\n  Validating API key... ");
                    let is_oauth = api_key.contains("sk-ant-oat");
                    let auth_resp = if is_oauth {
                        client
                            .get("https://api.anthropic.com/v1/models")
                            .header("Authorization", format!("Bearer {}", api_key))
                            .header("anthropic-version", "2023-06-01")
                            .send()
                            .await
                    } else {
                        client
                            .get("https://api.anthropic.com/v1/models")
                            .header("x-api-key", &api_key)
                            .header("anthropic-version", "2023-06-01")
                            .send()
                            .await
                    };
                    match auth_resp {
                        Ok(r) if r.status().is_success() => println!(""),
                        Ok(r) => println!("⚠️  HTTP {} (may still work)", r.status()),
                        Err(e) => println!("{}", e),
                    }
                }
                "openai" => {
                    print!("\n  Validating API key... ");
                    let auth_resp = client
                        .get("https://api.openai.com/v1/models")
                        .bearer_auth(&api_key)
                        .send()
                        .await;
                    match auth_resp {
                        Ok(r) if r.status().is_success() => println!(""),
                        Ok(r) => println!("⚠️  HTTP {} (may still work)", r.status()),
                        Err(e) => println!("{}", e),
                    }
                }
                _ if !api_key.is_empty() => {
                    println!(
                        "\n  Skipping remote key validation for provider '{}'.",
                        provider
                    );
                }
                _ => {}
            }

            if let Some(ref token) = tg_token {
                print!("  Validating Telegram token... ");
                let tg_resp = client
                    .get(format!("https://api.telegram.org/bot{}/getMe", token))
                    .send()
                    .await;
                match tg_resp {
                    Ok(r) => {
                        let body: serde_json::Value = r.json().await.unwrap_or_default();
                        if body["ok"].as_bool() == Some(true) {
                            let name = body["result"]["username"].as_str().unwrap_or("?");
                            println!("✅ @{}", name);
                        } else {
                            println!("❌ Invalid token");
                        }
                    }
                    Err(e) => println!("{}", e),
                }
            }

            // === Write .env ===
            let env_path = workspace.join(".env");
            let mut env_content = String::new();
            if provider == "ollama" {
                env_content.push_str("OLLAMA_BASE_URL=\"http://localhost:11434\"\n");
            } else if provider == "anthropic" || provider == "claude" {
                env_content.push_str(&format!("ANTHROPIC_API_KEY=\"{}\"\n", api_key));
            } else {
                env_content.push_str(&format!("OPENAI_API_KEY=\"{}\"\n", api_key));
            }
            if let Some(ref t) = tg_token {
                env_content.push_str(&format!("APOLLO_TELEGRAM_TOKEN=\"{}\"\n", t));
            }
            if let Some(ref c) = tg_chat_id {
                env_content.push_str(&format!("APOLLO_CHAT_ID=\"{}\"\n", c));
            }
            if let Some(ref t) = dc_token {
                env_content.push_str(&format!("APOLLO_DISCORD_TOKEN=\"{}\"\n", t));
            }
            if let Some(ref c) = dc_channel {
                env_content.push_str(&format!("APOLLO_DISCORD_CHANNEL=\"{}\"\n", c));
            }
            std::fs::write(&env_path, &env_content)?;

            // === Write config ===
            let mut cfg = Config::default_config();
            cfg.provider.name = provider.clone();
            cfg.provider.api_key = None; // Secrets stay in .env
            if provider == "ollama" {
                cfg.provider.base_url = Some("http://localhost:11434".to_string());
                if cfg.embeddings.provider == "noop" {
                    cfg.embeddings.enabled = true;
                    cfg.embeddings.provider = "ollama".to_string();
                    cfg.embeddings.model = Some("nomic-embed-text".to_string());
                    cfg.embeddings.base_url = Some("http://localhost:11434".to_string());
                }
            }
            cfg.model = model.clone();
            apply_permission_profile(&mut cfg, &permission_profile);
            let json = serde_json::to_string_pretty(&cfg)?;
            let config_path = workspace.join("apollo.json");
            std::fs::write(&config_path, &json)?;

            // === Write systemd service ===
            let bin_path = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("apollo"));
            let service_dir = dirs::home_dir()
                .unwrap_or_default()
                .join(".config/systemd/user");
            std::fs::create_dir_all(&service_dir)?;

            let mut exec_args = format!("{} chat --channel {}", bin_path.display(), channel);
            if tg_token.is_some() {
                exec_args.push_str(&format!(
                    " --telegram-token $APOLLO_TELEGRAM_TOKEN --telegram-chat-id {}",
                    tg_chat_id.as_deref().unwrap_or("0")
                ));
            }
            exec_args.push_str(&format!(" --model {}", model));

            let run_script = format!(
                "#!/bin/bash\nsource {}\nexport RUST_LOG=info\ncd {}\nexec {}\n",
                env_path.display(),
                workspace.display(),
                exec_args,
            );
            let run_path = workspace.join("run.sh");
            std::fs::write(&run_path, &run_script)?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&run_path, std::fs::Permissions::from_mode(0o755))?;
            }

            let service = format!(
                "[Unit]\nDescription=apollo AI agent\nAfter=network-online.target\n\n\
                [Service]\nType=simple\nExecStart={}\nRestart=always\nRestartSec=5\n\
                WorkingDirectory={}\nStandardOutput=append:/tmp/apollo.log\n\
                StandardError=append:/tmp/apollo.log\n\n\
                [Install]\nWantedBy=default.target\n",
                run_path.display(),
                workspace.display()
            );
            std::fs::write(service_dir.join("apollo.service"), &service)?;

            // === Summary ===
            println!("\n✅ Setup complete!\n");
            println!("  Provider:  {}", cfg.provider.name);
            println!("  Model:     {}", model);
            println!("  Channel:   {}", channel);
            println!(
                "  Safety:    {} (see agent.permission_profile in {})",
                cfg.agent.permission_profile,
                config_path.display()
            );
            println!("  Config:    {}", config_path.display());
            println!("  Secrets:   {}", env_path.display());
            println!("  Service:   ~/.config/systemd/user/apollo.service");
            println!("\n  Commands:");
            println!("    systemctl --user daemon-reload");
            println!("    systemctl --user enable --now apollo");
            println!("    journalctl --user -u apollo -f");

            // === Auto-start ===
            if start {
                println!("\n  Starting...");
                let _ = std::process::Command::new("systemctl")
                    .args(["--user", "daemon-reload"])
                    .status();
                let _ = std::process::Command::new("systemctl")
                    .args(["--user", "enable", "--now", "apollo"])
                    .status();
                println!("  🐾 apollo is running!");
            }
        }

        Commands::Message {
            message,
            chat_id: _,
            workspace: _,
        } => {
            let client = reqwest::Client::new();
            let resp = client
                .post("http://127.0.0.1:31337/message")
                .json(&serde_json::json!({ "message": message }))
                .send()
                .await;

            match resp {
                Ok(r) if r.status().is_success() => {
                    println!("✅ Sent to apollo");
                }
                Ok(r) => {
                    eprintln!(
                        "❌ HTTP {}: {}",
                        r.status(),
                        r.text().await.unwrap_or_default()
                    );
                }
                Err(_) => {
                    eprintln!(
                        "❌ Can't reach apollo. Is it running? (systemctl --user status apollo)"
                    );
                }
            }
        }

        Commands::Cron {
            action,
            workspace,
            config,
        } => {
            let workspace = workspace.unwrap_or_else(|| PathBuf::from("."));
            let cfg = load_config(&config);
            let memory = build_memory_backend(&workspace, &cfg).await?;

            if let Some(surreal_mem) = memory
                .as_any()
                .downcast_ref::<apollo::memory::surreal::SurrealMemory>()
            {
                let scheduler = CronScheduler::new(Arc::new(surreal_mem.clone()));

                match action {
                    CronAction::Add {
                        name,
                        schedule,
                        task,
                        channel,
                        chat_id,
                        model,
                    } => {
                        let id = scheduler
                            .add(&name, &schedule, &task, &channel, &chat_id, &model)
                            .await?;
                        println!("Added cron job: {} (id: {})", name, id);
                    }
                    CronAction::List => {
                        let jobs = scheduler.list().await?;
                        if jobs.is_empty() {
                            println!("No cron jobs configured.");
                        } else {
                            for job in &jobs {
                                println!(
                                    "{} [{}] {}\"{}\" (next: {})",
                                    if job.enabled { "+" } else { "-" },
                                    job.name,
                                    job.schedule,
                                    job.task,
                                    job.next_run.as_deref().unwrap_or("none"),
                                );
                            }
                        }
                    }
                    CronAction::Remove { id_or_name } => {
                        if scheduler.remove(&id_or_name).await? {
                            println!("Removed: {}", id_or_name);
                        } else {
                            println!("Not found: {}", id_or_name);
                        }
                    }
                    CronAction::Enable { id_or_name } => {
                        if scheduler.enable(&id_or_name).await? {
                            println!("Enabled: {}", id_or_name);
                        } else {
                            println!("Not found: {}", id_or_name);
                        }
                    }
                    CronAction::Disable { id_or_name } => {
                        if scheduler.disable(&id_or_name).await? {
                            println!("Disabled: {}", id_or_name);
                        } else {
                            println!("Not found: {}", id_or_name);
                        }
                    }
                }
            } else {
                anyhow::bail!("Cron scheduler requires SurrealDB backend");
            }
        }

        Commands::Autonomous {
            config,
            workspace,
            interval,
            start,
            resume,
        } => {
            let workspace = workspace.unwrap_or_else(|| load_config(&config).workspace.clone());
            let cfg = apollo::bootstrap::load_config_workspace(&config, Some(&workspace));
            let model = cfg.model.clone();
            let _ = apollo::workspace_init::ensure_workspace_kit(&workspace);

            let provider = build_provider(&cfg);
            let policy = Arc::new(ExecutionPolicy::from_config(&cfg.policy));
            let memory = build_memory_backend(&workspace, &cfg).await?;
            let embedding_provider = build_embedding_provider(&cfg)?;

            let system_prompt = prompt::build_system_prompt(&workspace).await;
            let discovered_skills = skills::discover_skills_for_workspace(Some(&workspace));

            #[cfg(feature = "zkr-memory")]
            let zkr_store = apollo::bootstrap::build_zkr_store(&workspace, &cfg)
                .ok()
                .flatten();
            #[cfg(feature = "zkr-memory")]
            let mut tools = build_base_tools(
                &workspace,
                Arc::clone(&policy),
                memory.clone(),
                embedding_provider,
                Arc::clone(&provider),
                &cfg,
                zkr_store.clone(),
            );
            #[cfg(not(feature = "zkr-memory"))]
            let mut tools = build_base_tools(
                &workspace,
                Arc::clone(&policy),
                memory.clone(),
                embedding_provider,
                Arc::clone(&provider),
                &cfg,
            );

            for dt in apollo::tools::dynamic::DynamicTool::load_all(Arc::clone(&policy)) {
                tools.push(Arc::new(dt));
            }

            let mut runner =
                AgentRunner::new(provider, tools, memory.clone(), &system_prompt, model)
                    .with_config(cfg.agent.clone())
                    .with_mode(agent_mode_from_permission_profile(
                        &cfg.agent.permission_profile,
                    ))
                    .with_workspace(workspace.clone())
                    .with_memory_ideas(cfg.memory.clone())
                    .with_group_chat(cfg.group_chat.clone())
                    .with_skills(discovered_skills)
                    .await;
            #[cfg(feature = "zkr-memory")]
            {
                runner = runner.with_zkr(zkr_store.clone(), cfg.zkr.clone());
            }

            {
                let mut host_reg = apollo::plugin::PluginRegistry::new();
                host_reg.ingest_host_plugins(&workspace, &cfg.plugin_layer.host_plugin_roots);
                runner = runner.with_plugin_registry(host_reg).await;
            }

            let runner_arc = Arc::new(runner);
            runner_arc.add_hook(Arc::new(PermissionHook::new(
                cfg.agent.permissions.deny.clone(),
                cfg.agent.permissions.allow.clone(),
            )));

            let mut autonomous_config = AutonomousConfig::default();
            if let Some(secs) = interval {
                autonomous_config.interval_secs = secs;
            }
            let interval_secs = autonomous_config.interval_secs;

            let mut autonomous_loop = AutonomousLoop::new(autonomous_config, workspace.clone());
            if start {
                autonomous_loop.start_fresh();
            } else if resume {
                autonomous_loop.resume();
            }

            println!(
                "apollo v{} — autonomous mode (interval={}s)",
                env!("CARGO_PKG_VERSION"),
                interval_secs
            );
            println!("   Workspace: {}", workspace.display());
            println!("   Press Ctrl+C to stop");

            autonomous_loop.run(runner_arc).await;
        }

        Commands::Swarm { action, workspace } => {
            #[cfg(not(feature = "swarm"))]
            {
                let _ = (action, workspace);
                eprintln!("Swarm requires the 'swarm' feature. Build with: cargo build --release --features swarm");
                std::process::exit(1);
            }

            #[cfg(feature = "swarm")]
            {
                use apollo::swarm::models::LinkDirection;
                use apollo::swarm::{
                    AgentCapability, SurrealBackend, SwarmCoordinator, SwarmStorage, TaskPriority,
                };

                let workspace = workspace.unwrap_or_else(|| PathBuf::from("."));
                let surreal_path = workspace.join(".apollo/swarm.surreal");

                // Ensure directory exists
                if let Some(parent) = surreal_path.parent() {
                    std::fs::create_dir_all(parent)?;
                }

                let storage: Arc<dyn SwarmStorage> =
                    Arc::new(SurrealBackend::new(&surreal_path).await?);
                let coordinator = SwarmCoordinator::new(storage.clone());
                coordinator.init().await?;

                match action {
                    SwarmAction::Start {
                        surreal_path: _,
                        cache_path: _,
                    } => {
                        println!(
                            "Swarm coordinator initialized at {}",
                            surreal_path.display()
                        );
                        println!("Ready for agent registration.");
                    }

                    SwarmAction::AgentCreate {
                        name,
                        model,
                        capabilities,
                        tools,
                        max_concurrent,
                    } => {
                        let caps: Vec<AgentCapability> = capabilities
                            .split(',')
                            .filter_map(|c| match c.trim() {
                                "coding" => Some(AgentCapability::Coding),
                                "research" => Some(AgentCapability::Research),
                                "review" => Some(AgentCapability::Review),
                                "testing" => Some(AgentCapability::Testing),
                                "documentation" => Some(AgentCapability::Documentation),
                                "design" => Some(AgentCapability::Design),
                                "devops" => Some(AgentCapability::DevOps),
                                "security" => Some(AgentCapability::Security),
                                _ => None,
                            })
                            .collect();

                        let tool_list =
                            tools.map(|t| t.split(',').map(|s| s.trim().to_string()).collect());

                        let agent_id = coordinator
                            .register_agent(name.clone(), caps, Some(model.clone()), tool_list)
                            .await?;

                        // Update max_concurrent
                        storage.update_agent_status(&agent_id, "active").await?;

                        println!("Agent '{}' created (id: {})", name, agent_id);
                        println!("  Model: {}", model);
                        println!("  Max concurrent: {}", max_concurrent);
                    }

                    SwarmAction::AgentLink {
                        source,
                        target,
                        direction,
                        max_concurrent,
                    } => {
                        let dir = match direction.as_str() {
                            "outbound" => LinkDirection::Outbound,
                            "inbound" => LinkDirection::Inbound,
                            "bidirectional" | "bidi" => LinkDirection::Bidirectional,
                            _ => {
                                eprintln!(
                                    "Unknown direction: {} (use: outbound, inbound, bidirectional)",
                                    direction
                                );
                                std::process::exit(1);
                            }
                        };

                        // Resolve names to IDs
                        let src = storage
                            .get_agent_by_name(&source)
                            .await?
                            .ok_or_else(|| anyhow::anyhow!("Agent '{}' not found", source))?;
                        let tgt = storage
                            .get_agent_by_name(&target)
                            .await?
                            .ok_or_else(|| anyhow::anyhow!("Agent '{}' not found", target))?;

                        let link = coordinator
                            .delegation
                            .create_link(&src.agent_id, &tgt.agent_id, dir, max_concurrent)
                            .await?;

                        println!(
                            "Link created: {} -> {} ({}, max {})",
                            source, target, direction, max_concurrent
                        );
                        println!("  Link ID: {}", link.link_id);
                    }

                    SwarmAction::TeamCreate { name, lead } => {
                        let lead_agent = storage
                            .get_agent_by_name(&lead)
                            .await?
                            .ok_or_else(|| anyhow::anyhow!("Lead agent '{}' not found", lead))?;

                        let team = coordinator
                            .teams
                            .create_team(&name, &lead_agent.agent_id)
                            .await?;
                        println!("Team '{}' created (id: {})", name, team.team_id);
                        println!("  Lead: {}", lead);
                    }

                    SwarmAction::TeamTaskAdd {
                        team,
                        subject,
                        priority,
                        blocked_by,
                    } => {
                        let team_obj = coordinator
                            .teams
                            .get_team_by_name(&team)
                            .await?
                            .ok_or_else(|| anyhow::anyhow!("Team '{}' not found", team))?;

                        let blockers = blocked_by
                            .map(|b| b.split(',').map(|s| s.trim().to_string()).collect())
                            .unwrap_or_default();

                        let task = coordinator
                            .teams
                            .create_task(&team_obj.team_id, &subject, None, priority, blockers)
                            .await?;
                        println!(
                            "Task added to team '{}': {} (id: {})",
                            team, subject, task.task_id
                        );
                    }

                    SwarmAction::Agents => {
                        let agents = coordinator.list_all_agents().await?;
                        if agents.is_empty() {
                            println!("No agents registered.");
                        } else {
                            println!(
                                "{:<20} {:<12} {:<25} {:<10}",
                                "NAME", "STATUS", "MODEL", "MAX_CONC"
                            );
                            for a in &agents {
                                println!(
                                    "{:<20} {:<12} {:<25} {:<10}",
                                    a.name,
                                    a.status.to_string(),
                                    a.model.as_deref().unwrap_or("-"),
                                    a.max_concurrent.unwrap_or(5),
                                );
                            }
                        }
                    }

                    SwarmAction::Tasks => {
                        let tasks = coordinator.list_pending_tasks().await?;
                        if tasks.is_empty() {
                            println!("No pending tasks.");
                        } else {
                            for t in &tasks {
                                println!("[{:?}] {}{}", t.priority, t.title, t.status);
                            }
                        }
                    }

                    SwarmAction::Teams => {
                        let teams = coordinator.teams.list_teams().await?;
                        if teams.is_empty() {
                            println!("No teams.");
                        } else {
                            let ids: Vec<String> =
                                teams.iter().map(|t| t.team_id.clone()).collect();
                            let counts = coordinator.teams.member_counts_for(&ids).await?;
                            for t in &teams {
                                let n = counts.get(&t.team_id).copied().unwrap_or(0);
                                println!(
                                    "{} (lead: {}, members: {}, status: {})",
                                    t.name, t.lead_agent_id, n, t.status
                                );
                            }
                        }
                    }

                    SwarmAction::Delegations { agent } => {
                        let agent_obj = storage
                            .get_agent_by_name(&agent)
                            .await?
                            .ok_or_else(|| anyhow::anyhow!("Agent '{}' not found", agent))?;
                        let delegations = coordinator
                            .delegation
                            .list_active(&agent_obj.agent_id)
                            .await?;
                        if delegations.is_empty() {
                            println!("No active delegations for '{}'.", agent);
                        } else {
                            for d in &delegations {
                                println!(
                                    "[{}] {} -> {} ({:?}): {}",
                                    d.status, d.source_agent_id, d.target_agent_id, d.mode, d.task
                                );
                            }
                        }
                    }

                    SwarmAction::Task {
                        description,
                        priority,
                        title,
                    } => {
                        let prio = match priority.as_str() {
                            "low" => TaskPriority::Low,
                            "medium" => TaskPriority::Medium,
                            "high" => TaskPriority::High,
                            "critical" => TaskPriority::Critical,
                            _ => TaskPriority::Medium,
                        };
                        let title = title.unwrap_or_else(|| {
                            description
                                .lines()
                                .next()
                                .unwrap_or(&description)
                                .to_string()
                        });
                        let task_id = coordinator
                            .submit_task(title.clone(), description, prio)
                            .await?;
                        println!("Task submitted: {} (id: {})", title, task_id);
                    }

                    SwarmAction::Queue { message } => {
                        coordinator.queue_message(message.clone()).await;
                        println!("Message queued: {}", message);
                    }

                    SwarmAction::Status => {
                        let status = coordinator.scheduler.get_status().await;
                        println!("Scheduler Status:");
                        for (lane, (active, max)) in &status.lane_usage {
                            println!("  {}: {}/{}", lane, active, max);
                        }
                        if !status.deadlocks.is_empty() {
                            println!("\nDEADLOCKS DETECTED:");
                            for cycle in &status.deadlocks {
                                println!("  Cycle: {}", cycle.join(" -> "));
                            }
                        }
                    }
                }
            }
        }

        Commands::Ui => {
            launch_apollo_ui().await?;
        }
    }

    Ok(())
}

async fn launch_apollo_ui() -> anyhow::Result<()> {
    let binary = find_apollo_ui_binary().await.ok_or_else(|| {
        eprintln!("apollo-ui binary not found.");
        eprintln!("  cargo run -p apollo-ui");
        eprintln!("  cargo build --release -p apollo-ui");
        anyhow::anyhow!("apollo-ui binary not found")
    })?;

    let cwd = std::env::current_dir()?;
    let status = tokio::process::Command::new(&binary)
        .current_dir(&cwd)
        .status()
        .await?;

    if !status.success() {
        anyhow::bail!("apollo-ui exited with status: {status}");
    }

    Ok(())
}

async fn find_apollo_ui_binary() -> Option<PathBuf> {
    if let Ok(current) = std::env::current_exe() {
        if let Some(dir) = current.parent() {
            let sibling = dir.join("apollo-ui");
            if sibling.is_file() {
                return Some(sibling);
            }
        }
    }

    let on_path = tokio::process::Command::new("which")
        .arg("apollo-ui")
        .output()
        .await
        .map(|output| output.status.success())
        .unwrap_or(false);

    if on_path {
        Some(PathBuf::from("apollo-ui"))
    } else {
        None
    }
}

fn compiled_in_providers() -> Vec<&'static str> {
    let mut names = vec![
        "cerebras",
        "cloudflare",
        "deepseek",
        "fireworks",
        "groq",
        "huggingface",
        "minimax",
        "mistral",
        "moonshot",
        "openai",
        "openrouter",
        "perplexity",
        "siliconflow",
        "together",
        "venice",
        "vercel",
        "xai",
    ];
    #[cfg(feature = "provider-anthropic")]
    names.push("anthropic");
    #[cfg(feature = "provider-copilot")]
    names.push("copilot");
    #[cfg(feature = "provider-ollama")]
    names.push("ollama");
    names.sort();
    names.dedup();
    names
}

fn get_provider_matches<'a>(all: &[&'a str], filter: &str) -> Vec<&'a str> {
    let needle = filter.trim().to_lowercase();
    if needle.is_empty() {
        all.to_vec()
    } else {
        all.iter()
            .copied()
            .filter(|n| n.to_lowercase().contains(&needle))
            .collect()
    }
}

fn print_provider_matches(matches: &[&str]) {
    if matches.is_empty() {
        println!("  (no matches — try another filter)");
    } else {
        println!("\n  Matching providers:");
        for (i, n) in matches.iter().enumerate() {
            println!("    [{}] {}", i + 1, n);
        }
    }
}

fn parse_provider_selection(input: &str, matches: &[&str], all: &[&str]) -> Option<String> {
    if input.is_empty() {
        if matches.len() == 1 {
            return Some(matches[0].to_string());
        }
        return None;
    }
    if let Ok(idx) = input.parse::<usize>() {
        if (1..=matches.len()).contains(&idx) {
            return Some(matches[idx - 1].to_string());
        }
    }
    if let Some(found) = matches.iter().find(|n| n.eq_ignore_ascii_case(input)) {
        return Some((*found).to_string());
    }
    if let Some(found) = all.iter().find(|n| n.eq_ignore_ascii_case(input)) {
        return Some((*found).to_string());
    }
    None
}

fn prompt_provider_interactive() -> anyhow::Result<String> {
    let all = compiled_in_providers();
    println!("  Choose a provider (type to filter the list, then pick a number or exact name):");
    let mut filter = String::new();
    loop {
        let matches = get_provider_matches(&all, &filter);
        print_provider_matches(&matches);

        eprint!("  Filter, #, or exact name (empty = pick if exactly one match): ");
        let mut line = String::new();
        std::io::stdin().read_line(&mut line)?;
        let t = line.trim();

        if let Some(selection) = parse_provider_selection(t, &matches, &all) {
            return Ok(selection);
        }

        if !t.is_empty() {
            filter = t.to_string();
        }
    }
}

fn prompt_permission_profile_interactive() -> anyhow::Result<String> {
    println!("\n  Permission profile:");
    println!("    full        — autonomous mode (no plan approval; shell and dynamic tools on)");
    println!("    auto        — default heuristics with shell enabled");
    println!("    prompt      — approve plans before executing tools (not per-tool prompts)");
    println!("    tools_only  — web + memory + session tools only (no shell or file writes)");
    eprint!("  Choose [full / auto / prompt / tools_only] [auto]: ");
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf)?;
    let s = buf.trim();
    if s.is_empty() {
        return Ok("auto".to_string());
    }
    Ok(s.to_string())
}

fn config_path_for_cli(cli: &Cli) -> Option<String> {
    match &cli.command {
        None => Some("apollo.json".into()),
        Some(Commands::Chat { config, .. })
        | Some(Commands::Ask { config, .. })
        | Some(Commands::Doctor { config, .. })
        | Some(Commands::Audit { config, .. })
        | Some(Commands::SelfUpdate { config, .. })
        | Some(Commands::Mcp { config, .. })
        | Some(Commands::Autonomous { config, .. }) => Some(config.clone()),
        Some(_) => None,
    }
}

fn init_tracing(cfg: &apollo::config::ObservabilityConfig) -> anyhow::Result<()> {
    let env_filter = tracing_subscriber::EnvFilter::from_default_env();
    let fmt = tracing_subscriber::fmt().with_env_filter(env_filter);
    if cfg.json_logs {
        fmt.json()
            .try_init()
            .map_err(|error| anyhow::anyhow!(error.to_string()))?;
    } else {
        fmt.try_init()
            .map_err(|error| anyhow::anyhow!(error.to_string()))?;
    }
    tracing::info!(
        service_name = %cfg.service_name,
        environment = %cfg.environment,
        trace_header = %cfg.trace_header_name,
        "tracing initialized"
    );
    Ok(())
}