mimir-mem 0.14.0

Mimir: unified local-first memory for AI coding agents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
use std::collections::HashMap;

use anyhow::{bail, Context, Result};
use mimir_core::config::{Config, Paths};
use mimir_core::format::agent_line;
use mimir_core::memory::{self, Remember, RememberOutcome};
use mimir_core::model::{now_unix, short_uid, Kind, MemoryType, Node, Rel, Scope};
use mimir_core::search::SearchQuery;
use mimir_core::{db, store, Mimir};

pub fn init(
    no_model: bool,
    hooks: bool,
    auto_recall: bool,
    context_guard: Option<&str>,
) -> Result<()> {
    let paths = Paths::resolve()?;
    let mut config = Config::load(&paths.config_file)?;
    if let Some(mode) = context_guard {
        if !matches!(mode, "off" | "pause" | "handoff") {
            bail!("--context-guard must be one of: off, pause, handoff (got {mode:?})");
        }
        config.hooks.context_guard = mode.to_string();
    }
    config.save(&paths.config_file)?;
    // Opening creates + migrates the database.
    let _conn = db::open(&paths.db_file)?;
    println!("config  {}", paths.config_file.display());
    println!("db      {}", paths.db_file.display());
    if no_model {
        println!(
            "model   skipped (BM25-only; run `mimir embed --fetch` to enable semantic search)"
        );
    } else {
        match mimir_core::embed::Embedder::load(
            &paths,
            &config.embedding.model,
            &config.embedding.device,
            true,
        ) {
            Ok(e) => println!("model   {} ready ({}-dim)", e.name, e.dim),
            Err(err) => {
                eprintln!("model   download failed ({err}); search is BM25-only until `mimir embed --fetch` succeeds")
            }
        }
    }
    install_agent_commands(&config);
    if hooks {
        if let Err(err) = install_hooks(&config, auto_recall) {
            eprintln!("hooks   install failed: {err}");
        }
    }
    println!();
    println!("Register the MCP server once, globally:");
    println!("  claude mcp add --scope user mimir -- mimir mcp");
    if !hooks {
        println!();
        println!("Token-saving hooks (filter command output + inject project rules) are opt-in:");
        println!("  mimir init --hooks");
    } else if !auto_recall {
        println!();
        println!("Per-prompt auto-recall (inject a relevant memory into every prompt) is opt-in:");
        println!("  mimir init --hooks --auto-recall");
    }
    if hooks && config.hooks.context_guard == "off" {
        println!();
        println!("Context-window guard (nudge before an auto-compact takes control) is opt-in:");
        println!("  mimir init --hooks --context-guard pause   # or: handoff");
    }
    Ok(())
}

/// The PreToolUse hook script: delegates all rewrite logic to `mimir rewrite`,
/// so rules live in the Rust binary (single source of truth), not this file.
const MIMIR_REWRITE_SH: &str = r#"#!/usr/bin/env bash
# mimir-hook-version: 1
# Mimir PreToolUse hook — rewrites noisy commands through `mimir run` to save
# tokens. All logic lives in `mimir rewrite`. Requires: mimir, jq.
command -v jq >/dev/null 2>&1 || exit 0
command -v mimir >/dev/null 2>&1 || exit 0
INPUT=$(cat)
CMD=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // empty')
[ -z "$CMD" ] && exit 0
REWRITTEN=$(mimir rewrite "$CMD" 2>/dev/null) || exit 0
[ "$CMD" = "$REWRITTEN" ] && exit 0
UPDATED=$(printf '%s' "$INPUT" | jq -c --arg cmd "$REWRITTEN" '.tool_input | .command = $cmd')
jq -n --argjson updated "$UPDATED" '{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow",
    "permissionDecisionReason": "Mimir token-saving rewrite",
    "updatedInput": $updated
  }
}'
"#;

/// The opt-in UserPromptSubmit hook script: tries the warm `/inject` HTTP
/// endpoint first (only live while `mimir mcp --http` is running — see
/// `mcp.rs::inject_router`), falling back to the cold `mimir recall-inject`
/// CLI path when that's unreachable. Both paths run the exact same
/// relevance-floor/formatting/budget logic (`mimir_core::inject::compute`),
/// so which one answers is purely a latency concern, never a behavior one.
/// Unlike `MIMIR_REWRITE_SH`, plain stdout (not a `hookSpecificOutput` JSON
/// envelope) is how Claude Code injects UserPromptSubmit context — same
/// mechanism as the SessionStart rules hook.
///
/// The warm endpoint's address is `config.hooks.inject_url`
/// (`HooksConfig::inject_url`, default `127.0.0.1:8077`, matching the port
/// documented in README.md's remote-MCP example) — baked into the script at
/// install time by `render_recall_script`. `MIMIR_INJECT_URL` still
/// overrides it at hook-invocation time, for a one-off run against a
/// different bind without touching config.toml. If no daemon answers there,
/// curl fails fast (2s timeout) and behavior is identical to before this
/// endpoint existed — just slower.
///
/// Also extracts a cheap enrichment signal from the caller's working tree:
/// the stems (basename, extension stripped) of up to 8 files changed since
/// HEAD, via `git diff --name-only`. Passed as `enrich=` on the warm URL and
/// `--enrich` on the cold CLI path — never mixed into `prompt` itself.
/// `inject::compute`/`clears_floor` treat it as strictly weaker than the raw
/// prompt: it can extend a real overlap but can never single-handedly clear
/// the relevance floor (see `inject.rs`'s self-licensing guard doc comment).
/// Silent if `git` isn't on PATH or the cwd isn't a repo — enrichment is a
/// nice-to-have, not a requirement.
const MIMIR_RECALL_SH: &str = r#"#!/usr/bin/env bash
# mimir-hook-version: 3
# Mimir UserPromptSubmit hook — prints at most one relevant memory (or
# nothing) as extra context for this turn. Tries the warm HTTP endpoint
# (fast; requires `mimir mcp --http` to be running) first, falls back to
# the cold CLI path (slower, always available). All relevance-floor logic
# lives in mimir_core::inject::compute, shared by both. Requires: mimir, jq;
# curl and git are optional (git enrichment and the warm path are both
# skipped gracefully when unavailable).
command -v jq >/dev/null 2>&1 || exit 0
command -v mimir >/dev/null 2>&1 || exit 0
INPUT=$(cat)
PROMPT=$(printf '%s' "$INPUT" | jq -r '.prompt // empty')
[ -z "$PROMPT" ] && exit 0
INJECT_URL="${MIMIR_INJECT_URL:-__MIMIR_INJECT_URL_DEFAULT__}"
PROJECT_DIR=$(printf '%s' "$INPUT" | jq -r '.cwd // empty')
[ -z "$PROJECT_DIR" ] && PROJECT_DIR="$PWD"
ENRICH=""
if command -v git >/dev/null 2>&1; then
    ENRICH=$(git -C "$PROJECT_DIR" diff --name-only HEAD 2>/dev/null | head -8 \
        | sed -E 's#.*/##; s#\.[^./]+$##' | tr '\n' ' ' | sed -E 's/^ +| +$//g')
fi
if command -v curl >/dev/null 2>&1; then
    ENC_PROMPT=$(printf '%s' "$PROMPT" | jq -sRr @uri)
    URL="${INJECT_URL}?prompt=${ENC_PROMPT}"
    if [ -n "$ENRICH" ]; then
        ENC_ENRICH=$(printf '%s' "$ENRICH" | jq -sRr @uri)
        URL="${URL}&enrich=${ENC_ENRICH}"
    fi
    if WARM=$(curl -sf --max-time 2 "$URL" 2>/dev/null); then
        [ -n "$WARM" ] && printf '%s\n' "$WARM"
        exit 0
    fi
fi
if [ -n "$ENRICH" ]; then
    mimir recall-inject --enrich "$ENRICH" -- "$PROMPT" 2>/dev/null
else
    mimir recall-inject -- "$PROMPT" 2>/dev/null
fi
exit 0
"#;

/// The PreToolUse(Bash|Edit|Write) guard-anchors hook script: unconditional
/// under `--hooks` (no separate opt-in flag) — a memory with no
/// `meta.anchors` makes every invocation a silent no-op, so there is
/// nothing to gate. All matching logic lives in `mimir_core::anchors` /
/// `mimir context-guard pretool`; this script only pipes the hook's stdin
/// JSON straight through (no jq needed — the JSON is parsed in Rust).
const MIMIR_ANCHORS_SH: &str = r#"#!/usr/bin/env bash
# mimir-hook-version: 1
# Mimir PreToolUse guard-anchors hook — surfaces at most one anchored
# memory (see `mimir remember --anchor`) as extra context when a matching
# file is edited/written, or mentioned in a Bash command. Requires: mimir.
command -v mimir >/dev/null 2>&1 || exit 0
mimir context-guard pretool 2>/dev/null
exit 0
"#;

/// The opt-in `[hooks] context_guard != "off"` hook scripts — one each for
/// UserPromptSubmit, PreCompact, SessionStart. All logic lives in
/// `mimir_core::context_guard` / `mimir context-guard <subcommand>`; each
/// script only pipes stdin through (no jq — parsed in Rust).
const MIMIR_CONTEXT_GUARD_PROMPT_SH: &str = r#"#!/usr/bin/env bash
# mimir-hook-version: 1
# Mimir UserPromptSubmit context-guard hook — see `mimir_core::context_guard`
# and `[hooks] context_guard` in config.toml. Requires: mimir.
command -v mimir >/dev/null 2>&1 || exit 0
mimir context-guard prompt 2>/dev/null
exit 0
"#;
const MIMIR_CONTEXT_GUARD_PRECOMPACT_SH: &str = r#"#!/usr/bin/env bash
# mimir-hook-version: 1
# Mimir PreCompact context-guard hook — see `mimir_core::context_guard`
# and `[hooks] context_guard` in config.toml. Requires: mimir.
command -v mimir >/dev/null 2>&1 || exit 0
mimir context-guard precompact 2>/dev/null
exit 0
"#;
const MIMIR_CONTEXT_GUARD_SESSION_SH: &str = r#"#!/usr/bin/env bash
# mimir-hook-version: 1
# Mimir SessionStart context-guard hook — see `mimir_core::context_guard`
# and `[hooks] context_guard` in config.toml. Requires: mimir.
command -v mimir >/dev/null 2>&1 || exit 0
mimir context-guard session-start 2>/dev/null
exit 0
"#;

/// Bakes `config.hooks.inject_url` into `MIMIR_RECALL_SH`'s fallback default,
/// split out as a pure function so it's unit-testable without touching disk.
fn render_recall_script(inject_url: &str) -> String {
    MIMIR_RECALL_SH.replace("__MIMIR_INJECT_URL_DEFAULT__", inject_url)
}

/// Install the opt-in Claude Code hooks: a PreToolUse(Bash) rewrite hook, a
/// PreToolUse(Bash|Edit|Write) guard-anchors hook, and a SessionStart hook
/// that injects the project rules pack — all unconditional under `--hooks`
/// — plus (when `auto_recall`) a UserPromptSubmit hook that injects at
/// most one relevant memory per prompt, and (when `config.hooks.
/// context_guard != "off"`) the UserPromptSubmit/PreCompact/SessionStart
/// context-guard hooks. Idempotent, backs up settings.json, and never
/// clobbers existing hooks. `auto_recall=false` leaves
/// `hooks.UserPromptSubmit`'s auto-recall entry untouched, and
/// `context_guard == "off"` (the default) adds none of the context-guard
/// entries at all — behavior is otherwise identical to before either flag
/// existed (see `merge_hook_settings`'s unit tests). Re-running after
/// editing `config.hooks.inject_url` rewrites `mimir-recall.sh`
/// unconditionally (step 2 below is a plain `fs::write`, no existence
/// check), so the new URL always lands on the next `mimir init --hooks
/// --auto-recall`.
fn install_hooks(config: &Config, auto_recall: bool) -> Result<()> {
    if std::env::var_os("MIMIR_HOME").is_some() {
        return Ok(()); // isolated instances never touch the user's agent config
    }
    let base = directories::BaseDirs::new().context("cannot resolve home directory")?;
    let claude = base.home_dir().join(".claude");
    if !claude.is_dir() {
        println!("hooks   ~/.claude not found — skipping (is Claude Code installed?)");
        return Ok(());
    }

    let hooks_dir = claude.join("hooks");
    std::fs::create_dir_all(&hooks_dir)?;

    let write_script = |name: &str, content: &str| -> Result<String> {
        let path = hooks_dir.join(name);
        std::fs::write(&path, content)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?;
        }
        Ok(path.to_string_lossy().into_owned())
    };

    // 1. Write the PreToolUse delegate scripts (executable).
    let script_str = write_script("mimir-rewrite.sh", MIMIR_REWRITE_SH)?;
    let anchors_script_str = write_script("mimir-anchors.sh", MIMIR_ANCHORS_SH)?;

    // 2. Auto-recall delegate script — only written when opted in. Always
    // rewritten (not skipped if already present), so changing
    // config.hooks.inject_url and re-running takes effect immediately.
    let recall_script_str = if auto_recall {
        Some(write_script(
            "mimir-recall.sh",
            &render_recall_script(&config.hooks.inject_url),
        )?)
    } else {
        None
    };

    // 3. Context-guard delegate scripts — only written when opted in.
    let context_guard_scripts = if config.hooks.context_guard != "off" {
        Some((
            write_script(
                "mimir-context-guard-prompt.sh",
                MIMIR_CONTEXT_GUARD_PROMPT_SH,
            )?,
            write_script(
                "mimir-context-guard-precompact.sh",
                MIMIR_CONTEXT_GUARD_PRECOMPACT_SH,
            )?,
            write_script(
                "mimir-context-guard-session.sh",
                MIMIR_CONTEXT_GUARD_SESSION_SH,
            )?,
        ))
    } else {
        None
    };
    let context_guard_scripts_ref = context_guard_scripts
        .as_ref()
        .map(|(p, c, s)| (p.as_str(), c.as_str(), s.as_str()));

    // 4. Merge into settings.json (back it up first).
    let settings_path = claude.join("settings.json");
    let root: serde_json::Value = match std::fs::read_to_string(&settings_path) {
        Ok(text) => {
            std::fs::write(claude.join("settings.json.mimir-bak"), &text)?;
            serde_json::from_str(&text).context("settings.json is not valid JSON")?
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}),
        Err(e) => return Err(e.into()),
    };
    let (root, messages) = merge_hook_settings(
        root,
        &script_str,
        recall_script_str.as_deref(),
        &anchors_script_str,
        context_guard_scripts_ref,
    )?;

    std::fs::write(&settings_path, serde_json::to_string_pretty(&root)?)?;
    println!("hooks   {}", messages.join("; "));
    println!(
        "hooks   backup at {}",
        claude.join("settings.json.mimir-bak").display()
    );
    Ok(())
}

/// Pure settings.json merge, split out of `install_hooks` so the merge
/// logic (idempotency, which keys get touched) is unit-testable without a
/// real `~/.claude` — `install_hooks` early-returns under `MIMIR_HOME`, so
/// this is the only way to test it at all. `recall_script = None` must
/// leave `hooks.UserPromptSubmit`'s auto-recall entry completely untouched
/// — that's what makes `auto_recall=false` byte-identical to
/// pre-auto-recall behavior. Likewise `context_guard_scripts = None`
/// (prompt, precompact, session_start script paths, in that order) must
/// add none of the UserPromptSubmit/PreCompact/SessionStart context-guard
/// entries — what makes `context_guard == "off"` byte-identical to
/// pre-context-guard behavior.
fn merge_hook_settings(
    mut root: serde_json::Value,
    rewrite_script: &str,
    recall_script: Option<&str>,
    anchors_script: &str,
    context_guard_scripts: Option<(&str, &str, &str)>,
) -> Result<(serde_json::Value, Vec<String>)> {
    if !root.is_object() {
        bail!("settings.json is not a JSON object");
    }
    let hooks = root
        .as_object_mut()
        .unwrap()
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    let hooks = hooks
        .as_object_mut()
        .context("settings.json `hooks` is not an object")?;

    let mut messages: Vec<String> = Vec::new();

    // SessionStart: inject the rules pack (stdout becomes session context).
    let session = hooks
        .entry("SessionStart")
        .or_insert_with(|| serde_json::json!([]));
    let session_arr = session
        .as_array_mut()
        .context("hooks.SessionStart is not an array")?;
    if entries_mention(session_arr, "mimir rules show") {
        messages.push("SessionStart already installed".into());
    } else {
        session_arr.push(serde_json::json!({
            "hooks": [{ "type": "command", "command": "mimir rules show" }]
        }));
        messages.push("SessionStart (project rules) added".into());
    }

    // PreToolUse(Bash): the rewrite hook. Skip if another rewrite hook (e.g.
    // RTK) is present — running both would double-wrap commands.
    let pre = hooks
        .entry("PreToolUse")
        .or_insert_with(|| serde_json::json!([]));
    let pre_arr = pre
        .as_array_mut()
        .context("hooks.PreToolUse is not an array")?;
    if entries_mention(pre_arr, "mimir-rewrite") {
        messages.push("PreToolUse already installed".into());
    } else if entries_mention(pre_arr, "rtk") || entries_mention(pre_arr, "rewrite") {
        messages.push(
            "PreToolUse SKIPPED — another rewrite hook (e.g. RTK) is present. Remove it \
             from ~/.claude/settings.json, then re-run `mimir init --hooks`."
                .into(),
        );
    } else {
        pre_arr.push(serde_json::json!({
            "matcher": "Bash",
            "hooks": [{ "type": "command", "command": rewrite_script }]
        }));
        messages.push("PreToolUse (command filter) added".into());
    }

    // PreToolUse(Bash|Edit|Write): guard anchors. Unconditional under
    // `--hooks` — see `MIMIR_ANCHORS_SH`'s doc comment for why there's no
    // separate opt-in.
    if entries_mention(pre_arr, "mimir-anchors") {
        messages.push("PreToolUse anchors already installed".into());
    } else {
        pre_arr.push(serde_json::json!({
            "matcher": "Bash|Edit|Write",
            "hooks": [{ "type": "command", "command": anchors_script }]
        }));
        messages.push("PreToolUse (guard anchors) added".into());
    }

    // UserPromptSubmit: opt-in auto-recall. Only touched when asked for.
    if let Some(recall_script) = recall_script {
        let prompt = hooks
            .entry("UserPromptSubmit")
            .or_insert_with(|| serde_json::json!([]));
        let prompt_arr = prompt
            .as_array_mut()
            .context("hooks.UserPromptSubmit is not an array")?;
        if entries_mention(prompt_arr, "mimir-recall") {
            messages.push("UserPromptSubmit already installed".into());
        } else {
            prompt_arr.push(serde_json::json!({
                "hooks": [{ "type": "command", "command": recall_script }]
            }));
            messages.push("UserPromptSubmit (auto-recall) added".into());
        }
    }

    // Context guard: UserPromptSubmit + PreCompact + SessionStart entries,
    // only when `[hooks] context_guard != "off"` — this is what keeps a
    // default (`"off"`) install byte-identical to pre-context-guard
    // settings.json output (see this fn's unit tests).
    if let Some((prompt_script, precompact_script, session_script)) = context_guard_scripts {
        let cg_prompt = hooks
            .entry("UserPromptSubmit")
            .or_insert_with(|| serde_json::json!([]));
        let cg_prompt_arr = cg_prompt
            .as_array_mut()
            .context("hooks.UserPromptSubmit is not an array")?;
        if entries_mention(cg_prompt_arr, "mimir-context-guard-prompt") {
            messages.push("UserPromptSubmit context-guard already installed".into());
        } else {
            cg_prompt_arr.push(serde_json::json!({
                "hooks": [{ "type": "command", "command": prompt_script }]
            }));
            messages.push("UserPromptSubmit (context guard) added".into());
        }

        let precompact = hooks
            .entry("PreCompact")
            .or_insert_with(|| serde_json::json!([]));
        let precompact_arr = precompact
            .as_array_mut()
            .context("hooks.PreCompact is not an array")?;
        if entries_mention(precompact_arr, "mimir-context-guard-precompact") {
            messages.push("PreCompact already installed".into());
        } else {
            precompact_arr.push(serde_json::json!({
                "hooks": [{ "type": "command", "command": precompact_script }]
            }));
            messages.push("PreCompact (context guard) added".into());
        }

        let session_cg = hooks
            .entry("SessionStart")
            .or_insert_with(|| serde_json::json!([]));
        let session_cg_arr = session_cg
            .as_array_mut()
            .context("hooks.SessionStart is not an array")?;
        if entries_mention(session_cg_arr, "mimir-context-guard-session") {
            messages.push("SessionStart context-guard already installed".into());
        } else {
            session_cg_arr.push(serde_json::json!({
                "hooks": [{ "type": "command", "command": session_script }]
            }));
            messages.push("SessionStart (context guard) added".into());
        }
    }

    Ok((root, messages))
}

/// True if any hook entry (or its nested hooks) has a command containing `needle`.
fn entries_mention(entries: &[serde_json::Value], needle: &str) -> bool {
    entries.iter().any(|e| {
        e.get("hooks")
            .and_then(|h| h.as_array())
            .map(|arr| {
                arr.iter().any(|h| {
                    h.get("command")
                        .and_then(|c| c.as_str())
                        .is_some_and(|c| c.contains(needle))
                })
            })
            .unwrap_or(false)
    })
}

/// One Mimir slash command: name carries the `m-` prefix (collision safety
/// with users' own commands), `allowed` is Claude-Code-only tool pre-approval.
struct SlashCmd {
    name: &'static str,
    desc: &'static str,
    body: &'static str,
    allowed: Option<&'static str>,
}

/// Every `/m-*` slash command Mimir ships. `{args}` becomes the app's own
/// argument placeholder at render time.
const SLASH_COMMANDS: &[SlashCmd] = &[
    SlashCmd {
        name: "m-graph",
        desc: "Open the interactive Mimir graph visualization (current project)",
        body: "Run `mimir graph viz --open {args}` with your shell tool from the current \
            project root, then report the output path it prints. If it fails with \
            \"not inside a project\", relay the suggestion in the error: it needs a \
            project root (.git/.hg/.svn/.jj), or `touch .mimir` to mark one.",
        allowed: Some("Bash(mimir graph viz:*)"),
    },
    SlashCmd {
        name: "m-stats",
        desc: "Open the Mimir stats dashboard (memories, docs, code, learning)",
        body: "Run `mimir dashboard --open {args}` with your shell tool, then report the \
            output path it prints.",
        allowed: Some("Bash(mimir dashboard:*)"),
    },
    SlashCmd {
        name: "m-report",
        desc: "Mimir activity report: day / week / month / year / all-time",
        body: "Run `mimir report` with your shell tool and show its complete output \
            verbatim in a code block. Do not summarize or reformat the table.",
        allowed: Some("Bash(mimir report:*)"),
    },
    SlashCmd {
        name: "m-savings",
        desc: "Mimir token-savings report (outline/peek/command-filter/proxy)",
        body: "Run `mimir savings` with your shell tool and show its complete output \
            verbatim. It reports tokens saved today/week/month/all-time and by source.",
        allowed: Some("Bash(mimir savings:*)"),
    },
    SlashCmd {
        name: "m-scan",
        desc: "Auto-link Mimir memories to the code symbols they mention",
        body: "Run `mimir link --scan` with your shell tool from the current project \
            root and show its output. If links were created, suggest /m-graph to see \
            the new memory-to-code connections.",
        allowed: Some("Bash(mimir link:*)"),
    },
    SlashCmd {
        name: "m-recall",
        desc: "Search Mimir memory (memories, docs, code)",
        body: "Run `mimir recall {args}` with your shell tool and show the results. \
            If a hit looks like exactly what the user needs, also run \
            `mimir get <id>` on it and show the full body.",
        allowed: Some("Bash(mimir recall:*), Bash(mimir get:*)"),
    },
    SlashCmd {
        name: "m-remember",
        desc: "Save a memory to Mimir",
        body: "Store this in Mimir: {args}\n\nUse the mimir remember MCP tool (or \
            `mimir remember` via shell). Pick the fitting type (gotcha / decision / \
            insight / idea / note / person) and concise tags. If it is about specific \
            code, pass `link` with the symbol name. Confirm what was stored.",
        allowed: Some("mcp__mimir__remember, mcp__mimir__recall, Bash(mimir remember:*)"),
    },
    SlashCmd {
        name: "m-impact",
        desc: "Blast radius of the current uncommitted changes (Mimir code graph)",
        body: "Run `mimir graph impact $(git diff --name-only)` with your shell tool \
            from the current project root and show the affected symbols. If the diff \
            is empty, say there are no uncommitted changes to analyze.",
        allowed: Some("Bash(mimir graph impact:*)"),
    },
    SlashCmd {
        name: "m-doctor",
        desc: "Mimir health check (database, search index, models)",
        body: "Run `mimir doctor` and `mimir status` with your shell tool and show \
            both outputs verbatim. If any check is not ok, explain what it means and \
            how to fix it.",
        allowed: Some("Bash(mimir doctor:*), Bash(mimir status:*)"),
    },
];

/// Installed only when `[sync]` is enabled (re-run `mimir init` after enabling).
const SYNC_SLASH_COMMANDS: &[SlashCmd] = &[SlashCmd {
    name: "m-sync",
    desc: "Sync Mimir memories with the central store",
    body: "Run `mimir sync` with your shell tool and show the push/pull summary. \
        If it reports an auth or connection error, check MIMIR_SYNC_TOKEN and the \
        [sync] endpoint/dir in the Mimir config.",
    allowed: Some("Bash(mimir sync:*)"),
}];

/// Install the `/m-*` slash commands for the agent CLIs that support
/// user-level custom commands. Installed only for apps already present on
/// the machine; existing files are never overwritten (user edits win).
/// Re-running `mimir init` after an upgrade refreshes missing files.
fn install_agent_commands(config: &Config) {
    // An isolated instance (tests, scratch homes) must not touch the user's
    // agent configs — MIMIR_HOME means "everything under one directory".
    if std::env::var_os("MIMIR_HOME").is_some() {
        return;
    }
    // /m-sync is only useful (and only installed) when sync is enabled.
    let extra: &[SlashCmd] = if config.sync.enabled() {
        SYNC_SLASH_COMMANDS
    } else {
        &[]
    };

    let md = |cmd: &SlashCmd, with_allowed: bool| {
        let allowed = match (with_allowed, cmd.allowed) {
            (true, Some(a)) => format!("allowed-tools: {a}\n"),
            _ => String::new(),
        };
        format!(
            "---\ndescription: {}\n{allowed}---\n\n{}\n",
            cmd.desc,
            cmd.body.replace("{args}", "$ARGUMENTS")
        )
    };
    let toml = |cmd: &SlashCmd| {
        format!(
            "description = \"{}\"\nprompt = \"\"\"\n{}\n\"\"\"\n",
            cmd.desc,
            cmd.body.replace("{args}", "{{args}}")
        )
    };

    let Some(base) = directories::BaseDirs::new() else {
        return;
    };
    let home = base.home_dir();

    // (app, detect dir, target dir, file ext, claude-style allowed-tools?)
    const APPS: &[(&str, &str, &str, &str, bool)] = &[
        ("claude", ".claude", ".claude/commands", "md", true),
        ("codex", ".codex", ".codex/prompts", "md", false),
        (
            "opencode",
            ".config/opencode",
            ".config/opencode/command",
            "md",
            false,
        ),
        ("gemini", ".gemini", ".gemini/commands", "toml", false),
        ("cursor", ".cursor", ".cursor/commands", "md", false),
    ];

    let mut installed: Vec<String> = Vec::new();
    let mut detected = 0usize;
    for (app, detect, target, ext, with_allowed) in APPS {
        if !home.join(detect).is_dir() {
            continue;
        }
        detected += 1;
        let dir = home.join(target);
        if std::fs::create_dir_all(&dir).is_err() {
            continue;
        }
        let mut wrote = Vec::new();
        for cmd in SLASH_COMMANDS.iter().chain(extra) {
            let content = if *ext == "toml" {
                toml(cmd)
            } else {
                md(cmd, *with_allowed)
            };
            let path = dir.join(format!("{}.{ext}", cmd.name));
            if !path.exists() && std::fs::write(&path, content).is_ok() {
                wrote.push(format!("/{}", cmd.name));
            }
        }
        if !wrote.is_empty() {
            installed.push(format!("{app} ({})", wrote.join(" ")));
        }
    }
    // Always say what happened — a silent installer is undiagnosable
    // (a stale release binary once looked identical to "no agents found").
    if !installed.is_empty() {
        println!("agents  slash commands installed: {}", installed.join(", "));
    } else if detected == 0 {
        println!(
            "agents  no agent CLI config dirs found (~/.claude, ~/.codex, \
             ~/.config/opencode, ~/.gemini, ~/.cursor) — slash commands not installed"
        );
    } else {
        println!("agents  slash commands already present (nothing new to install)");
    }
}

/// Embed pending content; --fetch additionally allows the model download,
/// --rerank (with --fetch) also downloads the reranker.
pub fn embed(fetch: bool, rerank: bool) -> Result<()> {
    let mut mimir = Mimir::open()?;
    if mimir.ensure_embedder(fetch).is_none() {
        bail!("embedding model unavailable; run `mimir embed --fetch` (or `mimir init`) to download it");
    }
    if rerank {
        if mimir.ensure_reranker(fetch).is_none() {
            bail!("reranker model unavailable; run `mimir embed --fetch --rerank` to download it");
        }
        println!("reranker {} ready", mimir.config.rerank.model);
    }
    let n = mimir.embed_pending()?;
    println!("embedded {n} node(s)");
    Ok(())
}

/// Count tokens in stdin (or the given text) with Mimir's bundled tokenizer —
/// the same counter the savings ledger uses, handy for measuring/benchmarking.
pub fn tokens(text: Vec<String>) -> Result<()> {
    let input = if text.is_empty() {
        let mut buf = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;
        buf
    } else {
        text.join(" ")
    };
    println!("{}", mimir_core::tokens::count(&input));
    Ok(())
}

pub fn status(json: bool) -> Result<()> {
    let mimir = Mimir::open()?;
    let counts = store::count_by_kind(&mimir.conn)?;
    let db_size = std::fs::metadata(&mimir.paths.db_file)
        .with_context(|| format!("stat {}", mimir.paths.db_file.display()))?
        .len();
    let (project, detection) = mimir.detect_project(&std::env::current_dir()?)?;
    let via = match &detection {
        mimir_core::scope::Detection::Found { via, .. } => Some(mimir_core::scope::via_label(via)),
        mimir_core::scope::Detection::NotFound { .. } => None,
    };

    if json {
        let counts_json: serde_json::Map<String, serde_json::Value> = counts
            .iter()
            .map(|(k, v)| (k.clone(), serde_json::json!(v)))
            .collect();
        println!(
            "{}",
            serde_json::json!({
                "db": mimir.paths.db_file,
                "db_bytes": db_size,
                "project": project.as_ref().and_then(|p| p.title.clone()),
                "project_path": project.as_ref().and_then(|p| p.path.clone()),
                "scope": if project.is_some() { "project" } else { "global" },
                "detected_via": via,
                "counts": counts_json,
            })
        );
        return Ok(());
    }

    match (&project, &detection) {
        (Some(p), _) => println!(
            "project {} ({})  [via: {}]",
            p.title.as_deref().unwrap_or("?"),
            p.path.as_deref().unwrap_or("?"),
            via.unwrap_or("?")
        ),
        (None, mimir_core::scope::Detection::NotFound { from }) => println!(
            "project (none) — no git root or project marker found above {}; \
             using global scope (touch .mimir here to make it a project)",
            from.display()
        ),
        (None, _) => println!("project (none — global scope)"),
    }
    if counts.is_empty() {
        println!("store   empty");
    } else {
        let summary: Vec<String> = counts.iter().map(|(k, v)| format!("{v} {k}")).collect();
        println!("store   {}", summary.join(", "));
    }
    println!(
        "db      {} ({} KB)",
        mimir.paths.db_file.display(),
        db_size / 1024
    );
    let sc = &mimir.config.sync;
    if sc.enabled() {
        let push = mimir_core::replicate::get_watermark(&mimir.conn, "last_push").unwrap_or(0);
        let pull = mimir_core::replicate::get_watermark(&mimir.conn, "last_pull").unwrap_or(0);
        let cadence = if sc.auto {
            format!("auto every {} min", sc.interval_mins)
        } else {
            "manual".into()
        };
        println!(
            "sync    {} {} ({cadence}); local watermarks push={push} pull={pull}",
            sc.mode, sc.endpoint
        );
    } else {
        println!("sync    off (local store only)");
    }
    Ok(())
}

pub fn doctor() -> Result<()> {
    let paths = Paths::resolve()?;
    let mut failures = 0;

    let check = |name: &str, ok: bool, detail: String, failures: &mut i32| {
        let mark = if ok { "ok " } else { "FAIL" };
        if !ok {
            *failures += 1;
        }
        println!("{mark}  {name}: {detail}");
    };

    match db::open(&paths.db_file) {
        Ok(conn) => {
            check(
                "db",
                true,
                paths.db_file.display().to_string(),
                &mut failures,
            );
            let integrity: String = conn
                .query_row("PRAGMA integrity_check", [], |r| r.get(0))
                .unwrap_or_else(|e| format!("error: {e}"));
            check("integrity", integrity == "ok", integrity, &mut failures);
            let fts = conn
                .prepare("SELECT count(*) FROM node_fts")
                .and_then(|mut s| s.query_row([], |r| r.get::<_, i64>(0)));
            check(
                "fts5",
                fts.is_ok(),
                fts.map(|n| format!("{n} rows indexed"))
                    .unwrap_or_else(|e| e.to_string()),
                &mut failures,
            );
        }
        Err(e) => check("db", false, e.to_string(), &mut failures),
    }

    println!(
        "ok   gpu: {}",
        mimir_core::embed::gpu_backend()
            .unwrap_or("not compiled in (CPU; rebuild with --features gpu-webgpu or gpu-cuda)")
    );

    let model_present = paths.models_dir.exists()
        && std::fs::read_dir(&paths.models_dir)
            .map(|mut d| d.next().is_some())
            .unwrap_or(false);
    check(
        "model",
        true, // informational until embeddings land; BM25-only is a valid state
        if model_present {
            format!("present at {}", paths.models_dir.display())
        } else {
            "not downloaded (search is BM25-only until `mimir init` fetches it)".into()
        },
        &mut failures,
    );

    // Informational only (ok=true regardless): whether `mimir daemon` /
    // `mimir mcp --http` is actually up. Absence is a normal, supported
    // state — the hooks fall back to the cold `mimir recall-inject` path —
    // so this must never fail `doctor`'s exit code, same precedent as the
    // "model" check above.
    let inject_url = Config::load(&paths.config_file)
        .map(|c| c.hooks.inject_url)
        .unwrap_or_else(|_| mimir_core::config::HooksConfig::default().inject_url);
    let warm = ureq::get(&inject_url)
        .timeout(std::time::Duration::from_secs(1))
        .call()
        .is_ok();
    check(
        "daemon",
        true,
        if warm {
            format!("warm ({inject_url} reachable — hooks use the fast HTTP path)")
        } else {
            format!(
                "cold ({inject_url} not reachable — hooks fall back to `mimir recall-inject`; \
                 run `mimir daemon` for the warm path)"
            )
        },
        &mut failures,
    );

    if failures > 0 {
        anyhow::bail!("{failures} check(s) failed");
    }
    Ok(())
}

// ---------- memory verbs ----------

#[allow(clippy::too_many_arguments)]
pub fn remember(
    json: bool,
    text: String,
    mtype: &str,
    tags: Vec<String>,
    global: bool,
    force: bool,
    link_ref: Option<String>,
    fires_when: Vec<String>,
    anchors: Vec<String>,
) -> Result<()> {
    let mut mimir = Mimir::open()?;
    let mtype: MemoryType = mtype.parse()?;
    let project = if global {
        None
    } else {
        mimir.project_for_cwd(&std::env::current_dir()?)?
    };
    let outcome = memory::remember(
        &mimir.conn,
        Remember {
            text,
            mtype,
            tags,
            project_id: project.as_ref().map(|p| p.id),
            force,
        },
    )?;
    let projects = store::project_titles(&mimir.conn)?;
    let snippet = mimir.config.output.snippet_chars;
    match outcome {
        RememberOutcome::Created(node) => {
            if json {
                println!("{}", node_json(&node, &projects));
            } else {
                println!("{}", line(&node, &projects, snippet));
            }
            if let Some(r) = link_ref {
                let target = store::resolve_ref(&mimir.conn, &r)?;
                store::link(&mimir.conn, node.id, target.id, Rel::Relates, 1.0)?;
                println!("linked → {}", line(&target, &projects, 0));
            }
            if !fires_when.is_empty() {
                let phrases = memory::sanitize_fires_when(fires_when);
                if !phrases.is_empty() {
                    store::set_fires_when(&mimir.conn, node.id, &phrases)?;
                }
            }
            if !anchors.is_empty() {
                let patterns = mimir_core::anchors::sanitize_anchors(anchors);
                if !patterns.is_empty() {
                    mimir_core::anchors::set_anchors(&mimir.conn, node.id, &patterns)?;
                }
            }
            // Keep semantic recall fresh; harmless no-op without a model.
            if let Err(err) = mimir.embed_pending() {
                tracing::warn!(%err, "embedding new memory failed");
            }
            Ok(())
        }
        RememberOutcome::Duplicate(existing) => bail!(
            "refused: near-duplicate of\n  {}\nuse --force to store anyway",
            line(&existing, &projects, snippet)
        ),
    }
}

#[allow(clippy::too_many_arguments)]
pub fn recall(
    json: bool,
    text: String,
    kind: &str,
    global: bool,
    all: bool,
    since: Option<String>,
    limit: Option<usize>,
    full: bool,
    rerank: bool,
    linked: bool,
    min_score: Option<f64>,
    include_superseded: bool,
) -> Result<()> {
    let mut mimir = Mimir::open()?;
    let query = SearchQuery {
        scope: read_scope(&mimir, global, all)?,
        kinds: parse_kind_filter(kind)?,
        since: since.map(|s| parse_since(&s)).transpose()?,
        limit: limit.unwrap_or(mimir.config.output.default_limit),
        strength_alpha: mimir.config.scoring.strength_alpha,
        recency_alpha: mimir.config.scoring.recency_alpha,
        type_prior_alpha: mimir.config.scoring.type_prior_alpha,
        code_damp: mimir.config.scoring.code_damp,
        include_superseded,
        text,
    };
    let mut hits = mimir.search_with(&query, rerank)?;
    if let Some(min) = min_score {
        hits.retain(|hit| hit.score >= min);
    }

    let query_hash = blake3::hash(query.text.as_bytes());
    let shown: Vec<(i64, i64, f64)> = hits
        .iter()
        .enumerate()
        .map(|(rank, hit)| (hit.node.id, rank as i64, hit.score))
        .collect();
    store::record_shown(&mimir.conn, query_hash.as_bytes(), &shown)?;
    if let Some(report) = mimir_core::consolidate::maybe_auto(
        &mimir.conn,
        &mimir.config.embedding.model,
        &mimir.config.consolidate.auto,
    ) {
        if !report.is_empty() {
            eprintln!(
                "(consolidated: {} superseded, {} distilled, {} archived)",
                report.superseded, report.distilled, report.archived
            );
        }
    }

    let projects = store::project_titles(&mimir.conn)?;
    if hits.is_empty() && !json {
        println!("no results");
        return Ok(());
    }
    for hit in &hits {
        if json {
            let mut value = node_json(&hit.node, &projects);
            value["score"] = serde_json::json!(hit.score);
            println!("{value}");
        } else if full {
            print_full(&hit.node, &mimir, &projects)?;
            println!();
        } else {
            println!(
                "{}",
                line(&hit.node, &projects, mimir.config.output.snippet_chars)
            );
        }
        if linked && !json {
            for edge in store::edges_of(&mimir.conn, hit.node.id)?.iter().take(4) {
                let other_id = if edge.src == hit.node.id {
                    edge.dst
                } else {
                    edge.src
                };
                let Ok(other) = store::get_node(&mimir.conn, other_id) else {
                    continue;
                };
                let l = match other.kind {
                    Kind::Symbol => mimir_graph::symbol_line(&other),
                    _ => line(&other, &projects, 60),
                };
                println!("  ~{} {}", edge.rel, l);
            }
        }
    }
    Ok(())
}

/// Print at most one relevant memory for `prompt`, or nothing if none
/// clears the relevance floor. This is the COLD fallback path: it opens a
/// fresh `Mimir` (ONNX load + full matrix rebuild) every invocation, so the
/// hook script (`MIMIR_RECALL_SH`) tries the warm `/inject` HTTP endpoint
/// first (see `mcp.rs::inject_router`, only live while `mimir mcp --http`
/// is running) and only falls back to this command when that's
/// unreachable. All relevance-floor/formatting/budget logic lives in
/// `mimir_core::inject::compute`/`compute_with_mode` — single-sourced so the
/// warm and cold paths can never disagree on *how* a hit is judged, only on
/// whether a vector leg is available to judge it with.
///
/// Config `[hooks] cold_mode` governs whether this cold path pays the
/// embedder's load cost:
///   - `"fast"` (default): BM25-only, via `compute_with_mode(.., bm25_only
///     = true)` — never calls `ensure_embedder`, so no ONNX load and no
///     matrix build. This is the mode actually measured for hook latency
///     (see CHANGELOG); an unrecognized value logs a warning and falls back
///     to `"full"`, the safe default, same precedent as `[rerank] auto`.
///   - `"full"`: restores the pre-`cold_mode` behavior — hybrid search with
///     the embedder loaded cold, same as the warm endpoint.
///
/// Only this cold CLI path reads `cold_mode`; the warm `/inject` endpoint
/// always uses the best available signal via the unchanged `compute`.
///
/// `enrich`: optional working-tree signal (changed-file stems from
/// `MIMIR_RECALL_SH`'s `git diff`), passed straight through to
/// `inject::compute_with_mode` — see that function's doc comment for how
/// it's used.
pub fn recall_inject(
    prompt: String,
    enrich: Option<String>,
    session: Option<String>,
) -> Result<()> {
    let mut mimir = Mimir::open()?;
    let scope = read_scope(&mimir, false, false)?;
    let enrich = enrich.unwrap_or_default();
    let bm25_only = match mimir.config.hooks.cold_mode.as_str() {
        "fast" => true,
        "full" => false,
        other => {
            tracing::warn!(
                cold_mode = other,
                "unknown [hooks] cold_mode value; treating as full"
            );
            false
        }
    };
    if let Some(text) = mimir_core::inject::compute_with_session(
        &mut mimir,
        &prompt,
        &enrich,
        scope,
        bm25_only,
        session.as_deref(),
    )? {
        println!("{text}");
    }
    Ok(())
}

/// `mimir daemon` — a thin, discoverable alias for `mimir mcp --http <addr>`.
/// The bind address is derived from `config.hooks.inject_url` (the exact
/// same key `MIMIR_RECALL_SH` already reads — see `render_recall_script`),
/// so there is one setting for "where does the warm path live" instead of
/// two independent ones that could drift apart. No auto-spawn, no process
/// supervision: this is purely a memorable name for a command the hooks
/// already know how to fall back from — see `contrib/mimir-daemon.service`
/// for running it unattended.
pub fn daemon() -> Result<()> {
    let mimir = Mimir::open()?;
    let addr = inject_addr(&mimir.config.hooks.inject_url)?;
    println!(
        "mimir daemon: warm path at http://{addr}/inject — the auto-recall hook will use \
         this instead of the cold `mimir recall-inject` fallback"
    );
    crate::mcp::run(Some(addr), false)
}

/// Strip `config.hooks.inject_url` (e.g. `"http://127.0.0.1:8077/inject"`)
/// down to the bare `host:port` that `mimir mcp --http` binds to. Split out
/// as a pure function so the parsing is unit-testable without a real config
/// file — mirrors `render_recall_script`'s split for the same reason.
fn inject_addr(inject_url: &str) -> Result<String> {
    let without_scheme = inject_url
        .split_once("://")
        .map(|(_, rest)| rest)
        .unwrap_or(inject_url);
    let host_port = without_scheme.split('/').next().unwrap_or("");
    if host_port.is_empty() {
        bail!("config.hooks.inject_url `{inject_url}` has no host:port to bind to");
    }
    Ok(host_port.to_string())
}

pub fn get(json: bool, refs: Vec<String>) -> Result<()> {
    let mimir = Mimir::open()?;
    let projects = store::project_titles(&mimir.conn)?;
    for (i, r) in refs.iter().enumerate() {
        if i > 0 && !json {
            println!();
        }
        if let Some(slice) = mimir_core::index::file_slice(&mimir.conn, r)? {
            println!("{slice}");
            continue;
        }
        let node = store::resolve_ref(&mimir.conn, r)?;
        mimir_core::learn::record_opened(&mimir.conn, node.id)?;
        if json {
            println!("{}", node_json(&node, &projects));
        } else {
            print_full(&node, &mimir, &projects)?;
        }
    }
    Ok(())
}

pub fn list(
    json: bool,
    mtype: Option<String>,
    tag: Option<String>,
    global: bool,
    all: bool,
    limit: usize,
) -> Result<()> {
    let mimir = Mimir::open()?;
    let scope = read_scope(&mimir, global, all)?;
    let mtype = mtype.map(|t| t.parse::<MemoryType>()).transpose()?;
    let nodes = memory::list(&mimir.conn, scope, mtype, tag.as_deref(), limit)?;
    let projects = store::project_titles(&mimir.conn)?;
    if nodes.is_empty() && !json {
        println!("no memories");
        return Ok(());
    }
    for node in &nodes {
        if json {
            println!("{}", node_json(node, &projects));
        } else {
            println!(
                "{}",
                line(node, &projects, mimir.config.output.snippet_chars)
            );
        }
    }
    Ok(())
}

pub fn mark(reference: &str, useful: bool) -> Result<()> {
    let mimir = Mimir::open()?;
    let node = resolve_any(&mimir, reference)?;
    let strength = mimir_core::learn::apply_mark(&mimir.conn, node.id, useful)?;
    println!(
        "{} {} → strength {strength:.2}",
        short_uid(node.kind, &node.uid),
        if useful { "useful" } else { "noise" },
    );
    Ok(())
}

pub fn consolidate(dry_run: bool) -> Result<()> {
    let mimir = Mimir::open()?;
    let report =
        mimir_core::consolidate::consolidate(&mimir.conn, &mimir.config.embedding.model, dry_run)?;
    print_consolidate_report(&report, dry_run);
    Ok(())
}

fn print_consolidate_report(report: &mimir_core::consolidate::Report, dry_run: bool) {
    let prefix = if dry_run { "would " } else { "" };
    if report.is_empty() {
        println!("nothing to consolidate");
        return;
    }
    if report.superseded > 0 {
        println!("{prefix}supersede {} near-duplicate(s)", report.superseded);
    }
    if report.distilled > 0 {
        println!(
            "{prefix}distill {} cluster(s) into summaries",
            report.distilled
        );
    }
    if report.archived > 0 {
        println!("{prefix}archive {} decayed memorie(s)", report.archived);
    }
    for (a, b) in &report.contradictions {
        println!("possible contradiction (review by hand):\n  {a}\n  {b}");
    }
}

pub fn forget(reference: &str, hard: bool) -> Result<()> {
    let mimir = Mimir::open()?;
    let node = store::resolve_ref(&mimir.conn, reference)?;
    if hard {
        store::hard_delete(&mimir.conn, node.id)?;
    } else {
        store::soft_delete(&mimir.conn, node.id)?;
    }
    println!(
        "forgot {} {}{}",
        short_uid(node.kind, &node.uid),
        node.title.as_deref().unwrap_or(""),
        if hard { " (permanently)" } else { "" }
    );
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub fn edit(
    json: bool,
    reference: &str,
    text: String,
    title: Option<String>,
    mtype: Option<String>,
    tags: Option<Vec<String>>,
    pin: Option<bool>,
) -> Result<()> {
    let mimir = Mimir::open()?;
    let node = store::resolve_ref(&mimir.conn, reference)?;
    let mtype = mtype.map(|t| t.parse::<MemoryType>()).transpose()?;
    let edit = memory::Edit {
        text: if text.is_empty() { None } else { Some(text) },
        title,
        mtype,
        tags,
    };
    if edit.text.is_none()
        && edit.title.is_none()
        && edit.mtype.is_none()
        && edit.tags.is_none()
        && pin.is_none()
    {
        bail!("nothing to change: pass TEXT, --title, --type, --tags, or --pin/--unpin");
    }
    if let Some(pin) = pin {
        store::set_pinned(&mimir.conn, node.id, pin)?;
    }
    let updated = memory::edit(&mimir.conn, node.id, edit)?;
    let projects = store::project_titles(&mimir.conn)?;
    if json {
        println!("{}", node_json(&updated, &projects));
    } else {
        println!(
            "{}",
            line(&updated, &projects, mimir.config.output.snippet_chars)
        );
    }
    Ok(())
}

pub fn link(a: &str, b: &str, rel: &str) -> Result<()> {
    let mimir = Mimir::open()?;
    let rel: Rel = rel.parse()?;
    let src = resolve_any(&mimir, a)?;
    let dst = resolve_any(&mimir, b)?;
    store::link(&mimir.conn, src.id, dst.id, rel, 1.0)?;
    println!(
        "{} —{rel}→ {}",
        short_uid(src.kind, &src.uid),
        short_uid(dst.kind, &dst.uid)
    );
    Ok(())
}

/// Mark OLD as superseded by NEW: OLD stops surfacing in recall (kept as
/// history) and a `supersedes` edge is recorded.
pub fn supersede(old: &str, by: &str) -> Result<()> {
    let mimir = Mimir::open()?;
    let old = resolve_any(&mimir, old)?;
    let new = resolve_any(&mimir, by)?;
    store::set_superseded(&mimir.conn, old.id, new.id)?;
    store::link(&mimir.conn, new.id, old.id, Rel::Supersedes, 1.0)?;
    println!(
        "{} superseded by {}",
        short_uid(old.kind, &old.uid),
        short_uid(new.kind, &new.uid)
    );
    Ok(())
}

/// Auto-link memories to the code symbols their text literally mentions
/// (current project + global memories vs the current project's graph).
/// Precision-first: only code-shaped names (snake_case, ::path, CamelCase)
/// or backticked mentions link, on word boundaries; ambiguous names that
/// resolve to many symbols are skipped. Idempotent: existing edges are kept.
pub fn link_scan(dry_run: bool) -> Result<()> {
    let mimir = Mimir::open()?;
    let proj = mimir
        .project_for_cwd(&std::env::current_dir()?)?
        .context("not inside a project (the scan links memories to this project's symbols)")?;

    // name → symbol nodes carrying it (bare name from meta, fallback title)
    let mut by_name: HashMap<String, Vec<(i64, String, String)>> = HashMap::new();
    {
        let mut stmt = mimir.conn.prepare(
            "SELECT id, uid, COALESCE(json_extract(meta,'$.name'), title) FROM node
             WHERE kind='symbol' AND project_id=?1 AND deleted_at IS NULL",
        )?;
        let mut rows = stmt.query([proj.id])?;
        while let Some(r) = rows.next()? {
            let (id, uid): (i64, String) = (r.get(0)?, r.get(1)?);
            let name: Option<String> = r.get(2)?;
            if let Some(name) = name {
                if name.len() >= 4 {
                    by_name
                        .entry(name)
                        .or_default()
                        .push((id, uid, String::new()));
                }
            }
        }
    }

    let memories: Vec<(i64, String, String)> = {
        let mut stmt = mimir.conn.prepare(
            "SELECT id, uid, COALESCE(title,'') || ' ' || COALESCE(body,'') FROM node
             WHERE kind='memory' AND deleted_at IS NULL AND superseded_by IS NULL
               AND (project_id=?1 OR project_id IS NULL)",
        )?;
        let rows = stmt.query_map([proj.id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?;
        rows.collect::<rusqlite::Result<_>>()?
    };

    let mut existing: std::collections::HashSet<(i64, i64)> = Default::default();
    {
        let mut stmt = mimir.conn.prepare("SELECT src, dst FROM edge")?;
        let mut rows = stmt.query([])?;
        while let Some(r) = rows.next()? {
            let (s, d): (i64, i64) = (r.get(0)?, r.get(1)?);
            existing.insert((s, d));
            existing.insert((d, s));
        }
    }

    let mut created = 0usize;
    for (mid, muid, text) in &memories {
        for (name, syms) in &by_name {
            if syms.len() > 3 {
                continue; // same name everywhere = ambiguous, skip
            }
            if !mentions_symbol(text, name) {
                continue;
            }
            for (sid, suid, _) in syms {
                if existing.contains(&(*mid, *sid)) {
                    continue;
                }
                if dry_run {
                    println!(
                        "would link m:{} —mentions→ {name} (c:{})",
                        tail(muid),
                        tail(suid)
                    );
                } else {
                    store::link(&mimir.conn, *mid, *sid, Rel::Mentions, 1.0)?;
                    println!("m:{} —mentions→ {name} (c:{})", tail(muid), tail(suid));
                }
                existing.insert((*mid, *sid));
                created += 1;
            }
        }
    }
    println!(
        "{} {created} link(s) ({} memories × {} distinct symbol names)",
        if dry_run { "would create" } else { "created" },
        memories.len(),
        by_name.len(),
    );
    Ok(())
}

fn tail(uid: &str) -> &str {
    &uid[uid.len().saturating_sub(6)..]
}

/// True when `text` mentions `name` as code: word-boundary matched AND
/// code-shaped (snake_case, ::path, or mixed-case with an uppercase letter
/// *after* the first — `MimirServer` yes, sentence-case `Pending` no).
/// Plain English words never match, even in backticks: `main` is usually
/// a git branch, not fn main. Precision beats recall here — a wrong link
/// pollutes recall, a missing one just waits for the next scan.
fn mentions_symbol(text: &str, name: &str) -> bool {
    let mixed_case = name.len() >= 6
        && name.chars().skip(1).any(|c| c.is_uppercase())
        && name.chars().any(|c| c.is_lowercase());
    let code_shaped = name.contains('_') || name.contains("::") || mixed_case;
    if !code_shaped {
        return false;
    }
    let mut start = 0;
    while let Some(pos) = text[start..].find(name) {
        let i = start + pos;
        let j = i + name.len();
        let is_word = |c: Option<char>| c.map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false);
        let pre = text[..i].chars().next_back();
        let post = text[j..].chars().next();
        if !is_word(pre) && !is_word(post) {
            return true;
        }
        start = j;
    }
    false
}

// ---------- docs & index ----------

pub fn docs_add(path: &str, name: Option<String>, global: bool) -> Result<()> {
    add_collection_cmd(path, name, global, "docs")
}

/// Register + index a source-code collection: chunks function/method bodies
/// (not just signatures) on tree-sitter symbol boundaries for recall —
/// mirrors `docs add`, indexing source instead of markdown. Idea credit:
/// nworks3d's THOR fork of Mimir (see CHANGELOG.md).
pub fn code_add(path: &str, name: Option<String>, global: bool) -> Result<()> {
    add_collection_cmd(path, name, global, "code")
}

fn add_collection_cmd(path: &str, name: Option<String>, global: bool, kind: &str) -> Result<()> {
    let mimir = Mimir::open()?;
    let root = std::path::Path::new(path);
    let canonical = std::fs::canonicalize(root).with_context(|| format!("no such dir: {path}"))?;
    let name = name.unwrap_or_else(|| {
        canonical
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.to_string())
    });
    let project = if global {
        None
    } else {
        mimir.project_for_cwd(&canonical)?
    };
    let coll = mimir_core::index::add_collection(
        &mimir.conn,
        &canonical,
        &name,
        project.as_ref().map(|p| p.id),
        kind,
    )?;
    println!(
        "{} {} {}",
        short_uid(coll.kind, &coll.uid),
        name,
        coll.path.as_deref().unwrap_or("?")
    );
    println!("run `mimir index` to scan it");
    Ok(())
}

pub fn docs_list(json: bool) -> Result<()> {
    let mimir = Mimir::open()?;
    let collections = mimir_core::index::list_collections(&mimir.conn)?;
    if collections.is_empty() && !json {
        println!("no collections (add one with `mimir docs add <path>`)");
        return Ok(());
    }
    let projects = store::project_titles(&mimir.conn)?;
    for coll in collections {
        let (files, chunks) = mimir_core::index::collection_stats(&mimir.conn, coll.id)?;
        if json {
            let mut v = node_json(&coll, &projects);
            v["files"] = serde_json::json!(files);
            v["chunks"] = serde_json::json!(chunks);
            println!("{v}");
        } else {
            let kind = coll
                .meta
                .get("kind")
                .and_then(|v| v.as_str())
                .unwrap_or("docs");
            println!(
                "{} [{kind}] {} {} ({files} files, {chunks} chunks)",
                short_uid(coll.kind, &coll.uid),
                coll.title.as_deref().unwrap_or("?"),
                coll.path.as_deref().unwrap_or("?"),
            );
        }
    }
    Ok(())
}

pub fn docs_remove(name: &str) -> Result<()> {
    let mimir = Mimir::open()?;
    let coll = mimir_core::index::find_collection(&mimir.conn, name)?;
    mimir_core::index::remove_collection(&mimir.conn, coll.id)?;
    println!("removed {}", coll.title.as_deref().unwrap_or(name));
    Ok(())
}

pub fn docs_note(target: &str, text: String) -> Result<()> {
    let mimir = Mimir::open()?;
    let target_node = mimir_core::index::find_collection(&mimir.conn, target)
        .or_else(|_| store::resolve_ref(&mimir.conn, target))?;
    let note = mimir_core::index::annotate(&mimir.conn, &target_node, &text)?;
    println!(
        "{} describes {} {}",
        short_uid(note.kind, &note.uid),
        short_uid(target_node.kind, &target_node.uid),
        target_node.title.as_deref().unwrap_or("")
    );
    Ok(())
}

pub fn index(name: Option<String>) -> Result<()> {
    let mut mimir = Mimir::open()?;
    let results = match name {
        Some(n) => {
            let coll = mimir_core::index::find_collection(&mimir.conn, &n)?;
            let stats = mimir_core::index::index_collection(&mut mimir.conn, &coll)?;
            vec![(coll.title.unwrap_or(n), stats)]
        }
        None => mimir_core::index::index_all(&mut mimir.conn)?,
    };
    if results.is_empty() {
        println!("no collections (add one with `mimir docs add <path>`)");
        return Ok(());
    }
    for (name, s) in results {
        println!(
            "{name}: {} files seen, {} indexed ({} chunks), {} unchanged, {} removed",
            s.seen, s.indexed, s.chunks, s.unchanged, s.removed
        );
    }
    let embedded = mimir.embed_pending()?;
    if embedded > 0 {
        println!("embedded {embedded} node(s)");
    }
    Ok(())
}

// ---------- import / export ----------

pub fn import_openbrain(file: &str) -> Result<()> {
    let mut mimir = Mimir::open()?;
    let text = if file == "-" {
        let mut buf = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;
        buf
    } else {
        std::fs::read_to_string(file).with_context(|| format!("read {file}"))?
    };
    let stats = mimir_core::import::openbrain(&mimir.conn, &text)?;
    finish_import(&mut mimir, stats)
}

pub fn import_claude_memory(dir: &str) -> Result<()> {
    let mut mimir = Mimir::open()?;
    let stats = mimir_core::import::claude_memory(&mimir.conn, std::path::Path::new(dir))?;
    finish_import(&mut mimir, stats)
}

pub fn import_qmd(file: Option<String>) -> Result<()> {
    let mimir = Mimir::open()?;
    let path = match file {
        Some(f) => std::path::PathBuf::from(f),
        None => directories::BaseDirs::new()
            .context("cannot resolve home")?
            .home_dir()
            .join(".config/qmd/index.yml"),
    };
    let yml = std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
    let collections = mimir_core::import::qmd_collections(&yml);
    if collections.is_empty() {
        bail!("no collections found in {}", path.display());
    }
    for (name, root) in &collections {
        let root_path = std::path::Path::new(root);
        if !root_path.is_dir() {
            eprintln!("skipping {name}: {root} is not a directory");
            continue;
        }
        let coll = mimir_core::index::add_collection(&mimir.conn, root_path, name, None, "docs")?;
        println!(
            "registered {} {} {}",
            short_uid(coll.kind, &coll.uid),
            name,
            root
        );
    }
    println!("run `mimir index` to scan them");
    Ok(())
}

fn finish_import(mimir: &mut Mimir, stats: mimir_core::import::ImportStats) -> Result<()> {
    println!(
        "imported {} memorie(s), skipped {} duplicate(s)",
        stats.imported, stats.skipped_duplicates
    );
    let embedded = mimir.embed_pending()?;
    if embedded > 0 {
        println!("embedded {embedded} node(s)");
    }
    Ok(())
}

pub fn export() -> Result<()> {
    let mimir = Mimir::open()?;
    let stdout = std::io::stdout();
    let mut lock = stdout.lock();
    let n = mimir_core::import::export_jsonl(&mimir.conn, &mut lock)?;
    eprintln!("exported {n} line(s)");
    Ok(())
}

// ---------- helpers ----------

/// Resolve ids first, then symbol names within the current project — so
/// `mimir link m:ABC123 resolve_ref --rel about` just works.
fn resolve_any(mimir: &Mimir, reference: &str) -> Result<Node> {
    match store::resolve_ref(&mimir.conn, reference) {
        Ok(node) => Ok(node),
        Err(id_err) => {
            if let Some(proj) = mimir.project_for_cwd(&std::env::current_dir()?)? {
                if let Ok(sym) = mimir_graph::resolve_symbol(&mimir.conn, proj.id, reference) {
                    return Ok(sym);
                }
            }
            Err(id_err.into())
        }
    }
}

/// Scope for read operations. Inside a project: that project + global.
/// Outside: everything (reads want breadth; -g narrows to global-only).
fn read_scope(mimir: &Mimir, global: bool, all: bool) -> Result<Scope> {
    if all {
        return Ok(Scope::All);
    }
    if global {
        return Ok(Scope::Global);
    }
    Ok(match mimir.project_for_cwd(&std::env::current_dir()?)? {
        Some(p) => Scope::Project(p.id),
        None => Scope::All,
    })
}

fn parse_kind_filter(kind: &str) -> Result<Vec<Kind>> {
    Ok(match kind {
        // No kind filter — deliberately includes CodeChunk. The point of
        // indexing function bodies (not just signatures) is that a plain
        // `recall` finds them without the caller knowing to ask for
        // `--kind code`; ScoringConfig::code_damp keeps code from drowning
        // out memories given its much larger corpus share.
        "all" => vec![],
        "memory" => vec![Kind::Memory],
        "doc" => vec![Kind::File, Kind::Chunk, Kind::Annotation],
        // Symbol = signature/doc only; CodeChunk = actual body/content text
        // (see chunker::chunk_source). Both belong under `code`.
        "code" => vec![Kind::Symbol, Kind::CodeChunk],
        other => bail!("unknown --kind '{other}' (use all|memory|doc|code)"),
    })
}

/// "12h" | "7d" | "2w" | "3m" | "1y" → unix cutoff.
fn parse_since(s: &str) -> Result<i64> {
    // Split on the last CHARACTER, not the last byte — a multibyte unit
    // (e.g. "5µ") would otherwise slice mid-codepoint and panic.
    let split = s.char_indices().next_back().map(|(i, _)| i).unwrap_or(0);
    let (num, unit) = s.split_at(split);
    let n: i64 = num
        .parse()
        .with_context(|| format!("bad --since '{s}' (use e.g. 12h, 7d, 2w, 3m, 1y)"))?;
    let secs = match unit {
        "h" => 3_600,
        "d" => 86_400,
        "w" => 604_800,
        "m" => 2_592_000,
        "y" => 31_536_000,
        _ => bail!("bad --since unit '{unit}' (use h, d, w, m, y)"),
    };
    Ok(now_unix() - n * secs)
}

fn line(node: &Node, projects: &HashMap<i64, String>, snippet_chars: usize) -> String {
    let project = node
        .project_id
        .and_then(|id| projects.get(&id))
        .map(String::as_str);
    agent_line(node, project, snippet_chars)
}

fn print_full(node: &Node, mimir: &Mimir, projects: &HashMap<i64, String>) -> Result<()> {
    println!(
        "{}",
        mimir_core::format::full_record(&mimir.conn, node, projects)?
    );
    Ok(())
}

fn node_json(node: &Node, projects: &HashMap<i64, String>) -> serde_json::Value {
    serde_json::json!({
        "id": short_uid(node.kind, &node.uid),
        "uid": node.uid,
        "kind": node.kind.as_str(),
        "type": node.subkind,
        "project": node.project_id.and_then(|id| projects.get(&id)),
        "title": node.title,
        "body": node.body,
        "path": node.path,
        "tags": node.tags(),
        "created_at": node.created_at,
        "updated_at": node.updated_at,
        "access_count": node.access_count,
        "strength": node.strength,
    })
}

#[cfg(test)]
mod since_tests {
    use super::parse_since;

    #[test]
    fn multibyte_unit_errors_not_panics() {
        // Regression: split_at on a byte offset panicked mid-codepoint.
        assert!(parse_since("5µ").is_err());
        assert!(parse_since("7€").is_err());
        assert!(parse_since("").is_err());
        assert!(parse_since("3d").is_ok());
    }
}

#[cfg(test)]
mod scan_tests {
    use super::mentions_symbol;

    #[test]
    fn snake_case_matches_on_word_boundaries() {
        assert!(mentions_symbol(
            "the record_opened path is the entry",
            "record_opened"
        ));
        assert!(!mentions_symbol("we prerecord_opened it", "record_opened"));
        assert!(mentions_symbol(
            "learn::record_opened is the single entry",
            "record_opened"
        ));
    }

    #[test]
    fn plain_words_never_match_even_backticked() {
        assert!(!mentions_symbol("we should update the docs", "update"));
        assert!(!mentions_symbol("we changed `update` semantics", "update"));
        assert!(!mentions_symbol("force push `main` to origin", "main"));
    }

    #[test]
    fn camel_case_matches_but_sentence_case_does_not() {
        assert!(mentions_symbol(
            "the MimirServer struct owns the router",
            "MimirServer"
        ));
        assert!(!mentions_symbol("nothing here", "MimirServer"));
        assert!(!mentions_symbol("Pending tasks for tomorrow", "Pending"));
    }
}

#[cfg(test)]
mod hooks_tests {
    use super::{merge_hook_settings, render_recall_script};

    /// A custom `config.hooks.inject_url` must land verbatim as the
    /// script's `MIMIR_INJECT_URL` fallback default — the actual install
    /// path (`install_hooks`) is only exercised end-to-end by the
    /// fake-$HOME e2e test (crates/mimir-cli/tests/e2e.rs), since it needs
    /// a real `~/.claude` dir and MIMIR_HOME must be *unset* for it to run
    /// at all; this covers the pure rendering logic in isolation.
    #[test]
    fn custom_inject_url_lands_in_generated_script() {
        let script = render_recall_script("http://10.0.0.5:9999/inject");
        assert!(
            script.contains(r#"INJECT_URL="${MIMIR_INJECT_URL:-http://10.0.0.5:9999/inject}""#),
            "custom URL missing from script:\n{script}"
        );
        // The env-var override placeholder syntax itself must survive
        // untouched — only the default inside it gets substituted.
        assert!(script.contains("${MIMIR_INJECT_URL:-"));
        assert!(!script.contains("__MIMIR_INJECT_URL_DEFAULT__"));
    }

    #[test]
    fn default_inject_url_matches_documented_port() {
        let script = render_recall_script("http://127.0.0.1:8077/inject");
        assert!(
            script.contains(r#"INJECT_URL="${MIMIR_INJECT_URL:-http://127.0.0.1:8077/inject}""#)
        );
    }

    /// `auto_recall=false` (recall_script = None) must be byte-identical to
    /// pre-auto-recall behavior: no `UserPromptSubmit` key appears at all.
    /// `context_guard_scripts = None` must likewise add none of the
    /// context-guard entries — this is the full default-off byte-identical
    /// case: only SessionStart(rules) + PreToolUse(rewrite, anchors) exist.
    #[test]
    fn no_recall_script_leaves_user_prompt_submit_untouched() {
        let (root, messages) = merge_hook_settings(
            serde_json::json!({}),
            "/path/mimir-rewrite.sh",
            None,
            "/path/mimir-anchors.sh",
            None,
        )
        .unwrap();
        assert!(
            root["hooks"].get("UserPromptSubmit").is_none(),
            "auto_recall=false and context_guard=off must not add hooks.UserPromptSubmit, got: {root}"
        );
        assert!(
            root["hooks"].get("PreCompact").is_none(),
            "context_guard=off must not add hooks.PreCompact, got: {root}"
        );
        // The pre-existing hooks still get installed as before, plus the
        // unconditional guard-anchors entry.
        assert!(root["hooks"]["SessionStart"].is_array());
        assert_eq!(
            root["hooks"]["SessionStart"].as_array().unwrap().len(),
            1,
            "context_guard=off must add exactly one SessionStart entry (rules), not two"
        );
        let pre_arr = root["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(
            pre_arr.len(),
            2,
            "rewrite + anchors, unconditionally under --hooks"
        );
        assert!(messages.iter().any(|m| m.contains("SessionStart")));
        assert!(messages
            .iter()
            .any(|m| m.contains("PreToolUse (command filter)")));
        assert!(messages
            .iter()
            .any(|m| m.contains("PreToolUse (guard anchors)")));
        assert!(!messages.iter().any(|m| m.contains("UserPromptSubmit")));
        assert!(!messages.iter().any(|m| m.contains("PreCompact")));
    }

    /// `auto_recall=true` adds exactly one `UserPromptSubmit` entry
    /// pointing at the recall script, and re-running is a no-op (idempotent).
    #[test]
    fn recall_script_adds_one_entry_idempotently() {
        let (root, messages) = merge_hook_settings(
            serde_json::json!({}),
            "/path/mimir-rewrite.sh",
            Some("/path/mimir-recall.sh"),
            "/path/mimir-anchors.sh",
            None,
        )
        .unwrap();
        let entries = root["hooks"]["UserPromptSubmit"].as_array().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(messages.iter().any(|m| m.contains("UserPromptSubmit")));

        // Re-run against the already-merged settings: still exactly one entry,
        // and the message says "already installed" instead of "added".
        let (root2, messages2) = merge_hook_settings(
            root,
            "/path/mimir-rewrite.sh",
            Some("/path/mimir-recall.sh"),
            "/path/mimir-anchors.sh",
            None,
        )
        .unwrap();
        let entries2 = root2["hooks"]["UserPromptSubmit"].as_array().unwrap();
        assert_eq!(entries2.len(), 1, "re-running must not duplicate the entry");
        assert!(messages2
            .iter()
            .any(|m| m.contains("UserPromptSubmit already installed")));
    }

    /// Guard anchors install unconditionally under `--hooks` regardless of
    /// `auto_recall`/`context_guard`, and re-running is idempotent.
    #[test]
    fn anchors_entry_is_unconditional_and_idempotent() {
        let (root, messages) = merge_hook_settings(
            serde_json::json!({}),
            "/path/mimir-rewrite.sh",
            None,
            "/path/mimir-anchors.sh",
            None,
        )
        .unwrap();
        let pre_arr = root["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre_arr.len(), 2);
        assert!(messages
            .iter()
            .any(|m| m.contains("PreToolUse (guard anchors) added")));

        let (root2, messages2) = merge_hook_settings(
            root,
            "/path/mimir-rewrite.sh",
            None,
            "/path/mimir-anchors.sh",
            None,
        )
        .unwrap();
        let pre_arr2 = root2["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(
            pre_arr2.len(),
            2,
            "re-running must not duplicate the anchors entry"
        );
        assert!(messages2
            .iter()
            .any(|m| m.contains("PreToolUse anchors already installed")));
    }

    /// `context_guard_scripts = Some(...)` adds exactly one UserPromptSubmit,
    /// one PreCompact, and a second SessionStart entry, all idempotently.
    #[test]
    fn context_guard_scripts_add_three_entries_idempotently() {
        let scripts = (
            "/path/mimir-context-guard-prompt.sh",
            "/path/mimir-context-guard-precompact.sh",
            "/path/mimir-context-guard-session.sh",
        );
        let (root, messages) = merge_hook_settings(
            serde_json::json!({}),
            "/path/mimir-rewrite.sh",
            None,
            "/path/mimir-anchors.sh",
            Some(scripts),
        )
        .unwrap();
        assert_eq!(
            root["hooks"]["UserPromptSubmit"].as_array().unwrap().len(),
            1
        );
        assert_eq!(root["hooks"]["PreCompact"].as_array().unwrap().len(), 1);
        assert_eq!(
            root["hooks"]["SessionStart"].as_array().unwrap().len(),
            2,
            "rules entry + context-guard entry"
        );
        assert!(messages
            .iter()
            .any(|m| m.contains("UserPromptSubmit (context guard) added")));
        assert!(messages
            .iter()
            .any(|m| m.contains("PreCompact (context guard) added")));
        assert!(messages
            .iter()
            .any(|m| m.contains("SessionStart (context guard) added")));

        let (root2, messages2) = merge_hook_settings(
            root,
            "/path/mimir-rewrite.sh",
            None,
            "/path/mimir-anchors.sh",
            Some(scripts),
        )
        .unwrap();
        assert_eq!(
            root2["hooks"]["UserPromptSubmit"].as_array().unwrap().len(),
            1
        );
        assert_eq!(root2["hooks"]["PreCompact"].as_array().unwrap().len(), 1);
        assert_eq!(root2["hooks"]["SessionStart"].as_array().unwrap().len(), 2);
        assert!(messages2
            .iter()
            .any(|m| m.contains("UserPromptSubmit context-guard already installed")));
        assert!(messages2
            .iter()
            .any(|m| m.contains("PreCompact already installed")));
        assert!(messages2
            .iter()
            .any(|m| m.contains("SessionStart context-guard already installed")));
    }
}

#[cfg(test)]
mod inject_addr_tests {
    use super::inject_addr;

    #[test]
    fn strips_scheme_and_inject_path() {
        assert_eq!(
            inject_addr("http://127.0.0.1:8077/inject").unwrap(),
            "127.0.0.1:8077"
        );
        assert_eq!(
            inject_addr("https://10.0.0.5:9999/inject").unwrap(),
            "10.0.0.5:9999"
        );
    }

    #[test]
    fn tolerates_a_bare_host_port_with_no_scheme_or_path() {
        assert_eq!(inject_addr("127.0.0.1:8077").unwrap(), "127.0.0.1:8077");
    }

    #[test]
    fn empty_url_is_an_error_not_a_panic() {
        assert!(inject_addr("").is_err());
        assert!(inject_addr("http://").is_err());
    }
}