Skip to main content

oxios_kernel/
orchestrator.rs

1//! Orchestrator: coordinates the unified intent lifecycle (RFC-027).
2//!
3//! The orchestrator is the "brain" that processes every user message:
4//! 1. assess — classify the message (conversation / clarify / task)
5//! 2. crystallize — build a Directive for substantial tasks
6//! 3. execute — run the agent via the lifecycle manager
7//! 4. review — check the result against acceptance criteria
8//! 5. retry — re-execute with feedback if review fails
9
10use 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/// Role of an agent within a group.
28#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
29pub enum AgentRole {
30    /// Executes a specific subtask.
31    #[default]
32    Worker,
33    /// Coordinates subtasks, synthesizes results.
34    Manager,
35}
36
37/// A subtask within a multi-agent plan.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct SubTask {
40    /// Unique subtask ID.
41    pub id: Uuid,
42    /// Human-readable description.
43    pub description: String,
44    /// Capability required (e.g., "code-review", "testing").
45    pub required_capability: Option<String>,
46    /// Result of the subtask (filled after execution).
47    pub result: Option<String>,
48    /// Whether this subtask succeeded.
49    pub success: bool,
50    /// Role of the agent assigned to this subtask.
51    #[serde(default)]
52    pub role: AgentRole,
53}
54
55impl SubTask {
56    /// Create a new subtask with the given description.
57    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    /// Set the required capability for this subtask.
69    pub fn with_capability(mut self, cap: impl Into<String>) -> Self {
70        self.required_capability = Some(cap.into());
71        self
72    }
73}
74
75/// The orchestrator coordinates the unified intent lifecycle (RFC-027).
76#[allow(dead_code)]
77pub struct Orchestrator {
78    /// IntentEngine for the unified handle() path (RFC-027).
79    /// Lazily available when the kernel wires it; None in legacy constructions.
80    intent_engine: RwLock<Option<Arc<dyn oxios_ouroboros::IntentEngineOps>>>,
81    event_bus: EventBus,
82    state_store: Arc<StateStore>,
83    /// Git version control layer for auto-commits.
84    git_layer: Option<Arc<GitLayer>>,
85    /// Agent lifecycle manager (fork, register, run, cleanup).
86    lifecycle: AgentLifecycleManager,
87    /// A2A protocol for inter-agent task delegation.
88    a2a: Option<Arc<crate::a2a::A2AProtocol>>,
89    /// Project manager for context partitioning.
90    project_manager: RwLock<Option<Arc<ProjectManager>>>,
91    /// Mount manager for path-alias context (RFC-025).
92    mount_manager: RwLock<Option<Arc<MountManager>>>,
93    /// Conversation buffer for topic shift detection.
94    conversation_buffer: RwLock<ConversationBuffer>,
95    /// Orchestrator configuration (Ouroboros protocol settings).
96    delegation_config: DelegationConfig,
97    /// A2A circuit breaker for delegation reliability.
98    a2a_breaker: Arc<crate::a2a::circuit_breaker::A2ACircuitBreaker>,
99    /// RFC-027 intent config (retry settings, etc).
100    intent_config: RwLock<crate::config::IntentConfig>,
101    /// RFC-029 recovery coordinator. When `Some`, the orchestrator's
102    /// execute path routes through it (L1 backoff / L2 model swap)
103    /// instead of calling lifecycle directly.
104    recovery: RwLock<Option<Arc<crate::resilience::RecoveryCoordinator>>>,
105}
106
107/// Configuration for A2A delegation retries.
108#[allow(dead_code)]
109struct DelegationConfig {
110    /// Maximum retry attempts for A2A delegation.
111    max_retries: u32,
112    /// Base delay for exponential backoff (milliseconds).
113    base_delay_ms: u64,
114    /// Maximum delay cap for exponential backoff (milliseconds).
115    max_delay_ms: u64,
116    /// Timeout per delegation attempt (milliseconds).
117    #[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    /// Calculate exponential backoff delay.
135    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    /// Creates a new orchestrator.
143    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    /// Creates a new orchestrator with custom config.
157    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    /// Wire the IntentEngine for unified handle() calls (RFC-027).
181    /// Called by the kernel assembler after construction.
182    pub fn set_intent_engine(&self, engine: Arc<dyn oxios_ouroboros::IntentEngineOps>) {
183        *self.intent_engine.write() = Some(engine);
184    }
185
186    /// Wire the RFC-029 recovery coordinator. Called by the kernel
187    /// assembler after construction (shares `RoutingStats` with
188    /// `EngineApi` / `AgentRuntime`).
189    pub fn set_recovery(&self, coordinator: Arc<crate::resilience::RecoveryCoordinator>) {
190        *self.recovery.write() = Some(coordinator);
191    }
192
193    /// Whether the IntentEngine is wired (unified path available).
194    pub fn has_intent_engine(&self) -> bool {
195        self.intent_engine.read().is_some()
196    }
197
198    /// Set the ProjectManager for context partitioning.
199    pub fn set_project_manager(&self, manager: Arc<ProjectManager>) {
200        *self.project_manager.write() = Some(manager);
201    }
202
203    /// Set the MountManager for path-alias context (RFC-025).
204    pub fn set_mount_manager(&self, manager: Arc<MountManager>) {
205        *self.mount_manager.write() = Some(manager);
206    }
207
208    /// Get a reference to the MountManager, if set (RFC-025).
209    pub fn mount_manager(&self) -> Option<Arc<MountManager>> {
210        self.mount_manager.read().as_ref().cloned()
211    }
212
213    /// Get a reference to the ProjectManager, if set.
214    pub fn project_manager(&self) -> Option<Arc<ProjectManager>> {
215        self.project_manager.read().as_ref().cloned()
216    }
217
218    /// Detect a project from a message, returning tag string.
219    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    /// Resolve the active Mounts for a message (RFC-025).
231    ///
232    /// Parses explicit `mount_ids` ("uuid1,uuid2,...", primary first); when
233    /// none are given, auto-detects from the message. Returns:
234    /// - the ordered list of active [`MountId`]s,
235    /// - the rendered `## Workspace Context` body (without the header),
236    /// - all resolved filesystem paths (primary first),
237    /// - a display tag like `[🔧 oxios + oxi-sdk]`.
238    ///
239    /// Honors the sticky-primary model: when `mount_ids` is explicitly
240    /// provided they are used as-is (detection is skipped). Detection only
241    /// runs when `mount_ids` is `None`, seeding the primary slot — it never
242    /// replaces an explicit primary, only appends a secondary.
243    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        // Parse explicit mount_ids; otherwise auto-detect (seeds the primary slot).
261        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        // De-duplicate while preserving order (handles non-consecutive dups).
273        let mut seen = std::collections::HashSet::new();
274        ids.retain(|id| seen.insert(*id));
275
276        // ── Project-referenced Mount activation (RFC-025) ──
277        // When a project_id is provided, auto-activate its referenced Mounts
278        // BEFORE we derive mounts/tag/context/paths, so they are fully
279        // visible in the system prompt and the badge — not just granted
280        // path access. (Previously this ran after the prompt was built, so
281        // project-referenced Mounts were invisible in the context body.)
282        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        // Touch each active Mount (record activity) — now includes any
306        // Project-referenced Mounts activated above.
307        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        // Collect all paths (primary first, deduped) over the full Mount set.
317        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        // Legacy fallback (RFC-025 migration window): a Project created
327        // before Mounts may carry explicit `paths` but no `mount_ids`. In
328        // that case grant path access directly so pre-RFC-025 Projects still
329        // resolve a CWD and populate `allowed_paths` (see agent_runtime.rs).
330        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        // Display tag.
342        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        // ── Project instructions (RFC-025) ──
352        // Inject the project's instructions into the context body. The
353        // "### Active Mounts" header above is only present when there are
354        // actual mount entries in `context`; the Project Instructions section
355        // stands on its own when only instructions exist.
356        if let Some(project) = project_for_instructions {
357            // Cap instructions to stay within the prompt budget (~500 tokens).
358            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        // Enforce a hard prompt budget on the final context body (~1500 tokens).
376        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    /// Set the A2A protocol for inter-agent task delegation.
395    pub fn set_a2a(&mut self, a2a: Arc<crate::a2a::A2AProtocol>) {
396        self.a2a = Some(a2a);
397    }
398
399    /// Set the GitLayer for auto-commits after state saves.
400    pub fn set_git_layer(&mut self, git_layer: Arc<GitLayer>) {
401        self.git_layer = Some(git_layer);
402    }
403
404    /// Restore sessions from persisted state.
405    ///
406    /// RFC-027: the in-memory interview session map is no longer used.
407    /// Clarify state is restored from the session store's conversation
408    /// history on demand by `handle_unified`. This function is a no-op.
409    pub async fn restore_sessions(&self) {
410        // No-op — see doc comment above.
411    }
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    // ──────────────────────────────────────────────────────────────────
423    // RFC-027 §3 — Unified intent handler
424    // ──────────────────────────────────────────────────────────────────
425    //
426    // Phase 5 entry point. Routes a single user message through:
427    //   assess → (crystallize) → execute → (review + retry) → Response
428    //
429    // The legacy `handle_message()` and `chat()` paths remain intact;
430    // this method coexists alongside them until Phase 6 cuts over.
431
432    /// Unified entry point for every user message (RFC-027 §3).
433    ///
434    /// One method, one match — depth falls out of [`Scope`]:
435    ///
436    /// 1. [`IntentEngine::assess`] classifies the message (conversation /
437    ///    clarify / task + scope). Always called once.
438    /// 2. For `Assessment::Task(scope)` we build a [`Directive`]:
439    ///    - `Scope::Trivial` — `Directive::from_message(msg)` verbatim.
440    ///    - `Scope::Substantial` — [`IntentEngine::crystallize`] produces a
441    ///      structured directive with goal, constraints, and acceptance
442    ///      criteria.
443    /// 3. The [`ExecEnv`] is resolved from [`MsgCtx`] independently of the
444    ///    directive (Mount workspace context, paths, project ID, cspace hint).
445    /// 4. Execution delegates to the existing [`AgentLifecycleManager`].
446    ///    In Phase 5 the Directive is shimmed into a [`Seed`] for the
447    ///    current pipeline; Phase 6 will replace this with
448    ///    `lifecycle.execute_directive(&Directive, &ExecEnv)`.
449    /// 5. For `Scope::Substantial` we call [`IntentEngine::review`] and, if
450    ///    the verdict fails, retry once with the verdict's gaps folded back
451    ///    into the directive as additional constraints.
452    ///
453    /// Does not modify or call the legacy `handle_message()` / `chat()`
454    /// paths — they remain the canonical entry points until Phase 6 cuts
455    /// the gateway over to `handle()`.
456    ///
457    /// # Parameters
458    /// - `engine` — the LLM-backed intent engine (assess/crystallize/review).
459    /// - `msg` — the user's raw message text.
460    /// - `ctx` — per-message context (session, history, project/mount hints).
461    pub async fn handle(
462        &self,
463        engine: &dyn oxios_ouroboros::IntentEngineOps,
464        msg: &str,
465        ctx: &oxios_ouroboros::MsgCtx,
466    ) -> Result<HandleResponse> {
467        // 1. assess — always called once, routes the message.
468        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                // 2. Build the Directive based on scope.
479                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                // 3. Resolve the execution environment from MsgCtx.
487                let env = self.resolve_exec_env(ctx, msg);
488
489                // 4. Execute (always). Trivial tasks skip review; substantial
490                //    tasks go through verify_or_retry below.
491                let mut result = self.execute_directive(&directive, &env).await?;
492
493                // 5. Verify + optional retry (Substantial only).
494                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    /// Unified entry point that accepts legacy-style parameters and returns
519    /// an `OrchestrationResult` (RFC-027).
520    ///
521    /// Builds a [`MsgCtx`] from the session history (if any), then delegates
522    /// to [`handle`](Self::handle). Falls back to `handle_message` if no
523    /// `IntentEngine` is wired.
524    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        // Get the IntentEngine (always wired by the kernel assembler).
534        let engine = self
535            .intent_engine
536            .read()
537            .clone()
538            .expect("IntentEngine not wired — kernel assembler bug");
539
540        // Build MsgCtx.
541        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        // Call the unified path.
552        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    /// Load conversation history for a session from the state store.
560    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    /// Resolve an [`ExecEnv`] from the per-message context.
688    ///
689    /// Mirrors the Mount workspace resolution done by `handle_message()`
690    /// and `chat()` but packages the result as the new [`ExecEnv`] type.
691    /// Independent of the directive — runs whether the task is Trivial
692    /// or Substantial.
693    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        // active_mount_ids + mount_tag are surfaced via the legacy path;
701        // ExecEnv carries the resolved paths/context/project that the
702        // agent runtime actually consumes.
703        let _ = active_mount_ids;
704
705        // Resolve a primary project ID (matches handle_message semantics):
706        // explicit project_ids takes precedence over auto-detection.
707        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        // Touch the project to record activity (mirrors handle_message).
728        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    /// Execute a [`Directive`] under an [`ExecEnv`].
745    ///
746    async fn execute_directive(
747        &self,
748        directive: &oxios_ouroboros::Directive,
749        env: &oxios_ouroboros::ExecEnv,
750    ) -> Result<ExecutionResult> {
751        // RFC-029: route through the recovery coordinator when wired
752        // (L1 backoff / L2 model swap on provider failure). Falls back
753        // to a direct lifecycle call when no coordinator is set.
754        //
755        // Clone the Arc out of the read guard so the parking_lot guard
756        // (which is !Send) is dropped before the .await — otherwise the
757        // future is !Send and breaks tokio::spawn in the gateway.
758        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    /// Review the result against the directive's criteria; on failure,
767    /// retry once with the verdict's gaps folded back as constraints.
768    ///
769    /// Phase 5 caps retries at one explicit attempt; once IntentConfig
770    /// lands (Phase 5 sibling subtask) this will read the configured
771    /// `max_retries` instead.
772    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        // Check if retry is enabled (RFC-027 Decision 6).
788        // When disabled, return the initial result with the failed verdict.
789        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        // Execute with feedback: previous output + gaps injected.
804        let retry_result = self
805            .lifecycle
806            .execute_with_feedback(directive, env, &initial_result, &verdict.gaps)
807            .await?;
808
809        // Re-review.
810        let retry_verdict = engine.review(directive, &retry_result).await?;
811
812        // Track retry effectiveness.
813        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        // Return best result.
822        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/// Response envelope for [`Orchestrator::handle`] (RFC-027 §3).
833///
834/// One variant per terminal state of the unified handler:
835///
836/// - [`HandleResponse::Reply`] — conversational answer, no agent spawned.
837/// - [`HandleResponse::Clarify`] — the message was ambiguous; ask these
838///   structured questions before acting.
839/// - [`HandleResponse::Task`] — an agent executed the task. Carries the
840///   scope, the directive that was run, the resolved environment, the
841///   execution result, and (for substantial tasks) the review verdict +
842///   pass/fail.
843#[derive(Debug, Clone)]
844pub enum HandleResponse {
845    /// Conversational reply — no agent was spawned.
846    Reply(String),
847    /// Structured clarifying questions to ask before acting.
848    Clarify(Vec<oxios_ouroboros::Question>),
849    /// A task was executed by an agent.
850    Task {
851        /// The scope decided by `assess` — Trivial skips review.
852        scope: oxios_ouroboros::Scope,
853        /// The directive that was executed (post-retry if a retry ran).
854        directive: Box<oxios_ouroboros::Directive>,
855        /// The execution environment resolved for this message.
856        env: Box<oxios_ouroboros::ExecEnv>,
857        /// The execution result.
858        result: Box<ExecutionResult>,
859        /// The review verdict — `None` for `Scope::Trivial`.
860        verdict: Option<oxios_ouroboros::Verdict>,
861        /// Whether the (final) verdict passed — `None` for `Scope::Trivial`.
862        evaluation_passed: Option<bool>,
863    },
864}
865
866/// Result of a full orchestration cycle.
867#[derive(Debug, Clone, Serialize, Deserialize)]
868pub struct OrchestrationResult {
869    /// Session ID for multi-turn interviews. Pass this on follow-up messages.
870    #[serde(skip_serializing_if = "Option::is_none")]
871    pub session_id: Option<String>,
872    /// The Space ID that handled this message.
873    #[serde(skip_serializing_if = "Option::is_none")]
874    pub primary_project_id: Option<Uuid>,
875    /// Space decoration tag for the response (e.g. "[🔧 oxios]").
876    #[serde(skip_serializing_if = "Option::is_none")]
877    pub project_tag: Option<String>,
878    /// Active Mount IDs for this message (RFC-025), primary first.
879    #[serde(default, skip_serializing_if = "Vec::is_empty")]
880    pub active_mount_ids: Vec<MountId>,
881    /// Mount decoration tag for the response (e.g. "[🔧 oxios + oxi-sdk]").
882    #[serde(skip_serializing_if = "Option::is_none")]
883    pub mount_tag: Option<String>,
884    /// The response to send back to the user.
885    pub response: String,
886    /// The agent that executed (if execute phase was reached).
887    #[serde(skip_serializing_if = "Option::is_none")]
888    pub agent_id: Option<AgentId>,
889    /// The furthest phase reached: "interview" (conversation/clarify) or "execute" (task executed).
890    pub phase_reached: String,
891    /// Whether evaluation passed.
892    ///
893    /// - `None` — evaluation was not applicable (interview, chat, non-task).
894    /// - `Some(true)` — evaluation passed.
895    /// - `Some(false)` — evaluation failed or execution unsuccessful.
896    pub evaluation_passed: Option<bool>,
897    /// Output or notes from evaluation.
898    #[serde(skip_serializing_if = "Option::is_none")]
899    pub output: Option<String>,
900    /// Tool calls recorded during execution.
901    #[serde(default, skip_serializing_if = "Vec::is_empty")]
902    pub tool_calls: Vec<oxios_ouroboros::ToolCallRecord>,
903    /// Structured interview questions (chat UI redesign — interactive
904    /// interview). Populated when the interview phase needs clarification
905    /// and the LLM produced a structured form of the questions. The
906    /// Gateway forwards this to the WebSocket as an `interview` chunk;
907    /// the Web UI renders it as interactive widgets (chips, yes/no
908    /// buttons). When `None`, the frontend falls back to rendering
909    /// `response` as plain markdown.
910    #[serde(default, skip_serializing_if = "Option::is_none")]
911    pub interview_questions: Option<Vec<oxios_ouroboros::InterviewQuestionOutput>>,
912    /// Current interview round (1-based). Populated alongside
913    /// `interview_questions`. Drives the "Round N/M" indicator.
914    #[serde(default, skip_serializing_if = "Option::is_none")]
915    pub interview_round: Option<u32>,
916}
917
918/// Render the body of the `## Workspace Context` prompt section (RFC-025).
919///
920/// The caller (`build_system_prompt`) wraps this in the `## Workspace
921/// Context` header. Returns `None` when there are no Mounts to describe.
922///
923/// Fill order respects the prompt budget (~1500 tokens soft):
924/// 1. Primary Mount — full (description + summary + path).
925/// 2. Secondary Mounts — name + path + one-line summary only.
926fn 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                // First ~3 lines of the agent-written description.
944                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            // Secondary: name + path + one-line summary only.
961            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        // Primary gets full description.
993        assert!(body.contains("Agent OS."));
994        assert!(body.contains("_Rust agent OS_"));
995        // Secondary is terse.
996        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    /// End-to-end: a real MountManager + Orchestrator-less call to
1005    /// `resolve_mount_workspace` proves that detection seeds the primary,
1006    /// builds the context body, and collects all paths (multi-path access).
1007    #[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        // Register two mounts.
1017        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        // Build a minimal Orchestrator-free resolver path: replicate what
1035        // resolve_mount_workspace does, but against the manager directly,
1036        // since the full Orchestrator needs many subsystems.
1037        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        // Collect paths like the orchestrator does.
1046        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    /// Detection layer 1 (name match) seeds the primary when no explicit
1060    /// mount_ids are given — the core promise of RFC-025.
1061    #[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}