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, KernelEvent};
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 publish_phase = |phase: &'static str| {
449 let _ = self.event_bus.publish(KernelEvent::PhaseStarted {
450 session_id: ctx.session_id.clone(),
451 phase: phase.to_string(),
452 summary: None,
453 });
454 };
455 let complete_phase = |phase: &'static str| {
456 let _ = self.event_bus.publish(KernelEvent::PhaseCompleted {
457 session_id: ctx.session_id.clone(),
458 phase: phase.to_string(),
459 });
460 };
461
462 let mut directive = oxios_ouroboros::Directive::from_message(msg);
464
465 let env = self.resolve_exec_env(ctx, msg);
467
468 publish_phase("execute");
470 let mut result = self.execute_directive(&directive, &env).await?;
471 complete_phase("execute");
472
473 let (verdict, evaluation_passed) = if directive.needs_review() {
478 publish_phase("review");
479 let (r, v) = self
480 .verify_or_retry(engine, &mut directive, &env, result, msg, ctx)
481 .await?;
482 complete_phase("review");
483 result = r;
484 let passed = v.all_passed();
485 (Some(v), Some(passed))
486 } else {
487 (None, None)
488 };
489
490 Ok(HandleResponse {
491 directive: Box::new(directive),
492 env: Box::new(env),
493 result: Box::new(result),
494 verdict,
495 evaluation_passed,
496 })
497 }
498
499 #[allow(clippy::too_many_arguments)]
506 pub async fn handle_unified(
507 &self,
508 user_id: &str,
509 msg: &str,
510 session_id: Option<&str>,
511 project_ids: Option<&str>,
512 mount_ids: Option<&str>,
513 role: Option<&str>,
514 model_override: Option<&str>,
515 request_id: &str,
516 ) -> Result<OrchestrationResult> {
517 let engine = self
519 .intent_engine
520 .read()
521 .clone()
522 .expect("IntentEngine not wired — kernel assembler bug");
523
524 let sid = session_id.unwrap_or(request_id).to_string();
526 let history = self.load_session_history(&sid).await;
527 let ctx = oxios_ouroboros::MsgCtx {
528 session_id: sid.clone(),
529 history,
530 project_ids: project_ids.map(String::from),
531 mount_ids: mount_ids.map(String::from),
532 role: role.map(String::from),
533 model_override: model_override.map(String::from),
534 user_id: user_id.to_string(),
535 };
536
537 let start = std::time::Instant::now();
539 let response = self.handle(engine.as_ref(), msg, &ctx).await?;
540 let duration_ms = start.elapsed().as_millis() as u64;
541
542 Ok(self.handle_response_to_orchestration_result(response, &ctx, duration_ms))
543 }
544
545 async fn load_session_history(&self, session_id: &str) -> Vec<oxios_ouroboros::Exchange> {
547 let sid = crate::state_store::SessionId(session_id.to_string());
548 match self.state_store.load_session(&sid).await {
549 Ok(Some(session)) => session
550 .user_messages
551 .iter()
552 .zip(session.agent_responses.iter())
553 .map(|(u, a)| oxios_ouroboros::Exchange {
554 user: u.content.clone(),
555 agent: a.content.clone(),
556 })
557 .collect(),
558 _ => Vec::new(),
559 }
560 }
561
562 fn handle_response_to_orchestration_result(
563 &self,
564 response: HandleResponse,
565 ctx: &oxios_ouroboros::MsgCtx,
566 duration_ms: u64,
567 ) -> OrchestrationResult {
568 let metrics = get_metrics();
569 metrics.orch_duration.observe(duration_ms as f64 / 1000.0);
570
571 let HandleResponse {
572 directive,
573 env,
574 result,
575 verdict,
576 evaluation_passed,
577 } = response;
578
579 let failure_class: Option<oxios_ouroboros::FailureClass> = result.failure_class;
583 let response_text = if !result.success && result.output.trim().is_empty() {
584 failure_class_to_user_message(failure_class.as_ref())
585 } else if directive.acceptance_criteria.is_empty() {
586 result.output.clone()
587 } else {
588 match &verdict {
589 Some(v) if v.all_passed() => result.output.clone(),
590 Some(v) => format!(
591 "{}\n\n⚠ Review notes:\n{}",
592 result.output,
593 v.notes.join("\n")
594 ),
595 None => result.output.clone(),
596 }
597 };
598 if evaluation_passed.unwrap_or(false) {
599 metrics.agents_completed.inc();
600 } else {
601 metrics.agents_failed.inc();
602 }
603 OrchestrationResult {
604 session_id: Some(ctx.session_id.clone()),
605 primary_project_id: env.project_id,
606 project_tag: None,
607 active_mount_ids: Vec::new(),
608 mount_tag: None,
609 response: response_text,
610 agent_id: None,
611 phase_reached: "execute".to_string(),
612 evaluation_passed,
613 output: Some(result.output.clone()),
614 tool_calls: result.tool_calls.clone(),
615 failure_class,
616 interview_questions: None,
617 interview_round: None,
618 reasoning_text: result.reasoning_text.clone(),
619 }
620 }
621 fn resolve_exec_env(
627 &self,
628 ctx: &oxios_ouroboros::MsgCtx,
629 msg: &str,
630 ) -> oxios_ouroboros::ExecEnv {
631 let (active_mount_ids, workspace_context, mount_paths, _mount_tag) =
632 self.resolve_mount_workspace(ctx.mount_ids.as_deref(), ctx.project_ids.as_deref(), msg);
633 let _ = active_mount_ids;
637
638 let project_id = ctx
641 .project_ids
642 .as_deref()
643 .and_then(|ids| {
644 ids.split(',')
645 .next()
646 .and_then(|s| Uuid::parse_str(s.trim()).ok())
647 })
648 .or_else(|| {
649 self.detect_project_tag(msg).and_then(|_tag| {
650 self.project_manager().and_then(|pm| {
651 let projects = pm.list_projects();
652 match crate::project::detect_project(msg, &projects) {
653 crate::project::DetectionResult::Found(id) => Some(id),
654 crate::project::DetectionResult::NoMatch { .. } => None,
655 }
656 })
657 })
658 });
659
660 if let Some(pid) = project_id
662 && let Some(pm) = self.project_manager()
663 {
664 pm.touch(pid);
665 }
666
667 oxios_ouroboros::ExecEnv {
668 workspace_context,
669 mount_paths,
670 project_id,
671 cspace_hint: None,
672 model_override: ctx.model_override.clone(),
673 role: ctx.role.clone(),
674 restore_state: None,
675 session_id: Some(ctx.session_id.clone()),
676 }
677 }
678
679 async fn execute_directive(
682 &self,
683 directive: &oxios_ouroboros::Directive,
684 env: &oxios_ouroboros::ExecEnv,
685 ) -> Result<ExecutionResult> {
686 let coordinator = self.recovery.read().as_ref().cloned();
694 if let Some(coordinator) = coordinator {
695 coordinator.execute(&self.lifecycle, directive, env).await
696 } else {
697 self.lifecycle.execute_directive(directive, env).await
698 }
699 }
700
701 async fn verify_or_retry(
713 &self,
714 engine: &dyn oxios_ouroboros::IntentEngineOps,
715 directive: &mut oxios_ouroboros::Directive,
716 env: &oxios_ouroboros::ExecEnv,
717 initial_result: ExecutionResult,
718 _msg: &str,
719 _ctx: &oxios_ouroboros::MsgCtx,
720 ) -> Result<(ExecutionResult, oxios_ouroboros::Verdict)> {
721 let verdict = engine.review(directive, &initial_result).await?;
722
723 if verdict.all_passed() || verdict.gaps.is_empty() {
724 return Ok((initial_result, verdict));
725 }
726
727 let enable_retry = self.intent_config.read().enable_retry;
730 if !enable_retry {
731 tracing::info!("Review failed but retry disabled (enable_retry=false)");
732 return Ok((initial_result, verdict));
733 }
734
735 let metrics = get_metrics();
736 metrics.retry_attempted.inc();
737
738 tracing::info!(
739 gaps = verdict.gaps.len(),
740 "Review failed — retrying with feedback"
741 );
742
743 let retry_result = self
745 .lifecycle
746 .execute_with_feedback(directive, env, &initial_result, &verdict.gaps)
747 .await?;
748
749 let retry_verdict = engine.review(directive, &retry_result).await?;
751
752 if retry_verdict.score > verdict.score {
754 metrics.retry_improved.inc();
755 } else if retry_verdict.score < verdict.score {
756 metrics.retry_degraded.inc();
757 } else {
758 metrics.retry_unchanged.inc();
759 }
760
761 let chosen_result = if retry_verdict.score >= verdict.score {
763 retry_result
764 } else {
765 initial_result
766 };
767
768 Ok((chosen_result, retry_verdict))
769 }
770}
771
772#[derive(Debug, Clone)]
780pub struct HandleResponse {
781 pub directive: Box<oxios_ouroboros::Directive>,
783 pub env: Box<oxios_ouroboros::ExecEnv>,
785 pub result: Box<ExecutionResult>,
787 pub verdict: Option<oxios_ouroboros::Verdict>,
789 pub evaluation_passed: Option<bool>,
791}
792
793#[derive(Debug, Clone, Serialize, Deserialize)]
795pub struct OrchestrationResult {
796 #[serde(skip_serializing_if = "Option::is_none")]
798 pub session_id: Option<String>,
799 #[serde(skip_serializing_if = "Option::is_none")]
801 pub primary_project_id: Option<Uuid>,
802 #[serde(skip_serializing_if = "Option::is_none")]
804 pub project_tag: Option<String>,
805 #[serde(default, skip_serializing_if = "Vec::is_empty")]
807 pub active_mount_ids: Vec<MountId>,
808 #[serde(skip_serializing_if = "Option::is_none")]
810 pub mount_tag: Option<String>,
811 pub response: String,
813 #[serde(skip_serializing_if = "Option::is_none")]
815 pub agent_id: Option<AgentId>,
816 pub phase_reached: String,
818 pub evaluation_passed: Option<bool>,
824 #[serde(skip_serializing_if = "Option::is_none")]
826 pub output: Option<String>,
827 #[serde(default, skip_serializing_if = "Vec::is_empty")]
829 pub tool_calls: Vec<oxios_ouroboros::ToolCallRecord>,
830 #[serde(default, skip_serializing_if = "Option::is_none")]
838 pub interview_questions: Option<Vec<oxios_ouroboros::InterviewQuestionOutput>>,
839 #[serde(default, skip_serializing_if = "Option::is_none")]
842 pub interview_round: Option<u32>,
843
844 #[serde(default, skip_serializing_if = "String::is_empty")]
849 pub reasoning_text: String,
850 #[serde(default, skip_serializing_if = "Option::is_none")]
854 pub failure_class: Option<oxios_ouroboros::FailureClass>,
855}
856fn failure_class_to_user_message(class: Option<&oxios_ouroboros::FailureClass>) -> String {
859 use oxios_ouroboros::FailureClass;
860 match class {
861 Some(FailureClass::BudgetExceeded) => {
862 "\u{26a0}\u{fe0f} Token budget exceeded for this provider. \
863 Try selecting a different model or configuring additional providers \
864 in Settings \u{2192} Engine."
865 .to_string()
866 }
867 Some(FailureClass::QuotaExhausted) => "\u{26a0}\u{fe0f} Provider quota exhausted. \
868 The selected provider has reached its rate or usage limit. \
869 Wait a moment and retry, or switch to a different model."
870 .to_string(),
871 Some(FailureClass::AuthFailure) => "\u{26a0}\u{fe0f} Authentication failed. \
872 Your API key for this provider may be invalid or expired. \
873 Check your credentials in Settings \u{2192} Engine."
874 .to_string(),
875 Some(FailureClass::ModelUnavailable) => "\u{26a0}\u{fe0f} Model unavailable. \
876 The selected model is no longer available or was not found. \
877 Choose a different model in Settings \u{2192} Engine."
878 .to_string(),
879 Some(FailureClass::ContextOverflow) => "\u{26a0}\u{fe0f} Context window exceeded. \
880 The conversation is too long for this model's context limit. \
881 Start a new session or switch to a model with a larger context window."
882 .to_string(),
883 Some(FailureClass::Transient) => {
884 "\u{26a0}\u{fe0f} A temporary error occurred while contacting the provider. \
885 The system will retry automatically. If the issue persists, \
886 try a different model or check your network connection."
887 .to_string()
888 }
889 Some(FailureClass::Unknown) | None => {
890 "\u{26a0}\u{fe0f} An unexpected error occurred during execution. \
891 Please try again. If the problem persists, check your provider \
892 configuration in Settings \u{2192} Engine."
893 .to_string()
894 }
895 }
896}
897
898fn build_workspace_context_body(mounts: &[crate::mount::Mount]) -> Option<String> {
907 if mounts.is_empty() {
908 return None;
909 }
910 let mut out = String::new();
911 out.push_str("### Active Mounts\n");
912
913 for (i, m) in mounts.iter().enumerate() {
914 let primary = i == 0;
915 let path = m
916 .primary_path()
917 .map(|p| p.to_string_lossy().to_string())
918 .unwrap_or_else(|| "(no path)".to_string());
919
920 if primary {
921 out.push_str(&format!("- **{}** → {}\n", m.name, path));
922 if !m.auto_description.is_empty() {
923 let desc: String = m
925 .auto_description
926 .lines()
927 .take(3)
928 .collect::<Vec<_>>()
929 .join("\n ");
930 out.push_str(&format!(" {}\n", desc));
931 }
932 let summary = m.summary_line();
933 if !summary.is_empty() {
934 out.push_str(&format!(" _{}_\n", summary));
935 }
936 if m.enrichment_pending {
937 out.push_str(" _(content changed — consider re-scanning this Mount)_\n");
938 }
939 } else {
940 let summary = m.summary_line();
942 let suffix = if summary.is_empty() {
943 String::new()
944 } else {
945 format!(" — {}", summary)
946 };
947 out.push_str(&format!("- **{}** → {}{}\n", m.name, path, suffix));
948 }
949 }
950
951 Some(out)
952}
953
954#[cfg(test)]
955mod mount_workspace_tests {
956 use super::*;
957 use crate::mount::{Mount, MountSource};
958 use std::path::PathBuf;
959
960 #[test]
961 fn test_workspace_context_primary_full_secondary_terse() {
962 let mut oxios =
963 Mount::from_name_and_path("oxios", PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
964 oxios.auto_description = "Agent OS.\nRust + tokio.".to_string();
965 oxios.auto_meta.summary = "Rust agent OS".to_string();
966
967 let mut oxi = Mount::from_name_and_path("oxi", PathBuf::from("/oxi"));
968 oxi.auto_meta.summary = "SDK".to_string();
969
970 let body = build_workspace_context_body(&[oxios, oxi]).unwrap();
971 assert!(body.contains("### Active Mounts"));
972 assert!(body.contains("Agent OS."));
974 assert!(body.contains("_Rust agent OS_"));
975 assert!(body.contains("**oxi** → /oxi — SDK"));
977 }
978
979 #[test]
980 fn test_workspace_context_empty_is_none() {
981 assert!(build_workspace_context_body(&[]).is_none());
982 }
983
984 #[test]
988 fn test_resolve_mount_workspace_detects_and_collects_paths() {
989 use crate::mount::MountManager;
990 use oxios_memory::memory::sqlite::MemoryDatabase;
991 use std::sync::Arc;
992
993 let db = Arc::new(MemoryDatabase::open_in_memory(64).unwrap());
994 let mm = Arc::new(MountManager::new(db, None).unwrap());
995
996 let oxios = mm
998 .create_mount(
999 "oxios".to_string(),
1000 vec![PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios")],
1001 MountSource::Manual,
1002 )
1003 .unwrap();
1004 let oxi_sdk = mm
1005 .create_mount(
1006 "oxi-sdk".to_string(),
1007 vec![PathBuf::from("/Users/me/oxi")],
1008 MountSource::Manual,
1009 )
1010 .unwrap();
1011 mm.update_enrichment(oxios.id, Some("Agent OS in Rust.".to_string()), None)
1012 .unwrap();
1013
1014 let mounts = mm.get_mounts_ordered(&[oxios.id, oxi_sdk.id]);
1018 assert_eq!(mounts.len(), 2);
1019
1020 let body = build_workspace_context_body(&mounts).unwrap();
1021 assert!(body.contains("oxios"));
1022 assert!(body.contains("Agent OS in Rust."));
1023 assert!(body.contains("oxi-sdk"));
1024
1025 let mut paths = Vec::new();
1027 for m in &mounts {
1028 for p in &m.paths {
1029 if !paths.contains(p) {
1030 paths.push(p.clone());
1031 }
1032 }
1033 }
1034 assert_eq!(paths.len(), 2);
1035 assert_eq!(paths[0], PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
1036 assert_eq!(paths[1], PathBuf::from("/Users/me/oxi"));
1037 }
1038
1039 #[test]
1042 fn test_detection_seeds_primary_on_name_mention() {
1043 use crate::mount::{DetectionResult, detect_mounts};
1044
1045 let oxios =
1046 Mount::from_name_and_path("oxios", PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
1047 let result = detect_mounts("oxios 코드리뷰해줘", std::slice::from_ref(&oxios));
1048 assert!(matches!(result, DetectionResult::Found(id) if id == oxios.id));
1049 }
1050}