1use std::sync::Arc;
11
12use anyhow::Result;
13use oxios_ouroboros::ExecutionResult;
14use parking_lot::RwLock;
15use serde::{Deserialize, Serialize};
16use uuid::Uuid;
17
18use crate::agent_lifecycle::AgentLifecycleManager;
19use crate::event_bus::EventBus;
20use crate::git_layer::GitLayer;
21use crate::metrics::get_metrics;
22use crate::mount::{MountId, MountManager};
23use crate::project::{ConversationBuffer, ProjectManager};
24use crate::state_store::StateStore;
25use crate::types::AgentId;
26
27#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
29pub enum AgentRole {
30 #[default]
32 Worker,
33 Manager,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct SubTask {
40 pub id: Uuid,
42 pub description: String,
44 pub required_capability: Option<String>,
46 pub result: Option<String>,
48 pub success: bool,
50 #[serde(default)]
52 pub role: AgentRole,
53}
54
55impl SubTask {
56 pub fn new(description: impl Into<String>) -> Self {
58 Self {
59 id: Uuid::new_v4(),
60 description: description.into(),
61 required_capability: None,
62 result: None,
63 success: false,
64 role: AgentRole::default(),
65 }
66 }
67
68 pub fn with_capability(mut self, cap: impl Into<String>) -> Self {
70 self.required_capability = Some(cap.into());
71 self
72 }
73}
74
75#[allow(dead_code)]
77pub struct Orchestrator {
78 intent_engine: RwLock<Option<Arc<dyn oxios_ouroboros::IntentEngineOps>>>,
81 event_bus: EventBus,
82 state_store: Arc<StateStore>,
83 git_layer: Option<Arc<GitLayer>>,
85 lifecycle: AgentLifecycleManager,
87 a2a: Option<Arc<crate::a2a::A2AProtocol>>,
89 project_manager: RwLock<Option<Arc<ProjectManager>>>,
91 mount_manager: RwLock<Option<Arc<MountManager>>>,
93 conversation_buffer: RwLock<ConversationBuffer>,
95 delegation_config: DelegationConfig,
97 a2a_breaker: Arc<crate::a2a::circuit_breaker::A2ACircuitBreaker>,
99 intent_config: RwLock<crate::config::IntentConfig>,
101 recovery: RwLock<Option<Arc<crate::resilience::RecoveryCoordinator>>>,
105}
106
107#[allow(dead_code)]
109struct DelegationConfig {
110 max_retries: u32,
112 base_delay_ms: u64,
114 max_delay_ms: u64,
116 #[allow(dead_code)]
118 timeout_ms: u64,
119}
120
121impl Default for DelegationConfig {
122 fn default() -> Self {
123 Self {
124 max_retries: 3,
125 base_delay_ms: 100,
126 max_delay_ms: 5000,
127 timeout_ms: 5000,
128 }
129 }
130}
131
132#[allow(dead_code)]
133impl DelegationConfig {
134 fn backoff_delay(&self, attempt: u32) -> u64 {
136 let delay = self.base_delay_ms * 2_u64.saturating_pow(attempt.min(10));
137 delay.min(self.max_delay_ms)
138 }
139}
140
141impl Orchestrator {
142 pub fn new(
144 event_bus: EventBus,
145 state_store: Arc<StateStore>,
146 lifecycle: AgentLifecycleManager,
147 ) -> Self {
148 Self::with_config(
149 event_bus,
150 state_store,
151 lifecycle,
152 crate::config::OrchestratorConfig::default(),
153 )
154 }
155
156 pub fn with_config(
158 event_bus: EventBus,
159 state_store: Arc<StateStore>,
160 lifecycle: AgentLifecycleManager,
161 _config: crate::config::OrchestratorConfig,
162 ) -> Self {
163 Self {
164 intent_engine: RwLock::new(None),
165 event_bus,
166 state_store,
167 git_layer: None,
168 lifecycle,
169 a2a: None,
170 project_manager: RwLock::new(None),
171 mount_manager: RwLock::new(None),
172 conversation_buffer: RwLock::new(ConversationBuffer::default()),
173 delegation_config: DelegationConfig::default(),
174 intent_config: RwLock::new(crate::config::IntentConfig::default()),
175 a2a_breaker: Arc::new(crate::a2a::circuit_breaker::A2ACircuitBreaker::new(5, 30)),
176 recovery: RwLock::new(None),
177 }
178 }
179
180 pub fn set_intent_engine(&self, engine: Arc<dyn oxios_ouroboros::IntentEngineOps>) {
183 *self.intent_engine.write() = Some(engine);
184 }
185
186 pub fn set_recovery(&self, coordinator: Arc<crate::resilience::RecoveryCoordinator>) {
190 *self.recovery.write() = Some(coordinator);
191 }
192
193 pub fn has_intent_engine(&self) -> bool {
195 self.intent_engine.read().is_some()
196 }
197
198 pub fn set_project_manager(&self, manager: Arc<ProjectManager>) {
200 *self.project_manager.write() = Some(manager);
201 }
202
203 pub fn set_mount_manager(&self, manager: Arc<MountManager>) {
205 *self.mount_manager.write() = Some(manager);
206 }
207
208 pub fn mount_manager(&self) -> Option<Arc<MountManager>> {
210 self.mount_manager.read().as_ref().cloned()
211 }
212
213 pub fn project_manager(&self) -> Option<Arc<ProjectManager>> {
215 self.project_manager.read().as_ref().cloned()
216 }
217
218 pub fn detect_project_tag(&self, message: &str) -> Option<String> {
220 self.project_manager.read().as_ref().and_then(|pm| {
221 let projects = pm.list_projects();
222 let result = crate::project::detect_project(message, &projects);
223 match result {
224 crate::project::DetectionResult::Found(id) => pm.get_project(id).map(|p| p.tag()),
225 crate::project::DetectionResult::NoMatch { .. } => None,
226 }
227 })
228 }
229
230 fn resolve_mount_workspace(
244 &self,
245 mount_ids: Option<&str>,
246 project_ids: Option<&str>,
247 user_message: &str,
248 ) -> (
249 Vec<MountId>,
250 Option<String>,
251 Vec<std::path::PathBuf>,
252 String,
253 ) {
254 use crate::mount::Mount;
255
256 let Some(mm) = self.mount_manager() else {
257 return (Vec::new(), None, Vec::new(), String::new());
258 };
259
260 let mut ids: Vec<MountId> = if let Some(ids_str) = mount_ids {
262 ids_str
263 .split(',')
264 .filter_map(|s| MountId::parse_str(s.trim()).ok())
265 .collect()
266 } else {
267 match mm.detect(user_message) {
268 crate::mount::DetectionResult::Found(id) => vec![id],
269 crate::mount::DetectionResult::NoMatch { .. } => vec![],
270 }
271 };
272 let mut seen = std::collections::HashSet::new();
274 ids.retain(|id| seen.insert(*id));
275
276 let project_for_instructions: Option<crate::project::Project> = if let Some(project_ids_str) =
283 project_ids
284 && let Some(first_id_str) = project_ids_str.split(',').next()
285 && let Some(pm) = self.project_manager()
286 && let Ok(pid) = Uuid::parse_str(first_id_str.trim())
287 {
288 let proj = pm.get_project(pid);
289 if let Some(ref project) = proj {
290 for mid in &project.mount_ids {
291 if !ids.contains(mid) {
292 ids.push(*mid);
293 }
294 }
295 }
296 proj
297 } else {
298 None
299 };
300
301 if ids.is_empty() {
302 return (Vec::new(), None, Vec::new(), String::new());
303 }
304
305 for id in &ids {
308 mm.touch(*id);
309 }
310
311 let mounts: Vec<Mount> = mm.get_mounts_ordered(&ids);
312 if mounts.is_empty() {
313 return (Vec::new(), None, Vec::new(), String::new());
314 }
315
316 let mut paths: Vec<std::path::PathBuf> = Vec::new();
318 for m in &mounts {
319 for p in &m.paths {
320 if !paths.contains(p) {
321 paths.push(p.clone());
322 }
323 }
324 }
325
326 let tag = if mounts.len() == 1 {
328 mounts[0].tag()
329 } else {
330 let names: Vec<&str> = mounts.iter().map(|m| m.name.as_str()).collect();
331 format!("[🔧 {}]", names.join(" + "))
332 };
333
334 let mut context = build_workspace_context_body(&mounts).unwrap_or_default();
335
336 if let Some(project) = project_for_instructions {
342 let instructions = if project.instructions.len() > 2000 {
344 let mut end = 2000;
345 while end > 0 && !project.instructions.is_char_boundary(end) {
346 end -= 1;
347 }
348 format!("{}...", &project.instructions[..end])
349 } else {
350 project.instructions.clone()
351 };
352 if !instructions.is_empty() {
353 context.push_str(&format!(
354 "\n### Project Instructions: {}\n{}\n",
355 project.name, instructions
356 ));
357 }
358 }
359
360 const MAX_CONTEXT_CHARS: usize = 6000;
362 if context.len() > MAX_CONTEXT_CHARS {
363 let mut end = MAX_CONTEXT_CHARS;
364 while end > 0 && !context.is_char_boundary(end) {
365 end -= 1;
366 }
367 context.truncate(end);
368 context.push_str("\n...(context truncated)...\n");
369 }
370
371 let context_opt = if context.is_empty() {
372 None
373 } else {
374 Some(context)
375 };
376 (ids, context_opt, paths, tag)
377 }
378
379 pub fn set_a2a(&mut self, a2a: Arc<crate::a2a::A2AProtocol>) {
381 self.a2a = Some(a2a);
382 }
383
384 pub fn set_git_layer(&mut self, git_layer: Arc<GitLayer>) {
386 self.git_layer = Some(git_layer);
387 }
388
389 pub async fn restore_sessions(&self) {
395 }
397
398 #[allow(dead_code)]
399 fn git_commit(&self, rel_path: &str, message: &str) {
400 if let Some(ref gl) = self.git_layer
401 && gl.is_enabled()
402 {
403 let _ = gl.commit_file(rel_path, message);
404 }
405 }
406
407 pub async fn handle(
443 &self,
444 engine: &dyn oxios_ouroboros::IntentEngineOps,
445 msg: &str,
446 ctx: &oxios_ouroboros::MsgCtx,
447 ) -> Result<HandleResponse> {
448 let mut directive = oxios_ouroboros::Directive::from_message(msg);
450
451 let env = self.resolve_exec_env(ctx, msg);
453
454 let mut result = self.execute_directive(&directive, &env).await?;
456
457 let (verdict, evaluation_passed) = if directive.needs_review() {
462 let (r, v) = self
463 .verify_or_retry(engine, &mut directive, &env, result, msg, ctx)
464 .await?;
465 result = r;
466 let passed = v.all_passed();
467 (Some(v), Some(passed))
468 } else {
469 (None, None)
470 };
471
472 Ok(HandleResponse {
473 directive: Box::new(directive),
474 env: Box::new(env),
475 result: Box::new(result),
476 verdict,
477 evaluation_passed,
478 })
479 }
480
481 #[allow(clippy::too_many_arguments)]
488 pub async fn handle_unified(
489 &self,
490 user_id: &str,
491 msg: &str,
492 session_id: Option<&str>,
493 project_ids: Option<&str>,
494 mount_ids: Option<&str>,
495 role: Option<&str>,
496 model_override: Option<&str>,
497 request_id: &str,
498 ) -> Result<OrchestrationResult> {
499 let engine = self
501 .intent_engine
502 .read()
503 .clone()
504 .expect("IntentEngine not wired — kernel assembler bug");
505
506 let sid = session_id.unwrap_or(request_id).to_string();
508 let history = self.load_session_history(&sid).await;
509 let ctx = oxios_ouroboros::MsgCtx {
510 session_id: sid.clone(),
511 history,
512 project_ids: project_ids.map(String::from),
513 mount_ids: mount_ids.map(String::from),
514 role: role.map(String::from),
515 model_override: model_override.map(String::from),
516 user_id: user_id.to_string(),
517 };
518
519 let start = std::time::Instant::now();
521 let response = self.handle(engine.as_ref(), msg, &ctx).await?;
522 let duration_ms = start.elapsed().as_millis() as u64;
523
524 Ok(self.handle_response_to_orchestration_result(response, &ctx, duration_ms))
525 }
526
527 async fn load_session_history(&self, session_id: &str) -> Vec<oxios_ouroboros::Exchange> {
529 let sid = crate::state_store::SessionId(session_id.to_string());
530 match self.state_store.load_session(&sid).await {
531 Ok(Some(session)) => session
532 .user_messages
533 .iter()
534 .zip(session.agent_responses.iter())
535 .map(|(u, a)| oxios_ouroboros::Exchange {
536 user: u.content.clone(),
537 agent: a.content.clone(),
538 })
539 .collect(),
540 _ => Vec::new(),
541 }
542 }
543
544 fn handle_response_to_orchestration_result(
545 &self,
546 response: HandleResponse,
547 ctx: &oxios_ouroboros::MsgCtx,
548 duration_ms: u64,
549 ) -> OrchestrationResult {
550 let metrics = get_metrics();
551 metrics.orch_duration.observe(duration_ms as f64 / 1000.0);
552
553 let HandleResponse {
554 directive,
555 env,
556 result,
557 verdict,
558 evaluation_passed,
559 } = response;
560
561 let failure_class: Option<oxios_ouroboros::FailureClass> = result.failure_class;
565 let response_text = if !result.success && result.output.trim().is_empty() {
566 failure_class_to_user_message(failure_class.as_ref())
567 } else if directive.acceptance_criteria.is_empty() {
568 result.output.clone()
569 } else {
570 match &verdict {
571 Some(v) if v.all_passed() => result.output.clone(),
572 Some(v) => format!(
573 "{}\n\n⚠ Review notes:\n{}",
574 result.output,
575 v.notes.join("\n")
576 ),
577 None => result.output.clone(),
578 }
579 };
580 if evaluation_passed.unwrap_or(false) {
581 metrics.agents_completed.inc();
582 } else {
583 metrics.agents_failed.inc();
584 }
585 OrchestrationResult {
586 session_id: Some(ctx.session_id.clone()),
587 primary_project_id: env.project_id,
588 project_tag: None,
589 active_mount_ids: Vec::new(),
590 mount_tag: None,
591 response: response_text,
592 agent_id: None,
593 phase_reached: "execute".to_string(),
594 evaluation_passed,
595 output: Some(result.output.clone()),
596 tool_calls: result.tool_calls.clone(),
597 failure_class,
598 interview_questions: None,
599 interview_round: None,
600 reasoning_text: result.reasoning_text.clone(),
601 }
602 }
603 fn resolve_exec_env(
609 &self,
610 ctx: &oxios_ouroboros::MsgCtx,
611 msg: &str,
612 ) -> oxios_ouroboros::ExecEnv {
613 let (active_mount_ids, workspace_context, mount_paths, _mount_tag) =
614 self.resolve_mount_workspace(ctx.mount_ids.as_deref(), ctx.project_ids.as_deref(), msg);
615 let _ = active_mount_ids;
619
620 let project_id = ctx
623 .project_ids
624 .as_deref()
625 .and_then(|ids| {
626 ids.split(',')
627 .next()
628 .and_then(|s| Uuid::parse_str(s.trim()).ok())
629 })
630 .or_else(|| {
631 self.detect_project_tag(msg).and_then(|_tag| {
632 self.project_manager().and_then(|pm| {
633 let projects = pm.list_projects();
634 match crate::project::detect_project(msg, &projects) {
635 crate::project::DetectionResult::Found(id) => Some(id),
636 crate::project::DetectionResult::NoMatch { .. } => None,
637 }
638 })
639 })
640 });
641
642 if let Some(pid) = project_id
644 && let Some(pm) = self.project_manager()
645 {
646 pm.touch(pid);
647 }
648
649 oxios_ouroboros::ExecEnv {
650 workspace_context,
651 mount_paths,
652 project_id,
653 cspace_hint: None,
654 model_override: ctx.model_override.clone(),
655 role: ctx.role.clone(),
656 restore_state: None,
657 session_id: Some(ctx.session_id.clone()),
658 }
659 }
660
661 async fn execute_directive(
664 &self,
665 directive: &oxios_ouroboros::Directive,
666 env: &oxios_ouroboros::ExecEnv,
667 ) -> Result<ExecutionResult> {
668 let coordinator = self.recovery.read().as_ref().cloned();
676 if let Some(coordinator) = coordinator {
677 coordinator.execute(&self.lifecycle, directive, env).await
678 } else {
679 self.lifecycle.execute_directive(directive, env).await
680 }
681 }
682
683 async fn verify_or_retry(
695 &self,
696 engine: &dyn oxios_ouroboros::IntentEngineOps,
697 directive: &mut oxios_ouroboros::Directive,
698 env: &oxios_ouroboros::ExecEnv,
699 initial_result: ExecutionResult,
700 _msg: &str,
701 _ctx: &oxios_ouroboros::MsgCtx,
702 ) -> Result<(ExecutionResult, oxios_ouroboros::Verdict)> {
703 let verdict = engine.review(directive, &initial_result).await?;
704
705 if verdict.all_passed() || verdict.gaps.is_empty() {
706 return Ok((initial_result, verdict));
707 }
708
709 let enable_retry = self.intent_config.read().enable_retry;
712 if !enable_retry {
713 tracing::info!("Review failed but retry disabled (enable_retry=false)");
714 return Ok((initial_result, verdict));
715 }
716
717 let metrics = get_metrics();
718 metrics.retry_attempted.inc();
719
720 tracing::info!(
721 gaps = verdict.gaps.len(),
722 "Review failed — retrying with feedback"
723 );
724
725 let retry_result = self
727 .lifecycle
728 .execute_with_feedback(directive, env, &initial_result, &verdict.gaps)
729 .await?;
730
731 let retry_verdict = engine.review(directive, &retry_result).await?;
733
734 if retry_verdict.score > verdict.score {
736 metrics.retry_improved.inc();
737 } else if retry_verdict.score < verdict.score {
738 metrics.retry_degraded.inc();
739 } else {
740 metrics.retry_unchanged.inc();
741 }
742
743 let chosen_result = if retry_verdict.score >= verdict.score {
745 retry_result
746 } else {
747 initial_result
748 };
749
750 Ok((chosen_result, retry_verdict))
751 }
752}
753
754#[derive(Debug, Clone)]
762pub struct HandleResponse {
763 pub directive: Box<oxios_ouroboros::Directive>,
765 pub env: Box<oxios_ouroboros::ExecEnv>,
767 pub result: Box<ExecutionResult>,
769 pub verdict: Option<oxios_ouroboros::Verdict>,
771 pub evaluation_passed: Option<bool>,
773}
774
775#[derive(Debug, Clone, Serialize, Deserialize)]
777pub struct OrchestrationResult {
778 #[serde(skip_serializing_if = "Option::is_none")]
780 pub session_id: Option<String>,
781 #[serde(skip_serializing_if = "Option::is_none")]
783 pub primary_project_id: Option<Uuid>,
784 #[serde(skip_serializing_if = "Option::is_none")]
786 pub project_tag: Option<String>,
787 #[serde(default, skip_serializing_if = "Vec::is_empty")]
789 pub active_mount_ids: Vec<MountId>,
790 #[serde(skip_serializing_if = "Option::is_none")]
792 pub mount_tag: Option<String>,
793 pub response: String,
795 #[serde(skip_serializing_if = "Option::is_none")]
797 pub agent_id: Option<AgentId>,
798 pub phase_reached: String,
800 pub evaluation_passed: Option<bool>,
806 #[serde(skip_serializing_if = "Option::is_none")]
808 pub output: Option<String>,
809 #[serde(default, skip_serializing_if = "Vec::is_empty")]
811 pub tool_calls: Vec<oxios_ouroboros::ToolCallRecord>,
812 #[serde(default, skip_serializing_if = "Option::is_none")]
820 pub interview_questions: Option<Vec<oxios_ouroboros::InterviewQuestionOutput>>,
821 #[serde(default, skip_serializing_if = "Option::is_none")]
824 pub interview_round: Option<u32>,
825
826 #[serde(default, skip_serializing_if = "String::is_empty")]
831 pub reasoning_text: String,
832 #[serde(default, skip_serializing_if = "Option::is_none")]
836 pub failure_class: Option<oxios_ouroboros::FailureClass>,
837}
838fn failure_class_to_user_message(class: Option<&oxios_ouroboros::FailureClass>) -> String {
841 use oxios_ouroboros::FailureClass;
842 match class {
843 Some(FailureClass::BudgetExceeded) => {
844 "\u{26a0}\u{fe0f} Token budget exceeded for this provider. \
845 Try selecting a different model or configuring additional providers \
846 in Settings \u{2192} Engine."
847 .to_string()
848 }
849 Some(FailureClass::QuotaExhausted) => "\u{26a0}\u{fe0f} Provider quota exhausted. \
850 The selected provider has reached its rate or usage limit. \
851 Wait a moment and retry, or switch to a different model."
852 .to_string(),
853 Some(FailureClass::AuthFailure) => "\u{26a0}\u{fe0f} Authentication failed. \
854 Your API key for this provider may be invalid or expired. \
855 Check your credentials in Settings \u{2192} Engine."
856 .to_string(),
857 Some(FailureClass::ModelUnavailable) => "\u{26a0}\u{fe0f} Model unavailable. \
858 The selected model is no longer available or was not found. \
859 Choose a different model in Settings \u{2192} Engine."
860 .to_string(),
861 Some(FailureClass::ContextOverflow) => "\u{26a0}\u{fe0f} Context window exceeded. \
862 The conversation is too long for this model's context limit. \
863 Start a new session or switch to a model with a larger context window."
864 .to_string(),
865 Some(FailureClass::Transient) => {
866 "\u{26a0}\u{fe0f} A temporary error occurred while contacting the provider. \
867 The system will retry automatically. If the issue persists, \
868 try a different model or check your network connection."
869 .to_string()
870 }
871 Some(FailureClass::Unknown) | None => {
872 "\u{26a0}\u{fe0f} An unexpected error occurred during execution. \
873 Please try again. If the problem persists, check your provider \
874 configuration in Settings \u{2192} Engine."
875 .to_string()
876 }
877 }
878}
879
880fn build_workspace_context_body(mounts: &[crate::mount::Mount]) -> Option<String> {
889 if mounts.is_empty() {
890 return None;
891 }
892 let mut out = String::new();
893 out.push_str("### Active Mounts\n");
894
895 for (i, m) in mounts.iter().enumerate() {
896 let primary = i == 0;
897 let path = m
898 .primary_path()
899 .map(|p| p.to_string_lossy().to_string())
900 .unwrap_or_else(|| "(no path)".to_string());
901
902 if primary {
903 out.push_str(&format!("- **{}** → {}\n", m.name, path));
904 if !m.auto_description.is_empty() {
905 let desc: String = m
907 .auto_description
908 .lines()
909 .take(3)
910 .collect::<Vec<_>>()
911 .join("\n ");
912 out.push_str(&format!(" {}\n", desc));
913 }
914 let summary = m.summary_line();
915 if !summary.is_empty() {
916 out.push_str(&format!(" _{}_\n", summary));
917 }
918 if m.enrichment_pending {
919 out.push_str(" _(content changed — consider re-scanning this Mount)_\n");
920 }
921 } else {
922 let summary = m.summary_line();
924 let suffix = if summary.is_empty() {
925 String::new()
926 } else {
927 format!(" — {}", summary)
928 };
929 out.push_str(&format!("- **{}** → {}{}\n", m.name, path, suffix));
930 }
931 }
932
933 Some(out)
934}
935
936#[cfg(test)]
937mod mount_workspace_tests {
938 use super::*;
939 use crate::mount::{Mount, MountSource};
940 use std::path::PathBuf;
941
942 #[test]
943 fn test_workspace_context_primary_full_secondary_terse() {
944 let mut oxios =
945 Mount::from_name_and_path("oxios", PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
946 oxios.auto_description = "Agent OS.\nRust + tokio.".to_string();
947 oxios.auto_meta.summary = "Rust agent OS".to_string();
948
949 let mut oxi = Mount::from_name_and_path("oxi", PathBuf::from("/oxi"));
950 oxi.auto_meta.summary = "SDK".to_string();
951
952 let body = build_workspace_context_body(&[oxios, oxi]).unwrap();
953 assert!(body.contains("### Active Mounts"));
954 assert!(body.contains("Agent OS."));
956 assert!(body.contains("_Rust agent OS_"));
957 assert!(body.contains("**oxi** → /oxi — SDK"));
959 }
960
961 #[test]
962 fn test_workspace_context_empty_is_none() {
963 assert!(build_workspace_context_body(&[]).is_none());
964 }
965
966 #[test]
970 fn test_resolve_mount_workspace_detects_and_collects_paths() {
971 use crate::mount::MountManager;
972 use oxios_memory::memory::sqlite::MemoryDatabase;
973 use std::sync::Arc;
974
975 let db = Arc::new(MemoryDatabase::open_in_memory(64).unwrap());
976 let mm = Arc::new(MountManager::new(db, None).unwrap());
977
978 let oxios = mm
980 .create_mount(
981 "oxios".to_string(),
982 vec![PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios")],
983 MountSource::Manual,
984 )
985 .unwrap();
986 let oxi_sdk = mm
987 .create_mount(
988 "oxi-sdk".to_string(),
989 vec![PathBuf::from("/Users/me/oxi")],
990 MountSource::Manual,
991 )
992 .unwrap();
993 mm.update_enrichment(oxios.id, Some("Agent OS in Rust.".to_string()), None)
994 .unwrap();
995
996 let mounts = mm.get_mounts_ordered(&[oxios.id, oxi_sdk.id]);
1000 assert_eq!(mounts.len(), 2);
1001
1002 let body = build_workspace_context_body(&mounts).unwrap();
1003 assert!(body.contains("oxios"));
1004 assert!(body.contains("Agent OS in Rust."));
1005 assert!(body.contains("oxi-sdk"));
1006
1007 let mut paths = Vec::new();
1009 for m in &mounts {
1010 for p in &m.paths {
1011 if !paths.contains(p) {
1012 paths.push(p.clone());
1013 }
1014 }
1015 }
1016 assert_eq!(paths.len(), 2);
1017 assert_eq!(paths[0], PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
1018 assert_eq!(paths[1], PathBuf::from("/Users/me/oxi"));
1019 }
1020
1021 #[test]
1024 fn test_detection_seeds_primary_on_name_mention() {
1025 use crate::mount::{DetectionResult, detect_mounts};
1026
1027 let oxios =
1028 Mount::from_name_and_path("oxios", PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
1029 let result = detect_mounts("oxios 코드리뷰해줘", std::slice::from_ref(&oxios));
1030 assert!(matches!(result, DetectionResult::Found(id) if id == oxios.id));
1031 }
1032}