mentedb-mcp 0.5.30

MCP server for MenteDB, the cognition aware database for AI agent memory
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
mod cloud_client;
mod cloud_server;
mod config;
#[cfg(feature = "local")]
mod daemon;
mod hook;
#[cfg(feature = "local")]
mod resources;
#[cfg(feature = "local")]
mod server;
#[cfg(feature = "local")]
mod tools;

use clap::{Parser, Subcommand};
use tracing_appender::non_blocking;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::fmt;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;

#[cfg(feature = "local")]
use config::ServerConfig;
use config::resolve_data_dir;

fn home_dir() -> Option<String> {
    std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .ok()
}

/// Every Claude Code settings directory on this machine. Users running
/// separate configs (work vs personal) set CLAUDE_CONFIG_DIR or keep
/// multiple ~/.claude-* directories; writing hooks to only ~/.claude then
/// configures an instance they never run. Order: CLAUDE_CONFIG_DIR first,
/// then ~/.claude, then any ~/.claude-* directory that already has a
/// settings.json.
fn claude_config_dirs(home: &str) -> Vec<std::path::PathBuf> {
    let mut dirs: Vec<std::path::PathBuf> = Vec::new();
    if let Ok(v) = std::env::var("CLAUDE_CONFIG_DIR")
        && !v.trim().is_empty()
    {
        dirs.push(std::path::PathBuf::from(v));
    }

    let default = std::path::PathBuf::from(home).join(".claude");
    if !dirs.contains(&default) {
        dirs.push(default);
    }

    if let Ok(entries) = std::fs::read_dir(home) {
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if name.starts_with(".claude-")
                && entry.path().is_dir()
                && entry.path().join("settings.json").exists()
                && !dirs.contains(&entry.path())
            {
                dirs.push(entry.path());
            }
        }
    }
    dirs
}

#[derive(Parser)]
#[command(name = "mentedb-mcp", about = "MCP server for MenteDB")]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Path to the data directory
    #[arg(long, default_value = "~/.mentedb", global = true)]
    data_dir: String,

    /// Embedding dimension (local mode only)
    #[cfg(feature = "local")]
    #[arg(long, default_value = "128")]
    embedding_dim: usize,

    /// LLM provider: openai, anthropic, ollama, or mock (local mode only)
    #[cfg(feature = "local")]
    #[arg(long, default_value = "mock", env = "MENTEDB_LLM_PROVIDER")]
    llm_provider: String,

    /// API key for the LLM provider (local mode only)
    #[cfg(feature = "local")]
    #[arg(long, env = "MENTEDB_LLM_API_KEY")]
    llm_api_key: Option<String>,

    /// Model name override for the LLM provider (local mode only)
    #[cfg(feature = "local")]
    #[arg(long, env = "MENTEDB_LLM_MODEL")]
    llm_model: Option<String>,

    /// Expose all tools (local mode only)
    #[cfg(feature = "local")]
    #[arg(long)]
    full_tools: bool,

    /// Force local mode (use embedded database even when cloud credentials exist)
    #[arg(long)]
    local: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Auto-configure MenteDB for your MCP client (Copilot CLI, Claude, Cursor, etc.)
    Setup {
        /// Target client
        #[arg(value_enum, default_value = "claude-code")]
        client: SetupClient,
    },
    /// Update MCP config and agent instructions (overwrites existing entries)
    Update {
        /// Target client
        #[arg(value_enum, default_value = "claude-code")]
        client: SetupClient,
    },
    /// Authenticate with MenteDB Cloud
    Login,
    /// Remove cloud credentials
    Logout,
    /// Manage named MenteDB accounts (add, list, use, remove)
    Accounts {
        #[command(subcommand)]
        command: AccountsCommand,
    },
    /// Check cloud connection status
    Status,
    /// Diagnose the full memory pipeline (credentials, hooks, capture, spool)
    Doctor,
    /// Push memories from the local database up to MenteDB Cloud
    #[cfg(feature = "local")]
    Sync,
    /// Process a client lifecycle hook (reads JSON payload from stdin)
    Hook {
        /// Hook event to process
        #[arg(value_enum)]
        event: hook::HookEvent,
    },
    /// Run the local hook daemon (owns the embedded database)
    #[cfg(feature = "local")]
    Daemon,
}

#[derive(Subcommand)]
enum AccountsCommand {
    /// Register a named account with an mdb_ API key (prompts if --key omitted)
    Add {
        /// Account name, e.g. "work" or "personal"
        name: String,
        /// The mdb_ API key. If omitted, you are prompted (key is not echoed).
        #[arg(long)]
        key: Option<String>,
        /// Optional per-account cloud API URL override
        #[arg(long)]
        cloud_url: Option<String>,
    },
    /// List accounts, showing which is active (keys are masked)
    List,
    /// Set the active account (all cloud operations use its key)
    Use {
        /// Account name to activate
        name: String,
    },
    /// Remove a named account
    Remove {
        /// Account name to remove
        name: String,
    },
}

#[derive(Clone, clap::ValueEnum)]
enum SetupClient {
    Copilot,
    Claude,
    Cursor,
    /// Claude Code (the CLI): lifecycle hooks, no MCP tool schemas
    ClaudeCode,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Some(Commands::Setup { client }) => return run_setup(client, false),
        Some(Commands::Update { client }) => return run_setup(client, true),
        Some(Commands::Login) => return run_login().await,
        Some(Commands::Logout) => return run_logout(),
        Some(Commands::Accounts { command }) => return run_accounts(command).await,
        Some(Commands::Status) => return run_status().await,
        Some(Commands::Doctor) => {
            let data_dir = resolve_data_dir(&cli.data_dir);
            return run_doctor(&data_dir).await;
        }
        #[cfg(feature = "local")]
        Some(Commands::Sync) => {
            let data_dir = resolve_data_dir(&cli.data_dir);
            return run_sync(&data_dir).await;
        }
        Some(Commands::Hook { event }) => {
            // Hooks print only their payload on stdout; logging goes to the
            // data directory so a noisy logger can never corrupt the output
            // the client parses.
            let data_dir = resolve_data_dir(&cli.data_dir);
            std::fs::create_dir_all(&data_dir).ok();
            let file_appender = tracing_appender::rolling::daily(&data_dir, "mentedb-hook.log");
            let (file_writer, _guard) = non_blocking(file_appender);
            tracing_subscriber::registry()
                .with(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
                .with(fmt::layer().with_writer(file_writer).with_ansi(false))
                .init();
            return hook::run(event, data_dir, cli.local).await;
        }
        #[cfg(feature = "local")]
        Some(Commands::Daemon) => {
            let data_dir = resolve_data_dir(&cli.data_dir);
            std::fs::create_dir_all(&data_dir).ok();
            let file_appender = tracing_appender::rolling::daily(&data_dir, "mentedb-daemon.log");
            let (file_writer, _guard) = non_blocking(file_appender);
            tracing_subscriber::registry()
                .with(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
                .with(fmt::layer().with_writer(file_writer).with_ansi(false))
                .init();
            let config = ServerConfig::new(
                data_dir,
                cli.embedding_dim,
                cli.llm_provider,
                cli.llm_api_key,
                cli.llm_model,
                cli.full_tools,
            );
            return daemon::run(config).await;
        }
        None => {}
    }

    let data_dir = resolve_data_dir(&cli.data_dir);

    // Ensure data directory exists for log file
    std::fs::create_dir_all(&data_dir).ok();

    // File logger (persistent, all levels)
    let log_path = data_dir.join("mentedb-mcp.log");
    let file_appender = tracing_appender::rolling::daily(&data_dir, "mentedb-mcp.log");
    let (file_writer, _guard) = non_blocking(file_appender);

    // Stderr logger (for MCP clients that capture stderr)
    let (stderr_writer, _stderr_guard) = non_blocking(std::io::stderr());

    tracing_subscriber::registry()
        .with(EnvFilter::from_default_env().add_directive(tracing::Level::INFO.into()))
        .with(
            fmt::layer()
                .with_writer(file_writer)
                .with_ansi(false)
                .with_target(true)
                .with_thread_ids(true),
        )
        .with(
            fmt::layer()
                .with_writer(stderr_writer)
                .with_ansi(false)
                .with_target(false),
        )
        .init();

    tracing::info!(
        version = env!("CARGO_PKG_VERSION"),
        data_dir = %data_dir.display(),
        log_file = %log_path.display(),
        "mentedb-mcp starting"
    );

    // Auto-update agent instructions on startup (silent, best-effort)
    auto_update_instructions();

    // If stdin is a TTY, the user ran this directly — show help instead of hanging.
    if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        eprintln!("mentedb-mcp v{}", env!("CARGO_PKG_VERSION"));
        eprintln!();
        eprintln!("This is an MCP (Model Context Protocol) server that communicates over stdio.");
        eprintln!("It's designed to be launched by an MCP client, not run directly.");
        eprintln!();
        eprintln!("Quick start:");
        eprintln!(
            "  mentedb-mcp setup     Set up MenteDB in your editor (Copilot CLI, Cursor, etc.)"
        );
        eprintln!("  mentedb-mcp login     Authenticate with MenteDB Cloud");
        eprintln!("  mentedb-mcp status    Check connection and configuration");
        eprintln!();
        eprintln!("For more info: https://mentedb.com/docs");
        std::process::exit(0);
    }

    // Check for cloud credentials — if present, use cloud mode (HTTP proxy, no local DB).
    // This allows multiple MCP server instances to run concurrently.
    if !cli.local
        && let Some((api_url, token)) = load_cloud_credentials()
    {
        tracing::info!("Cloud credentials found, starting in cloud mode (no local database)");
        return cloud_server::run(api_url, token).await;
    }

    // No cloud credentials or --local flag — fall back to local embedded database mode.
    #[cfg(feature = "local")]
    {
        tracing::info!("Starting in local mode (embedded database)");

        let config = ServerConfig::new(
            data_dir,
            cli.embedding_dim,
            cli.llm_provider,
            cli.llm_api_key,
            cli.llm_model,
            cli.full_tools,
        );

        server::run(config).await
    }

    #[cfg(not(feature = "local"))]
    {
        tracing::error!(
            "No cloud credentials found. Run `mentedb-mcp login` to connect to MenteDB Cloud, or rebuild with --features local for embedded mode."
        );
        anyhow::bail!(
            "No cloud credentials found. Run `mentedb-mcp login` to connect to MenteDB Cloud."
        )
    }
}

/// Auto-update agent instructions on startup.
/// Checks all known instruction file paths and updates any with stale version markers.
/// Runs silently — errors are logged but never block server startup.
fn auto_update_instructions() {
    let home = match home_dir() {
        Some(h) => h,
        None => return,
    };

    let current_version = env!("CARGO_PKG_VERSION");
    let version_marker = format!("<!-- mentedb-instructions-v{current_version} -->");

    let instruction_paths = [
        // Copilot CLI
        format!("{home}/.copilot/copilot-instructions.md"),
        // Cursor
        format!("{home}/.cursor/rules/mentedb.md"),
    ];

    for path_str in &instruction_paths {
        let path = std::path::Path::new(path_str);
        if !path.exists() {
            continue;
        }

        // Check if update is needed before calling append_instructions
        let needs_update = std::fs::read_to_string(path)
            .map(|content| !content.contains(&version_marker))
            .unwrap_or(false);

        if !needs_update {
            continue;
        }

        let old_version = std::fs::read_to_string(path)
            .ok()
            .and_then(|c| {
                c.lines()
                    .find(|l| l.contains("<!-- mentedb-instructions-v"))
                    .and_then(|l| {
                        l.trim()
                            .strip_prefix("<!-- mentedb-instructions-v")
                            .and_then(|s| s.strip_suffix(" -->"))
                            .map(String::from)
                    })
            })
            .unwrap_or_else(|| "unknown".to_string());

        match append_instructions(path, false, false) {
            Ok(()) => {
                tracing::info!(
                    path = %path.display(),
                    from = %old_version,
                    to = %current_version,
                    "auto-updated agent instructions"
                );
            }
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "auto-update instructions failed");
            }
        }
    }
}

const TOOL_NAMES: &[&str] = &[
    "process_turn",
    "store_memory",
    "search_memories",
    "forget_memory",
];

const AGENT_INSTRUCTIONS: &str = r#"# Memory

You have persistent memory via MenteDB. You have 4 tools — use them.

## process_turn — CALL EVERY TURN

Call `process_turn` on EVERY turn. Pass `user_message` and `assistant_response`.
- It returns relevant context from past conversations, stores the current turn, and detects contradictions.
- Without this call, nothing is remembered.
- Increment `turn_id` each turn (start at 0).
- `assistant_response` can be brief or empty if you have not yet drafted a response.

## USE the returned context

When `process_turn` returns:
- **context**: Summaries with IDs from past conversations. Reference them in your response.
- **pain_warnings**: If non-empty, WARN the user — a similar situation caused problems before.
- **contradictions**: If > 0, flag the inconsistency.

## store_memory — Save important facts

When you notice important information, call `store_memory`:
- **Preferences**: "User prefers Rust" → type: semantic, tags: [preference]
- **Decisions**: "Using PostgreSQL" → type: semantic, tags: [decision]
- **Corrections**: "Deadline is April, not March" → type: correction
- **Procedures**: "Deploy with: cargo build --release" → type: procedural
- **Mistakes**: "Never retag releases" → type: anti_pattern

When the user explicitly says "remember this", "always remember", "don't forget", or similar — call `store_memory` immediately in that same turn. Do not rely on process_turn extraction for explicit requests.

Don't store chitchat. Store facts, preferences, decisions, corrections.

## search_memories — Look things up

Pass a text query to search by similarity, or a memory UUID to get full content.
Use proactively — if the user mentions a project, search for what you know about it.

## forget_memory — Delete memories

When the user says "forget" or "don't remember that", delete the memory by ID.

## Scope

Set `scope: 'always'` for critical rules that must be surfaced every turn regardless of topic. Default is `scope: 'contextual'` (retrieved by semantic similarity). Use `'always'` when the user says "always remember this" or states a hard rule.

## Writing good memories

- One fact per memory — self-contained with project context
- Keep under 200 words. Summarize if needed.
- If a fact changes, store as a `correction` — contradictions are detected automatically.
- Do NOT store: greetings, temporary info, large code blocks, one-off details

## Resilience

Even if `process_turn` fails or errors on a turn, ALWAYS call it again on the next turn. Never skip because of a prior failure.
"#;

async fn run_login() -> anyhow::Result<()> {
    use std::net::TcpListener;
    use tokio::sync::oneshot;

    println!("\nAuthenticating with MenteDB Cloud...\n");

    // Find available port
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let port = listener.local_addr()?.port();
    drop(listener);

    // Channel to receive the token
    let (tx, rx) = oneshot::channel::<String>();
    let tx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(tx)));

    // One-time nonce: the callback only accepts a token from the browser tab
    // this login opened, so another local process or a malicious page cannot
    // plant its own credentials.
    let state_nonce = uuid::Uuid::new_v4().to_string();
    let expected_state = state_nonce.clone();

    let cloud_url = std::env::var("MENTEDB_CLOUD_URL")
        .unwrap_or_else(|_| "https://app.mentedb.com".to_string());

    // Build CORS headers with the cloud dashboard as allowed origin
    let origin_value = axum::http::HeaderValue::from_str(&cloud_url)
        .unwrap_or_else(|_| axum::http::HeaderValue::from_static("https://app.mentedb.com"));
    let origin_for_post = origin_value.clone();

    // Start local HTTP server
    let tx_clone = tx.clone();
    let server = axum::Router::new()
        .route(
            "/callback",
            axum::routing::post(move |body: axum::Json<serde_json::Value>| {
                let tx = tx_clone.clone();
                let origin = origin_for_post.clone();
                let expected_state = expected_state.clone();
                async move {
                    let api_key = body
                        .get("api_key")
                        .and_then(|v| v.as_str())
                        .unwrap_or_default()
                        .to_string();
                    let state = body.get("state").and_then(|v| v.as_str()).unwrap_or("");

                    if state == expected_state {
                        if let Some(sender) = tx.lock().await.take() {
                            let _ = sender.send(api_key);
                        }
                    } else {
                        eprintln!("  [warn] callback with wrong state nonce rejected");
                    }

                    let headers = [
                        (axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN, origin),
                        (
                            axum::http::header::ACCESS_CONTROL_ALLOW_HEADERS,
                            axum::http::HeaderValue::from_static("content-type"),
                        ),
                        (
                            axum::http::header::ACCESS_CONTROL_ALLOW_METHODS,
                            axum::http::HeaderValue::from_static("POST, OPTIONS"),
                        ),
                    ];
                    (
                        axum::http::StatusCode::OK,
                        headers,
                        axum::Json(serde_json::json!({"ok": true})),
                    )
                }
            }),
        )
        .route(
            "/callback",
            axum::routing::options(move || {
                let origin = origin_value.clone();
                async move {
                    let headers = [
                        (axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN, origin),
                        (
                            axum::http::header::ACCESS_CONTROL_ALLOW_HEADERS,
                            axum::http::HeaderValue::from_static("content-type"),
                        ),
                        (
                            axum::http::header::ACCESS_CONTROL_ALLOW_METHODS,
                            axum::http::HeaderValue::from_static("POST, OPTIONS"),
                        ),
                    ];
                    (axum::http::StatusCode::OK, headers, "")
                }
            }),
        );

    let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await?;
    let server_handle = tokio::spawn(async move {
        axum::serve(listener, server).await.ok();
    });

    // Open browser
    let url = format!("{cloud_url}/auth/device?callback_port={port}&state={state_nonce}");
    println!("  Opening browser: {url}");

    if open::that(&url).is_err() {
        println!("  Could not open browser automatically.");
        println!("  Please visit: {url}");
    }

    let api_url =
        std::env::var("MENTEDB_API_URL").unwrap_or_else(|_| "https://api.mentedb.com".to_string());

    println!("\n  Waiting for authorization...");
    println!("  On SSH or a remote machine, the browser cannot reach this process.");
    println!("  In that case the page shows a connection code after you authorize.");
    println!("  Paste it here and press Enter:\n");

    // Whichever arrives first wins: the browser callback (same machine) or a
    // manually pasted connection code (SSH and remote sessions).
    async fn read_pasted_code() -> Option<String> {
        use tokio::io::AsyncBufReadExt;
        let mut lines = tokio::io::BufReader::new(tokio::io::stdin()).lines();
        loop {
            match lines.next_line().await {
                Ok(Some(line)) => {
                    let code = line.trim().to_string();
                    if !code.is_empty() {
                        return Some(code);
                    }
                }
                _ => return None,
            }
        }
    }

    let token = tokio::select! {
        cb = rx => {
            let t = cb.map_err(|_| anyhow::anyhow!("Login cancelled"))?;
            if t.is_empty() {
                anyhow::bail!("Received empty token");
            }
            t
        }
        pasted = read_pasted_code() => {
            let Some(code) = pasted else {
                anyhow::bail!("Login cancelled");
            };
            // A pasted code is typed by hand; verify it against the API
            // before persisting so typos fail loudly here.
            print!("  Verifying code... ");
            let client = reqwest::Client::new();
            let ok = client
                .get(format!("{api_url}/api/usage"))
                .bearer_auth(&code)
                .send()
                .await
                .map(|r| r.status().is_success())
                .unwrap_or(false);
            if !ok {
                anyhow::bail!("The pasted code was rejected by the API. Run login again.");
            }
            println!("ok");
            code
        }
        _ = tokio::time::sleep(std::time::Duration::from_secs(300)) => {
            anyhow::bail!("Login timed out after 5 minutes");
        }
    };

    // Save to ~/.mentedb/cloud.json, merging into the multi-account config.
    // `login` targets the active account (or "default" when none is set), so
    // it keeps behaving like a single-account login while `accounts add`
    // manages the rest.
    let dir = mentedb_dir().unwrap_or_else(|| std::path::PathBuf::from("~/.mentedb"));
    std::fs::create_dir_all(&dir)?;

    let target = {
        let config = config::load_accounts(&dir)?;
        config
            .active_name()
            .unwrap_or_else(|| config::DEFAULT_ACCOUNT.to_string())
    };
    let cloud_url = std::env::var("MENTEDB_API_URL").ok();
    let config_path = upsert_account(&dir, &target, &token, cloud_url, true)?;

    server_handle.abort();

    println!("  Authenticated successfully!");
    println!("  Account: {target}");
    println!("  Credentials saved to: {}", config_path.display());
    println!("\n  Your MCP server will now sync with MenteDB Cloud.");

    Ok(())
}

/// Insert or update a named account in `<dir>/cloud.json`, writing the file
/// with 0600 permissions. When `make_active` is set (or no account is active
/// yet) the account is also made active. Returns the credentials file path.
fn upsert_account(
    dir: &std::path::Path,
    name: &str,
    api_key: &str,
    cloud_url: Option<String>,
    make_active: bool,
) -> anyhow::Result<std::path::PathBuf> {
    let mut config = config::load_accounts(dir)?;
    let entry = config.accounts.entry(name.to_string()).or_default();
    entry.api_key = api_key.to_string();
    // Only overwrite the stored URL when a new one was supplied, so re-running
    // login does not clobber an account's pinned cloud_url.
    if cloud_url.is_some() {
        entry.cloud_url = cloud_url;
    }
    if make_active || config.active_account.is_none() {
        config.active_account = Some(name.to_string());
    }

    let config_path = config::credentials_path(dir);
    write_secret_file(&config_path, &config.to_json_string()?)?;
    Ok(config_path)
}

/// Persist a fetched email onto an account, best-effort (never fails status).
fn cache_account_email(dir: &std::path::Path, name: &str, email: &str) {
    let Ok(mut config) = config::load_accounts(dir) else {
        return;
    };
    if let Some(account) = config.accounts.get_mut(name) {
        if account.email.as_deref() == Some(email) {
            return; // Unchanged: avoid a needless write.
        }
        account.email = Some(email.to_string());
        if let Ok(body) = config.to_json_string() {
            write_secret_file(&config::credentials_path(dir), &body).ok();
        }
    }
}

/// Remove an account and, if it was active, clear the active pointer.
/// Best-effort: used to drop a revoked account during `status`.
fn remove_account_silent(dir: &std::path::Path, name: &str) {
    let Ok(mut config) = config::load_accounts(dir) else {
        return;
    };
    if config.accounts.remove(name).is_some() {
        if config.active_account.as_deref() == Some(name) {
            config.active_account = None;
        }
        if let Ok(body) = config.to_json_string() {
            write_secret_file(&config::credentials_path(dir), &body).ok();
        }
    }
}

/// Dispatch `mentedb-mcp accounts <subcommand>`.
async fn run_accounts(cmd: AccountsCommand) -> anyhow::Result<()> {
    let dir = mentedb_dir().unwrap_or_else(|| std::path::PathBuf::from("~/.mentedb"));
    match cmd {
        AccountsCommand::Add {
            name,
            key,
            cloud_url,
        } => run_accounts_add(&dir, &name, key, cloud_url).await,
        AccountsCommand::List => run_accounts_list(&dir),
        AccountsCommand::Use { name } => run_accounts_use(&dir, &name),
        AccountsCommand::Remove { name } => run_accounts_remove(&dir, &name),
    }
}

/// Register (or update) a named account with an `mdb_` API key.
async fn run_accounts_add(
    dir: &std::path::Path,
    name: &str,
    key: Option<String>,
    cloud_url: Option<String>,
) -> anyhow::Result<()> {
    if name.trim().is_empty() {
        anyhow::bail!("Account name cannot be empty.");
    }

    // Take the key from the flag, else prompt. Never echo it back.
    let key = match key {
        Some(k) => k.trim().to_string(),
        None => {
            print!("  Paste the mdb_ API key for account '{name}': ");
            use std::io::Write;
            std::io::stdout().flush().ok();
            let mut line = String::new();
            std::io::stdin().read_line(&mut line)?;
            line.trim().to_string()
        }
    };

    if key.is_empty() {
        anyhow::bail!("No API key provided.");
    }
    if !key.starts_with("mdb_") {
        // A warning, not an error: keys are opaque and the prefix may change.
        eprintln!("  [warn] key does not start with 'mdb_'; storing it anyway.");
    }

    std::fs::create_dir_all(dir)?;
    let existed = config::load_accounts(dir)?.accounts.contains_key(name);
    let config_path = upsert_account(dir, name, &key, cloud_url, false)?;

    let verb = if existed { "Updated" } else { "Added" };
    println!("  {verb} account '{name}' ({}).", config::mask_secret(&key));
    // Report whether this became the active account.
    let active = config::load_accounts(dir)?.active_name();
    if active.as_deref() == Some(name) {
        println!("  Active account is now '{name}'.");
    } else if let Some(active) = active {
        println!(
            "  Active account remains '{active}'. Switch with `mentedb-mcp accounts use {name}`."
        );
    }
    println!("  Saved to: {}", config_path.display());
    Ok(())
}

/// List every account, marking the active one and masking keys.
fn run_accounts_list(dir: &std::path::Path) -> anyhow::Result<()> {
    let config = config::load_accounts(dir)?;
    if config.accounts.is_empty() {
        println!("  No accounts configured.");
        println!("  Add one with `mentedb-mcp accounts add <name>` or `mentedb-mcp login`.");
        return Ok(());
    }

    let active = config.active_name();
    println!("  Accounts:");
    for (name, account) in &config.accounts {
        let marker = if active.as_deref() == Some(name.as_str()) {
            "*"
        } else {
            " "
        };
        let email = account.email.as_deref().unwrap_or("-");
        let url = account
            .cloud_url
            .as_deref()
            .unwrap_or(config::DEFAULT_CLOUD_URL);
        println!(
            "  {marker} {name}  key={}  email={email}  url={url}",
            config::mask_secret(&account.api_key)
        );
    }
    println!("\n  (* = active)");
    Ok(())
}

/// Set the active account.
fn run_accounts_use(dir: &std::path::Path, name: &str) -> anyhow::Result<()> {
    let mut config = config::load_accounts(dir)?;
    if !config.accounts.contains_key(name) {
        anyhow::bail!(
            "No account named '{name}'. Run `mentedb-mcp accounts list` to see configured accounts."
        );
    }
    config.active_account = Some(name.to_string());
    std::fs::create_dir_all(dir)?;
    write_secret_file(&config::credentials_path(dir), &config.to_json_string()?)?;
    println!("  Active account is now '{name}'.");
    Ok(())
}

/// Remove an account. Clears the active pointer if it named the removed one.
fn run_accounts_remove(dir: &std::path::Path, name: &str) -> anyhow::Result<()> {
    let mut config = config::load_accounts(dir)?;
    if config.accounts.remove(name).is_none() {
        anyhow::bail!(
            "No account named '{name}'. Run `mentedb-mcp accounts list` to see configured accounts."
        );
    }
    let was_active = config.active_account.as_deref() == Some(name);
    if was_active {
        config.active_account = None;
    }
    std::fs::create_dir_all(dir)?;
    write_secret_file(&config::credentials_path(dir), &config.to_json_string()?)?;

    println!("  Removed account '{name}'.");
    if was_active {
        if let Some(next) = config.active_name() {
            // A single remaining account is resolved implicitly; make that
            // explicit so later commands are unambiguous.
            config.active_account = Some(next.clone());
            write_secret_file(&config::credentials_path(dir), &config.to_json_string()?)?;
            println!("  Active account is now '{next}'.");
        } else if !config.accounts.is_empty() {
            println!("  No active account set. Choose one with `mentedb-mcp accounts use <name>`.");
        }
    }
    Ok(())
}

fn run_logout() -> anyhow::Result<()> {
    let home = home_dir().unwrap_or_else(|| "~".to_string());
    let mentedb_dir = std::path::PathBuf::from(&home).join(".mentedb");
    let config_path = mentedb_dir.join("cloud.json");

    if config_path.exists() {
        std::fs::remove_file(&config_path)?;
        println!("  Logged out. Cloud credentials removed.");
    } else {
        println!("  Not logged in (no credentials found).");
    }
    Ok(())
}

async fn run_status() -> anyhow::Result<()> {
    let dir = mentedb_dir().unwrap_or_else(|| std::path::PathBuf::from("~/.mentedb"));
    let config_path = config::credentials_path(&dir);

    if !config_path.exists() {
        println!("  Status: Not logged in");
        println!("  Run `mentedb-mcp login` to authenticate.");
        return Ok(());
    }

    let config = config::load_accounts(&dir)?;
    let Some((active_name, account)) = config.active_account() else {
        if config.accounts.is_empty() {
            println!("  Status: Not logged in");
            println!("  Run `mentedb-mcp login` to authenticate.");
        } else {
            println!("  Status: No active account");
            println!("  Run `mentedb-mcp accounts use <name>` to select one.");
        }
        return Ok(());
    };
    let active_name = active_name.to_string();

    let token = account.api_key.clone();
    if token.is_empty() {
        println!("  Status: Invalid credentials (empty key)");
        println!("  Run `mentedb-mcp login` to re-authenticate.");
        return Ok(());
    }
    // MENTEDB_API_URL overrides the account's pinned URL, matching how
    // credentials are loaded for actual requests.
    let api_url = std::env::var("MENTEDB_API_URL")
        .ok()
        .or_else(|| account.cloud_url.clone())
        .unwrap_or_else(|| config::DEFAULT_CLOUD_URL.to_string());

    println!("  Active account: {active_name}");
    println!("  Checking cloud connection...");

    let client = reqwest::Client::new();
    let res = client
        .get(format!("{api_url}/api/sessions"))
        .header("Authorization", format!("Bearer {token}"))
        .timeout(std::time::Duration::from_secs(10))
        .send()
        .await;

    match res {
        Ok(resp) => match resp.status().as_u16() {
            200 => {
                println!("  Status: Connected");
                println!("  Cloud URL: {api_url}");
                println!("  Key: {}", config::mask_secret(&token));

                // Fetch account info
                match client
                    .get(format!("{api_url}/api/me"))
                    .header("Authorization", format!("Bearer {token}"))
                    .timeout(std::time::Duration::from_secs(5))
                    .send()
                    .await
                {
                    Ok(me_resp) if me_resp.status().is_success() => {
                        if let Ok(me) = me_resp.json::<serde_json::Value>().await {
                            if let Some(email) = me.get("email").and_then(|v| v.as_str()) {
                                println!("  Email: {email}");
                                // Cache the email on the account for offline
                                // `accounts list` display.
                                cache_account_email(&dir, &active_name, email);
                            }
                            if let Some(plan) = me.get("plan").and_then(|v| v.as_str()) {
                                println!("  Plan: {plan}");
                            }
                        }
                    }
                    _ => {}
                }
            }
            401 | 403 => {
                println!("  Status: Session revoked");
                println!();
                println!("  Your session has been revoked (possibly from the web dashboard).");
                println!("  Run `mentedb-mcp login` to create a new session.");
                // Remove only the stale account, preserving the others.
                remove_account_silent(&dir, &active_name);
            }
            code => {
                println!("  Status: Error (HTTP {code})");
                println!("  The cloud service may be temporarily unavailable.");
            }
        },
        Err(e) => {
            if e.is_timeout() {
                println!("  Status: Timeout");
                println!("  Could not reach {api_url} within 10 seconds.");
            } else {
                println!("  Status: Connection failed");
                println!("  Error: {e}");
            }
        }
    }

    Ok(())
}

/// Directory holding MenteDB credentials and state (`~/.mentedb`).
fn mentedb_dir() -> Option<std::path::PathBuf> {
    Some(std::path::PathBuf::from(home_dir()?).join(".mentedb"))
}

/// Load cloud credentials for the ACTIVE account from ~/.mentedb/cloud.json.
/// Returns (api_url, token) if a valid active account exists.
///
/// The legacy single-key shape is migrated on read (see
/// `config::AccountsConfig`), so pre-existing single-key installs keep working.
/// Also checks the MENTEDB_API_URL env var as an override for the API URL.
fn load_cloud_credentials() -> Option<(String, String)> {
    let dir = mentedb_dir()?;
    let config = config::load_accounts(&dir).ok()?;
    let (_, account) = config.active_account()?;
    if account.api_key.is_empty() {
        return None;
    }

    // MENTEDB_API_URL env var takes precedence over the account's cloud_url.
    let api_url = std::env::var("MENTEDB_API_URL")
        .ok()
        .or_else(|| account.cloud_url.clone())
        .unwrap_or_else(|| config::DEFAULT_CLOUD_URL.to_string());

    Some((api_url, account.api_key.clone()))
}

/// Write a credentials file created with 0600 from the first byte, instead
/// of writing world-readable and tightening afterwards.
fn write_secret_file(path: &std::path::Path, contents: &str) -> anyhow::Result<()> {
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(path)?;
        f.write_all(contents.as_bytes())?;
        // mode() only applies on create; correct pre-existing files too.
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
    }
    #[cfg(not(unix))]
    {
        std::fs::write(path, contents)?;
    }
    Ok(())
}

/// End-to-end pipeline diagnosis: answers "is memory actually working?"
/// in one command.
async fn run_doctor(data_dir: &std::path::Path) -> anyhow::Result<()> {
    println!("\nMenteDB doctor v{}\n", env!("CARGO_PKG_VERSION"));
    let mut problems = 0usize;

    // 1. Backend credentials.
    let creds = load_cloud_credentials();
    match &creds {
        Some((api_url, token)) => {
            println!(
                "  [ok]   Cloud credentials: {} ({})",
                config::mask_secret(token),
                api_url
            );
            let client = reqwest::Client::new();
            match client
                .get(format!("{api_url}/api/me"))
                .header("Authorization", format!("Bearer {token}"))
                .timeout(std::time::Duration::from_secs(10))
                .send()
                .await
            {
                Ok(resp) if resp.status().is_success() => {
                    let me: serde_json::Value = resp.json().await.unwrap_or_default();
                    let email = me.get("email").and_then(|v| v.as_str()).unwrap_or("?");
                    let plan = me.get("plan").and_then(|v| v.as_str()).unwrap_or("?");
                    println!("  [ok]   Cloud reachable, account {email} (plan: {plan})");
                }
                Ok(resp) if resp.status().as_u16() == 401 || resp.status().as_u16() == 403 => {
                    problems += 1;
                    println!("  [FAIL] Token revoked or expired. Run `mentedb-mcp login`.");
                }
                Ok(resp) => {
                    problems += 1;
                    println!("  [warn] Cloud returned HTTP {}", resp.status());
                }
                Err(e) => {
                    problems += 1;
                    println!("  [FAIL] Cloud unreachable: {e}");
                }
            }
        }
        None => {
            println!("  [info] Not logged in: hooks use the local daemon backend.");
            #[cfg(not(feature = "local"))]
            {
                problems += 1;
                println!("  [FAIL] This build has no local mode. Run `mentedb-mcp login`.");
            }
        }
    }

    // 2. Claude Code hooks registered, in every config directory.
    let home = home_dir().unwrap_or_else(|| "~".to_string());
    let expected = [
        "UserPromptSubmit",
        "Stop",
        "SessionStart",
        "PostToolUse",
        "PreCompact",
    ];
    for dir in claude_config_dirs(&home) {
        let settings_path = dir.join("settings.json");
        match std::fs::read_to_string(&settings_path)
            .ok()
            .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
        {
            Some(settings) => {
                let mut missing = Vec::new();
                for event in expected {
                    let present = settings["hooks"][event].as_array().is_some_and(|groups| {
                        groups.iter().any(|g| {
                            g["hooks"].as_array().is_some_and(|hs| {
                                hs.iter().any(|h| {
                                    h["command"]
                                        .as_str()
                                        .is_some_and(|c| c.contains("mentedb-mcp"))
                                })
                            })
                        })
                    });
                    if !present {
                        missing.push(event);
                    }
                }
                if missing.is_empty() {
                    println!("  [ok]   Hooks in {}: all 5 registered", dir.display());
                } else {
                    problems += 1;
                    println!(
                        "  [FAIL] Hooks in {} missing: {}. Run `npx mentedb-mcp@latest setup claude-code`.",
                        dir.display(),
                        missing.join(", ")
                    );
                }
            }
            None => {
                problems += 1;
                println!(
                    "  [warn] No Claude Code settings at {}. Run `npx mentedb-mcp@latest setup claude-code`.",
                    settings_path.display()
                );
            }
        }
    }

    // 3. Recent capture activity.
    let sessions_dir = data_dir.join("hook_sessions");
    let newest = std::fs::read_dir(&sessions_dir)
        .ok()
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|e| e.metadata().ok().and_then(|m| m.modified().ok()))
        .max();
    match newest {
        Some(t) => {
            let ago = t.elapsed().map(|d| d.as_secs()).unwrap_or(0);
            let human = if ago < 120 {
                format!("{ago}s ago")
            } else if ago < 7_200 {
                format!("{}m ago", ago / 60)
            } else {
                format!("{}h ago", ago / 3_600)
            };
            println!("  [ok]   Last hook activity: {human}");
        }
        None => {
            println!(
                "  [info] No hook activity yet. Hooks fire in sessions started after setup; start a new Claude Code session."
            );
        }
    }

    // 4. Offline spool depth.
    let depth = hook::spool::depth(data_dir);
    if depth == 0 {
        println!("  [ok]   Offline spool: empty");
    } else {
        println!("  [warn] Offline spool: {depth} undelivered entries (retried on next turn)");
    }

    // 5. Recent hook errors from the log.
    let today = chrono_free_today();
    let log_path = data_dir.join(format!("mentedb-hook.log.{today}"));
    let warns: Vec<String> = std::fs::read_to_string(&log_path)
        .map(|raw| {
            raw.lines()
                .filter(|l| l.contains("WARN") || l.contains("ERROR"))
                .rev()
                .take(3)
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default();
    if warns.is_empty() {
        println!("  [ok]   Hook log: no recent errors");
    } else {
        println!("  [warn] Recent hook errors ({}):", log_path.display());
        for w in warns.iter().rev() {
            let trimmed: String = w.chars().take(160).collect();
            println!("           {trimmed}");
        }
    }

    // 6. Local daemon, when that is the active backend.
    #[cfg(feature = "local")]
    if creds.is_none() {
        match crate::daemon::read_info(data_dir) {
            Some(info) => {
                let url = format!("http://127.0.0.1:{}/health", info.port);
                let healthy = reqwest::Client::new()
                    .get(&url)
                    .timeout(std::time::Duration::from_secs(2))
                    .send()
                    .await
                    .map(|r| r.status().is_success())
                    .unwrap_or(false);
                if healthy {
                    println!("  [ok]   Local daemon: running on port {}", info.port);
                } else {
                    println!("  [info] Local daemon: not running (auto-starts on first hook)");
                }
            }
            None => println!("  [info] Local daemon: not started yet (auto-starts on first hook)"),
        }
    }

    println!();
    if problems == 0 {
        println!("  Everything looks healthy.");
    } else {
        println!("  {problems} problem(s) found. Fix the [FAIL] items above.");
    }
    Ok(())
}

/// Today's UTC date as YYYY-MM-DD without pulling in a date crate: the
/// tracing_appender daily logs use this suffix.
fn chrono_free_today() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let days = secs / 86_400;
    // Civil-from-days (Howard Hinnant's algorithm), valid for the era we run in.
    let z = days as i64 + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}-{m:02}-{d:02}")
}

/// Push every memory in the local database up to MenteDB Cloud, so a user
/// who started local and later logs in keeps their history. Idempotent via
/// a ledger of already-pushed memory IDs.
#[cfg(feature = "local")]
async fn run_sync(data_dir: &std::path::Path) -> anyhow::Result<()> {
    let Some((api_url, token)) = load_cloud_credentials() else {
        anyhow::bail!("Not logged in. Run `mentedb-mcp login` first, then `mentedb-mcp sync`.");
    };

    println!("\nSyncing local memories to MenteDB Cloud...\n");

    let daemon = hook::backend::LocalDaemonClient::connect_or_spawn(data_dir).await?;
    let export = daemon.post("/v1/export", serde_json::json!({})).await?;
    let memories = export
        .get("memories")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    if memories.is_empty() {
        println!("  Local database has no memories to sync.");
        return Ok(());
    }

    let ledger_path = data_dir.join("sync_state.json");
    let mut pushed: std::collections::HashSet<String> = std::fs::read_to_string(&ledger_path)
        .ok()
        .and_then(|raw| serde_json::from_str(&raw).ok())
        .unwrap_or_default();

    let client = cloud_client::CloudClient::new(api_url, token);
    let total = memories.len();
    let mut sent = 0usize;
    let mut skipped = 0usize;
    let mut failed = 0usize;

    for m in &memories {
        let id = m
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let content = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
        if id.is_empty() || content.is_empty() || pushed.contains(&id) {
            skipped += 1;
            continue;
        }
        let mut tags: Vec<String> = m
            .get("tags")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|t| t.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default();
        tags.push("synced-from-local".to_string());

        let args = serde_json::json!({
            "content": content,
            "memory_type": m.get("memory_type").and_then(|v| v.as_str()).unwrap_or("episodic"),
            "tags": tags,
        });
        match client.call_tool("store_memory", args).await {
            Ok(_) => {
                pushed.insert(id);
                sent += 1;
                if sent.is_multiple_of(25) {
                    println!("  {sent}/{total} pushed...");
                    std::fs::write(&ledger_path, serde_json::to_string(&pushed)?).ok();
                }
            }
            Err(e) => {
                failed += 1;
                if failed <= 3 {
                    eprintln!("  [warn] failed to push {id}: {e}");
                }
            }
        }
    }
    std::fs::write(&ledger_path, serde_json::to_string(&pushed)?)?;

    println!("\n  Done: {sent} pushed, {skipped} already synced or empty, {failed} failed.");
    if failed > 0 {
        println!("  Re-run `mentedb-mcp sync` to retry failures.");
    }
    Ok(())
}

fn run_setup(client: SetupClient, force: bool) -> anyhow::Result<()> {
    let home = home_dir().unwrap_or_else(|| "~".to_string());
    let binary = which_mentedb_mcp();

    match client {
        SetupClient::Copilot => setup_copilot(&home, &binary, force),
        SetupClient::Claude => setup_claude(&home, &binary, force),
        SetupClient::Cursor => setup_cursor(&home, &binary, force),
        SetupClient::ClaudeCode => setup_claude_code(&home, &binary, force),
    }
}

/// Configure Claude Code (the CLI) with lifecycle hooks instead of MCP.
///
/// Hooks cost zero tool-schema tokens and run deterministically every turn:
/// UserPromptSubmit injects recalled context, Stop stores the completed turn,
/// SessionStart injects the user profile (including right after compaction).
fn setup_claude_code(home: &str, binary: &str, force: bool) -> anyhow::Result<()> {
    println!("\nSetting up MenteDB hooks for Claude Code...\n");

    let hook_command = if binary == "npx" {
        "npx -y mentedb-mcp@latest hook".to_string()
    } else {
        format!("{binary} hook")
    };

    // Install into every Claude config directory on the machine, so users
    // with separate work and personal configs get hooks in all of them.
    for dir in claude_config_dirs(home) {
        eprintln!("  Claude config: {}", dir.display());
        install_claude_code_hooks(&dir.join("settings.json"), &hook_command, force)?;
    }

    println!("\nDone. MenteDB now runs on every Claude Code turn via hooks:");
    println!("  UserPromptSubmit  recalls context for the prompt");
    println!("  PostToolUse       captures significant actions as they happen");
    println!("  Stop              stores the completed turn");
    println!("  PreCompact        flushes memory before context is compacted");
    println!("  SessionStart      injects your profile and standing rules");
    println!("\nBackend: cloud when logged in (mentedb-mcp login), otherwise a");
    println!("local daemon that starts automatically on first use.");
    println!("\nRestart any open Claude Code sessions to activate.");
    Ok(())
}

fn install_claude_code_hooks(
    settings_path: &std::path::Path,
    hook_command: &str,
    force: bool,
) -> anyhow::Result<()> {
    let raw = std::fs::read_to_string(settings_path).unwrap_or_else(|_| "{}".to_string());
    let mut settings: serde_json::Value =
        serde_json::from_str(&raw).unwrap_or_else(|_| serde_json::json!({}));
    if !settings.is_object() {
        settings = serde_json::json!({});
    }

    let hooks = settings
        .as_object_mut()
        .expect("settings is an object")
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    if !hooks.is_object() {
        *hooks = serde_json::json!({});
    }

    let events: [(&str, &str, &str); 5] = [
        ("UserPromptSubmit", "user-prompt", ""),
        ("Stop", "stop", ""),
        ("SessionStart", "session-start", "startup|resume|compact"),
        (
            "PostToolUse",
            "post-tool-use",
            "Write|Edit|MultiEdit|NotebookEdit|Bash",
        ),
        ("PreCompact", "pre-compact", ""),
    ];

    for (event, subcommand, matcher) in events {
        let command = format!("{hook_command} {subcommand}");
        let entries = hooks
            .as_object_mut()
            .expect("hooks is an object")
            .entry(event)
            .or_insert_with(|| serde_json::json!([]));
        if !entries.is_array() {
            *entries = serde_json::json!([]);
        }
        let arr = entries.as_array_mut().expect("entries is an array");

        let already = arr.iter().any(|group| {
            group["hooks"].as_array().is_some_and(|hs| {
                hs.iter().any(|h| {
                    h["command"]
                        .as_str()
                        .is_some_and(|c| c.contains("mentedb-mcp") && c.contains(subcommand))
                })
            })
        });
        if already && !force {
            eprintln!("  [skip] {event} hook already configured");
            continue;
        }
        if already && force {
            arr.retain(|group| {
                !group["hooks"].as_array().is_some_and(|hs| {
                    hs.iter().any(|h| {
                        h["command"]
                            .as_str()
                            .is_some_and(|c| c.contains("mentedb-mcp"))
                    })
                })
            });
        }

        let mut group = serde_json::json!({
            "hooks": [ { "type": "command", "command": command } ]
        });
        if !matcher.is_empty() {
            group["matcher"] = serde_json::json!(matcher);
        }
        arr.push(group);
        eprintln!("  [added] {event} hook");
    }

    if let Some(parent) = settings_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(settings_path, serde_json::to_string_pretty(&settings)?)?;
    eprintln!("  [updated] {}", settings_path.display());
    Ok(())
}

fn which_mentedb_mcp() -> String {
    // If running via npx, use "npx" as the command so it stays version-proof.
    // npx sets npm_execpath and npm_lifecycle_event env vars.
    let is_npx = std::env::var("npm_execpath").is_ok()
        || std::env::current_exe()
            .ok()
            .and_then(|p| p.to_str().map(String::from))
            .is_some_and(|p| p.contains(".npm/_npx") || p.contains("npx"));

    if is_npx {
        return "npx".to_string();
    }

    std::env::current_exe()
        .ok()
        .and_then(|p| p.to_str().map(String::from))
        .unwrap_or_else(|| "mentedb-mcp".to_string())
}

fn write_if_missing(path: &std::path::Path, content: &str, label: &str) -> anyhow::Result<bool> {
    if path.exists() {
        eprintln!("  [skip] {label} already exists: {}", path.display());
        Ok(false)
    } else {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(path, content)?;
        eprintln!("  [created] {label}: {}", path.display());
        Ok(true)
    }
}

fn merge_mcp_config(path: &std::path::Path, binary: &str, force: bool) -> anyhow::Result<()> {
    let allow_list: Vec<&str> = TOOL_NAMES.to_vec();

    // When running via npx, use "npx" as command and prepend package args
    let (command, base_args) = if binary == "npx" {
        ("npx", vec!["-y", "mentedb-mcp@latest"])
    } else {
        (binary, vec![])
    };

    let mut mentedb_entry = serde_json::json!({
        "command": command,
        "args": base_args,
        "alwaysAllow": allow_list,
    });

    // If LLM env vars are set, include them so MCP clients pass them through
    let mut env_vars = serde_json::Map::new();
    if let Ok(provider) = std::env::var("MENTEDB_LLM_PROVIDER") {
        env_vars.insert(
            "MENTEDB_LLM_PROVIDER".to_string(),
            serde_json::Value::String(provider),
        );
    }
    if let Ok(key) = std::env::var("MENTEDB_LLM_API_KEY") {
        env_vars.insert(
            "MENTEDB_LLM_API_KEY".to_string(),
            serde_json::Value::String(key),
        );
    } else if let Ok(key) = std::env::var("OPENAI_API_KEY") {
        env_vars.insert("OPENAI_API_KEY".to_string(), serde_json::Value::String(key));
    }
    if let Ok(model) = std::env::var("MENTEDB_LLM_MODEL") {
        env_vars.insert(
            "MENTEDB_LLM_MODEL".to_string(),
            serde_json::Value::String(model),
        );
    }
    if !env_vars.is_empty() {
        mentedb_entry
            .as_object_mut()
            .unwrap()
            .insert("env".to_string(), serde_json::Value::Object(env_vars));
    }

    let mut config: serde_json::Value = if path.exists() {
        let content = std::fs::read_to_string(path)?;
        serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({}))
    } else {
        serde_json::json!({})
    };

    let servers = config
        .as_object_mut()
        .unwrap()
        .entry("mcpServers")
        .or_insert_with(|| serde_json::json!({}));

    let existing = servers.get("mentedb").cloned();
    if existing.is_some() && !force {
        eprintln!("  [skip] mentedb already in MCP config: {}", path.display());
    } else {
        // When updating, preserve user-configured args and env.
        if let Some(old) = &existing
            && let Some(old_obj) = old.as_object()
        {
            let new_obj = mentedb_entry.as_object_mut().unwrap();

            // Extract user args from old config (skip npx prefix args like "-y", "mentedb-mcp@latest")
            if let Some(old_args) = old_obj.get("args").and_then(|a| a.as_array()) {
                let user_args: Vec<&serde_json::Value> = old_args
                    .iter()
                    .filter(|a| {
                        let s = a.as_str().unwrap_or_default();
                        // Skip npx meta-args; keep user args like --data-dir, --llm-provider
                        s != "-y" && !s.starts_with("mentedb-mcp")
                    })
                    .collect();

                if !user_args.is_empty() {
                    let new_args = new_obj
                        .get_mut("args")
                        .and_then(|a| a.as_array_mut())
                        .unwrap();
                    for arg in user_args {
                        new_args.push(arg.clone());
                    }
                }
            }

            // Merge env: keep old vars, overlay new ones
            if let Some(old_env) = old_obj.get("env").and_then(|e| e.as_object()) {
                let new_env = new_obj
                    .entry("env")
                    .or_insert_with(|| serde_json::json!({}));
                if let Some(new_env_obj) = new_env.as_object_mut() {
                    for (k, v) in old_env {
                        new_env_obj.entry(k.clone()).or_insert(v.clone());
                    }
                }
            }
        }
        servers
            .as_object_mut()
            .unwrap()
            .insert("mentedb".to_string(), mentedb_entry);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(path, serde_json::to_string_pretty(&config)?)?;
        let verb = if existing.is_some() {
            "updated"
        } else {
            "created"
        };
        eprintln!("  [{verb}] MCP config: {}", path.display());
    }

    Ok(())
}

fn append_instructions(
    path: &std::path::Path,
    interactive: bool,
    force: bool,
) -> anyhow::Result<()> {
    let version_marker = format!(
        "<!-- mentedb-instructions-v{} -->",
        env!("CARGO_PKG_VERSION")
    );

    if path.exists() {
        let content = std::fs::read_to_string(path)?;
        if content.contains(&version_marker) && !force {
            eprintln!(
                "  [skip] instructions already up-to-date: {}",
                path.display()
            );
            return Ok(());
        }

        // Extract old version for display
        let old_version = content
            .lines()
            .find(|l| l.contains("<!-- mentedb-instructions-v"))
            .and_then(|l| {
                l.trim()
                    .strip_prefix("<!-- mentedb-instructions-v")
                    .and_then(|s| s.strip_suffix(" -->"))
            })
            .unwrap_or("unknown");

        // Extract the current MenteDB block to detect user edits
        let has_mentedb_block =
            content.contains("# Memory\n\nYou have persistent memory via MenteDB");

        // Check for user customizations inside the MenteDB block
        let user_customized = if has_mentedb_block {
            let start = content
                .find("# Memory\n\nYou have persistent memory via MenteDB")
                .unwrap();
            let rest = &content[start..];
            let end = rest
                .find("\n# ")
                .map(|i| start + i)
                .unwrap_or(content.len());
            let old_block = &content[start..end];
            // Compare with what the old version would have had
            // If user edited the block, the content won't match a clean install
            // Simple heuristic: check for lines not in AGENT_INSTRUCTIONS
            let agent_lines: std::collections::HashSet<&str> =
                AGENT_INSTRUCTIONS.lines().map(|l| l.trim()).collect();
            old_block
                .lines()
                .any(|l| !l.trim().is_empty() && !agent_lines.contains(l.trim()))
        } else {
            false
        };

        if interactive {
            eprintln!(
                "\n  Agent instructions update: v{} → v{}",
                old_version,
                env!("CARGO_PKG_VERSION")
            );
            eprintln!("  File: {}", path.display());

            // Show the full instructions that will be written
            eprintln!("\n  ┌─── Instructions to be written ───────────────────────────");
            for line in AGENT_INSTRUCTIONS.lines() {
                eprintln!("  │ {line}");
            }
            eprintln!("  └─────────────────────────────────────────────────────────");

            if user_customized {
                eprintln!("\n  [warn] Your file has custom edits inside the MenteDB block.");
                eprintln!(
                    "         These will be replaced. Your content OUTSIDE the block is preserved."
                );
                eprintln!("         A backup will be saved to: {}.bak", path.display());
            }

            eprint!("\n  Apply these instructions? [Y/n] ");
            let mut input = String::new();
            std::io::stdin().read_line(&mut input)?;
            let input = input.trim().to_lowercase();
            if input == "n" || input == "no" {
                eprintln!("  [skip] user declined update");
                return Ok(());
            }

            // Create backup if user has customizations
            if user_customized {
                let backup_path = path.with_extension("md.bak");
                std::fs::copy(path, &backup_path)?;
                eprintln!("  [backup] saved to: {}", backup_path.display());
            }
        }

        // Remove old MenteDB instructions block, preserve everything else
        let cleaned = if has_mentedb_block {
            let start = content
                .find("# Memory\n\nYou have persistent memory via MenteDB")
                .unwrap();
            let rest = &content[start..];
            let end = rest
                .find("\n# ")
                .map(|i| start + i)
                .unwrap_or(content.len());
            // Also remove old version marker line above the block
            let mut prefix_end = start;
            if let Some(marker_start) = content[..start].rfind("<!-- mentedb-instructions-v") {
                prefix_end = marker_start;
            }
            let prefix = content[..prefix_end].trim_end().to_string();
            let suffix = content[end..].to_string();
            format!("{prefix}\n{suffix}")
        } else {
            content
        };

        let updated = format!(
            "{}\n\n{version_marker}\n{AGENT_INSTRUCTIONS}",
            cleaned.trim_end()
        );
        std::fs::write(path, updated)?;
        eprintln!(
            "  [updated] refreshed MenteDB instructions: {}",
            path.display()
        );
    } else {
        let content = format!("{version_marker}\n{AGENT_INSTRUCTIONS}");
        write_if_missing(path, &content, "agent instructions")?;
    }
    Ok(())
}

fn setup_copilot(home: &str, binary: &str, force: bool) -> anyhow::Result<()> {
    println!("\nSetting up MenteDB for GitHub Copilot CLI...\n");

    let copilot_dir = std::path::PathBuf::from(home).join(".copilot");
    merge_mcp_config(&copilot_dir.join("mcp-config.json"), binary, force)?;
    append_instructions(&copilot_dir.join("copilot-instructions.md"), true, force)?;

    println!("\nDone! Restart Copilot CLI to activate MenteDB memory.");
    println!("\nTo sync memories across devices, run: mentedb-mcp login");
    Ok(())
}

fn setup_claude(home: &str, binary: &str, force: bool) -> anyhow::Result<()> {
    println!("\nSetting up MenteDB for Claude Desktop...\n");

    let config_dir = if cfg!(target_os = "macos") {
        std::path::PathBuf::from(home).join("Library/Application Support/Claude")
    } else if cfg!(target_os = "windows") {
        std::env::var("APPDATA")
            .map(|d| std::path::PathBuf::from(d).join("Claude"))
            .unwrap_or_else(|_| std::path::PathBuf::from(home).join("AppData/Roaming/Claude"))
    } else {
        // Linux: ~/.config/Claude
        std::path::PathBuf::from(home).join(".config/Claude")
    };
    merge_mcp_config(
        &config_dir.join("claude_desktop_config.json"),
        binary,
        force,
    )?;

    println!("\nDone! Restart Claude Desktop to activate MenteDB memory.");
    println!("Note: Claude Desktop reads server instructions automatically from the MCP server.");
    println!("\nTo sync memories across devices, run: mentedb-mcp login");
    Ok(())
}

fn setup_cursor(home: &str, binary: &str, force: bool) -> anyhow::Result<()> {
    println!("\nSetting up MenteDB for Cursor...\n");

    let cursor_dir = std::path::PathBuf::from(home).join(".cursor");
    merge_mcp_config(&cursor_dir.join("mcp.json"), binary, force)?;
    append_instructions(&cursor_dir.join("rules/mentedb.md"), true, force)?;

    println!("\nDone! Restart Cursor to activate MenteDB memory.");
    println!("\nTo sync memories across devices, run: mentedb-mcp login");
    Ok(())
}