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_intent_config(&self, cfg: crate::config::IntentConfig) {
190 *self.intent_config.write() = cfg;
191 }
192
193 pub fn set_recovery(&self, coordinator: Arc<crate::resilience::RecoveryCoordinator>) {
197 *self.recovery.write() = Some(coordinator);
198 }
199
200 pub fn has_intent_engine(&self) -> bool {
202 self.intent_engine.read().is_some()
203 }
204
205 pub fn set_project_manager(&self, manager: Arc<ProjectManager>) {
207 *self.project_manager.write() = Some(manager);
208 }
209
210 pub fn set_mount_manager(&self, manager: Arc<MountManager>) {
212 *self.mount_manager.write() = Some(manager);
213 }
214
215 pub fn mount_manager(&self) -> Option<Arc<MountManager>> {
217 self.mount_manager.read().as_ref().cloned()
218 }
219
220 pub fn project_manager(&self) -> Option<Arc<ProjectManager>> {
222 self.project_manager.read().as_ref().cloned()
223 }
224
225 pub fn detect_project_tag(&self, message: &str) -> Option<String> {
227 self.project_manager.read().as_ref().and_then(|pm| {
228 let projects = pm.list_projects();
229 let result = crate::project::detect_project(message, &projects);
230 match result {
231 crate::project::DetectionResult::Found(id) => pm.get_project(id).map(|p| p.tag()),
232 crate::project::DetectionResult::NoMatch { .. } => None,
233 }
234 })
235 }
236
237 fn resolve_mount_workspace(
251 &self,
252 mount_ids: Option<&str>,
253 project_ids: Option<&str>,
254 user_message: &str,
255 ) -> (
256 Vec<MountId>,
257 Option<String>,
258 Vec<std::path::PathBuf>,
259 String,
260 ) {
261 use crate::mount::Mount;
262
263 let Some(mm) = self.mount_manager() else {
264 return (Vec::new(), None, Vec::new(), String::new());
265 };
266
267 let mut ids: Vec<MountId> = if let Some(ids_str) = mount_ids {
269 ids_str
270 .split(',')
271 .filter_map(|s| MountId::parse_str(s.trim()).ok())
272 .collect()
273 } else {
274 match mm.detect(user_message) {
275 crate::mount::DetectionResult::Found(id) => vec![id],
276 crate::mount::DetectionResult::NoMatch { .. } => vec![],
277 }
278 };
279 let mut seen = std::collections::HashSet::new();
281 ids.retain(|id| seen.insert(*id));
282
283 let project_for_instructions: Option<crate::project::Project> = if let Some(project_ids_str) =
290 project_ids
291 && let Some(first_id_str) = project_ids_str.split(',').next()
292 && let Some(pm) = self.project_manager()
293 && let Ok(pid) = Uuid::parse_str(first_id_str.trim())
294 {
295 let proj = pm.get_project(pid);
296 if let Some(ref project) = proj {
297 for mid in &project.mount_ids {
298 if !ids.contains(mid) {
299 ids.push(*mid);
300 }
301 }
302 }
303 proj
304 } else {
305 None
306 };
307
308 if ids.is_empty() {
309 return (Vec::new(), None, Vec::new(), String::new());
310 }
311
312 for id in &ids {
315 mm.touch(*id);
316 }
317
318 let mounts: Vec<Mount> = mm.get_mounts_ordered(&ids);
319 if mounts.is_empty() {
320 return (Vec::new(), None, Vec::new(), String::new());
321 }
322
323 let mut paths: Vec<std::path::PathBuf> = Vec::new();
325 for m in &mounts {
326 for p in &m.paths {
327 if !paths.contains(p) {
328 paths.push(p.clone());
329 }
330 }
331 }
332
333 let tag = if mounts.len() == 1 {
335 mounts[0].tag()
336 } else {
337 let names: Vec<&str> = mounts.iter().map(|m| m.name.as_str()).collect();
338 format!("[🔧 {}]", names.join(" + "))
339 };
340
341 let mut context = build_workspace_context_body(&mounts).unwrap_or_default();
342
343 if let Some(project) = project_for_instructions {
349 let instructions = if project.instructions.len() > 2000 {
351 let mut end = 2000;
352 while end > 0 && !project.instructions.is_char_boundary(end) {
353 end -= 1;
354 }
355 format!("{}...", &project.instructions[..end])
356 } else {
357 project.instructions.clone()
358 };
359 if !instructions.is_empty() {
360 context.push_str(&format!(
361 "\n### Project Instructions: {}\n{}\n",
362 project.name, instructions
363 ));
364 }
365 }
366
367 const MAX_CONTEXT_CHARS: usize = 6000;
369 if context.len() > MAX_CONTEXT_CHARS {
370 let mut end = MAX_CONTEXT_CHARS;
371 while end > 0 && !context.is_char_boundary(end) {
372 end -= 1;
373 }
374 context.truncate(end);
375 context.push_str("\n...(context truncated)...\n");
376 }
377
378 let context_opt = if context.is_empty() {
379 None
380 } else {
381 Some(context)
382 };
383 (ids, context_opt, paths, tag)
384 }
385
386 pub fn set_a2a(&mut self, a2a: Arc<crate::a2a::A2AProtocol>) {
388 self.a2a = Some(a2a);
389 }
390
391 pub fn set_git_layer(&mut self, git_layer: Arc<GitLayer>) {
393 self.git_layer = Some(git_layer);
394 }
395
396 pub async fn restore_sessions(&self) {
402 }
404
405 #[allow(dead_code)]
406 fn git_commit(&self, rel_path: &str, message: &str) {
407 if let Some(ref gl) = self.git_layer
408 && gl.is_enabled()
409 {
410 let _ = gl.commit_file(rel_path, message);
411 }
412 }
413
414 pub async fn handle(
450 &self,
451 engine: &dyn oxios_ouroboros::IntentEngineOps,
452 msg: &str,
453 ctx: &oxios_ouroboros::MsgCtx,
454 ) -> Result<HandleResponse> {
455 let mut directive = oxios_ouroboros::Directive::from_message(msg);
457
458 let env = self.resolve_exec_env(ctx, msg);
460
461 let mut result = self.execute_directive(&directive, &env).await?;
463
464 let (verdict, evaluation_passed) = if directive.needs_review() {
469 let (r, v) = self
470 .verify_or_retry(engine, &mut directive, &env, result, msg, ctx)
471 .await?;
472 result = r;
473 let passed = v.all_passed();
474 (Some(v), Some(passed))
475 } else {
476 (None, None)
477 };
478
479 Ok(HandleResponse {
480 directive: Box::new(directive),
481 env: Box::new(env),
482 result: Box::new(result),
483 verdict,
484 evaluation_passed,
485 })
486 }
487
488 #[allow(clippy::too_many_arguments)]
495 pub async fn handle_unified(
496 &self,
497 user_id: &str,
498 msg: &str,
499 session_id: Option<&str>,
500 project_ids: Option<&str>,
501 mount_ids: Option<&str>,
502 role: Option<&str>,
503 model_override: Option<&str>,
504 model_params: Option<oxios_ouroboros::ModelParams>,
505 request_id: &str,
506 ) -> Result<OrchestrationResult> {
507 let engine = self
509 .intent_engine
510 .read()
511 .clone()
512 .expect("IntentEngine not wired — kernel assembler bug");
513
514 let sid = session_id.unwrap_or(request_id).to_string();
516 let history = self.load_session_history(&sid).await;
517 let ctx = oxios_ouroboros::MsgCtx {
518 session_id: sid.clone(),
519 history,
520 project_ids: project_ids.map(String::from),
521 mount_ids: mount_ids.map(String::from),
522 role: role.map(String::from),
523 model_override: model_override.map(String::from),
524 user_id: user_id.to_string(),
525 model_params,
526 };
527
528 let start = std::time::Instant::now();
530 let response = self.handle(engine.as_ref(), msg, &ctx).await?;
531 let duration_ms = start.elapsed().as_millis() as u64;
532
533 Ok(self.handle_response_to_orchestration_result(response, &ctx, duration_ms))
534 }
535
536 async fn load_session_history(&self, session_id: &str) -> Vec<oxios_ouroboros::Exchange> {
538 let sid = crate::state_store::SessionId(session_id.to_string());
539 match self.state_store.load_session(&sid).await {
540 Ok(Some(session)) => session
541 .user_messages
542 .iter()
543 .zip(session.agent_responses.iter())
544 .map(|(u, a)| oxios_ouroboros::Exchange {
545 user: u.content.clone(),
546 agent: a.content.clone(),
547 })
548 .collect(),
549 _ => Vec::new(),
550 }
551 }
552
553 fn handle_response_to_orchestration_result(
554 &self,
555 response: HandleResponse,
556 ctx: &oxios_ouroboros::MsgCtx,
557 duration_ms: u64,
558 ) -> OrchestrationResult {
559 let metrics = get_metrics();
560 metrics.orch_duration.observe(duration_ms as f64 / 1000.0);
561
562 let HandleResponse {
563 directive,
564 env,
565 result,
566 verdict,
567 evaluation_passed,
568 } = response;
569
570 let failure_class: Option<oxios_ouroboros::FailureClass> = result.failure_class;
574 let response_text = if !result.success && result.output.trim().is_empty() {
575 failure_class_to_user_message(failure_class.as_ref())
576 } else if directive.acceptance_criteria.is_empty() {
577 result.output.clone()
578 } else {
579 match &verdict {
580 Some(v) if v.all_passed() => result.output.clone(),
581 Some(v) => format!(
582 "{}\n\n⚠ Review notes:\n{}",
583 result.output,
584 v.notes.join("\n")
585 ),
586 None => result.output.clone(),
587 }
588 };
589 if evaluation_passed.unwrap_or(false) {
590 metrics.agents_completed.inc();
591 } else {
592 metrics.agents_failed.inc();
593 }
594 OrchestrationResult {
595 session_id: Some(ctx.session_id.clone()),
596 primary_project_id: env.project_id,
597 project_tag: None,
598 active_mount_ids: Vec::new(),
599 mount_tag: None,
600 response: response_text,
601 agent_id: None,
602 phase_reached: "execute".to_string(),
603 evaluation_passed,
604 output: Some(result.output.clone()),
605 tool_calls: result.tool_calls.clone(),
606 failure_class,
607 interview_questions: None,
608 interview_round: None,
609 reasoning_text: result.reasoning_text.clone(),
610 }
611 }
612 fn resolve_exec_env(
618 &self,
619 ctx: &oxios_ouroboros::MsgCtx,
620 msg: &str,
621 ) -> oxios_ouroboros::ExecEnv {
622 let (active_mount_ids, workspace_context, mount_paths, _mount_tag) =
623 self.resolve_mount_workspace(ctx.mount_ids.as_deref(), ctx.project_ids.as_deref(), msg);
624 let _ = active_mount_ids;
628
629 let project_id = ctx
632 .project_ids
633 .as_deref()
634 .and_then(|ids| {
635 ids.split(',')
636 .next()
637 .and_then(|s| Uuid::parse_str(s.trim()).ok())
638 })
639 .or_else(|| {
640 self.detect_project_tag(msg).and_then(|_tag| {
641 self.project_manager().and_then(|pm| {
642 let projects = pm.list_projects();
643 match crate::project::detect_project(msg, &projects) {
644 crate::project::DetectionResult::Found(id) => Some(id),
645 crate::project::DetectionResult::NoMatch { .. } => None,
646 }
647 })
648 })
649 });
650
651 if let Some(pid) = project_id
653 && let Some(pm) = self.project_manager()
654 {
655 pm.touch(pid);
656 }
657
658 oxios_ouroboros::ExecEnv {
659 workspace_context,
660 mount_paths,
661 project_id,
662 cspace_hint: None,
663 model_override: ctx.model_override.clone(),
664 role: ctx.role.clone(),
665 restore_state: None,
666 session_id: Some(ctx.session_id.clone()),
667 model_params: ctx.model_params.clone(),
668 }
669 }
670
671 async fn execute_directive(
674 &self,
675 directive: &oxios_ouroboros::Directive,
676 env: &oxios_ouroboros::ExecEnv,
677 ) -> Result<ExecutionResult> {
678 let coordinator = self.recovery.read().as_ref().cloned();
686 if let Some(coordinator) = coordinator {
687 coordinator.execute(&self.lifecycle, directive, env).await
688 } else {
689 self.lifecycle.execute_directive(directive, env).await
690 }
691 }
692
693 async fn verify_or_retry(
705 &self,
706 engine: &dyn oxios_ouroboros::IntentEngineOps,
707 directive: &mut oxios_ouroboros::Directive,
708 env: &oxios_ouroboros::ExecEnv,
709 initial_result: ExecutionResult,
710 _msg: &str,
711 _ctx: &oxios_ouroboros::MsgCtx,
712 ) -> Result<(ExecutionResult, oxios_ouroboros::Verdict)> {
713 let verdict = engine.review(directive, &initial_result).await?;
714
715 if verdict.all_passed() || verdict.gaps.is_empty() {
716 return Ok((initial_result, verdict));
717 }
718
719 let enable_retry = self.intent_config.read().enable_retry;
722 if !enable_retry {
723 tracing::info!("Review failed but retry disabled (enable_retry=false)");
724 return Ok((initial_result, verdict));
725 }
726
727 let metrics = get_metrics();
728 metrics.retry_attempted.inc();
729
730 tracing::info!(
731 gaps = verdict.gaps.len(),
732 "Review failed — retrying with feedback"
733 );
734
735 let retry_result = self
737 .lifecycle
738 .execute_with_feedback(directive, env, &initial_result, &verdict.gaps)
739 .await?;
740
741 let retry_verdict = engine.review(directive, &retry_result).await?;
743
744 if retry_verdict.score > verdict.score {
746 metrics.retry_improved.inc();
747 } else if retry_verdict.score < verdict.score {
748 metrics.retry_degraded.inc();
749 } else {
750 metrics.retry_unchanged.inc();
751 }
752
753 let chosen_result = if retry_verdict.score >= verdict.score {
755 retry_result
756 } else {
757 initial_result
758 };
759
760 Ok((chosen_result, retry_verdict))
761 }
762}
763
764#[derive(Debug, Clone)]
772pub struct HandleResponse {
773 pub directive: Box<oxios_ouroboros::Directive>,
775 pub env: Box<oxios_ouroboros::ExecEnv>,
777 pub result: Box<ExecutionResult>,
779 pub verdict: Option<oxios_ouroboros::Verdict>,
781 pub evaluation_passed: Option<bool>,
783}
784
785#[derive(Debug, Clone, Serialize, Deserialize)]
787pub struct OrchestrationResult {
788 #[serde(skip_serializing_if = "Option::is_none")]
790 pub session_id: Option<String>,
791 #[serde(skip_serializing_if = "Option::is_none")]
793 pub primary_project_id: Option<Uuid>,
794 #[serde(skip_serializing_if = "Option::is_none")]
796 pub project_tag: Option<String>,
797 #[serde(default, skip_serializing_if = "Vec::is_empty")]
799 pub active_mount_ids: Vec<MountId>,
800 #[serde(skip_serializing_if = "Option::is_none")]
802 pub mount_tag: Option<String>,
803 pub response: String,
805 #[serde(skip_serializing_if = "Option::is_none")]
807 pub agent_id: Option<AgentId>,
808 pub phase_reached: String,
810 pub evaluation_passed: Option<bool>,
816 #[serde(skip_serializing_if = "Option::is_none")]
818 pub output: Option<String>,
819 #[serde(default, skip_serializing_if = "Vec::is_empty")]
821 pub tool_calls: Vec<oxios_ouroboros::ToolCallRecord>,
822 #[serde(default, skip_serializing_if = "Option::is_none")]
830 pub interview_questions: Option<Vec<oxios_ouroboros::InterviewQuestionOutput>>,
831 #[serde(default, skip_serializing_if = "Option::is_none")]
834 pub interview_round: Option<u32>,
835
836 #[serde(default, skip_serializing_if = "String::is_empty")]
841 pub reasoning_text: String,
842 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub failure_class: Option<oxios_ouroboros::FailureClass>,
847}
848fn failure_class_to_user_message(class: Option<&oxios_ouroboros::FailureClass>) -> String {
851 use oxios_ouroboros::FailureClass;
852 match class {
853 Some(FailureClass::BudgetExceeded) => {
854 "\u{26a0}\u{fe0f} Token budget exceeded for this provider. \
855 Try selecting a different model or configuring additional providers \
856 in Settings \u{2192} Engine."
857 .to_string()
858 }
859 Some(FailureClass::QuotaExhausted) => "\u{26a0}\u{fe0f} Provider quota exhausted. \
860 The selected provider has reached its rate or usage limit. \
861 Wait a moment and retry, or switch to a different model."
862 .to_string(),
863 Some(FailureClass::AuthFailure) => "\u{26a0}\u{fe0f} Authentication failed. \
864 Your API key for this provider may be invalid or expired. \
865 Check your credentials in Settings \u{2192} Engine."
866 .to_string(),
867 Some(FailureClass::ModelUnavailable) => "\u{26a0}\u{fe0f} Model unavailable. \
868 The selected model is no longer available or was not found. \
869 Choose a different model in Settings \u{2192} Engine."
870 .to_string(),
871 Some(FailureClass::ContextOverflow) => "\u{26a0}\u{fe0f} Context window exceeded. \
872 The conversation is too long for this model's context limit. \
873 Start a new session or switch to a model with a larger context window."
874 .to_string(),
875 Some(FailureClass::Transient) => {
876 "\u{26a0}\u{fe0f} A temporary error occurred while contacting the provider. \
877 The system will retry automatically. If the issue persists, \
878 try a different model or check your network connection."
879 .to_string()
880 }
881 Some(FailureClass::Unknown) | None => {
882 "\u{26a0}\u{fe0f} An unexpected error occurred during execution. \
883 Please try again. If the problem persists, check your provider \
884 configuration in Settings \u{2192} Engine."
885 .to_string()
886 }
887 }
888}
889
890fn build_workspace_context_body(mounts: &[crate::mount::Mount]) -> Option<String> {
899 if mounts.is_empty() {
900 return None;
901 }
902 let mut out = String::new();
903 out.push_str("### Active Mounts\n");
904
905 for (i, m) in mounts.iter().enumerate() {
906 let primary = i == 0;
907 let path = m
908 .primary_path()
909 .map(|p| p.to_string_lossy().to_string())
910 .unwrap_or_else(|| "(no path)".to_string());
911
912 if primary {
913 out.push_str(&format!("- **{}** → {}\n", m.name, path));
914 if !m.auto_description.is_empty() {
915 let desc: String = m
917 .auto_description
918 .lines()
919 .take(3)
920 .collect::<Vec<_>>()
921 .join("\n ");
922 out.push_str(&format!(" {}\n", desc));
923 }
924 let summary = m.summary_line();
925 if !summary.is_empty() {
926 out.push_str(&format!(" _{}_\n", summary));
927 }
928 if m.enrichment_pending {
929 out.push_str(" _(content changed — consider re-scanning this Mount)_\n");
930 }
931 } else {
932 let summary = m.summary_line();
934 let suffix = if summary.is_empty() {
935 String::new()
936 } else {
937 format!(" — {}", summary)
938 };
939 out.push_str(&format!("- **{}** → {}{}\n", m.name, path, suffix));
940 }
941 }
942
943 Some(out)
944}
945
946#[cfg(test)]
947mod mount_workspace_tests {
948 use super::*;
949 use crate::mount::{Mount, MountSource};
950 use std::path::PathBuf;
951
952 #[test]
953 fn test_workspace_context_primary_full_secondary_terse() {
954 let mut oxios =
955 Mount::from_name_and_path("oxios", PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
956 oxios.auto_description = "Agent OS.\nRust + tokio.".to_string();
957 oxios.auto_meta.summary = "Rust agent OS".to_string();
958
959 let mut oxi = Mount::from_name_and_path("oxi", PathBuf::from("/oxi"));
960 oxi.auto_meta.summary = "SDK".to_string();
961
962 let body = build_workspace_context_body(&[oxios, oxi]).unwrap();
963 assert!(body.contains("### Active Mounts"));
964 assert!(body.contains("Agent OS."));
966 assert!(body.contains("_Rust agent OS_"));
967 assert!(body.contains("**oxi** → /oxi — SDK"));
969 }
970
971 #[test]
972 fn test_workspace_context_empty_is_none() {
973 assert!(build_workspace_context_body(&[]).is_none());
974 }
975
976 #[test]
980 fn test_resolve_mount_workspace_detects_and_collects_paths() {
981 use crate::mount::MountManager;
982 use oxios_memory::memory::sqlite::MemoryDatabase;
983 use std::sync::Arc;
984
985 let db = Arc::new(MemoryDatabase::open_in_memory(64).unwrap());
986 let mm = Arc::new(MountManager::new(db, None).unwrap());
987
988 let oxios = mm
990 .create_mount(
991 "oxios".to_string(),
992 vec![PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios")],
993 MountSource::Manual,
994 )
995 .unwrap();
996 let oxi_sdk = mm
997 .create_mount(
998 "oxi-sdk".to_string(),
999 vec![PathBuf::from("/Users/me/oxi")],
1000 MountSource::Manual,
1001 )
1002 .unwrap();
1003 mm.update_enrichment(oxios.id, Some("Agent OS in Rust.".to_string()), None)
1004 .unwrap();
1005
1006 let mounts = mm.get_mounts_ordered(&[oxios.id, oxi_sdk.id]);
1010 assert_eq!(mounts.len(), 2);
1011
1012 let body = build_workspace_context_body(&mounts).unwrap();
1013 assert!(body.contains("oxios"));
1014 assert!(body.contains("Agent OS in Rust."));
1015 assert!(body.contains("oxi-sdk"));
1016
1017 let mut paths = Vec::new();
1019 for m in &mounts {
1020 for p in &m.paths {
1021 if !paths.contains(p) {
1022 paths.push(p.clone());
1023 }
1024 }
1025 }
1026 assert_eq!(paths.len(), 2);
1027 assert_eq!(paths[0], PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
1028 assert_eq!(paths[1], PathBuf::from("/Users/me/oxi"));
1029 }
1030
1031 #[test]
1034 fn test_detection_seeds_primary_on_name_mention() {
1035 use crate::mount::{DetectionResult, detect_mounts};
1036
1037 let oxios =
1038 Mount::from_name_and_path("oxios", PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
1039 let result = detect_mounts("oxios 코드리뷰해줘", std::slice::from_ref(&oxios));
1040 assert!(matches!(result, DetectionResult::Found(id) if id == oxios.id));
1041 }
1042}