Skip to main content

lean_ctx/tools/
server_lifecycle.rs

1use std::path::Path;
2use std::sync::Arc;
3use std::sync::atomic::AtomicUsize;
4use std::time::Instant;
5use tokio::sync::RwLock;
6
7use crate::core::cache::SessionCache;
8use crate::core::session::SessionState;
9
10use super::server::{InteractionMode, LeanCtxServer, SessionMode};
11use super::startup::detect_startup_context;
12
13const MAX_WARM_SESSIONS: usize = 8;
14
15/// How often a connection re-checks that its bus presence is still listed.
16/// Shorter than the default worker lease, so a presence an older binary
17/// retired is restored before the dashboard polls twice.
18const PRESENCE_VERIFY_INTERVAL: std::time::Duration = std::time::Duration::from_mins(1);
19
20/// Last successful presence verification per presence id. A process holds
21/// one presence per connection, so this stays a handful of entries.
22fn presence_verifications() -> &'static std::sync::Mutex<std::collections::HashMap<String, Instant>>
23{
24    static VERIFIED: std::sync::OnceLock<
25        std::sync::Mutex<std::collections::HashMap<String, Instant>>,
26    > = std::sync::OnceLock::new();
27    VERIFIED.get_or_init(Default::default)
28}
29
30fn presence_verification_due(agent_id: &str) -> bool {
31    presence_verifications()
32        .lock()
33        .unwrap_or_else(std::sync::PoisonError::into_inner)
34        .get(agent_id)
35        .is_none_or(|at| at.elapsed() >= PRESENCE_VERIFY_INTERVAL)
36}
37
38fn mark_presence_verified(agent_id: &str) {
39    presence_verifications()
40        .lock()
41        .unwrap_or_else(std::sync::PoisonError::into_inner)
42        .insert(agent_id.to_string(), Instant::now());
43}
44
45fn forget_presence_verification(agent_id: &str) {
46    presence_verifications()
47        .lock()
48        .unwrap_or_else(std::sync::PoisonError::into_inner)
49        .remove(agent_id);
50}
51
52fn collect_warming_history(
53    project_root: Option<&str>,
54) -> Vec<crate::core::cache::warming::RecentFile> {
55    let Some(project_root) = project_root else {
56        return Vec::new();
57    };
58
59    let sessions = SessionState::load_recent_for_project_root(project_root, MAX_WARM_SESSIONS);
60    crate::core::cache::warming::collect_recent_files_in_project(&sessions, project_root)
61}
62
63/// GH #2006: collecting the history resolves every touched file of the recent
64/// sessions inside the project root. On a network drive that is a round trip
65/// per path, and it ran synchronously before the server logged or answered
66/// `initialize` (95-150 s on SMB). It now runs on the warming thread, before
67/// that thread takes the cache lock, so neither the handshake nor the first
68/// tool call waits for it.
69fn warm_cache_in_background(cache: Arc<RwLock<SessionCache>>, project_root: Option<String>) {
70    if project_root.is_none() {
71        return;
72    }
73
74    if let Err(error) = std::thread::Builder::new()
75        .name("lean-ctx-cache-warm".to_string())
76        .spawn(move || {
77            let history = collect_warming_history(project_root.as_deref());
78            if history.is_empty() {
79                return;
80            }
81            let mut cache = cache.blocking_write();
82            crate::core::cache::warming::warm_cache(&mut cache, &history);
83        })
84    {
85        tracing::debug!("lean-ctx: failed to start cache warming task: {error}");
86    }
87}
88
89impl Default for LeanCtxServer {
90    fn default() -> Self {
91        Self::new()
92    }
93}
94
95impl LeanCtxServer {
96    /// Creates a new server with default settings, auto-detecting the project root.
97    pub fn new() -> Self {
98        Self::new_with_project_root(None)
99    }
100
101    /// Creates a new server rooted at the given project directory.
102    pub fn new_with_project_root(project_root: Option<&str>) -> Self {
103        Self::new_with_startup(
104            project_root,
105            std::env::current_dir().ok().as_deref(),
106            SessionMode::Personal,
107            "default",
108            "default",
109        )
110    }
111
112    /// Creates a new server in Context OS shared mode for a specific workspace/channel.
113    pub fn new_shared_with_context(
114        project_root: &str,
115        workspace_id: &str,
116        channel_id: &str,
117    ) -> Self {
118        Self::new_with_startup(
119            Some(project_root),
120            std::env::current_dir().ok().as_deref(),
121            SessionMode::Shared,
122            workspace_id,
123            channel_id,
124        )
125    }
126
127    /// Ensures this MCP connection owns a durable local bus presence before
128    /// executing a tool. Construction registers eagerly; this is the
129    /// fail-closed retry for a transient startup lock or registry failure.
130    pub(crate) async fn ensure_session_presence(&self) -> Result<(), String> {
131        if self.presence_is_current().await {
132            return Ok(());
133        }
134        // Concurrent first calls (16 parallel reads on a fresh engine) each
135        // registered their own agent and timed out on the registry file lock
136        // on Windows. One registers; the rest wait and reuse its id.
137        let _init = self.presence_init.lock().await;
138        if self.presence_is_current().await {
139            return Ok(());
140        }
141
142        let project_root = self.presence_root();
143        // #1766: once `initialize` has resolved the session's role, the retry
144        // must register with it — falling back to the `context-engine`
145        // placeholder rewrote a `reviewer` presence.
146        let requested_role = self.presence_role.read().await.clone();
147        let registration = match requested_role.as_deref() {
148            Some(role) => {
149                let role_source = if crate::core::agents::declared_session_role().is_some() {
150                    crate::core::agents::RoleSource::Declared
151                } else {
152                    crate::core::agents::RoleSource::Assumed
153                };
154                crate::core::agents::AgentRegistry::register_mcp_process_as(
155                    project_root,
156                    role,
157                    role_source,
158                    None,
159                )
160            }
161            None => crate::core::agents::AgentRegistry::register_mcp_process(project_root, None),
162        };
163        let retired = self.presence_agent_id.read().await.clone();
164        match registration {
165            Ok(agent_id) => {
166                if let Some(retired) = retired.as_deref()
167                    && retired != agent_id
168                {
169                    tracing::info!("lean-ctx: MCP presence {retired} was retired; now {agent_id}");
170                    forget_presence_verification(retired);
171                }
172                mark_presence_verified(&agent_id);
173                *self.presence_agent_id.write().await = Some(agent_id);
174                Ok(())
175            }
176            // Re-registering a retired presence is best effort: a transient
177            // registry failure must not block a connection that already
178            // passed the fail-closed gate once. Retry after the interval.
179            Err(error) if retired.is_some() => {
180                tracing::warn!("lean-ctx: failed to re-register retired MCP presence: {error}");
181                if let Some(retired) = retired.as_deref() {
182                    mark_presence_verified(retired);
183                }
184                Ok(())
185            }
186            Err(error) => Err(error),
187        }
188    }
189
190    /// True while this connection holds a presence that is still listed.
191    /// The registry is shared with other processes: an older binary finishes
192    /// quiet presences after the worker lease, and finished history is
193    /// pruned. A retired presence reports `false` so the caller re-registers
194    /// instead of heartbeating a dead id forever (`/api/agents` went empty
195    /// while five MCP servers were connected). Verification reads the
196    /// registry at most once per `PRESENCE_VERIFY_INTERVAL` per presence.
197    async fn presence_is_current(&self) -> bool {
198        let Some(agent_id) = self.presence_agent_id.read().await.clone() else {
199            return false;
200        };
201        if !presence_verification_due(&agent_id) {
202            return true;
203        }
204        let id = agent_id.clone();
205        let live = tokio::task::spawn_blocking(move || {
206            crate::core::agents::AgentRegistry::transport_presence_is_live(&id)
207        })
208        .await
209        // A failed check must not knock out a working presence.
210        .unwrap_or(true);
211        if live {
212            mark_presence_verified(&agent_id);
213        }
214        live
215    }
216
217    fn presence_root(&self) -> &str {
218        self.startup_project_root
219            .as_deref()
220            .or(self.startup_shell_cwd.as_deref())
221            .unwrap_or(".")
222    }
223
224    pub(crate) fn new_with_startup(
225        project_root: Option<&str>,
226        startup_cwd: Option<&Path>,
227        session_mode: SessionMode,
228        workspace_id: &str,
229        channel_id: &str,
230    ) -> Self {
231        let ttl = std::env::var("LEAN_CTX_CACHE_TTL")
232            .ok()
233            .and_then(|v| v.parse().ok())
234            .unwrap_or_else(|| {
235                let cfg = crate::core::config::Config::load();
236                crate::core::config::MemoryCleanup::effective(&cfg).idle_ttl_secs()
237            });
238
239        // Purge stale graph indices on startup to prevent serving outdated data
240        crate::core::graph_index::ProjectIndex::purge_stale_indices();
241
242        let mut startup = detect_startup_context(project_root, startup_cwd);
243        // Launchd daemons commonly start in `/`. A broad root must never become
244        // session state: it creates a cross-project mega-session and, before
245        // the bounded project index, also made every later MCP launch scan it.
246        if startup.project_root.as_deref().is_some_and(|root| {
247            crate::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(root))
248        }) {
249            tracing::debug!("lean-ctx: ignoring broad startup project root");
250            startup.project_root = None;
251        }
252        let (session, context_os) = match session_mode {
253            SessionMode::Personal => {
254                // A personal MCP server owns one fresh, PID-qualified session.
255                // Reusing a persisted project "latest" session lets concurrent
256                // servers inject each other's state during initialize.
257                let mut session = SessionState::new();
258                if let Some(ref root) = startup.project_root {
259                    session.project_root = Some(root.clone());
260                }
261                if let Some(ref cwd) = startup.shell_cwd {
262                    session.shell_cwd = Some(cwd.clone());
263                }
264                (Arc::new(RwLock::new(session)), None)
265            }
266            SessionMode::Shared => {
267                // Every client of a shared session works in its root, so it
268                // must be an existing absolute directory (AP04-G5).
269                let Some(root) = startup.project_root.as_ref().filter(|root| {
270                    let root = std::path::Path::new(root);
271                    root.is_absolute() && root.is_dir()
272                }) else {
273                    // Shared mode without a project root is not useful; fall back to personal.
274                    return Self::new_with_startup(
275                        project_root,
276                        startup_cwd,
277                        SessionMode::Personal,
278                        workspace_id,
279                        channel_id,
280                    );
281                };
282                let rt = crate::core::context_os::runtime();
283                let session = rt
284                    .shared_sessions
285                    .get_or_load(root, workspace_id, channel_id);
286                rt.metrics.record_session_loaded();
287                // Ensure shell_cwd is refreshed (best-effort).
288                if let Some(ref cwd) = startup.shell_cwd
289                    && let Ok(mut s) = session.try_write()
290                {
291                    s.shell_cwd = Some(cwd.clone());
292                }
293                (session, Some(rt))
294            }
295        };
296
297        // Indices are NOT built eagerly here. A freshly connected agent that sits
298        // idle — or only uses ctx_read/ctx_shell/ctx_tree — must pay zero indexing
299        // cost. Heavy/search tools warm their indices lazily on first use via
300        // `index_orchestrator::ensure_warm_for_tool`, driven from dispatch (#152).
301        // An eager full graph + BM25 scan on every `new()` pegged a CPU core on
302        // each server start; multiplied across multiple agents and stdio respawns
303        // it was the root cause of the idle-high-CPU report (#453).
304
305        // Rehydrate the persistent stub index (#955) so the first unchanged
306        // re-read after this restart can collapse to the `[unchanged]` stub
307        // instead of re-delivering the whole file — gated by conversation +
308        // mtime/md5 so it can never serve a stale or cross-chat stub.
309        crate::core::read_stub_index::load();
310
311        let cache = Arc::new(RwLock::new(SessionCache::new()));
312        let bm25_cache: Arc<std::sync::Mutex<Option<crate::core::bm25_cache::Bm25CacheEntry>>> =
313            Arc::new(std::sync::Mutex::new(None));
314
315        // Register every server-local cache with the single process-wide guardian.
316        // The registry stores weak targets, so closed HTTP/MCP sessions are not retained.
317        let eviction_target = std::sync::Arc::new(
318            crate::core::eviction_orchestrator::EvictionOrchestrator::new(
319                cache.clone(),
320                bm25_cache.clone(),
321            ),
322        );
323        crate::core::eviction_orchestrator::register(&eviction_target);
324        crate::core::memory_guard::start_guard(std::sync::Arc::new(
325            crate::core::eviction_orchestrator::on_memory_pressure,
326        ));
327        warm_cache_in_background(cache.clone(), startup.project_root.clone());
328
329        let presence_root = startup
330            .project_root
331            .as_deref()
332            .or(startup.shell_cwd.as_deref())
333            .unwrap_or(".");
334        let presence_agent_id =
335            match crate::core::agents::AgentRegistry::register_mcp_process(presence_root, None) {
336                Ok(agent_id) => Some(agent_id),
337                Err(error) => {
338                    tracing::warn!("lean-ctx: failed to register MCP agent presence: {error}");
339                    None
340                }
341            };
342
343        Self {
344            cache,
345            session: crate::core::session::SessionSlot::new(session),
346            tool_calls: Arc::new(RwLock::new(Vec::new())),
347            call_count: Arc::new(AtomicUsize::new(0)),
348            background_tick: Arc::new(AtomicUsize::new(0)),
349            cache_ttl_secs: ttl,
350            last_call: Arc::new(RwLock::new(Instant::now())),
351            agent_id: Arc::new(RwLock::new(None)),
352            task_envelope: Arc::new(RwLock::new(None)),
353            native_receipt_authority: None,
354            presence_agent_id: Arc::new(RwLock::new(presence_agent_id)),
355            presence_init: Arc::new(tokio::sync::Mutex::new(())),
356            presence_role: Arc::new(RwLock::new(None)),
357            client_name: Arc::new(RwLock::new(String::new())),
358            autonomy: Arc::new(crate::core::autonomy::AutonomyState::new()),
359            loop_detector: Arc::new(RwLock::new(
360                crate::core::loop_detection::LoopDetector::with_config(
361                    &crate::core::config::Config::load().loop_detection,
362                ),
363            )),
364            // ctx_workflow was removed (focus release): nothing can start or stop
365            // a run, so a run left on disk by an older version must not gate
366            // tools here. The gate code goes with the workflow store.
367            workflow: Arc::new(RwLock::new(None)),
368            ledger: Arc::new(RwLock::new(
369                crate::core::context_ledger::ContextLedger::load(),
370            )),
371            pipeline_stats: Arc::new(RwLock::new(crate::core::pipeline::PipelineStats::new())),
372            session_mode,
373            workspace_id: if workspace_id.trim().is_empty() {
374                "default".to_string()
375            } else {
376                workspace_id.trim().to_string()
377            },
378            channel_id: if channel_id.trim().is_empty() {
379                "default".to_string()
380            } else {
381                channel_id.trim().to_string()
382            },
383            context_os,
384            context_ir: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
385                crate::core::context_ir::ContextIrV1::load(),
386            ))),
387            registry: Some(std::sync::Arc::new(
388                crate::server::registry::build_registry(),
389            )),
390            rules_stale_checked: Arc::new(std::sync::atomic::AtomicBool::new(false)),
391            rules_tip_shown: Arc::new(std::sync::atomic::AtomicBool::new(false)),
392            last_seen_event_id: Arc::new(std::sync::atomic::AtomicI64::new(0)),
393            startup_project_root: startup.project_root,
394            startup_shell_cwd: startup.shell_cwd,
395            peer: Arc::new(tokio::sync::RwLock::new(None)),
396            shell_approvals: Arc::default(),
397            has_client_roots: Arc::new(std::sync::atomic::AtomicBool::new(false)),
398            roots_resolved: Arc::new(std::sync::atomic::AtomicBool::new(false)),
399            roots_list_attempts: Arc::new(std::sync::atomic::AtomicU32::new(0)),
400            bm25_cache,
401            progress_sender: Arc::new(std::sync::Mutex::new(None)),
402            _eviction_target: eviction_target,
403            last_tools_config_hash: Arc::new(std::sync::atomic::AtomicU64::new(
404                crate::server::tools_config_watch::current_hash(),
405            )),
406            interaction_mode: Arc::new(std::sync::atomic::AtomicU8::new(
407                InteractionMode::Agent as u8,
408            )),
409        }
410    }
411
412    /// Clears the cache and saves the session if the TTL idle threshold has been exceeded.
413    pub async fn check_idle_expiry(&self) {
414        if self.cache_ttl_secs == 0 {
415            return;
416        }
417        let last = *self.last_call.read().await;
418        if last.elapsed().as_secs() >= self.cache_ttl_secs {
419            self.clear_idle_cache().await;
420        }
421        *self.last_call.write().await = Instant::now();
422    }
423
424    /// Idle TTL of the read cache (`memory_cleanup` / `LEAN_CTX_CACHE_TTL`); 0 = off.
425    pub fn idle_ttl(&self) -> std::time::Duration {
426        std::time::Duration::from_secs(self.cache_ttl_secs)
427    }
428
429    async fn clear_idle_cache(&self) {
430        tokio::spawn(crate::core::session::SessionState::save_shared_logged(
431            self.session.instance(),
432        ));
433        let mut cache = self.cache.write().await;
434        let count = cache.clear();
435        // The persisted stub index outlives the warm-cache clear, so a
436        // same-conversation re-read after idle still collapses to the stub
437        // via the cold fallback (#955). Flush it now for durability.
438        crate::core::read_stub_index::persist();
439        if count > 0 {
440            tracing::info!(
441                "Cache auto-cleared after {}s idle ({count} file(s))",
442                self.cache_ttl_secs
443            );
444        }
445    }
446
447    /// Release what an idle server holds without waiting for the next call:
448    /// the read cache (as `check_idle_expiry` would), the resident indexes and
449    /// the allocator's free pages. Everything reloads on demand. Restarts the
450    /// TTL so the next call does not clear (and count) the cache a second time.
451    pub async fn release_idle_memory(&self) {
452        use crate::core::memory_guard;
453        let before = (
454            memory_guard::get_rss_bytes(),
455            memory_guard::allocator_stats(),
456        );
457        self.clear_idle_cache().await;
458        *self.last_call.write().await = Instant::now();
459        let _ = tokio::task::spawn_blocking(|| {
460            crate::core::eviction_orchestrator::on_memory_pressure(
461                memory_guard::PressureLevel::Hard,
462            );
463            memory_guard::jemalloc_purge();
464            memory_guard::release_system_heap();
465        })
466        .await;
467        let after = (
468            memory_guard::get_rss_bytes(),
469            memory_guard::allocator_stats(),
470        );
471        let mb = |bytes: Option<u64>| bytes.map_or_else(|| "?".into(), |b| format!("{}", b >> 20));
472        tracing::info!(
473            "[mcp-idle] released: RSS {} → {} MB, heap {} → {} MB",
474            mb(before.0),
475            mb(after.0),
476            mb(before.1.map(|s| s.0)),
477            mb(after.1.map(|s| s.0)),
478        );
479    }
480
481    async fn record_shutdown_episode(&self, until: Instant) {
482        let tool_calls: Vec<(String, u64)> = self
483            .tool_calls
484            .read()
485            .await
486            .iter()
487            .map(|call| (call.tool.clone(), call.duration_ms))
488            .collect();
489        if tool_calls.is_empty() {
490            return;
491        }
492
493        let session = self.session.read().await.clone();
494        let Some(project_root) = session
495            .project_root
496            .clone()
497            .or_else(|| self.startup_project_root.clone())
498        else {
499            return;
500        };
501        let agent_id = self.agent_id.read().await.clone();
502        let agent_id = match agent_id {
503            Some(agent_id) => Some(agent_id),
504            None => self.presence_agent_id.read().await.clone(),
505        };
506        let policy = crate::core::config::Config::load()
507            .memory_policy_effective()
508            .unwrap_or_default();
509        let project_hash = crate::core::project_hash::hash_project_root(&project_root);
510
511        // Storage admission of the session's text: off the async executor and
512        // within the shutdown's enrichment time.
513        let recorded = within_shutdown("episode", until, move || {
514            crate::core::episodic_memory::record_session_episode(
515                &project_hash,
516                &session,
517                &tool_calls,
518                agent_id.as_deref(),
519                &policy.episodic,
520                true,
521            )
522        })
523        .await;
524        match recorded {
525            Some(Ok(Some(id))) => tracing::info!("lean-ctx: recorded shutdown episode {id}"),
526            Some(Ok(None)) | None => {}
527            Some(Err(error)) => {
528                tracing::warn!("lean-ctx: failed to record shutdown episode: {error}");
529            }
530        }
531    }
532
533    /// Aggressive cleanup on connection drop: save session, consolidate knowledge, clear caches.
534    ///
535    /// Order and bounds: the host that closed the connection waits a bounded
536    /// time and then kills the process. What must not be lost comes first —
537    /// the session's last state — and what only enriches later sessions (the
538    /// shutdown episode, the knowledge consolidation) runs afterwards within
539    /// `SHUTDOWN_ENRICHMENT`. With a semantic detector bound each of the
540    /// two re-admits the session's text through the model; run first and
541    /// unbounded, they kept the server alive beyond the host's wait while
542    /// the last state was still to be saved. The consolidation reads the
543    /// SAVED session, so it also belongs after the save.
544    pub async fn shutdown(&self) {
545        let stage = Instant::now();
546        let last_state_durable =
547            crate::core::session::SessionState::save_shared_at_shutdown(self.session.instance())
548                .await;
549        let stage = shutdown_stage("session save", stage);
550        if !last_state_durable {
551            // The save's own warning says why. Its changes stay pending as
552            // after any failed save, and nothing later in this process saves
553            // them. What follows must not make that worse: the consolidation
554            // imports from the SAVED session and advances its watermark, so
555            // on a state that is not the last one it is not run.
556            tracing::error!(
557                "lean-ctx: the session's last state is NOT durable at shutdown; \
558                 knowledge consolidation is skipped"
559            );
560        }
561        crate::core::savings_tracker::persist_session_summary();
562        if let Some(agent_id) = self.presence_agent_id.read().await.clone() {
563            forget_presence_verification(&agent_id);
564            if let Err(error) = crate::core::agents::AgentRegistry::finish_persistent(&agent_id) {
565                tracing::warn!("lean-ctx: failed to finish MCP agent presence: {error}");
566            }
567        }
568        let stage = shutdown_stage("summary and presence", stage);
569
570        let enrichment_ends = Instant::now() + SHUTDOWN_ENRICHMENT;
571        self.record_shutdown_episode(enrichment_ends).await;
572        let stage = shutdown_stage("episode", stage);
573        {
574            let session = self.session.read().await;
575            let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
576            let root = session.project_root.clone();
577            let hive_target = root.clone().map(|root| (root, session.id.clone()));
578            drop(session);
579
580            if last_state_durable
581                && has_insights
582                && let Some(root) = root
583            {
584                // Incremental, and only this server's own session — never the
585                // project's latest saved one, which may be another agent's
586                // (I07/S03). What is not consolidated now stays newer than the
587                // session's watermark, which advances only after the knowledge
588                // write: when this agent resumes the session explicitly
589                // (`ctx_session` load with `session_id`, or a handoff), its next
590                // consolidation (checkpoint, compaction or shutdown) imports
591                // those items. A new server starts its own fresh session and
592                // never takes this one up by itself; nothing consolidates at
593                // start-up.
594                let own = self.session.instance();
595                within_shutdown("knowledge consolidation", enrichment_ends, move || {
596                    crate::core::session::caller::scope(Some(own), || {
597                        crate::tools::startup::auto_consolidate_knowledge(&root);
598                    });
599                })
600                .await;
601            }
602            // Queue this session's learnings for Hive (local only, no network).
603            if last_state_durable && let Some((root, session_id)) = hive_target {
604                crate::core::hive::knowledge::draft::on_session_event(
605                    &root,
606                    &session_id,
607                    crate::core::hive::knowledge::draft::Trigger::Shutdown,
608                );
609            }
610        }
611        // Give back this process's Hive task claims (each bounded; one
612        // Hive cannot be reached for ends at its expiry there).
613        within_shutdown("hive task claims", enrichment_ends, || {
614            crate::core::hive::tasks::release_own_claims("the agent session ended")
615        })
616        .await;
617        shutdown_stage("knowledge consolidation", stage);
618        // Persist buffered stats (incl. CEP cache-hit/session counters) before
619        // the process exits. Short bridge sessions — e.g. a phase-isolated
620        // benchmark harness that spawns a fresh server per phase — may never
621        // reach the 30s live-stats flush cadence, which left
622        // `cep.sessions`/`total_cache_hits` at 0 in stats.json despite real
623        // cache hits (#361).
624        crate::core::stats::flush();
625        // A dropped connection ends its read/edit sequence: book the bounces
626        // still waiting for their edit window instead of losing them.
627        crate::core::bounce_tracker::flush_pending();
628        // Flush the persistent stub index (#955) so an unchanged re-read survives
629        // this restart as a cheap stub instead of a full re-delivery.
630        crate::core::read_stub_index::persist();
631        {
632            let mut cache = self.cache.write().await;
633            let count = cache.clear();
634            if count > 0 {
635                tracing::info!("[shutdown] cleared {count} cached file(s)");
636            }
637        }
638        crate::core::memory_guard::force_purge();
639    }
640}
641
642/// Time the shutdown gives to what only enriches later sessions, AFTER the
643/// session's last state is durable. An engineering bound, not a contract of
644/// any host: hosts wait differently long before they kill a server.
645const SHUTDOWN_ENRICHMENT: std::time::Duration = std::time::Duration::from_secs(8);
646
647/// Run blocking shutdown work off the async executor until `until` at the
648/// latest. `None`: it was not started (no time left) or did not finish in
649/// time; the log names the stage.
650///
651/// The bound ends the WAIT, not the work: a blocking task cannot be stopped.
652/// Work that did not finish keeps running until the process ends (or to its
653/// end, when the server object lives on). Both stages write their store in
654/// one atomic replace at the end (`episodic_memory::mutate_locked_admitted`,
655/// `knowledge::persist::write_json_atomic`), so a process that ends first
656/// leaves the store as it was — this session's episode is then missing, and
657/// the consolidation's items stay ahead of the session's watermark for the
658/// next consolidation of the continued session.
659async fn within_shutdown<T: Send + 'static>(
660    stage: &'static str,
661    until: Instant,
662    work: impl FnOnce() -> T + Send + 'static,
663) -> Option<T> {
664    let left = until.saturating_duration_since(Instant::now());
665    if left.is_zero() {
666        tracing::info!("lean-ctx: shutdown stage `{stage}` skipped: no time left for it");
667        return None;
668    }
669    match tokio::time::timeout(left, tokio::task::spawn_blocking(work)).await {
670        Ok(Ok(value)) => Some(value),
671        Ok(Err(error)) => {
672            tracing::warn!("lean-ctx: shutdown stage `{stage}` failed: {error}");
673            None
674        }
675        Err(_) => {
676            tracing::info!(
677                "lean-ctx: shutdown stage `{stage}` not finished within its time and left behind"
678            );
679            None
680        }
681    }
682}
683
684/// Name a shutdown stage that took a second or more, and return the start of
685/// the next one. A host waits a bounded time for the server to end after it
686/// closed the connection and kills it afterwards; without these lines a
687/// shutdown that outlives that wait leaves no trace of where the time went.
688pub(crate) fn shutdown_stage(stage: &'static str, started: Instant) -> Instant {
689    let milliseconds = started.elapsed().as_millis();
690    if milliseconds >= 1000 {
691        tracing::info!("lean-ctx: shutdown stage `{stage}` took {milliseconds} ms");
692    } else {
693        tracing::debug!("lean-ctx: shutdown stage `{stage}` took {milliseconds} ms");
694    }
695    Instant::now()
696}
697
698#[cfg(test)]
699mod tests {
700    use super::LeanCtxServer;
701
702    #[tokio::test]
703    async fn missing_presence_is_registered_before_first_tool() {
704        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
705        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
706        *server.presence_agent_id.write().await = None;
707
708        server
709            .ensure_session_presence()
710            .await
711            .expect("registration retry succeeds");
712        let agent_id = server
713            .presence_agent_id
714            .read()
715            .await
716            .clone()
717            .expect("presence id is retained");
718        let registry = crate::core::agents::AgentRegistry::load().expect("registry persisted");
719        assert!(
720            registry
721                .agents
722                .iter()
723                .any(|agent| agent.agent_id == agent_id)
724        );
725    }
726
727    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
728    async fn concurrent_presence_retries_register_once() {
729        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
730        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
731        *server.presence_agent_id.write().await = None;
732        let before = crate::core::agents::AgentRegistry::load()
733            .map(|registry| registry.agents.len())
734            .unwrap_or(0);
735
736        let calls: Vec<_> = (0..16)
737            .map(|_| {
738                let server = server.clone();
739                tokio::spawn(async move { server.ensure_session_presence().await })
740            })
741            .collect();
742        for call in calls {
743            call.await
744                .expect("task joined")
745                .expect("presence retry succeeds");
746        }
747
748        let agent_id = server
749            .presence_agent_id
750            .read()
751            .await
752            .clone()
753            .expect("presence id is retained");
754        let registry = crate::core::agents::AgentRegistry::load().expect("registry persisted");
755        assert!(
756            registry.agents.len() <= before + 1,
757            "no duplicate registrations"
758        );
759        assert!(
760            registry
761                .agents
762                .iter()
763                .any(|agent| agent.agent_id == agent_id)
764        );
765    }
766
767    /// Audit bug 1: another process (an older binary's lease expiry) finished
768    /// this live connection's presence; the server kept heartbeating the dead
769    /// id and the dashboard listed no agents. The next tool call re-registers.
770    #[tokio::test]
771    async fn retired_presence_is_replaced_on_next_tool_call() {
772        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
773        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
774        server
775            .ensure_session_presence()
776            .await
777            .expect("initial presence");
778        let retired = server
779            .presence_agent_id
780            .read()
781            .await
782            .clone()
783            .expect("presence id");
784        crate::core::agents::AgentRegistry::mutate_locked(|registry| {
785            registry.set_status(
786                &retired,
787                crate::core::agents::AgentStatus::Finished,
788                Some("worker lease expired; register again before continuing"),
789            )
790        })
791        .expect("registry writable")
792        .1
793        .expect("presence exists");
794        super::forget_presence_verification(&retired);
795
796        server
797            .ensure_session_presence()
798            .await
799            .expect("re-registration succeeds");
800
801        let current = server
802            .presence_agent_id
803            .read()
804            .await
805            .clone()
806            .expect("presence id");
807        assert_ne!(current, retired, "a retired presence id must be replaced");
808        assert!(crate::core::agents::AgentRegistry::transport_presence_is_live(&current));
809        let registry = crate::core::agents::AgentRegistry::load().expect("registry persisted");
810        let entry = registry
811            .agents
812            .iter()
813            .find(|agent| agent.agent_id == current)
814            .expect("new presence persisted");
815        assert!(entry.transport.is_some(), "re-registered as a transport");
816    }
817
818    /// Verification is throttled: a live presence is not re-read per call.
819    #[test]
820    fn presence_verification_is_throttled_per_presence() {
821        let id = "throttle-test-presence";
822        super::forget_presence_verification(id);
823        assert!(super::presence_verification_due(id));
824        super::mark_presence_verified(id);
825        assert!(!super::presence_verification_due(id));
826        super::forget_presence_verification(id);
827        assert!(super::presence_verification_due(id));
828    }
829
830    #[tokio::test]
831    async fn session_presence_failure_is_observable_to_tool_gate() {
832        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
833        let data_dir = crate::core::data_dir::lean_ctx_data_dir().expect("data dir");
834        std::fs::create_dir_all(&data_dir).expect("data dir exists");
835        std::fs::write(data_dir.join("agents"), "not a directory").expect("poison agents path");
836
837        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
838        assert!(server.presence_agent_id.read().await.is_none());
839        assert!(server.ensure_session_presence().await.is_err());
840    }
841}