Skip to main content

lean_ctx_server/tools/
server_lifecycle.rs

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