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 if let Some(project) = &project_for_instructions
331 && project.mount_ids.is_empty()
332 && !project.paths.is_empty()
333 {
334 for p in &project.paths {
335 if !paths.contains(p) {
336 paths.push(p.clone());
337 }
338 }
339 }
340
341 let tag = if mounts.len() == 1 {
343 mounts[0].tag()
344 } else {
345 let names: Vec<&str> = mounts.iter().map(|m| m.name.as_str()).collect();
346 format!("[🔧 {}]", names.join(" + "))
347 };
348
349 let mut context = build_workspace_context_body(&mounts).unwrap_or_default();
350
351 if let Some(project) = project_for_instructions {
357 let instructions = if project.instructions.len() > 2000 {
359 let mut end = 2000;
360 while end > 0 && !project.instructions.is_char_boundary(end) {
361 end -= 1;
362 }
363 format!("{}...", &project.instructions[..end])
364 } else {
365 project.instructions.clone()
366 };
367 if !instructions.is_empty() {
368 context.push_str(&format!(
369 "\n### Project Instructions: {}\n{}\n",
370 project.name, instructions
371 ));
372 }
373 }
374
375 const MAX_CONTEXT_CHARS: usize = 6000;
377 if context.len() > MAX_CONTEXT_CHARS {
378 let mut end = MAX_CONTEXT_CHARS;
379 while end > 0 && !context.is_char_boundary(end) {
380 end -= 1;
381 }
382 context.truncate(end);
383 context.push_str("\n...(context truncated)...\n");
384 }
385
386 let context_opt = if context.is_empty() {
387 None
388 } else {
389 Some(context)
390 };
391 (ids, context_opt, paths, tag)
392 }
393
394 pub fn set_a2a(&mut self, a2a: Arc<crate::a2a::A2AProtocol>) {
396 self.a2a = Some(a2a);
397 }
398
399 pub fn set_git_layer(&mut self, git_layer: Arc<GitLayer>) {
401 self.git_layer = Some(git_layer);
402 }
403
404 pub async fn restore_sessions(&self) {
410 }
412
413 #[allow(dead_code)]
414 fn git_commit(&self, rel_path: &str, message: &str) {
415 if let Some(ref gl) = self.git_layer
416 && gl.is_enabled()
417 {
418 let _ = gl.commit_file(rel_path, message);
419 }
420 }
421
422 pub async fn handle(
462 &self,
463 engine: &dyn oxios_ouroboros::IntentEngineOps,
464 msg: &str,
465 ctx: &oxios_ouroboros::MsgCtx,
466 ) -> Result<HandleResponse> {
467 let assessment = engine.assess(msg, ctx).await?;
469
470 match assessment {
471 oxios_ouroboros::Assessment::Conversation(reply) => Ok(HandleResponse::Reply(reply)),
472
473 oxios_ouroboros::Assessment::Clarify { questions } => {
474 Ok(HandleResponse::Clarify(questions))
475 }
476
477 oxios_ouroboros::Assessment::Task(scope) => {
478 let mut directive = match scope {
480 oxios_ouroboros::Scope::Trivial => {
481 oxios_ouroboros::Directive::from_message(msg)
482 }
483 oxios_ouroboros::Scope::Substantial => engine.crystallize(msg, ctx).await?,
484 };
485
486 let env = self.resolve_exec_env(ctx, msg);
488
489 let mut result = self.execute_directive(&directive, &env).await?;
492
493 let (verdict, evaluation_passed) = match scope {
495 oxios_ouroboros::Scope::Trivial => (None, None),
496 oxios_ouroboros::Scope::Substantial => {
497 let (r, v) = self
498 .verify_or_retry(engine, &mut directive, &env, result, msg, ctx)
499 .await?;
500 result = r;
501 let passed = v.all_passed();
502 (Some(v), Some(passed))
503 }
504 };
505
506 Ok(HandleResponse::Task {
507 scope,
508 directive: Box::new(directive),
509 env: Box::new(env),
510 result: Box::new(result),
511 verdict,
512 evaluation_passed,
513 })
514 }
515 }
516 }
517
518 pub async fn handle_unified(
525 &self,
526 user_id: &str,
527 msg: &str,
528 session_id: Option<&str>,
529 project_ids: Option<&str>,
530 mount_ids: Option<&str>,
531 request_id: &str,
532 ) -> Result<OrchestrationResult> {
533 let engine = self
535 .intent_engine
536 .read()
537 .clone()
538 .expect("IntentEngine not wired — kernel assembler bug");
539
540 let sid = session_id.unwrap_or(request_id).to_string();
542 let history = self.load_session_history(&sid).await;
543 let ctx = oxios_ouroboros::MsgCtx {
544 session_id: sid.clone(),
545 history,
546 project_ids: project_ids.map(String::from),
547 mount_ids: mount_ids.map(String::from),
548 user_id: user_id.to_string(),
549 };
550
551 let start = std::time::Instant::now();
553 let response = self.handle(engine.as_ref(), msg, &ctx).await?;
554 let duration_ms = start.elapsed().as_millis() as u64;
555
556 Ok(self.handle_response_to_orchestration_result(response, &ctx, duration_ms))
557 }
558
559 async fn load_session_history(&self, session_id: &str) -> Vec<oxios_ouroboros::Exchange> {
561 let sid = crate::state_store::SessionId(session_id.to_string());
562 match self.state_store.load_session(&sid).await {
563 Ok(Some(session)) => session
564 .user_messages
565 .iter()
566 .zip(session.agent_responses.iter())
567 .map(|(u, a)| oxios_ouroboros::Exchange {
568 user: u.content.clone(),
569 agent: a.content.clone(),
570 })
571 .collect(),
572 _ => Vec::new(),
573 }
574 }
575
576 fn handle_response_to_orchestration_result(
577 &self,
578 response: HandleResponse,
579 ctx: &oxios_ouroboros::MsgCtx,
580 duration_ms: u64,
581 ) -> OrchestrationResult {
582 let metrics = get_metrics();
583 metrics.orch_duration.observe(duration_ms as f64 / 1000.0);
584
585 match response {
586 HandleResponse::Reply(reply) => OrchestrationResult {
587 session_id: Some(ctx.session_id.clone()),
588 primary_project_id: None,
589 project_tag: None,
590 active_mount_ids: Vec::new(),
591 mount_tag: None,
592 response: reply,
593 agent_id: None,
594 phase_reached: "interview".to_string(),
595 evaluation_passed: None,
596 output: None,
597 tool_calls: Vec::new(),
598 interview_questions: None,
599 interview_round: None,
600 },
601 HandleResponse::Clarify(questions) => {
602 let questions_text = questions
603 .iter()
604 .map(|q| q.text.clone())
605 .collect::<Vec<_>>()
606 .join("\n");
607 let structured = Some(
608 questions
609 .iter()
610 .map(|q| oxios_ouroboros::InterviewQuestionOutput {
611 id: q.id.clone(),
612 text: q.text.clone(),
613 kind: format!("{:?}", q.kind).to_lowercase(),
614 options: q
615 .options
616 .iter()
617 .map(|o| oxios_ouroboros::InterviewOptionOutput {
618 value: o.value.clone(),
619 label: o.label.clone(),
620 description: String::new(),
621 })
622 .collect(),
623 })
624 .collect(),
625 );
626 OrchestrationResult {
627 session_id: Some(ctx.session_id.clone()),
628 primary_project_id: None,
629 project_tag: None,
630 active_mount_ids: Vec::new(),
631 mount_tag: None,
632 response: questions_text,
633 agent_id: None,
634 phase_reached: "interview".to_string(),
635 evaluation_passed: None,
636 output: None,
637 tool_calls: Vec::new(),
638 interview_questions: structured,
639 interview_round: Some(((ctx.history.len() / 2) as u32).max(1)),
640 }
641 }
642 HandleResponse::Task {
643 scope: _,
644 directive,
645 env,
646 result,
647 verdict,
648 evaluation_passed,
649 } => {
650 let response_text = if directive.acceptance_criteria.is_empty() {
651 result.output.clone()
652 } else {
653 match &verdict {
654 Some(v) if v.all_passed() => result.output.clone(),
655 Some(v) => format!(
656 "{}\n\n⚠ Review notes:\n{}",
657 result.output,
658 v.notes.join("\n")
659 ),
660 None => result.output.clone(),
661 }
662 };
663 if evaluation_passed.unwrap_or(false) {
664 metrics.agents_completed.inc();
665 } else {
666 metrics.agents_failed.inc();
667 }
668 OrchestrationResult {
669 session_id: Some(ctx.session_id.clone()),
670 primary_project_id: env.project_id,
671 project_tag: None,
672 active_mount_ids: Vec::new(),
673 mount_tag: None,
674 response: response_text,
675 agent_id: None,
676 phase_reached: "execute".to_string(),
677 evaluation_passed,
678 output: Some(result.output.clone()),
679 tool_calls: result.tool_calls.clone(),
680 interview_questions: None,
681 interview_round: None,
682 }
683 }
684 }
685 }
686
687 fn resolve_exec_env(
694 &self,
695 ctx: &oxios_ouroboros::MsgCtx,
696 msg: &str,
697 ) -> oxios_ouroboros::ExecEnv {
698 let (active_mount_ids, workspace_context, mount_paths, _mount_tag) =
699 self.resolve_mount_workspace(ctx.mount_ids.as_deref(), ctx.project_ids.as_deref(), msg);
700 let _ = active_mount_ids;
704
705 let project_id = ctx
708 .project_ids
709 .as_deref()
710 .and_then(|ids| {
711 ids.split(',')
712 .next()
713 .and_then(|s| Uuid::parse_str(s.trim()).ok())
714 })
715 .or_else(|| {
716 self.detect_project_tag(msg).and_then(|_tag| {
717 self.project_manager().and_then(|pm| {
718 let projects = pm.list_projects();
719 match crate::project::detect_project(msg, &projects) {
720 crate::project::DetectionResult::Found(id) => Some(id),
721 crate::project::DetectionResult::NoMatch { .. } => None,
722 }
723 })
724 })
725 });
726
727 if let Some(pid) = project_id
729 && let Some(pm) = self.project_manager()
730 {
731 pm.touch(pid);
732 }
733
734 oxios_ouroboros::ExecEnv {
735 workspace_context,
736 mount_paths,
737 project_id,
738 cspace_hint: None,
739 model_override: None,
740 restore_state: None,
741 }
742 }
743
744 async fn execute_directive(
747 &self,
748 directive: &oxios_ouroboros::Directive,
749 env: &oxios_ouroboros::ExecEnv,
750 ) -> Result<ExecutionResult> {
751 let coordinator = self.recovery.read().as_ref().cloned();
759 if let Some(coordinator) = coordinator {
760 coordinator.execute(&self.lifecycle, directive, env).await
761 } else {
762 self.lifecycle.execute_directive(directive, env).await
763 }
764 }
765
766 async fn verify_or_retry(
773 &self,
774 engine: &dyn oxios_ouroboros::IntentEngineOps,
775 directive: &mut oxios_ouroboros::Directive,
776 env: &oxios_ouroboros::ExecEnv,
777 initial_result: ExecutionResult,
778 _msg: &str,
779 _ctx: &oxios_ouroboros::MsgCtx,
780 ) -> Result<(ExecutionResult, oxios_ouroboros::Verdict)> {
781 let verdict = engine.review(directive, &initial_result).await?;
782
783 if verdict.all_passed() || verdict.gaps.is_empty() {
784 return Ok((initial_result, verdict));
785 }
786
787 let enable_retry = self.intent_config.read().enable_retry;
790 if !enable_retry {
791 tracing::info!("Review failed but retry disabled (enable_retry=false)");
792 return Ok((initial_result, verdict));
793 }
794
795 let metrics = get_metrics();
796 metrics.retry_attempted.inc();
797
798 tracing::info!(
799 gaps = verdict.gaps.len(),
800 "Review failed — retrying with feedback"
801 );
802
803 let retry_result = self
805 .lifecycle
806 .execute_with_feedback(directive, env, &initial_result, &verdict.gaps)
807 .await?;
808
809 let retry_verdict = engine.review(directive, &retry_result).await?;
811
812 if retry_verdict.score > verdict.score {
814 metrics.retry_improved.inc();
815 } else if retry_verdict.score < verdict.score {
816 metrics.retry_degraded.inc();
817 } else {
818 metrics.retry_unchanged.inc();
819 }
820
821 let chosen_result = if retry_verdict.score >= verdict.score {
823 retry_result
824 } else {
825 initial_result
826 };
827
828 Ok((chosen_result, retry_verdict))
829 }
830}
831
832#[derive(Debug, Clone)]
844pub enum HandleResponse {
845 Reply(String),
847 Clarify(Vec<oxios_ouroboros::Question>),
849 Task {
851 scope: oxios_ouroboros::Scope,
853 directive: Box<oxios_ouroboros::Directive>,
855 env: Box<oxios_ouroboros::ExecEnv>,
857 result: Box<ExecutionResult>,
859 verdict: Option<oxios_ouroboros::Verdict>,
861 evaluation_passed: Option<bool>,
863 },
864}
865
866#[derive(Debug, Clone, Serialize, Deserialize)]
868pub struct OrchestrationResult {
869 #[serde(skip_serializing_if = "Option::is_none")]
871 pub session_id: Option<String>,
872 #[serde(skip_serializing_if = "Option::is_none")]
874 pub primary_project_id: Option<Uuid>,
875 #[serde(skip_serializing_if = "Option::is_none")]
877 pub project_tag: Option<String>,
878 #[serde(default, skip_serializing_if = "Vec::is_empty")]
880 pub active_mount_ids: Vec<MountId>,
881 #[serde(skip_serializing_if = "Option::is_none")]
883 pub mount_tag: Option<String>,
884 pub response: String,
886 #[serde(skip_serializing_if = "Option::is_none")]
888 pub agent_id: Option<AgentId>,
889 pub phase_reached: String,
891 pub evaluation_passed: Option<bool>,
897 #[serde(skip_serializing_if = "Option::is_none")]
899 pub output: Option<String>,
900 #[serde(default, skip_serializing_if = "Vec::is_empty")]
902 pub tool_calls: Vec<oxios_ouroboros::ToolCallRecord>,
903 #[serde(default, skip_serializing_if = "Option::is_none")]
911 pub interview_questions: Option<Vec<oxios_ouroboros::InterviewQuestionOutput>>,
912 #[serde(default, skip_serializing_if = "Option::is_none")]
915 pub interview_round: Option<u32>,
916}
917
918fn build_workspace_context_body(mounts: &[crate::mount::Mount]) -> Option<String> {
927 if mounts.is_empty() {
928 return None;
929 }
930 let mut out = String::new();
931 out.push_str("### Active Mounts\n");
932
933 for (i, m) in mounts.iter().enumerate() {
934 let primary = i == 0;
935 let path = m
936 .primary_path()
937 .map(|p| p.to_string_lossy().to_string())
938 .unwrap_or_else(|| "(no path)".to_string());
939
940 if primary {
941 out.push_str(&format!("- **{}** → {}\n", m.name, path));
942 if !m.auto_description.is_empty() {
943 let desc: String = m
945 .auto_description
946 .lines()
947 .take(3)
948 .collect::<Vec<_>>()
949 .join("\n ");
950 out.push_str(&format!(" {}\n", desc));
951 }
952 let summary = m.summary_line();
953 if !summary.is_empty() {
954 out.push_str(&format!(" _{}_\n", summary));
955 }
956 if m.enrichment_pending {
957 out.push_str(" _(content changed — consider re-scanning this Mount)_\n");
958 }
959 } else {
960 let summary = m.summary_line();
962 let suffix = if summary.is_empty() {
963 String::new()
964 } else {
965 format!(" — {}", summary)
966 };
967 out.push_str(&format!("- **{}** → {}{}\n", m.name, path, suffix));
968 }
969 }
970
971 Some(out)
972}
973
974#[cfg(test)]
975mod mount_workspace_tests {
976 use super::*;
977 use crate::mount::{Mount, MountSource};
978 use std::path::PathBuf;
979
980 #[test]
981 fn test_workspace_context_primary_full_secondary_terse() {
982 let mut oxios =
983 Mount::from_name_and_path("oxios", PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
984 oxios.auto_description = "Agent OS.\nRust + tokio.".to_string();
985 oxios.auto_meta.summary = "Rust agent OS".to_string();
986
987 let mut oxi = Mount::from_name_and_path("oxi", PathBuf::from("/oxi"));
988 oxi.auto_meta.summary = "SDK".to_string();
989
990 let body = build_workspace_context_body(&[oxios, oxi]).unwrap();
991 assert!(body.contains("### Active Mounts"));
992 assert!(body.contains("Agent OS."));
994 assert!(body.contains("_Rust agent OS_"));
995 assert!(body.contains("**oxi** → /oxi — SDK"));
997 }
998
999 #[test]
1000 fn test_workspace_context_empty_is_none() {
1001 assert!(build_workspace_context_body(&[]).is_none());
1002 }
1003
1004 #[test]
1008 fn test_resolve_mount_workspace_detects_and_collects_paths() {
1009 use crate::mount::MountManager;
1010 use oxios_memory::memory::sqlite::MemoryDatabase;
1011 use std::sync::Arc;
1012
1013 let db = Arc::new(MemoryDatabase::open_in_memory(64).unwrap());
1014 let mm = Arc::new(MountManager::new(db, None).unwrap());
1015
1016 let oxios = mm
1018 .create_mount(
1019 "oxios".to_string(),
1020 vec![PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios")],
1021 MountSource::Manual,
1022 )
1023 .unwrap();
1024 let oxi_sdk = mm
1025 .create_mount(
1026 "oxi-sdk".to_string(),
1027 vec![PathBuf::from("/Users/me/oxi")],
1028 MountSource::Manual,
1029 )
1030 .unwrap();
1031 mm.update_enrichment(oxios.id, Some("Agent OS in Rust.".to_string()), None)
1032 .unwrap();
1033
1034 let mounts = mm.get_mounts_ordered(&[oxios.id, oxi_sdk.id]);
1038 assert_eq!(mounts.len(), 2);
1039
1040 let body = build_workspace_context_body(&mounts).unwrap();
1041 assert!(body.contains("oxios"));
1042 assert!(body.contains("Agent OS in Rust."));
1043 assert!(body.contains("oxi-sdk"));
1044
1045 let mut paths = Vec::new();
1047 for m in &mounts {
1048 for p in &m.paths {
1049 if !paths.contains(p) {
1050 paths.push(p.clone());
1051 }
1052 }
1053 }
1054 assert_eq!(paths.len(), 2);
1055 assert_eq!(paths[0], PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
1056 assert_eq!(paths[1], PathBuf::from("/Users/me/oxi"));
1057 }
1058
1059 #[test]
1062 fn test_detection_seeds_primary_on_name_mention() {
1063 use crate::mount::{DetectionResult, detect_mounts};
1064
1065 let oxios =
1066 Mount::from_name_and_path("oxios", PathBuf::from("/Volumes/MERCURY/PROJECTS/oxios"));
1067 let result = detect_mounts("oxios 코드리뷰해줘", std::slice::from_ref(&oxios));
1068 assert!(matches!(result, DetectionResult::Found(id) if id == oxios.id));
1069 }
1070}