velesdb-memory 0.11.6

VelesDB-memory: local-first MCP memory server for AI agents (remember/recall/relate/forget/why + deterministic context compiler).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! `velesdb-memory` — MCP memory server binary (stdio transport by default).
//!
//! Serves the memory tools over stdio so any MCP client (Claude Code, Cursor,
//! Cline, Zed, …) can use it locally. The store never leaves the machine.
//! Configure the store directory with `VELESDB_MEMORY_PATH` (default
//! `~/.velesdb-memory`) and the embedding
//! backend with `VELESDB_MEMORY_EMBEDDER` (`hash` | `ollama`). When built with
//! `--features extract`, set `VELESDB_MEMORY_EXTRACTOR=ollama` to enable the
//! `remember_extracted` tool (auto text → fact↔topic graph). Set
//! `VELESDB_MEMORY_DEFAULT_TTL` (seconds) to expire remembered facts by default.
//! Set `VELESDB_MEMORY_INGEST_ROOTS` (a `PATH`-list of directories) to let
//! `compile_context`/`explain_compilation` fragments reference a file by
//! `path` instead of inline `content`; unset disables that field entirely.
//! Run with `--version` (or `-V`) to print the binary's version and exit,
//! without opening the store.
//!
//! When built with `--features http`, pass `--http` (or set
//! `VELESDB_MEMORY_HTTP=1`) to serve over the streamable-HTTP transport
//! instead of stdio — letting several MCP clients share ONE process instead
//! of each fighting over the store's single-writer `flock`. See
//! `velesdb_memory::http` and the README's "HTTP transport" section.
//!
//! The HTTP transport serves HTTPS by default, terminated with a locally
//! generated CA + leaf certificate (see `velesdb_memory::tls` — no external
//! `mkcert`/`openssl`/reverse proxy required; some MCP clients, e.g. Claude
//! Desktop's "Add custom connector", refuse any URL that isn't `https://`,
//! even for `127.0.0.1`). Pass `--http-insecure` (or set
//! `VELESDB_MEMORY_HTTP_INSECURE=1`) to fall back to plain HTTP instead —
//! for local debugging, or when a trusted TLS-terminating proxy already
//! sits in front.

use std::time::Duration;

use rmcp::ServiceExt;
use velesdb_memory::mcp::McpServer;
use velesdb_memory::{DynEmbedder, HashEmbedder, MemoryService, NativeStore, DEFAULT_DIMENSION};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = std::env::args().collect();

    // Handled before anything else touches the filesystem or the embedder:
    // `--version`/`-V` must work even when the store path is unwritable or
    // absent (e.g. a fresh dev running it once to sanity-check the install),
    // so it short-circuits ahead of the store open below.
    if args
        .get(1)
        .is_some_and(|arg| arg == "--version" || arg == "-V")
    {
        println!("velesdb-memory {}", env!("CARGO_PKG_VERSION"));
        return Ok(());
    }

    // Short-circuits for the same reason as `--version`: `compile-stdin` is
    // the hook-facing surface (see `integrations/agent-hooks`). A PostToolUse
    // hook runs SYNCHRONOUSLY after every tool call, in a process of its own,
    // while the agent's own MCP server already holds the store's
    // single-writer `flock` — so this path must never open the store. It
    // doesn't have to: the compiler
    // (`velesdb_memory::context::ContextCompiler::compile`) is pure — no
    // store, no index, no clock — and the `context` feature is
    // `persistence`-free by design.
    if args.get(1).is_some_and(|arg| arg == "compile-stdin") {
        return run_compile_stdin(&args[2..]);
    }

    // Captured FIRST — before the (possibly seconds-long) embedder probe and
    // store open — so a client that exits during our own startup still
    // reparents us AFTER the baseline, and the watchdog sees the change. A
    // baseline taken later would read the already-reparented pid and go
    // permanently inert (review finding on #1449).
    #[cfg(unix)]
    let original_parent = std::os::unix::process::parent_id();
    #[cfg(not(unix))]
    let original_parent = 0_u32;
    // All synchronous setup (config file, env probing, blocking HTTP to
    // Ollama, disk open) happens in here, before the async runtime starts, so
    // we never block a tokio worker thread on a synchronous operation.
    let service = build_configured_service(&args)?;

    // Read AFTER the config file has been applied, since the file can set
    // `VELESDB_MEMORY_HTTP`. Same manual-parsing style as `--version` above
    // (no `clap` for a two-flag CLI) — the transport choice only affects how
    // the server is *served*, further down, since store opening (and its
    // `flock`) is identical either way.
    let http_bind = requested_http_bind(&args);
    let server = apply_ingest_roots(apply_default_ttl(build_server(service)?)?)?;

    tokio::runtime::Runtime::new()?.block_on(async move {
        match http_bind {
            #[cfg(feature = "http")]
            Some(request) => serve_http(server, request).await,
            #[cfg(not(feature = "http"))]
            Some(_never) => unreachable!(
                "requested_http_bind only returns Some when built with --features http"
            ),
            None => {
                // The orphan watchdog only makes sense for stdio: it exists to
                // detect a *client process* dying without closing our stdin
                // (#1448). An HTTP daemon has no such single-client lifecycle
                // to watch — it's meant to outlive any one client — so it is
                // never spawned in HTTP mode.
                spawn_orphan_watchdog(original_parent);
                let running = server
                    .serve((tokio::io::stdin(), tokio::io::stdout()))
                    .await?;
                running.waiting().await?;
                Ok::<(), Box<dyn std::error::Error>>(())
            }
        }
    })
}

/// A resolved `--http`/`VELESDB_MEMORY_HTTP=1` request: where to bind, and
/// whether TLS should be skipped (`--http-insecure` /
/// `VELESDB_MEMORY_HTTP_INSECURE=1` — see [`requested_http_bind`]).
#[cfg(feature = "http")]
struct HttpServeRequest {
    bind_addr: String,
    insecure: bool,
}

/// Detect the streamable-HTTP transport request (`--http` flag or
/// `VELESDB_MEMORY_HTTP=1`) and resolve how it should be served, BEFORE the
/// store is opened. Returns `None` for the default stdio transport.
///
/// Without the `http` feature, `--http`/`VELESDB_MEMORY_HTTP=1` is rejected
/// with an actionable message instead of silently falling back to stdio —
/// the binary was built without the code to honor the request at all.
#[cfg(feature = "http")]
fn requested_http_bind(args: &[String]) -> Option<HttpServeRequest> {
    let http_flag = args.iter().any(|arg| arg == "--http");
    let http_env = std::env::var("VELESDB_MEMORY_HTTP").as_deref() == Ok("1");
    if !http_flag && !http_env {
        return None;
    }

    let port_override = args
        .iter()
        .position(|arg| arg == "--http-port")
        .and_then(|flag_index| args.get(flag_index + 1));

    let default_bind = std::env::var("VELESDB_MEMORY_HTTP_BIND")
        .unwrap_or_else(|_| velesdb_memory::http::DEFAULT_HTTP_BIND.to_owned());

    let bind_addr = match port_override {
        Some(port) => match default_bind.rsplit_once(':') {
            Some((host, _existing_port)) => format!("{host}:{port}"),
            None => format!("127.0.0.1:{port}"),
        },
        None => default_bind,
    };

    // The router (`velesdb_memory::http::router`) authenticates no one: any
    // caller that can reach the socket gets full `remember`/`recall`/`relate`
    // access to the store. That's only safe because the default bind is
    // loopback-only. `VELESDB_MEMORY_HTTP_BIND` lets the *port* be
    // overridden freely, but overriding the *host* to something reachable
    // off-box would turn an unauthenticated local daemon into an
    // unauthenticated network service — so that requires an explicit,
    // separate opt-in rather than falling out of a bind-address typo.
    if !is_loopback_host(&bind_addr)
        && std::env::var("VELESDB_MEMORY_HTTP_ALLOW_REMOTE").as_deref() != Ok("1")
    {
        eprintln!(
            "[velesdb-memory] refusing to bind the HTTP transport to '{bind_addr}': it is not a \
             loopback address, and the streamable-HTTP transport has no authentication — anyone \
             who can reach that socket gets full read/write access to the store. Set \
             VELESDB_MEMORY_HTTP_ALLOW_REMOTE=1 to override (put an authenticating reverse proxy \
             in front first)."
        );
        std::process::exit(1);
    }

    // `--http-insecure` / `VELESDB_MEMORY_HTTP_INSECURE=1` is the explicit
    // opt-out of HTTPS-by-default (see the crate-level doc comment above and
    // `velesdb_memory::tls`'s module docs for why HTTPS is the default at
    // all) — an "insecure escape hatch, loud at startup" flag, same shape as
    // `VELESDB_MEMORY_HTTP_ALLOW_REMOTE` above. Kept as its own flag rather
    // than folded into that one: that one is about *who* can reach the
    // socket, this one is about *whether the bytes on the wire are
    // encrypted* — independent axes, and conflating them would make an
    // operator who only wants one silently get the other too.
    let insecure_flag = args.iter().any(|arg| arg == "--http-insecure");
    let insecure_env = std::env::var("VELESDB_MEMORY_HTTP_INSECURE").as_deref() == Ok("1");
    let insecure = insecure_flag || insecure_env;

    Some(HttpServeRequest {
        bind_addr,
        insecure,
    })
}

/// Whether `bind_addr`'s host component (`host:port` or `[ipv6]:port`)
/// resolves to a loopback address. Used to gate non-local HTTP binds behind
/// an explicit opt-in — see `requested_http_bind` above. An unparseable host
/// (e.g. a hostname like `mcp.example.com` rather than a literal IP) is
/// treated as non-loopback: `TcpListener::bind` does its own DNS resolution
/// later, so this is a conservative pre-check, not the only one.
#[cfg(feature = "http")]
fn is_loopback_host(bind_addr: &str) -> bool {
    let host = bind_addr
        .rsplit_once(':')
        .map_or(bind_addr, |(host, _port)| host)
        .trim_start_matches('[')
        .trim_end_matches(']');
    host.parse::<std::net::IpAddr>()
        .is_ok_and(|ip| ip.is_loopback())
}

/// See the `http`-feature variant above. Without `http`, no bind address can
/// ever be resolved — the binary has no HTTP transport built in — so a
/// `--http`/`VELESDB_MEMORY_HTTP=1` request fails fast with guidance instead
/// of being silently ignored (which would otherwise look like the server
/// just hung, or served the wrong transport).
#[cfg(not(feature = "http"))]
fn requested_http_bind(args: &[String]) -> Option<String> {
    let http_flag = args.iter().any(|arg| arg == "--http");
    let http_env = std::env::var("VELESDB_MEMORY_HTTP").as_deref() == Ok("1");
    if http_flag || http_env {
        eprintln!(
            "[velesdb-memory] --http / VELESDB_MEMORY_HTTP=1 requires a binary built with \
             `--features http` (e.g. `cargo install velesdb-memory --features http`) — \
             this binary was built without it"
        );
        std::process::exit(1);
    }
    None
}

/// Serve the MCP server over the streamable-HTTP transport (multi-client
/// mode): binds `request.bind_addr`, mounts [`velesdb_memory::http::router`],
/// and runs until either the process receives Ctrl-C or the returned future
/// is dropped (e.g. process termination) — a background daemon (launchd,
/// systemd) is expected to just kill the process on stop, which is safe: the
/// store's `flock` is released by the kernel on exit regardless (see the
/// orphan-watchdog docs above).
///
/// HTTPS by default (a locally-generated CA + leaf cert — see
/// `velesdb_memory::tls`), unless `request.insecure` opts out
/// (`--http-insecure` / `VELESDB_MEMORY_HTTP_INSECURE=1`), in which case
/// this serves plain HTTP via `axum::serve` exactly as before HTTPS
/// support was added.
#[cfg(feature = "http")]
async fn serve_http(
    server: McpServer,
    request: HttpServeRequest,
) -> Result<(), Box<dyn std::error::Error>> {
    let HttpServeRequest {
        bind_addr,
        insecure,
    } = request;

    let ct = tokio_util::sync::CancellationToken::new();
    let app = velesdb_memory::http::router(server, ct.child_token());
    let listener = tokio::net::TcpListener::bind(&bind_addr).await?;

    spawn_shutdown_signals(ct.clone());

    if insecure {
        eprintln!(
            "[velesdb-memory] WARNING: --http-insecure / VELESDB_MEMORY_HTTP_INSECURE=1 is set — \
             serving PLAIN HTTP (no TLS) on http://{bind_addr}/mcp. Every request is readable by \
             anyone who can reach that socket (loopback-only by default — see \
             VELESDB_MEMORY_HTTP_ALLOW_REMOTE above). Use this only for local debugging, or when \
             a trusted TLS-terminating proxy already sits in front."
        );
        eprintln!("[velesdb-memory] HTTP server listening on http://{bind_addr}/mcp");
        axum::serve(listener, app)
            .with_graceful_shutdown(async move { ct.cancelled_owned().await })
            .await?;
        return Ok(());
    }

    let tls_dir = velesdb_memory::tls::tls_dir_from_env();
    let material = velesdb_memory::tls::ensure_tls_material(&tls_dir)?;
    let acceptor = velesdb_memory::tls::tls_acceptor_from_material(&material)?;
    eprintln!("[velesdb-memory] HTTPS server listening on https://{bind_addr}/mcp");
    eprintln!(
        "[velesdb-memory] Local CA: {} — a client only needs to trust this once (see \
         ./scripts/install-memory-daemon.sh, which does this automatically on macOS); every \
         future leaf certificate this daemon issues is signed by the same CA and is trusted \
         automatically after that.",
        material.ca_cert_path.display()
    );

    velesdb_memory::http::serve_tls(app, listener, acceptor, ct).await;
    Ok(())
}

/// How often the orphan watchdog re-checks its parent pid. The MCP stdio
/// transport only observes disconnects via stdin EOF, which a client that
/// leaks its child process (the #1448 scenario) never delivers — so this is
/// the *only* signal that would otherwise catch that leak. 2s keeps the
/// worst-case self-exit latency low (a handful of polls) without burning
/// meaningful CPU on an idle server.
#[cfg(unix)]
const ORPHAN_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);

/// Detect a dead parent and self-exit, releasing the store's `flock` even
/// when stdin is artificially kept open (a leaked child process, #1448).
///
/// A normal MCP stdio client closes the child's stdin on disconnect, which
/// the existing EOF path already handles. But a client that merely forgets
/// to reap/close its child (observed in practice: a headless `claude -p`
/// run left its server running) never closes that pipe — the server then
/// legitimately keeps serving forever, holding the single-writer store lock
/// and making every later session fail `Storage(DatabaseLocked)`.
///
/// This has no other shutdown trigger to lean on, so it polls: capture the
/// parent pid at startup, and if it ever changes, the parent is gone (Unix
/// re-parents orphans to init/launchd, pid 1 or the user's launchd pid —
/// never the original parent), so exit. `std::os::unix::process::parent_id`
/// is pure `std`, avoiding a new dependency (e.g. `libc::getppid`) for a
/// single syscall.
///
/// Process exit (even via `std::process::exit`, which skips destructors)
/// still releases the store's `flock`: that lock is a kernel-held resource
/// tied to the process's open file descriptors, which the kernel closes —
/// and therefore unlocks — unconditionally on process exit, confirmed by
/// the investigation on #1448 ("released by the kernel even on SIGKILL").
#[cfg(unix)]
fn spawn_orphan_watchdog(original_parent: u32) {
    use std::os::unix::process::parent_id;

    tokio::spawn(async move {
        loop {
            tokio::time::sleep(ORPHAN_CHECK_INTERVAL).await;
            let current_parent = parent_id();
            if current_parent != original_parent {
                eprintln!(
                    "[velesdb-memory] parent process (pid {original_parent}) is gone \
                     (now reparented under pid {current_parent}) — exiting to release \
                     the store lock rather than leak a zombie session (#1448)"
                );
                std::process::exit(0);
            }
        }
    });
}

/// Windows has no equivalent of `parent_id()` re-parenting to detect a dead
/// parent this cheaply, so this hardening is Unix-only for now — behavior on
/// Windows is unchanged (still relies on the stdin-EOF path).
#[cfg(not(unix))]
fn spawn_orphan_watchdog(_original_parent: u32) {}

/// Attempts before giving up on a locked store and printing the actionable
/// error. Three short tries (with [`LOCK_RETRY_DELAY`] between them) is
/// enough to ride out the handover between one session's process exiting
/// and the next one starting — the case the retry is *for* — without making
/// a genuinely-stuck lock (the leaked-process scenario from #1448) hang
/// startup for long.
const LOCK_RETRY_ATTEMPTS: u32 = 3;

/// Delay between retries of an already-locked store. See
/// [`LOCK_RETRY_ATTEMPTS`] for the reasoning on the total budget.
const LOCK_RETRY_DELAY: Duration = Duration::from_millis(500);

/// Open the native store at `store_path`, retrying briefly through a
/// `DatabaseLocked` error before giving up with actionable stderr guidance.
///
/// Bypasses [`MemoryService::open`] in favor of [`NativeStore::open`] +
/// [`MemoryService::with_store`] because the retry only needs
/// `embedder.dimension()` (a plain `usize`, trivially reusable across
/// attempts) — not the embedder itself — so `embedder` can move into the
/// service exactly once, on the attempt that finally succeeds, with no
/// `Clone` bound required on `E`.
///
/// # Errors
/// Returns any [`MemoryError`] other than `DatabaseLocked` unchanged (e.g. a
/// dimension mismatch against an existing store). On a `DatabaseLocked` that
/// outlives every retry, prints the actionable message and exits the process
/// with a non-zero status instead of returning — that message, not a
/// generic `Result` bubble-up, is the point: a bare
/// `Storage(DatabaseLocked(..))` debug dump gives a user nothing to act on
/// (#1448).
fn open_store_with_actionable_lock_error(
    store_path: &str,
    embedder: DynEmbedder,
) -> Result<MemoryService<DynEmbedder>, Box<dyn std::error::Error>> {
    use velesdb_memory::MemoryError;

    let dimension = embedder.dimension();
    let mut last_locked_path: Option<String> = None;
    for attempt in 0..LOCK_RETRY_ATTEMPTS {
        match NativeStore::open(store_path, dimension) {
            Ok(store) => return Ok(MemoryService::with_store(store, embedder)),
            Err(MemoryError::Storage(velesdb_core::Error::DatabaseLocked(locked_path))) => {
                last_locked_path = Some(locked_path);
                if attempt + 1 < LOCK_RETRY_ATTEMPTS {
                    std::thread::sleep(LOCK_RETRY_DELAY);
                }
            }
            Err(other) => return Err(other.into()),
        }
    }

    let locked_path = last_locked_path.unwrap_or_else(|| store_path.to_owned());
    eprintln!(
        "[velesdb-memory] another velesdb-memory process holds {locked_path}\
         kill it (pkill velesdb-memory) or point VELESDB_MEMORY_PATH elsewhere"
    );
    std::process::exit(1);
}

/// Default store location when `VELESDB_MEMORY_PATH` is unset: `~/.velesdb-memory`
/// (the path advertised in `server.json`, the README, and every client-config
/// snippet). A stable home-based path — never a `./`-relative one: an MCP server
/// is launched by its client with an unpredictable working directory, so a
/// cwd-relative default would scatter (or lose) the store between sessions. Falls
/// back to a cwd-relative path only when no home directory can be resolved.
/// Load the config file, then build the store-backed service it describes.
///
/// The config file is read BEFORE the first variable is consulted, because it
/// can set any of them — including the store path. Everything downstream keeps
/// reading the environment exactly as it always did; the file only fills in
/// what the environment left unset, which is what makes the precedence
/// `command line > environment > file > default`.
fn build_configured_service(
    args: &[String],
) -> Result<MemoryService<DynEmbedder>, Box<dyn std::error::Error>> {
    apply_config_file(args)?;
    let store_path = std::env::var("VELESDB_MEMORY_PATH").unwrap_or_else(|_| default_store_path());
    let embedder = build_embedder()?;
    apply_autograph(open_store_with_actionable_lock_error(
        &store_path,
        embedder,
    )?)
}

/// Cancel `ct` on the signals a supervisor actually sends.
///
/// SIGINT alone is not enough. `launchctl kickstart -k`, `systemctl restart`
/// and `docker stop` all send **SIGTERM**, and an unhandled SIGTERM kills the
/// process outright: the streamable-HTTP sessions clients hold are dropped
/// mid-flight, so the next call on a live session hangs until the client's own
/// timeout instead of reconnecting. Handling it lets `with_graceful_shutdown`
/// close those sessions, which is what turns a restart into a reconnect.
#[cfg(feature = "http")]
fn spawn_shutdown_signals(ct: tokio_util::sync::CancellationToken) {
    let interrupt = ct.clone();
    tokio::spawn(async move {
        if tokio::signal::ctrl_c().await.is_ok() {
            interrupt.cancel();
        }
    });

    #[cfg(unix)]
    tokio::spawn(async move {
        // `signal()` only fails if the handler cannot be registered at all; a
        // daemon that cannot listen for SIGTERM still serves, it just loses the
        // graceful path, so this is not worth aborting startup for.
        if let Ok(mut term) =
            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
        {
            term.recv().await;
            ct.cancel();
        }
    });
    // On Windows there is no SIGTERM; Ctrl-C above is the whole contract.
    #[cfg(not(unix))]
    drop(ct);
}

/// Attach the extraction backend to the SERVICE when
/// `VELESDB_MEMORY_AUTOGRAPH=1` (`[graph] autograph = true`), so every
/// `remember` also wires the entities, typed edges and attributes its text
/// states.
///
/// Distinct from [`build_server`]'s extractor, which powers the explicit
/// `remember_extracted` tool. Both can be on; they share one backend and one
/// setting pair, and `remember_extracted` deliberately does not re-extract.
///
/// Asking for autograph without an extraction backend is a startup error, not
/// a silent no-op: the operator turned on a feature, and a daemon that
/// answers by doing nothing is how you spend a week wondering why the graph
/// is empty.
#[cfg(feature = "extract")]
fn apply_autograph(
    service: MemoryService<DynEmbedder>,
) -> Result<MemoryService<DynEmbedder>, Box<dyn std::error::Error>> {
    if std::env::var("VELESDB_MEMORY_AUTOGRAPH").as_deref() != Ok("1") {
        return Ok(service);
    }
    if std::env::var("VELESDB_MEMORY_EXTRACTOR").as_deref() != Ok("ollama") {
        return Err(
            "autograph is on ([graph] autograph = true / VELESDB_MEMORY_AUTOGRAPH=1) but no \
             extraction backend is configured — set [extractor] backend = \"ollama\" (and a \
             model), or turn autograph off"
                .into(),
        );
    }
    Ok(service.with_autograph(build_ollama_extractor()?))
}

/// Without the `extract` feature there is no backend to attach. A request for
/// autograph still fails loudly rather than being ignored — the binary was
/// built without the code to honour it, exactly like `--http` without `http`.
#[cfg(not(feature = "extract"))]
fn apply_autograph(
    service: MemoryService<DynEmbedder>,
) -> Result<MemoryService<DynEmbedder>, Box<dyn std::error::Error>> {
    if std::env::var("VELESDB_MEMORY_AUTOGRAPH").as_deref() == Ok("1") {
        return Err(
            "autograph is on but this binary was built without --features extract, so no \
             extraction backend exists"
                .into(),
        );
    }
    Ok(service)
}

/// Locate and apply the optional `velesdb-memory.toml`.
///
/// The lookup uses the DEFAULT store directory, never the configured one:
/// the store path is itself one of the settings the file may carry, so
/// resolving the file through it would be circular.
///
/// A missing file is normal and silent. A file that exists but does not parse
/// aborts startup — a daemon quietly running on defaults the operator believes
/// they overrode is a worse outcome than a loud failure at boot.
fn apply_config_file(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let explicit = args
        .iter()
        .position(|arg| arg == "--config")
        .and_then(|at| args.get(at + 1))
        .map(String::as_str);
    // The EFFECTIVE store, not the default one. `VELESDB_MEMORY_PATH` moves the
    // store, and the config file lives beside it — looking it up in the default
    // directory instead means a caller who moved the store silently reads a
    // config from a store they are not using. That is how a test spawning this
    // binary with its own scratch store picked up the developer's personal
    // `~/.velesdb-memory/velesdb-memory.toml`.
    let store_dir = std::env::var("VELESDB_MEMORY_PATH").unwrap_or_else(|_| default_store_path());
    let Some(path) =
        velesdb_memory::config::resolve_path(explicit, Some(std::path::Path::new(&store_dir)))
    else {
        return Ok(());
    };
    let loaded = velesdb_memory::config::load(&path)?;
    let applied = velesdb_memory::config::apply(&loaded.values);
    if !applied.is_empty() && std::env::var_os("VELESDB_MEMORY_QUIET").is_none() {
        eprintln!(
            "velesdb-memory: {} setting(s) from {}",
            applied.len(),
            path.display()
        );
    }
    Ok(())
}

fn default_store_path() -> String {
    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .filter(|h| !h.is_empty());
    match home {
        Some(home) => std::path::Path::new(&home)
            .join(".velesdb-memory")
            .to_string_lossy()
            .into_owned(),
        None => "./velesdb-memory-store".to_owned(),
    }
}

/// Apply `VELESDB_MEMORY_DEFAULT_TTL` (seconds) as the default expiry for facts
/// stored without their own `ttl_seconds`. Unset means facts are permanent.
fn apply_default_ttl(server: McpServer) -> Result<McpServer, Box<dyn std::error::Error>> {
    match std::env::var("VELESDB_MEMORY_DEFAULT_TTL") {
        Ok(raw) => {
            let ttl_seconds: u64 = raw.trim().parse().map_err(|_| {
                format!(
                    "VELESDB_MEMORY_DEFAULT_TTL must be a non-negative integer (seconds), got '{raw}'"
                )
            })?;
            Ok(server.with_default_ttl(ttl_seconds))
        }
        Err(_) => Ok(server),
    }
}

/// Apply `VELESDB_MEMORY_INGEST_ROOTS` (V2b-1) — a platform `PATH`-list of
/// directories a `path`-referenced context fragment may read from — enabling
/// the `compile_context`/`explain_compilation` `path` field. Unset or empty
/// leaves path ingestion disabled (every `path` fragment then fails with an
/// explicit error, not a silent no-op). Parsed here, at startup, so a
/// misconfigured root (missing directory, broken symlink) fails fast instead
/// of surfacing on a caller's first `path` fragment.
#[cfg(feature = "context")]
fn apply_ingest_roots(server: McpServer) -> Result<McpServer, Box<dyn std::error::Error>> {
    match std::env::var("VELESDB_MEMORY_INGEST_ROOTS") {
        Ok(raw) if !raw.trim().is_empty() => {
            let roots = velesdb_memory::context::IngestRoots::parse(&raw)?;
            Ok(server.with_ingest_roots(roots))
        }
        _ => Ok(server),
    }
}

/// Without the `context` feature there is no `IngestRoots` type (or `path`
/// field) to configure. The `Result` return mirrors the `context` arm's
/// signature so the caller is identical for both builds.
#[cfg(not(feature = "context"))]
#[allow(clippy::unnecessary_wraps)]
fn apply_ingest_roots(server: McpServer) -> Result<McpServer, Box<dyn std::error::Error>> {
    Ok(server)
}

/// Build the MCP server, attaching an extraction backend from
/// `VELESDB_MEMORY_EXTRACTOR` (`ollama`) when built with `--features extract`.
#[cfg(feature = "extract")]
fn build_server(
    service: MemoryService<DynEmbedder>,
) -> Result<McpServer, Box<dyn std::error::Error>> {
    let server = McpServer::new(service);
    match std::env::var("VELESDB_MEMORY_EXTRACTOR").as_deref() {
        Ok("ollama") => Ok(server.with_extractor(build_ollama_extractor()?)),
        Ok("none") | Err(_) => Ok(server),
        Ok(other) => {
            Err(format!("unknown VELESDB_MEMORY_EXTRACTOR '{other}' (expected 'ollama')").into())
        }
    }
}

/// Without the `extract` feature there is no extraction backend to attach. The
/// `Result` return mirrors the `extract` variant's signature so the caller is
/// identical for both builds.
#[cfg(not(feature = "extract"))]
#[allow(clippy::unnecessary_wraps)]
fn build_server(
    service: MemoryService<DynEmbedder>,
) -> Result<McpServer, Box<dyn std::error::Error>> {
    Ok(McpServer::new(service))
}

/// Build the Ollama-backed extractor from `VELESDB_MEMORY_EXTRACTOR_URL`
/// (default local) and the required `VELESDB_MEMORY_EXTRACTOR_MODEL`.
#[cfg(feature = "extract")]
fn build_ollama_extractor() -> Result<velesdb_memory::DynExtractor, Box<dyn std::error::Error>> {
    use std::sync::Arc;
    use velesdb_memory::extract::DEFAULT_OLLAMA_URL;
    use velesdb_memory::OllamaExtractor;

    let url = std::env::var("VELESDB_MEMORY_EXTRACTOR_URL")
        .unwrap_or_else(|_| DEFAULT_OLLAMA_URL.to_owned());
    let model = std::env::var("VELESDB_MEMORY_EXTRACTOR_MODEL").map_err(|_| {
        "VELESDB_MEMORY_EXTRACTOR=ollama requires VELESDB_MEMORY_EXTRACTOR_MODEL \
         (e.g. qwen3.6:35b-mlx)"
    })?;
    Ok(Arc::new(OllamaExtractor::new(url, model)))
}

/// Select the embedding backend from `VELESDB_MEMORY_EMBEDDER`: `hash`
/// (default) is deterministic and fully offline; `ollama` gives real on-device
/// semantic recall and requires building with `--features ollama`.
fn build_embedder() -> Result<DynEmbedder, Box<dyn std::error::Error>> {
    match std::env::var("VELESDB_MEMORY_EMBEDDER").as_deref() {
        Ok("ollama") => build_ollama_embedder(),
        Ok("hash") | Err(_) => {
            warn_hash_embedder_not_semantic();
            Ok(Box::new(HashEmbedder::new(DEFAULT_DIMENSION)))
        }
        Ok(other) => Err(format!(
            "unknown VELESDB_MEMORY_EMBEDDER '{other}' (expected 'hash' or 'ollama')"
        )
        .into()),
    }
}

/// Warn (on **stderr**, never stdout — that carries the MCP JSON-RPC stream)
/// that the default `hash` embedder is deterministic but **not semantic**:
/// `recall` matches on lexical/hash proximity, not meaning. This is the single
/// most common "why is recall bad?" surprise, so make the trade-off explicit
/// and point to the opt-in. Silence it for scripted/offline runs with
/// `VELESDB_MEMORY_QUIET=1`.
fn warn_hash_embedder_not_semantic() {
    if std::env::var_os("VELESDB_MEMORY_QUIET").is_some() {
        return;
    }
    eprintln!(
        "[velesdb-memory] Using the default 'hash' embedder: deterministic and \
         fully offline, but NOT semantic — recall matches surface form, not meaning. \
         For real semantic recall, run an Ollama build with \
         VELESDB_MEMORY_EMBEDDER=ollama (see crates/velesdb-memory/README.md). \
         Set VELESDB_MEMORY_QUIET=1 to silence this notice."
    );
}

#[cfg(feature = "ollama")]
fn build_ollama_embedder() -> Result<DynEmbedder, Box<dyn std::error::Error>> {
    use velesdb_memory::{OllamaEmbedder, DEFAULT_OLLAMA_MODEL, DEFAULT_OLLAMA_URL};

    let url = std::env::var("VELESDB_MEMORY_OLLAMA_URL")
        .unwrap_or_else(|_| DEFAULT_OLLAMA_URL.to_owned());
    let model = std::env::var("VELESDB_MEMORY_OLLAMA_MODEL")
        .unwrap_or_else(|_| DEFAULT_OLLAMA_MODEL.to_owned());
    Ok(Box::new(OllamaEmbedder::new(url, model)?))
}

#[cfg(not(feature = "ollama"))]
fn build_ollama_embedder() -> Result<DynEmbedder, Box<dyn std::error::Error>> {
    Err("the 'ollama' embedder requires building with `--features ollama`".into())
}

/// Default token budget of `compile-stdin` when `--budget` is omitted.
///
/// Sized for the job the hook does: a tool result big enough to be worth
/// compiling, compressed to something an agent can still read in full.
// Tous ses consommateurs sont gates sur `context` : sans cette feature la
// constante est reellement morte, et -D warnings en fait une erreur.
#[cfg(feature = "context")]
const DEFAULT_COMPILE_STDIN_BUDGET: u64 = 2_000;

/// Parsed `compile-stdin` invocation.
#[cfg(feature = "context")]
#[derive(Debug, PartialEq, Eq)]
struct CompileStdinOptions {
    token_budget: u64,
    query: String,
}

#[cfg(feature = "context")]
impl Default for CompileStdinOptions {
    fn default() -> Self {
        Self {
            token_budget: DEFAULT_COMPILE_STDIN_BUDGET,
            query: String::new(),
        }
    }
}

/// What `compile-stdin` writes to stdout: one JSON object, so a shell hook
/// gets the compiled text AND the accounting from a single stream (`jq` is
/// already a hard requirement of the hooks).
#[cfg(feature = "context")]
#[derive(serde::Serialize)]
struct CompileStdinOutput {
    content: String,
    tokens_in: u64,
    tokens_out: u64,
    tokens_saved: u64,
    risk: String,
}

/// Parse `compile-stdin`'s flags. Hand-rolled for the same reason as
/// `--version`/`--http` above: two flags do not justify a `clap` dependency
/// in the shipped binary.
///
/// # Errors
/// A message naming the offending flag when it is unknown, when its value is
/// missing, or when `--budget` is not a positive integer.
/// Validate `--budget`'s value. Split out of [`parse_compile_stdin_args`] to
/// keep that loop's branching within the repo's complexity ceiling.
///
/// # Errors
/// When the value is absent, not an integer, or zero — a zero budget fits no
/// fragment at all, so it can only ever produce the empty-compilation failure
/// [`compile_stdin_json`] rejects anyway.
#[cfg(feature = "context")]
fn parse_compile_stdin_budget(value: Option<&String>) -> Result<u64, String> {
    let raw = value.ok_or_else(|| "--budget requires a value".to_owned())?;
    let parsed: u64 = raw
        .parse()
        .map_err(|_| format!("--budget expects a positive integer, got {raw:?}"))?;
    if parsed == 0 {
        return Err("--budget must be greater than 0".to_owned());
    }
    Ok(parsed)
}

#[cfg(feature = "context")]
fn parse_compile_stdin_args(args: &[String]) -> Result<CompileStdinOptions, String> {
    let mut options = CompileStdinOptions::default();
    let mut index = 0;
    while index < args.len() {
        let flag = args[index].as_str();
        let value = args.get(index + 1);
        match flag {
            "--budget" => {
                options.token_budget = parse_compile_stdin_budget(value)?;
                index += 2;
            }
            "--query" => {
                options
                    .query
                    .clone_from(value.ok_or_else(|| "--query requires a value".to_owned())?);
                index += 2;
            }
            other => return Err(format!("unknown compile-stdin flag {other:?}")),
        }
    }
    Ok(options)
}

/// Compile `text` under `options` and render the JSON payload.
///
/// # Errors
/// When `text` is empty, when segmentation hits a [`velesdb_memory::limits`]
/// cap, or when the budget leaves no room for any context.
#[cfg(feature = "context")]
fn compile_stdin_json(
    text: &str,
    options: &CompileStdinOptions,
) -> Result<String, Box<dyn std::error::Error>> {
    use velesdb_memory::context::{
        segment_transcript, CompilePolicy, CompileRequest, ContextCompiler, SegmentationPolicy,
    };

    if text.trim().is_empty() {
        return Err("compile-stdin received empty input on stdin".into());
    }

    let outcome = segment_transcript(text, &SegmentationPolicy::default())?;
    let request = CompileRequest {
        query: options.query.clone(),
        fragments: outcome
            .segments
            .into_iter()
            .map(|segment| segment.fragment)
            .collect(),
        project: None,
        target_model: None,
        token_budget: options.token_budget,
        memory_scope: None,
        policy: None,
    };
    let compiled = ContextCompiler::new(CompilePolicy::default()).compile(&request)?;

    // The compiler externalizes rather than truncates: when no single
    // fragment fits, everything moves behind a retrieval handle and the
    // assembled content is empty. That is a legitimate compilation, but a
    // useless one to return as a *replacement* for real content — surface it
    // as an error so the caller keeps the original instead of shipping an
    // empty string.
    if compiled.content.is_empty() {
        return Err(format!(
            "a budget of {} tokens fits none of the {} input tokens — every fragment was \
             externalized and the compiled context is empty; raise --budget",
            options.token_budget, compiled.insights.tokens_in
        )
        .into());
    }

    let output = CompileStdinOutput {
        content: compiled.content,
        tokens_in: compiled.insights.tokens_in,
        tokens_out: compiled.insights.tokens_out,
        tokens_saved: compiled.insights.tokens_saved,
        risk: format!("{:?}", compiled.risk).to_lowercase(),
    };
    Ok(serde_json::to_string(&output)?)
}

/// Read stdin, compile it, print the JSON payload.
///
/// # Errors
/// Propagates flag-parsing, stdin-read, and compilation failures.
#[cfg(feature = "context")]
fn run_compile_stdin(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    use std::io::Read as _;

    let options = parse_compile_stdin_args(args)?;
    let mut text = String::new();
    std::io::stdin().read_to_string(&mut text)?;
    println!("{}", compile_stdin_json(&text, &options)?);
    Ok(())
}

#[cfg(not(feature = "context"))]
fn run_compile_stdin(_args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    Err("`compile-stdin` requires building with `--features context`".into())
}

#[cfg(all(test, feature = "context"))]
mod compile_stdin_tests {
    use super::{
        compile_stdin_json, parse_compile_stdin_args, CompileStdinOptions,
        DEFAULT_COMPILE_STDIN_BUDGET,
    };

    /// A tool-output-shaped corpus: repetitive log lines, the exact case a
    /// `PostToolUse` hook has to shrink.
    fn noisy_tool_output() -> String {
        use std::fmt::Write as _;

        let mut text = String::new();
        for i in 0..120 {
            let _ = writeln!(
                text,
                "[2026-07-25T01:0{}:00Z] INFO  worker: processing batch {} of 120 — retry=0 status=ok",
                i % 10,
                i
            );
        }
        text
    }

    fn parse(value: &str) -> serde_json::Value {
        serde_json::from_str(value).expect("compile-stdin must emit valid JSON")
    }

    #[test]
    fn tight_budget_actually_shrinks_the_payload() {
        let options = CompileStdinOptions {
            token_budget: 1_500,
            query: "what did the worker do".to_owned(),
        };
        let compiled = parse(&compile_stdin_json(&noisy_tool_output(), &options).unwrap());

        let tokens_in = compiled["tokens_in"].as_u64().unwrap();
        let tokens_out = compiled["tokens_out"].as_u64().unwrap();
        assert!(tokens_in > 0, "tokens_in must be measured, got {tokens_in}");
        assert!(
            tokens_out < tokens_in,
            "a 200-token budget over {tokens_in} tokens of logs must compress: got {tokens_out}"
        );
        assert_eq!(
            compiled["tokens_saved"].as_u64().unwrap(),
            tokens_in - tokens_out
        );
        let content = compiled["content"].as_str().unwrap();
        assert!(
            !content.is_empty(),
            "an empty compilation is worse than no compilation — the caller would replace a \
             real tool result with nothing"
        );
        assert!(
            content.len() < noisy_tool_output().len(),
            "the compiled content must be shorter than the raw tool output"
        );
    }

    /// A budget too small to fit even one fragment makes the compiler
    /// externalize everything and emit an EMPTY context. Returning that as a
    /// success is a trap: `compile-stdin`'s caller (a `PostToolUse` hook) would
    /// swap a real tool result for an empty string. Fail loudly instead, so
    /// the caller falls back to the untouched output.
    #[test]
    fn budget_too_small_for_any_fragment_is_an_error() {
        let options = CompileStdinOptions {
            token_budget: 50,
            query: String::new(),
        };
        let error = compile_stdin_json(&noisy_tool_output(), &options).unwrap_err();
        let message = error.to_string();
        assert!(
            message.contains("budget"),
            "the error must point at the budget, got {message}"
        );
    }

    #[test]
    fn compilation_is_byte_identical_across_runs() {
        let options = CompileStdinOptions {
            token_budget: 1_500,
            query: "worker batches".to_owned(),
        };
        let first = compile_stdin_json(&noisy_tool_output(), &options).unwrap();
        let second = compile_stdin_json(&noisy_tool_output(), &options).unwrap();
        assert_eq!(first, second, "the compiler must be deterministic");
    }

    #[test]
    fn empty_stdin_is_rejected() {
        let error = compile_stdin_json("   \n\t ", &CompileStdinOptions::default()).unwrap_err();
        assert!(
            error.to_string().contains("empty"),
            "the error must name the cause, got {error}"
        );
    }

    #[test]
    fn flags_default_and_override() {
        assert_eq!(
            parse_compile_stdin_args(&[]).unwrap(),
            CompileStdinOptions {
                token_budget: DEFAULT_COMPILE_STDIN_BUDGET,
                query: String::new(),
            }
        );
        let parsed = parse_compile_stdin_args(&[
            "--budget".to_owned(),
            "512".to_owned(),
            "--query".to_owned(),
            "why did it fail".to_owned(),
        ])
        .unwrap();
        assert_eq!(parsed.token_budget, 512);
        assert_eq!(parsed.query, "why did it fail");
    }

    #[test]
    fn malformed_flags_are_rejected() {
        for bad in [
            vec!["--budget".to_owned()],
            vec!["--budget".to_owned(), "zero".to_owned()],
            vec!["--budget".to_owned(), "0".to_owned()],
            vec!["--nope".to_owned()],
        ] {
            assert!(
                parse_compile_stdin_args(&bad).is_err(),
                "must reject {bad:?}"
            );
        }
    }
}

#[cfg(all(test, feature = "http"))]
mod tests {
    use super::is_loopback_host;

    #[test]
    fn loopback_v4_and_v6_are_recognized() {
        assert!(is_loopback_host("127.0.0.1:18090"));
        assert!(is_loopback_host("127.0.0.5:18090"));
        assert!(is_loopback_host("[::1]:18090"));
    }

    #[test]
    fn non_loopback_hosts_are_rejected() {
        assert!(!is_loopback_host("0.0.0.0:18090"));
        assert!(!is_loopback_host("192.168.1.10:18090"));
        assert!(!is_loopback_host("[::]:18090"));
        assert!(!is_loopback_host("mcp.example.com:18090"));
    }
}