Repository navigation
Expand file tree
/
Copy pathserve.rs
More file actions
4796 lines (4562 loc) · 183 KB
/
Copy pathserve.rs
File metadata and controls
4796 lines (4562 loc) · 183 KB
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
//! `ai-memory serve` — MCP server with optional filesystem watcher.
use std::future::{Future, IntoFuture};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use ai_memory_consolidate::{
AutoImproveReviewConfig, Consolidator, EmbedBackfillOptions, ObservationRetention,
ScheduledAutoImproveSettings, run_auto_improve_scheduler_tick, run_embedding_backfill,
run_lint,
};
use ai_memory_core::{ActiveProject, ProjectId, Sanitizer, WorkspaceId};
use ai_memory_hooks::{
DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, WorkstreamState, hook_router,
workstream_router,
};
use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, build_embedder};
use ai_memory_mcp::human_auth::{Cidr, HumanAuthRuntime, LoginLimiter};
use ai_memory_mcp::{
AdminState, AiMemoryServer, ScopeInvalidation, admin_router_with_sweep_tuning,
expire_legacy_cookie_mw, internal_auth_router, public_auth_router, require_dual_auth,
session_auth_router,
};
use ai_memory_store::{
ReaderPool, Store, TokenPepper, WriterHandle, hash_session_secret, hash_token,
};
use ai_memory_web::{WebMountSpec, normalize_prefix, split_web_routers, web_base_href};
use ai_memory_wiki::{WatcherHandle, Wiki, migrations, run_wiki_migrations};
use anyhow::{Context, Result};
use axum::body::Body;
use axum::extract::{DefaultBodyLimit, State};
use axum::http::{Request, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use rmcp::ServiceExt;
use rmcp::transport::stdio;
use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
};
use secrecy::ExposeSecret;
use tokio_util::sync::CancellationToken;
use tracing::info;
use crate::cli::{ServeArgs, TransportKind};
use crate::config::{AuthSettings, AutoImproveSettings, Config, MaintenanceSettings};
use ai_memory_mcp::auth::{AuthState, require_bearer};
/// 10 MB cap on inbound HTTP bodies. The /hook ingress accepts the
/// agent's raw payload which can include a tool output excerpt
/// (capped at 2 KB on our side via `truncate_excerpt`), but Claude
/// Code et al. send the full envelope, which can run to a few KB.
/// 10 MB is generous headroom; without a cap, axum streams unbounded
/// bodies into memory (audit critical #2).
const MAX_BODY_BYTES: usize = 10 * 1024 * 1024;
/// `POST /admin/bootstrap` may carry a large JSON array of sources even
/// after client-side prune; keep hooks/MCP at [`MAX_BODY_BYTES`].
const BOOTSTRAP_MAX_BODY_BYTES: usize = 32 * 1024 * 1024;
/// Startup and failure retry delay, capped by each job's configured interval.
const MAINTENANCE_STARTUP_DELAY_CAP: Duration = Duration::from_secs(60);
/// How often the durable SessionEnd consolidation worker checks for work when
/// no hook notification arrives (including jobs recovered after restart).
const SESSION_CONSOLIDATION_POLL_INTERVAL: Duration = Duration::from_secs(15);
/// A claimed job may be recovered after this long without completion. Provider
/// requests are expected to finish well inside this lease.
const SESSION_CONSOLIDATION_LEASE: Duration = Duration::from_secs(10 * 60);
/// Lock file guarding a data dir against a second `ai-memory serve` (#563).
const SERVE_LOCK_FILE: &str = ".serve.lock";
/// How long a wait on the shutdown path may run before the drain it is
/// waiting for is abandoned. axum's graceful shutdown waits for every
/// in-flight connection and a stateful or SSE MCP client can hold one open
/// indefinitely, so an unbounded drain is indistinguishable from ignoring the
/// signal: `docker stop` and `systemctl stop` would still burn their own
/// grace period and finish with SIGKILL (#699). Each wait is bounded on its
/// own, so a stop can take a small multiple of this.
const SHUTDOWN_GRACE: Duration = Duration::from_secs(5);
/// The signals that stop a running server, listened for on both transports.
///
/// Installed before the transport starts. The server runs as PID 1 under
/// `docker run` (no init shim), and for PID 1 the kernel discards any signal
/// whose handler is not installed — so a SIGTERM arriving during a slow boot
/// (the pre-migration archive, wiki migrations) must already have a listener
/// waiting for it. A tokio `Signal` queues a signal received before the first
/// `recv`, so registering early loses nothing (#699).
struct ShutdownSignals {
#[cfg(unix)]
interrupt: Option<tokio::signal::unix::Signal>,
#[cfg(unix)]
terminate: Option<tokio::signal::unix::Signal>,
}
impl ShutdownSignals {
/// Install the listeners.
///
/// A listener that cannot be registered degrades to the remaining one with
/// a warning: losing one way to stop the server is bad, refusing to start
/// over it is worse.
#[cfg(unix)]
fn install() -> Self {
use tokio::signal::unix::{SignalKind, signal};
fn listen(kind: SignalKind, name: &str) -> Option<tokio::signal::unix::Signal> {
match signal(kind) {
Ok(stream) => Some(stream),
Err(error) => {
tracing::warn!(
%error,
signal = name,
"cannot listen for this shutdown signal; the server will not stop on it"
);
None
}
}
}
Self {
interrupt: listen(SignalKind::interrupt(), "SIGINT"),
terminate: listen(SignalKind::terminate(), "SIGTERM"),
}
}
/// Install the listeners. Non-unix has only ctrl-c.
#[cfg(not(unix))]
fn install() -> Self {
Self {}
}
/// Resolve with the name of the first shutdown signal to arrive.
#[cfg(unix)]
async fn recv(&mut self) -> &'static str {
match (self.interrupt.as_mut(), self.terminate.as_mut()) {
(Some(interrupt), Some(terminate)) => tokio::select! {
_ = interrupt.recv() => "SIGINT",
_ = terminate.recv() => "SIGTERM",
},
(Some(interrupt), None) => {
interrupt.recv().await;
"SIGINT"
}
(None, Some(terminate)) => {
terminate.recv().await;
"SIGTERM"
}
// Both registrations failed: there is nothing left to wait for.
(None, None) => std::future::pending().await,
}
}
/// Resolve with the name of the first shutdown signal to arrive.
#[cfg(not(unix))]
async fn recv(&mut self) -> &'static str {
if let Err(error) = tokio::signal::ctrl_c().await {
tracing::warn!(%error, "ctrl-c listener failed; the server will not stop on it");
std::future::pending::<()>().await;
}
"ctrl-c"
}
}
/// The single-instance guard for `ai-memory serve`: an exclusive `flock` on
/// `<data-dir>/.serve.lock` held for the process lifetime. The OS releases it
/// when the process exits, so a crashed server never locks the operator out of
/// their own data.
#[derive(Debug)]
struct ServeLock {
_file: std::fs::File,
}
/// Unlocked sidecar naming the lock holder (`pid=<n>`). Separate from the
/// lock file because Windows' exclusive lock blocks reads of the locked
/// file from other handles; informational only, rewritten by each holder.
fn holder_info_path(data_dir: &Path) -> std::path::PathBuf {
data_dir.join(".serve.lock.holder")
}
/// Take the single-instance serve lock for `data_dir`.
///
/// A contended lock refuses startup naming the holder, unless `force` is set:
/// the operator who knows the previous server is gone (a hung holder, or a
/// mount with unreliable locking) must not be stranded. A filesystem that
/// cannot lock at all only downgrades the guard to a warning — refusing to
/// start there would be worse than the unguarded risk.
/// Transient failures `open`/`try_lock_exclusive` can raise on a healthy but
/// loaded machine: fd exhaustion (EMFILE per-process, ENFILE system-wide) and
/// interrupted syscalls (EINTR). These deserve a short retry. A `WouldBlock`
/// (another server already holds the lock, classified by
/// `is_drain_lock_busy_error`) is deliberately excluded — that is the correct
/// "someone else owns it" refusal and must surface immediately, never retried.
fn is_transient_serve_lock_error(err: &std::io::Error) -> bool {
if err.kind() == std::io::ErrorKind::Interrupted {
return true;
}
#[cfg(unix)]
if let Some(code) = err.raw_os_error() {
// EMFILE (per-process fd limit) / ENFILE (system-wide fd limit).
const EMFILE: i32 = 24;
const ENFILE: i32 = 23;
if code == EMFILE || code == ENFILE {
return true;
}
}
false
}
fn acquire_serve_lock(data_dir: &Path, force: bool) -> Result<Option<ServeLock>> {
std::fs::create_dir_all(data_dir)
.with_context(|| format!("creating data directory {}", data_dir.display()))?;
let path = data_dir.join(SERVE_LOCK_FILE);
use fs2::FileExt as _;
// Open the file and take the exclusive flock under a short bounded retry
// for transient errors only. A loaded machine (parallel test runs, an fd
// storm) can bounce `open` with EMFILE/ENFILE or interrupt the lock call
// with EINTR; a real server must not hard-fail on that. Mirrors
// `acquire_drain_lock`'s bounded ~25ms backoff. A `WouldBlock` (another
// holder) is never retried here — it falls through to the refusal path.
const SERVE_LOCK_ACQUIRE_ATTEMPTS: u32 = 5;
const SERVE_LOCK_ACQUIRE_BACKOFF: Duration = Duration::from_millis(25);
let mut attempt: u32 = 0;
let (file, lock_result) = loop {
attempt += 1;
let retriable = attempt < SERVE_LOCK_ACQUIRE_ATTEMPTS;
let file = match std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(&path)
{
Ok(file) => file,
Err(err) if retriable && is_transient_serve_lock_error(&err) => {
std::thread::sleep(SERVE_LOCK_ACQUIRE_BACKOFF);
continue;
}
Err(err) => {
return Err(err).with_context(|| format!("opening serve lock {}", path.display()));
}
};
match file.try_lock_exclusive() {
Err(err) if retriable && is_transient_serve_lock_error(&err) => {
std::thread::sleep(SERVE_LOCK_ACQUIRE_BACKOFF);
continue;
}
result => break (file, result),
}
};
match lock_result {
Ok(()) => {
// Informational only: the flock is the guard, and this names the
// holder in a later refusal message. Best-effort, and written to
// an UNLOCKED sidecar — on Windows the exclusive lock blocks
// other handles from reading the locked file itself, which made
// every refusal report "holder unknown".
let _ = std::fs::write(
holder_info_path(data_dir),
format!("pid={}\n", std::process::id()),
);
tracing::info!(lock = %path.display(), "single-instance serve lock held");
Ok(Some(ServeLock { _file: file }))
}
Err(err) if crate::commands::hook_spool::is_drain_lock_busy_error(&err) => {
let holder = std::fs::read_to_string(holder_info_path(data_dir))
.map(|text| text.trim().to_string())
.unwrap_or_default();
if force {
tracing::warn!(
lock = %path.display(),
holder = %holder,
"another process holds the serve lock; continuing unguarded per --force"
);
return Ok(None);
}
anyhow::bail!(
"another ai-memory serve process appears to be using {} ({}); two servers on one data directory corrupt wiki and index state — stop the other process, or pass --force if you are certain it is gone",
data_dir.display(),
if holder.is_empty() {
"holder unknown".to_owned()
} else {
holder
},
)
}
Err(err) => {
tracing::warn!(
lock = %path.display(),
error = %err,
"cannot lock the data directory; running without the single-instance guard"
);
Ok(None)
}
}
}
fn validate_api_credential_pepper(api_credentials_exist: bool, auth: &AuthSettings) -> Result<()> {
let pepper_present = auth
.token_pepper
.as_deref()
.is_some_and(|value| !value.trim().is_empty());
if api_credentials_exist && !pepper_present {
anyhow::bail!(
"api credentials exist but [auth].token_pepper is missing or blank; restore the original pepper from configuration backup before serving"
);
}
Ok(())
}
/// Validate the credentials that keep an existing multi-user installation
/// closed. Bootstrap installs have no user rows yet and retain their historical
/// compatibility behavior regardless of placeholder auth values.
fn validate_existing_users_auth(
users_exist: bool,
api_credentials_exist: bool,
human_mode: bool,
auth: &AuthSettings,
) -> Result<()> {
validate_api_credential_pepper(api_credentials_exist, auth)?;
let pepper_present = auth
.token_pepper
.as_deref()
.is_some_and(|value| !value.trim().is_empty());
let bearer_present = auth
.bearer_token
.as_deref()
.is_some_and(|value| !value.trim().is_empty());
if users_exist && !human_mode {
return match (pepper_present, bearer_present) {
(true, true) => Ok(()),
(false, false) => anyhow::bail!(
"users exist but [auth].token_pepper and [auth].bearer_token are missing or blank; restore both original secrets from configuration backup before serving"
),
(false, true) => anyhow::bail!(
"users exist but [auth].token_pepper is missing or blank; restore the original pepper from configuration backup before serving"
),
(true, false) => anyhow::bail!(
"users exist but [auth].bearer_token is missing or blank; configure the original static root bearer token before serving"
),
};
}
Ok(())
}
fn secret_configured(secret: Option<&secrecy::SecretString>) -> bool {
secret.is_some_and(|s| !s.expose_secret().trim().is_empty())
}
fn parse_trusted_proxy_cidrs(auth: &AuthSettings) -> Result<Vec<Cidr>> {
auth.trusted_proxy_cidrs
.iter()
.map(|spec| {
Cidr::parse(spec).map_err(|e| {
anyhow::anyhow!("invalid [auth].trusted_proxy_cidrs entry {spec:?}: {e}")
})
})
.collect()
}
async fn maybe_bootstrap_root(store: &Store, auth: &AuthSettings) -> Result<()> {
if store.reader.bootstrap_completed().await? {
if secret_configured(auth.initial_root_password.as_ref()) {
tracing::warn!(
"[auth].initial_root_password is ignored because bootstrap already completed; unset AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD"
);
}
return Ok(());
}
let Some(password) = auth
.initial_root_password
.as_ref()
.map(|s| s.expose_secret().to_string())
.filter(|s| !s.trim().is_empty())
else {
return Ok(());
};
let username = auth
.root_username
.as_deref()
.filter(|s| !s.trim().is_empty())
.unwrap_or("root");
let recovery = auth
.recovery_token
.as_ref()
.map(ExposeSecret::expose_secret)
.filter(|s| !s.trim().is_empty());
let reserved: Vec<&str> = [
auth.bearer_token
.as_deref()
.filter(|s| !s.trim().is_empty()),
auth.actor_proxy_bearer_token
.as_deref()
.filter(|s| !s.trim().is_empty()),
recovery,
]
.into_iter()
.flatten()
.collect();
ai_memory_core::validate_human_password(&password, Some(username), &reserved)
.context("initial root password does not meet policy")?;
if let Some(pepper) = auth
.token_pepper
.as_deref()
.filter(|p| !p.trim().is_empty())
{
let hash = hash_token(&password, &TokenPepper::new(pepper.to_string()));
if store.reader.token_hash_exists(hash).await? {
anyhow::bail!(
"[auth].initial_root_password collides with an existing API credential; choose a different password"
);
}
}
let phc = ai_memory_store::password::hash_password(password)
.await
.context("hashing initial root password")?;
store
.writer
.bootstrap_root(
username.to_string(),
auth.root_name.clone(),
auth.root_email.clone(),
phc,
)
.await
.context("bootstrapping root user")?;
tracing::warn!(
"root user bootstrapped; unset AI_MEMORY_AUTH__INITIAL_ROOT_PASSWORD so the plaintext is not kept in the process environment"
);
Ok(())
}
async fn validate_configured_secret_collisions(
store: &Store,
auth: &AuthSettings,
include_initial_password: bool,
) -> Result<()> {
let Some(pepper) = auth
.token_pepper
.as_deref()
.filter(|value| !value.trim().is_empty())
.map(|value| TokenPepper::new(value.to_string()))
else {
return Ok(());
};
let mut secrets = Vec::new();
if let Some(value) = auth
.bearer_token
.as_deref()
.filter(|value| !value.trim().is_empty())
{
secrets.push(("[auth].bearer_token", value));
}
if let Some(value) = auth
.actor_proxy_bearer_token
.as_deref()
.filter(|value| !value.trim().is_empty())
{
secrets.push(("[auth].actor_proxy_bearer_token", value));
}
if let Some(value) = auth
.recovery_token
.as_ref()
.map(ExposeSecret::expose_secret)
.filter(|value| !value.trim().is_empty())
{
secrets.push(("[auth].recovery_token", value));
}
if include_initial_password
&& let Some(value) = auth
.initial_root_password
.as_ref()
.map(ExposeSecret::expose_secret)
.filter(|value| !value.trim().is_empty())
{
secrets.push(("[auth].initial_root_password", value));
}
for (name, value) in secrets {
if store
.reader
.token_hash_exists(hash_token(value, &pepper))
.await?
{
anyhow::bail!(
"{name} collides with an existing API credential; configure a distinct secret"
);
}
}
Ok(())
}
fn human_auth_intended(auth: &AuthSettings, bootstrap_completed: bool, any_password: bool) -> bool {
bootstrap_completed
|| any_password
|| secret_configured(auth.initial_root_password.as_ref())
|| secret_configured(auth.recovery_token.as_ref())
}
fn require_recoverable_root_or_recovery(
human_mode: bool,
recoverable_roots: i64,
recovery_configured: bool,
) -> Result<()> {
if human_mode && recoverable_roots == 0 && !recovery_configured {
anyhow::bail!(
"human authentication is enabled but no recoverable root user exists; set [auth].recovery_token to rebuild root via POST /auth/recovery"
);
}
Ok(())
}
fn reserved_human_passwords(auth: &AuthSettings) -> Vec<String> {
let mut out = Vec::new();
if let Some(v) = auth
.bearer_token
.as_deref()
.filter(|s| !s.trim().is_empty())
{
out.push(v.to_string());
}
if let Some(v) = auth
.actor_proxy_bearer_token
.as_deref()
.filter(|s| !s.trim().is_empty())
{
out.push(v.to_string());
}
out
}
fn configured(value: Option<&String>) -> bool {
value.is_some_and(|v| !v.trim().is_empty())
}
/// What the bound address tells us about network exposure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HttpExposure {
/// Loopback-only, or authenticated. Nothing to warn about.
Safe,
/// Unauthenticated on a non-loopback address, allowed because the
/// operator passed `--allow-insecure-no-auth`.
InsecureByOverride,
/// Unauthenticated on a non-loopback address inside a container, where
/// the bind address is not evidence either way. See
/// [`validate_http_exposure`].
UndeterminedInContainer,
}
/// Detect that this process is running inside a container.
///
/// `/.dockerenv` is created by Docker, `/run/.containerenv` by Podman. The
/// official image also sets `AI_MEMORY_IN_CONTAINER`, so the signal survives
/// runtimes that create neither file.
fn running_in_container() -> bool {
if std::env::var("AI_MEMORY_IN_CONTAINER").is_ok_and(|v| !v.trim().is_empty()) {
return true;
}
Path::new("/.dockerenv").exists() || Path::new("/run/.containerenv").exists()
}
/// Refuse accidental unauthenticated network exposure after the listener has
/// selected its actual local address (which may differ from the bind input).
///
/// The check reads the bind address as evidence of reachability. That
/// inference holds on a host, but **not** inside a container: publishing a
/// port with `-p` requires binding `0.0.0.0` inside the namespace, and
/// whether that port reaches the network is decided by the host-side publish
/// spec — `-p 127.0.0.1:49374:49374` versus `-p 0.0.0.0:49374:49374` — which
/// the process cannot observe. Refusing there is a false positive that took
/// down the documented Quick Start container (#407), so containers get a
/// loud warning instead.
///
/// Note this is deliberately not backstopped by the `Host` allowlist: that
/// allowlist defends against DNS rebinding, where a browser sets the header.
/// A client that can route to the port sets `Host` freely, so it is not an
/// access control and cannot substitute for a token here.
fn validate_http_exposure(
local_addr: SocketAddr,
auth_enabled: bool,
human_mode: bool,
secure_cookie: bool,
allow_insecure_no_auth: bool,
containerized: bool,
) -> Result<HttpExposure> {
if local_addr.ip().is_loopback() {
return Ok(HttpExposure::Safe);
}
if human_mode && !secure_cookie {
anyhow::bail!(
"refusing human authentication on non-loopback plain HTTP address {local_addr}: \
passwords and session cookies require [auth].secure_cookie=true behind a trusted \
HTTPS reverse proxy. Non-Secure human cookies are allowed only on loopback."
);
}
if auth_enabled {
return Ok(HttpExposure::Safe);
}
if allow_insecure_no_auth {
return Ok(HttpExposure::InsecureByOverride);
}
if containerized {
return Ok(HttpExposure::UndeterminedInContainer);
}
anyhow::bail!(
"refusing unauthenticated plain HTTP on non-loopback address {local_addr}: anyone on the network could access ai-memory. Configure AI_MEMORY_AUTH_TOKEN or bind to a loopback address. For intentional LAN use, pass --allow-insecure-no-auth explicitly and review TLS options in docs/https-via-proxy.md."
);
}
/// Validate the trusted proxy's least-privilege credential and optional stable
/// root identity before binding the server.
fn validate_trusted_proxy_auth(auth: &AuthSettings) -> Result<()> {
let proxy_enabled = configured(auth.actor_proxy_bearer_token.as_ref());
if proxy_enabled && !configured(auth.bearer_token.as_ref()) {
anyhow::bail!(
"[auth].actor_proxy_bearer_token requires [auth].bearer_token so administration keeps a distinct root credential"
);
}
if proxy_enabled
&& auth.actor_proxy_bearer_token.as_deref().map(str::trim)
== auth.bearer_token.as_deref().map(str::trim)
{
anyhow::bail!(
"[auth].actor_proxy_bearer_token must differ from [auth].bearer_token; sharing the root credential would let a missing proxy identity fall through as root"
);
}
let root_issuer = configured(auth.root_issuer.as_ref());
let root_subject = configured(auth.root_subject.as_ref());
if root_issuer != root_subject {
anyhow::bail!(
"[auth].root_issuer and [auth].root_subject must be configured together because an OIDC subject is unique only within its issuer"
);
}
Ok(())
}
/// Can a trusted proxy actually assert identities on this server?
///
/// The MCP admin gates read this to know that distinct operators are in play
/// even when a proxied deployment never writes a `users` row.
fn trusted_proxy_identity_enabled(auth: &AuthSettings) -> bool {
configured(auth.actor_proxy_bearer_token.as_ref())
}
struct ConsolidatorSetup {
server: AiMemoryServer,
consolidator: Option<Arc<Consolidator>>,
admin_llm: Option<Arc<dyn LlmProvider>>,
}
fn maintenance_start_delay(
last_success_at: Option<i64>,
now_microseconds: i64,
interval: Duration,
) -> Duration {
let fallback = interval.min(MAINTENANCE_STARTUP_DELAY_CAP);
let Some(last_success_at) = last_success_at else {
return fallback;
};
let interval_microseconds = i64::try_from(interval.as_micros()).unwrap_or(i64::MAX);
let due_at = last_success_at.saturating_add(interval_microseconds);
if due_at <= now_microseconds {
fallback
} else {
// A future persisted timestamp (clock correction / restore) must not
// defer maintenance longer than its configured interval.
Duration::from_micros(due_at.saturating_sub(now_microseconds) as u64).min(interval)
}
}
async fn run_persisted_maintenance_job<F, Fut, R, RFut, N>(
writer: WriterHandle,
job: ai_memory_store::MaintenanceJob,
interval: Duration,
mut load_last_success: R,
now_microseconds: N,
mut tick: F,
) where
F: FnMut() -> Fut + Send + 'static,
Fut: Future<Output = Result<()>> + Send,
R: FnMut() -> RFut + Send + 'static,
RFut: Future<Output = Result<Option<i64>>> + Send,
N: Fn() -> i64 + Send + 'static,
{
let retry_delay = interval.min(MAINTENANCE_STARTUP_DELAY_CAP);
let mut cadence_known = false;
let mut delay = Duration::ZERO;
loop {
tokio::time::sleep(delay).await;
if !cadence_known {
match load_last_success().await {
Ok(last_success_at) => {
delay = maintenance_start_delay(last_success_at, now_microseconds(), interval);
cadence_known = true;
}
Err(error) => {
tracing::warn!(%error, job = job.as_str(), "maintenance cadence state read failed; retrying before running work");
delay = retry_delay;
}
}
continue;
}
match tick().await {
Ok(()) => match writer.record_maintenance_job_success(job).await {
Ok(()) => delay = interval,
Err(error) => {
tracing::warn!(%error, job = job.as_str(), "maintenance success state write failed; retrying job");
delay = retry_delay;
}
},
Err(error) => {
tracing::warn!(%error, job = job.as_str(), "scheduled maintenance job failed; retrying");
delay = retry_delay;
}
}
}
}
fn session_consolidation_retry_delay(attempt: u32) -> Duration {
let exponent = attempt.saturating_sub(1).min(4);
Duration::from_secs(30_u64.saturating_mul(1_u64 << exponent))
}
async fn run_session_consolidation_worker(
writer: WriterHandle,
consolidator: Arc<Consolidator>,
notify: Arc<tokio::sync::Notify>,
cancel: CancellationToken,
#[cfg(test)] completed: Arc<tokio::sync::Notify>,
) {
loop {
let now = jiff::Timestamp::now().as_microsecond();
let lease_micros =
i64::try_from(SESSION_CONSOLIDATION_LEASE.as_micros()).unwrap_or(i64::MAX);
let job = match writer
.claim_session_consolidation(now, now.saturating_sub(lease_micros))
.await
{
Ok(job) => job,
Err(error) => {
tracing::warn!(%error, "SessionEnd consolidation queue claim failed");
tokio::select! {
() = cancel.cancelled() => return,
() = notify.notified() => {},
() = tokio::time::sleep(SESSION_CONSOLIDATION_POLL_INTERVAL) => {},
}
continue;
}
};
let Some(job) = job else {
tokio::select! {
() = cancel.cancelled() => return,
() = notify.notified() => {},
() = tokio::time::sleep(SESSION_CONSOLIDATION_POLL_INTERVAL) => {},
}
continue;
};
let session_id = job.session_id();
let generation = job.generation();
let attempts = job.attempts();
let consolidation = consolidator.consolidate_session(
session_id,
false,
ai_memory_core::ActorContext::anonymous(),
None,
None,
);
tokio::pin!(consolidation);
let result = tokio::select! {
() = cancel.cancelled() => {
if let Err(error) = writer.release_session_consolidation(job).await {
tracing::warn!(%error, %session_id, generation, "failed to release SessionEnd consolidation during shutdown");
}
return;
}
result = &mut consolidation => result,
};
match result {
Ok(outcome) => match writer.complete_session_consolidation(job).await {
Ok(()) => {
info!(
session = %session_id,
generation,
attempts,
path = %outcome.path,
"SessionEnd: queued LLM consolidation written (opt-in)",
);
#[cfg(test)]
completed.notify_one();
}
Err(error) => tracing::warn!(
%error,
session = %session_id,
generation,
"SessionEnd consolidation succeeded but queue completion failed",
),
},
Err(error) => {
let retry_at = if attempts < ai_memory_store::SESSION_CONSOLIDATION_MAX_ATTEMPTS {
let delay = session_consolidation_retry_delay(attempts);
let delay_micros = i64::try_from(delay.as_micros()).unwrap_or(i64::MAX);
Some(
jiff::Timestamp::now()
.as_microsecond()
.saturating_add(delay_micros),
)
} else {
None
};
let terminal = retry_at.is_none();
if let Err(store_error) = writer
.fail_session_consolidation(job, error.to_string(), retry_at)
.await
{
tracing::warn!(
error = %store_error,
session = %session_id,
generation,
"failed to persist SessionEnd consolidation failure",
);
} else if terminal {
tracing::error!(
%error,
session = %session_id,
generation,
attempts,
"SessionEnd LLM consolidation exhausted retries; heuristic page remains",
);
} else {
tracing::warn!(
%error,
session = %session_id,
generation,
attempts,
"SessionEnd LLM consolidation failed; queued for retry",
);
}
}
}
}
}
/// Run the `serve` subcommand.
///
/// # Errors
/// Returns an error if the store cannot be opened, the watcher cannot
/// install, or the transport setup fails.
pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
// Before anything slow: boot takes the pre-migration archive and runs the
// wiki migrations, and a signal arriving in that window has to be caught
// rather than fall through to the default disposition (#699).
let mut shutdown = ShutdownSignals::install();
validate_web_ui_args(args.enable_web, args.web_ui_dir.as_deref())?;
config.require_llm_fallback_credentials()?;
// Merge config + CLI CORS origins (config first, CLI adds new entries).
// Validation runs before binding so a misconfigured origin is caught early.
let cors_origins = merge_cors_origins(&config.cors_allow_origins, &args.cors_allow_origin);
validate_cors_origins(&cors_origins)?;
// Guard the data dir before anything opens it: a second serve process
// means a second writer actor, a second git handle on the wiki, and a
// second active-project pointer (#563). Held until `run` returns.
let _serve_lock = acquire_serve_lock(&config.data_dir, args.force)?;
// #633: take the pre-migration safety archive BEFORE `Store::open` advances
// the SQLite schema, so the archive captures the true pre-2.0 state a 1.x
// binary can reopen. `Store::open` below runs the DB migrations; if the
// backup ran after it (as it used to, inside the wiki migration), the
// archived `db/` would already be at the 2.x schema and the documented
// rollback to 1.x would be impossible. A no-op for a fresh install or an
// already-migrated store; the OKF wiki migration reuses this archive instead
// of taking a second, post-DB-migration one.
let backup_dest_override = std::env::var("AI_MEMORY_BACKUP_DIR")
.ok()
.map(std::path::PathBuf::from);
migrations::snapshot_before_db_migration(&config.data_dir, backup_dest_override.as_deref())
.with_context(|| "taking the pre-migration safety backup")?;
let mut store = Store::open(&config.data_dir)
.with_context(|| format!("opening store at {}", config.data_dir.display()))?;
// Every reader handle below is cloned from this one, so the opt-in
// ranking signals are set once, here, and inherited everywhere.
store.reader.set_retrieval_tuning(config.retrieval.tuning());
let store = store;
// One-shot legacy heal (issue #103): NULL out any project repo_path that
// is a prefix-match catch-all. That means the $HOME and filesystem-root
// sentinels, plus any path that exists locally but is not a git work-tree
// root, so existing broken installs self-correct on upgrade. Uses the same
// $HOME source as the router's match-time guard (captured once in `Config`)
// so heal and guard agree on its meaning.
let healed = store
.writer
.heal_catch_all_repo_paths(config.home_dir.clone())
.await?;
if healed > 0 {
tracing::info!(
healed,
"healed catch-all project repo_path rows ($HOME, filesystem root, or non-git-root path)"
);
}
let api_credentials_exist = store.reader.api_credentials_exist().await?;
validate_api_credential_pepper(api_credentials_exist, &config.auth)?;
let bootstrap_completed_before_start = store.reader.bootstrap_completed().await?;
validate_configured_secret_collisions(&store, &config.auth, !bootstrap_completed_before_start)
.await?;
maybe_bootstrap_root(&store, &config.auth).await?;
let bootstrap_completed = store.reader.bootstrap_completed().await?;
let any_password = store.reader.any_password_hash().await?;
let human_mode = human_auth_intended(&config.auth, bootstrap_completed, any_password);
require_recoverable_root_or_recovery(
human_mode,
store.reader.count_recoverable_roots().await?,
secret_configured(config.auth.recovery_token.as_ref()),
)?;
validate_existing_users_auth(
store.reader.users_exist().await?,
api_credentials_exist,
human_mode,
&config.auth,
)?;
validate_trusted_proxy_auth(&config.auth)?;
let trusted_proxy_cidrs = parse_trusted_proxy_cidrs(&config.auth)?;
// Run any outstanding wiki-structure migrations before the watcher starts
// so file moves and renames are never raced by the reconciler.
let wiki_root = config.data_dir.join("wiki");
run_wiki_migrations(
&store.writer,
&store.reader,
&wiki_root,
&migrations::registry(),
)
.await
.with_context(|| "applying wiki-structure migrations")?;
let ws = store
.writer
.get_or_create_workspace(args.workspace.clone())
.await?;
let proj = store
.writer
.get_or_create_project(ws, args.project.clone(), None)
.await?;
// Build the privacy strip from config. Compile errors in
// user-supplied regex abort startup with a clear message so
// operators discover misconfiguration immediately.
let sanitizer = Sanitizer::new(&config.sanitize)
.context("compiling sanitizer.extra_patterns from config")?;
let wiki = Wiki::new(&config.data_dir, store.writer.clone())?
.with_sanitizer(sanitizer.clone())
// Reader attached unconditionally: admission name-resolution uses it
// when a chain is configured, and the startup scope-manifest backfill
// (below) always needs it to enumerate scopes.
.with_store_reader(store.reader.clone());
// Attach the admission webhook chain (operator-configured via
// `[[admission_webhooks]]` in config.toml or `AI_MEMORY_ADMISSION_WEBHOOKS__N__*`
// env vars). Empty config = no chain attached, zero overhead. The store
// reader is forwarded so the chain can resolve workspace_id/project_id
// into the human names webhooks address pages by.
let wiki = if config.admission_webhooks.is_empty() {
wiki
} else {
let chain = ai_memory_wiki::AdmissionChain::new(config.admission_webhooks.clone())
.context("building admission webhook chain")?;
tracing::info!(
count = config.admission_webhooks.len(),
"admission webhook chain attached"
);
wiki.with_admission_chain(chain)
};
let provider_health = ProviderHealth::default();
let (wiki, embedder) = configure_embedder(config, &store, wiki, &provider_health).await?;
// Make the wiki tree self-describing: write each scope's `_meta.md`
// (workspace/project name + repo_path) if missing, so the markdown alone
// can rebuild the index via `ai-memory reindex`. Idempotent; non-fatal.
match wiki.backfill_scope_manifests().await {
Ok(0) => {}
Ok(n) => tracing::info!(count = n, "wrote _meta.md scope manifests"),
Err(e) => tracing::warn!(error = %e, "scope-manifest backfill failed (non-fatal)"),
}
match wiki.ensure_upgrade_baseline_checkpoint() {
Ok(Some(oid)) => {
tracing::info!(checkpoint = %oid, "created wiki upgrade baseline checkpoint")
}
Ok(None) => {}
Err(e) => tracing::warn!(error = %e, "wiki upgrade baseline checkpoint failed (non-fatal)"),
}
// Keep the guard alive for the lifetime of `serve`.