1use super::server::LeanCtxServer;
3use super::startup::{
4 has_project_marker, is_suspicious_root, maybe_derive_project_root_from_absolute,
5};
6
7const ADOPTION_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
11
12const MAX_ADOPTION_PROBES: usize = 2;
17static ADOPTION_PROBES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18
19struct ProbeSlot;
21
22impl ProbeSlot {
23 fn take() -> Option<Self> {
24 use std::sync::atomic::Ordering;
25 ADOPTION_PROBES
26 .try_update(Ordering::AcqRel, Ordering::Acquire, |n| {
27 (n < MAX_ADOPTION_PROBES).then_some(n + 1)
28 })
29 .ok()
30 .map(|_| Self)
31 }
32}
33
34impl Drop for ProbeSlot {
35 fn drop(&mut self) {
36 ADOPTION_PROBES.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
37 }
38}
39
40#[cfg(test)]
41tokio::task_local! {
42 pub(crate) static ADOPTION_BARRIER:
45 std::cell::RefCell<Option<std::sync::Arc<tokio::sync::Barrier>>>;
46}
47
48impl LeanCtxServer {
49 pub fn checkpoint_interval_effective() -> usize {
50 if let Ok(v) = std::env::var("LEAN_CTX_CHECKPOINT_INTERVAL")
51 && let Ok(parsed) = v.trim().parse::<usize>()
52 {
53 return parsed;
54 }
55 let profile_interval = lean_ctx::core::profiles::active_profile()
56 .autonomy
57 .checkpoint_interval_effective();
58 if profile_interval > 0 {
59 return profile_interval as usize;
60 }
61 lean_ctx::core::config::Config::load().checkpoint_interval as usize
62 }
63
64 pub async fn resolve_path(&self, path: &str) -> Result<String, String> {
68 self.resolve_path_refusing(path)
69 .await
70 .map_err(|refusal| refusal.message)
71 }
72
73 pub(crate) async fn record_path_refusal(
76 &self,
77 tool: &str,
78 refusal: &lean_ctx::core::path_resolve::PathRefusal,
79 ) {
80 let Some(class) = refusal.class else {
81 return;
82 };
83 let agent_id = self
84 .agent_id
85 .read()
86 .await
87 .clone()
88 .unwrap_or_else(|| "unknown".to_string());
89 lean_ctx::core::security_events::record_refusals(tool, &agent_id, class, 1);
90 }
91
92 pub(crate) async fn resolve_path_refusing(
96 &self,
97 path: &str,
98 ) -> Result<String, lean_ctx::core::path_resolve::PathRefusal> {
99 self.resolve_path_for_tool(path, "unknown").await
103 }
104
105 pub(crate) async fn resolve_path_for_tool(
108 &self,
109 path: &str,
110 tool: &str,
111 ) -> Result<String, lean_ctx::core::path_resolve::PathRefusal> {
112 use lean_ctx::core::path_resolve::PathRefusal;
113 let normalized = lean_ctx::core::pathutil::normalize_tool_path(path);
114 if normalized.is_empty() || normalized == "." {
115 let root = self.session.read().await.project_root.clone();
116 return Ok(lean_ctx::core::workspace_authority::project_dot(
117 &normalized,
118 root.as_deref(),
119 )?);
120 }
121 let p = std::path::Path::new(&normalized);
122
123 let (resolved, jail_root, extra_roots) = {
124 let session = self.session.read().await;
125 let jail_root = session
126 .project_root
127 .as_deref()
128 .or(session.shell_cwd.as_deref())
129 .unwrap_or(".")
130 .to_string();
131
132 let worktree_cwd = if p.is_absolute() {
140 None
141 } else {
142 session
143 .project_root
144 .as_deref()
145 .zip(session.shell_cwd.as_deref())
146 .filter(|(root, cwd)| {
147 lean_ctx::core::path_resolve::shell_cwd_is_divergent_checkout(root, cwd)
148 })
149 .map(|(_, cwd)| std::path::Path::new(cwd).join(&normalized))
150 };
151
152 let resolved = if let Some(overridden) = worktree_cwd {
153 overridden
154 } else if p.is_absolute() || p.exists() {
155 std::path::PathBuf::from(&normalized)
156 } else if let Some(ref root) = session.project_root {
157 let joined = std::path::Path::new(root).join(&normalized);
158 if joined.exists() {
159 joined
160 } else if let Some(ref cwd) = session.shell_cwd {
161 std::path::Path::new(cwd).join(&normalized)
162 } else {
163 std::path::Path::new(&jail_root).join(&normalized)
164 }
165 } else if let Some(ref cwd) = session.shell_cwd {
166 std::path::Path::new(cwd).join(&normalized)
167 } else {
168 std::path::Path::new(&jail_root).join(&normalized)
169 };
170
171 if session.project_root.is_none()
174 && let Some(error) =
175 lean_ctx::core::path_resolve::unbound_relative_path(path, &resolved, &jail_root)
176 {
177 return Err(error.into());
178 }
179 (resolved, jail_root, session.extra_roots.clone())
180 };
181
182 let jail_root_path = std::path::Path::new(&jail_root);
183 let jailed = match lean_ctx::core::pathjail::jail_path_with_roots(
184 &resolved,
185 jail_root_path,
186 &extra_roots,
187 ) {
188 Ok(p) => self
189 .maybe_reroot_for_absolute_path(&resolved, jail_root_path, &extra_roots, tool)
190 .await?
191 .unwrap_or(p),
192 Err(e) => {
193 if lean_ctx::core::pathjail::detect_language_cache_root(&resolved).is_some() {
199 match lean_ctx::core::pathjail::jail_path_auto_admitting(
200 &resolved,
201 jail_root_path,
202 &extra_roots,
203 ) {
204 Ok(jailed) => jailed,
205 Err(retry) => {
206 lean_ctx_cloud::metrics_v2::signals::blocked(
207 &lean_ctx_cloud::metrics_v2::signals::path_jail_rule(),
208 );
209 return Err(PathRefusal::jail(&retry));
210 }
211 }
212 } else if let Some(jailed) = self
213 .maybe_reroot_for_absolute_path(&resolved, jail_root_path, &extra_roots, tool)
214 .await?
215 {
216 jailed
217 } else {
218 lean_ctx_cloud::metrics_v2::signals::blocked(
219 &lean_ctx_cloud::metrics_v2::signals::path_jail_rule(),
220 );
221 return Err(PathRefusal::jail(&e));
222 }
223 }
224 };
225
226 lean_ctx::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)
227 .map_err(PathRefusal::secret_path)?;
228
229 Ok(lean_ctx::core::pathutil::normalize_tool_path(
230 &jailed.to_string_lossy().replace('\\', "/"),
231 ))
232 }
233
234 async fn maybe_reroot_for_absolute_path(
235 &self,
236 resolved: &std::path::Path,
237 jail_root_path: &std::path::Path,
238 extra_roots: &[String],
239 tool: &str,
240 ) -> Result<Option<std::path::PathBuf>, String> {
241 if !resolved.is_absolute() || self.session_mode == super::SessionMode::Shared {
244 return Ok(None);
245 }
246 if lean_ctx::core::workspace_authority::is_configured() {
249 return Ok(None);
250 }
251 if crate::server::roots::pinned_root().is_some_and(|pinned| {
256 lean_ctx::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(&pinned))
257 == lean_ctx::core::pathutil::safe_canonicalize_or_self(jail_root_path)
258 }) {
259 return Ok(None);
260 }
261 let bound = self.session.read().await.project_root.clone();
265 if bound
266 .as_deref()
267 .is_some_and(|root| std::path::Path::new(root) != jail_root_path)
268 && let Some(rejailed) =
269 Self::rejail_in_bound_root(resolved, bound.as_deref(), extra_roots)
270 {
271 return rejailed.map(Some);
272 }
273 if self.session_is_unbound().await
278 && lean_ctx::core::pathjail_autobind::hardened_adoption_available()
279 {
280 return self.adopt_project_root(resolved, extra_roots, tool).await;
281 }
282 self.reroot_to_derived_project(resolved, jail_root_path, extra_roots)
283 .await
284 }
285
286 async fn reroot_to_derived_project(
290 &self,
291 resolved: &std::path::Path,
292 jail_root_path: &std::path::Path,
293 extra_roots: &[String],
294 ) -> Result<Option<std::path::PathBuf>, String> {
295 let Some(new_root) = maybe_derive_project_root_from_absolute(resolved)
299 .filter(|root| !lean_ctx::core::pathutil::is_broad_or_unsafe_root(root))
300 else {
301 return Ok(None);
302 };
303 let jail_is_real_project =
304 has_project_marker(jail_root_path) && !is_suspicious_root(jail_root_path);
305 let candidate_under_jail = resolved.starts_with(jail_root_path);
306 if jail_is_real_project
309 && new_root.starts_with(jail_root_path)
310 && new_root != jail_root_path
311 {
312 return Ok(None);
313 }
314 let allow_reroot = if candidate_under_jail && jail_is_real_project {
318 false
319 } else {
320 !jail_is_real_project || self.session.read().await.project_root.is_none()
321 };
322
323 if !allow_reroot {
324 return Ok(None);
325 }
326
327 if !self.reroot_to_project(&new_root).await {
328 return Ok(None);
329 }
330 lean_ctx::core::pathjail::jail_path_with_roots(resolved, &new_root, extra_roots)
331 .map(Some)
332 .map_err(|e| e.to_string())
333 }
334
335 async fn session_is_unbound(&self) -> bool {
338 self.session
339 .read()
340 .await
341 .project_root
342 .as_deref()
343 .is_none_or(|root| is_suspicious_root(std::path::Path::new(root)))
344 }
345
346 async fn adopt_project_root(
363 &self,
364 resolved: &std::path::Path,
365 extra_roots: &[String],
366 tool: &str,
367 ) -> Result<Option<std::path::PathBuf>, String> {
368 let already = self.autobind.try_lock().is_ok_and(|adopted| *adopted);
376 let slot = (!already).then(ProbeSlot::take).flatten();
377 let adoptable = match slot {
378 None => None,
379 Some(slot) => {
380 let candidate = resolved.to_path_buf();
381 let judged = tokio::time::timeout(
382 ADOPTION_PROBE_TIMEOUT,
383 tokio::task::spawn_blocking(move || {
384 let _slot = slot;
385 lean_ctx::core::pathjail_autobind::adoptable_root(&candidate)
386 .filter(|root| !lean_ctx::core::pathutil::is_broad_or_unsafe_root(root))
387 }),
388 )
389 .await;
390 judged.ok().and_then(Result::ok).flatten()
392 }
393 };
394 let agent_id = self
395 .agent_id
396 .read()
397 .await
398 .clone()
399 .unwrap_or_else(|| "unknown".to_string());
400
401 #[cfg(test)]
404 if let Some(barrier) = ADOPTION_BARRIER
405 .try_with(|barrier| barrier.borrow_mut().take())
406 .ok()
407 .flatten()
408 {
409 barrier.wait().await;
410 }
411 let mut adopted = self.autobind.lock().await;
412 let bound = self.session.read().await.project_root.clone();
413 let still_open = !*adopted
414 && bound
415 .as_deref()
416 .is_none_or(|root| is_suspicious_root(std::path::Path::new(root)));
417 if !still_open {
418 drop(adopted);
419 return Self::rejail_in_bound_root(resolved, bound.as_deref(), extra_roots).transpose();
420 }
421 let Some(root) = adoptable else {
422 return Ok(None);
423 };
424 let Some(saves) = self.switch_to_project(&root).await else {
425 return Ok(None);
426 };
427 *adopted = true;
435 lean_ctx::core::pathjail_autobind::mark_adopted(&root);
436 let audit = {
437 let (tool, agent_id, root) = (tool.to_string(), agent_id, root.clone());
438 tokio::task::spawn_blocking(move || {
439 lean_ctx::core::pathjail_autobind::record_autobind(&tool, &agent_id, &root);
440 })
441 };
442 tracing::warn!(
443 "[SECURITY] PathJail: unbound session adopted the project of its first path (tool {tool})"
444 );
445 let _ = audit.await;
446 drop(adopted);
447 for save in saves {
450 let _ = save.await;
451 }
452 lean_ctx::core::pathjail::jail_path_with_roots(resolved, &root, extra_roots)
453 .map(Some)
454 .map_err(|e| e.to_string())
455 }
456
457 fn rejail_in_bound_root(
462 resolved: &std::path::Path,
463 bound: Option<&str>,
464 extra_roots: &[String],
465 ) -> Option<Result<std::path::PathBuf, String>> {
466 let root = std::path::Path::new(bound?);
467 if is_suspicious_root(root) {
468 return None;
469 }
470 Some(
471 lean_ctx::core::pathjail::jail_path_with_roots(resolved, root, extra_roots)
472 .map_err(|e| e.to_string()),
473 )
474 }
475
476 async fn reroot_to_project(&self, new_root: &std::path::Path) -> bool {
481 let Some(saves) = self.switch_to_project(new_root).await else {
482 return false;
483 };
484 for save in saves {
485 let _ = save.await;
486 }
487 true
488 }
489
490 async fn switch_to_project(
493 &self,
494 new_root: &std::path::Path,
495 ) -> Option<Vec<tokio::task::JoinHandle<()>>> {
496 if lean_ctx::core::policy::runtime::inherited_source_view().is_some() {
497 return None;
498 }
499 let new_root_str = new_root.to_string_lossy().to_string();
500 let shell_cwd = self
501 .startup_shell_cwd
502 .as_ref()
503 .filter(|cwd| std::path::Path::new(cwd).starts_with(new_root))
504 .cloned()
505 .or_else(|| Some(new_root_str.clone()));
506 let current = self.session.instance();
507 let extra_roots = current.read().await.extra_roots.clone();
508 let switch = crate::server::SessionSwitch {
509 new_root: &new_root_str,
510 extra_roots,
511 shell_cwd,
512 rebind_request: true,
513 };
514 self.switch_session_root(¤t, switch).await
515 }
516
517 pub async fn resolve_path_or_passthrough(&self, path: &str) -> String {
519 self.resolve_path(path)
520 .await
521 .unwrap_or_else(|_| path.to_string())
522 }
523}