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, 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/// 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        // Display tag.
327        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        // ── Project instructions (RFC-025) ──
337        // Inject the project's instructions into the context body. The
338        // "### Active Mounts" header above is only present when there are
339        // actual mount entries in `context`; the Project Instructions section
340        // stands on its own when only instructions exist.
341        if let Some(project) = project_for_instructions {
342            // Cap instructions to stay within the prompt budget (~500 tokens).
343            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        // Enforce a hard prompt budget on the final context body (~1500 tokens).
361        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    /// Set the A2A protocol for inter-agent task delegation.
380    pub fn set_a2a(&mut self, a2a: Arc<crate::a2a::A2AProtocol>) {
381        self.a2a = Some(a2a);
382    }
383
384    /// Set the GitLayer for auto-commits after state saves.
385    pub fn set_git_layer(&mut self, git_layer: Arc<GitLayer>) {
386        self.git_layer = Some(git_layer);
387    }
388
389    /// Restore sessions from persisted state.
390    ///
391    /// RFC-027: the in-memory interview session map is no longer used.
392    /// Clarify state is restored from the session store's conversation
393    /// history on demand by `handle_unified`. This function is a no-op.
394    pub async fn restore_sessions(&self) {
395        // No-op — see doc comment above.
396    }
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    // ──────────────────────────────────────────────────────────────────
408    // RFC-033 — Unified streaming orchestration
409    // ──────────────────────────────────────────────────────────────────
410    //
411    // The assess/crystallize external LLM gates were removed. Every message
412    // streams through the agent loop directly — the agent's own
413    // UNDERSTAND → PLAN → EXECUTE → VERIFY → REPORT protocol classifies and
414    // plans inline. The only surviving external call is `review`, which
415    // fires when a Directive carries acceptance criteria.
416
417    /// Unified entry point for every user message (RFC-033).
418    ///
419    /// A single path with no routing gate: build a [`Directive`] verbatim
420    /// from the message, resolve the [`ExecEnv`], execute via the agent
421    /// loop (which streams every token/tool/thinking event), and — only
422    /// when the directive carries acceptance criteria — run an external
423    /// [`IntentEngineOps::review`] with one retry.
424    ///
425    /// Conversation, clarification, and task depth are all decided *inside*
426    /// the agent loop now (simple chat → plain streaming reply; ambiguity →
427    /// `ask_user` / `pi-questionnaire` tool; complex work → tool calls).
428    /// This matches Claude.ai / Gemini Web, where the model's intelligence
429    /// is the classifier and there is no pre-classification step.
430    ///
431    /// # Why `review` is gated on `needs_review()`
432    /// `Directive::from_message` (used for interactive chat) carries no
433    /// acceptance criteria, so interactive chat never triggers external
434    /// review — the agent's internal VERIFY step replaces it. The review
435    /// path survives for any future/automated producer of criteria-bearing
436    /// directives; until one is wired, `verify_or_retry` is dormant.
437    ///
438    /// # Parameters
439    /// - `engine` — the LLM-backed intent engine (review only, RFC-033).
440    /// - `msg` — the user's raw message text.
441    /// - `ctx` — per-message context (session, history, project/mount hints).
442    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        // 1. Build the Directive verbatim from the message (no crystallize).
463        let mut directive = oxios_ouroboros::Directive::from_message(msg);
464
465        // 2. Resolve the execution environment from MsgCtx.
466        let env = self.resolve_exec_env(ctx, msg);
467
468        // 3. Execute — every message streams through the agent loop.
469        publish_phase("execute");
470        let mut result = self.execute_directive(&directive, &env).await?;
471        complete_phase("execute");
472
473        // 4. Optional external review — only when the directive carries
474        //    acceptance criteria (RFC-033 §3.5). Interactive chat uses
475        //    Directive::from_message (no criteria), so this is skipped and
476        //    the agent's internal VERIFY step stands in for review.
477        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    /// Unified entry point that accepts legacy-style parameters and returns
500    /// an `OrchestrationResult` (RFC-027).
501    ///
502    /// Builds a [`MsgCtx`] from the session history (if any), then delegates
503    /// to [`handle`](Self::handle). Falls back to `handle_message` if no
504    /// `IntentEngine` is wired.
505    #[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        // Get the IntentEngine (always wired by the kernel assembler).
518        let engine = self
519            .intent_engine
520            .read()
521            .clone()
522            .expect("IntentEngine not wired — kernel assembler bug");
523
524        // Build MsgCtx.
525        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        // Call the unified path.
538        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    /// Load conversation history for a session from the state store.
546    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        // RFC-032: when execution failed (budget/quota/auth/etc) and the
580        // output is empty, generate a user-friendly error message so the WS
581        // handler can relay it as an `type: "error"` chunk.
582        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    ///
622    /// Mirrors the Mount workspace resolution done by `handle_message()`
623    /// and `chat()` but packages the result as the new [`ExecEnv`] type.
624    /// Independent of the directive — runs whether the task is Trivial
625    /// or Substantial.
626    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        // active_mount_ids + mount_tag are surfaced via the legacy path;
634        // ExecEnv carries the resolved paths/context/project that the
635        // agent runtime actually consumes.
636        let _ = active_mount_ids;
637
638        // Resolve a primary project ID (matches handle_message semantics):
639        // explicit project_ids takes precedence over auto-detection.
640        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        // Touch the project to record activity (mirrors handle_message).
661        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    /// Execute a [`Directive`] under an [`ExecEnv`].
680    ///
681    async fn execute_directive(
682        &self,
683        directive: &oxios_ouroboros::Directive,
684        env: &oxios_ouroboros::ExecEnv,
685    ) -> Result<ExecutionResult> {
686        // RFC-029: route through the recovery coordinator when wired
687        // (L1 backoff / L2 model swap on provider failure). Falls back
688        // to a direct lifecycle call when no coordinator is set.
689        //
690        // Clone the Arc out of the read guard so the parking_lot guard
691        // (which is !Send) is dropped before the .await — otherwise the
692        // future is !Send and breaks tokio::spawn in the gateway.
693        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    /// Review the result against the directive's criteria; on failure,
702    /// retry once with the verdict's gaps folded back as constraints.
703    ///
704    /// RFC-033: this is the sole surviving external LLM gate. It is reached
705    /// only when `Directive::needs_review()` is true (acceptance criteria or
706    /// output schema present). `Orchestrator::handle` builds directives via
707    /// `Directive::from_message` for interactive chat, which carries no
708    /// criteria — so for interactive chat this method is **dormant** and the
709    /// agent's internal VERIFY step stands in for review. It remains wired so
710    /// any future/automated producer of criteria-bearing directives gets
711    /// impartial post-execution review. Retries are capped at one attempt.
712    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        // Check if retry is enabled (RFC-027 Decision 6).
728        // When disabled, return the initial result with the failed verdict.
729        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        // Execute with feedback: previous output + gaps injected.
744        let retry_result = self
745            .lifecycle
746            .execute_with_feedback(directive, env, &initial_result, &verdict.gaps)
747            .await?;
748
749        // Re-review.
750        let retry_verdict = engine.review(directive, &retry_result).await?;
751
752        // Track retry effectiveness.
753        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        // Return best result.
762        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/// Response envelope for [`Orchestrator::handle`] (RFC-033).
773///
774/// RFC-033 collapsed the former `Reply` / `Clarify` / `Task` variants into a
775/// single shape: every message now executes through the agent loop, so there
776/// is only ever one terminal state. The agent's reply text, tool calls, and
777/// reasoning live in `result`; `verdict` / `evaluation_passed` are `Some`
778/// only when an external review ran (a criteria-bearing directive).
779#[derive(Debug, Clone)]
780pub struct HandleResponse {
781    /// The directive that was executed (post-retry if a retry ran).
782    pub directive: Box<oxios_ouroboros::Directive>,
783    /// The execution environment resolved for this message.
784    pub env: Box<oxios_ouroboros::ExecEnv>,
785    /// The execution result (agent reply text, tool calls, reasoning).
786    pub result: Box<ExecutionResult>,
787    /// The external review verdict — `None` when no review ran.
788    pub verdict: Option<oxios_ouroboros::Verdict>,
789    /// Whether the (final) verdict passed — `None` when no review ran.
790    pub evaluation_passed: Option<bool>,
791}
792
793/// Result of a full orchestration cycle.
794#[derive(Debug, Clone, Serialize, Deserialize)]
795pub struct OrchestrationResult {
796    /// Session ID for multi-turn interviews. Pass this on follow-up messages.
797    #[serde(skip_serializing_if = "Option::is_none")]
798    pub session_id: Option<String>,
799    /// The Space ID that handled this message.
800    #[serde(skip_serializing_if = "Option::is_none")]
801    pub primary_project_id: Option<Uuid>,
802    /// Space decoration tag for the response (e.g. "[🔧 oxios]").
803    #[serde(skip_serializing_if = "Option::is_none")]
804    pub project_tag: Option<String>,
805    /// Active Mount IDs for this message (RFC-025), primary first.
806    #[serde(default, skip_serializing_if = "Vec::is_empty")]
807    pub active_mount_ids: Vec<MountId>,
808    /// Mount decoration tag for the response (e.g. "[🔧 oxios + oxi-sdk]").
809    #[serde(skip_serializing_if = "Option::is_none")]
810    pub mount_tag: Option<String>,
811    /// The response to send back to the user.
812    pub response: String,
813    /// The agent that executed (if execute phase was reached).
814    #[serde(skip_serializing_if = "Option::is_none")]
815    pub agent_id: Option<AgentId>,
816    /// The furthest phase reached: "interview" (conversation/clarify) or "execute" (task executed).
817    pub phase_reached: String,
818    /// Whether evaluation passed.
819    ///
820    /// - `None` — evaluation was not applicable (interview, chat, non-task).
821    /// - `Some(true)` — evaluation passed.
822    /// - `Some(false)` — evaluation failed or execution unsuccessful.
823    pub evaluation_passed: Option<bool>,
824    /// Output or notes from evaluation.
825    #[serde(skip_serializing_if = "Option::is_none")]
826    pub output: Option<String>,
827    /// Tool calls recorded during execution.
828    #[serde(default, skip_serializing_if = "Vec::is_empty")]
829    pub tool_calls: Vec<oxios_ouroboros::ToolCallRecord>,
830    /// Structured interview questions (chat UI redesign — interactive
831    /// interview). Populated when the interview phase needs clarification
832    /// and the LLM produced a structured form of the questions. The
833    /// Gateway forwards this to the WebSocket as an `interview` chunk;
834    /// the Web UI renders it as interactive widgets (chips, yes/no
835    /// buttons). When `None`, the frontend falls back to rendering
836    /// `response` as plain markdown.
837    #[serde(default, skip_serializing_if = "Option::is_none")]
838    pub interview_questions: Option<Vec<oxios_ouroboros::InterviewQuestionOutput>>,
839    /// Current interview round (1-based). Populated alongside
840    /// `interview_questions`. Drives the "Round N/M" indicator.
841    #[serde(default, skip_serializing_if = "Option::is_none")]
842    pub interview_round: Option<u32>,
843
844    /// P4 (§7 persistence): full concatenated reasoning text from the
845    /// agent's `ThinkingDelta` stream. Surfaced into the terminal
846    /// `OutgoingMessage` metadata so chat.rs can persist it alongside
847    /// `tool_calls` and restore on session reopen.
848    #[serde(default, skip_serializing_if = "String::is_empty")]
849    pub reasoning_text: String,
850    /// Provider failure classification (RFC-029). `Some` when execution
851    /// failed with a classifiable provider/infra error; `None` on success,
852    /// interview, clarify, or unclassified failure.
853    #[serde(default, skip_serializing_if = "Option::is_none")]
854    pub failure_class: Option<oxios_ouroboros::FailureClass>,
855}
856/// Generate a user-facing error message based on the failure class.
857/// Used when execution failed with no output text to show.
858fn 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
898/// Render the body of the `## Workspace Context` prompt section (RFC-025).
899///
900/// The caller (`build_system_prompt`) wraps this in the `## Workspace
901/// Context` header. Returns `None` when there are no Mounts to describe.
902///
903/// Fill order respects the prompt budget (~1500 tokens soft):
904/// 1. Primary Mount — full (description + summary + path).
905/// 2. Secondary Mounts — name + path + one-line summary only.
906fn 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                // First ~3 lines of the agent-written description.
924                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            // Secondary: name + path + one-line summary only.
941            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        // Primary gets full description.
973        assert!(body.contains("Agent OS."));
974        assert!(body.contains("_Rust agent OS_"));
975        // Secondary is terse.
976        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    /// End-to-end: a real MountManager + Orchestrator-less call to
985    /// `resolve_mount_workspace` proves that detection seeds the primary,
986    /// builds the context body, and collects all paths (multi-path access).
987    #[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        // Register two mounts.
997        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        // Build a minimal Orchestrator-free resolver path: replicate what
1015        // resolve_mount_workspace does, but against the manager directly,
1016        // since the full Orchestrator needs many subsystems.
1017        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        // Collect paths like the orchestrator does.
1026        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    /// Detection layer 1 (name match) seeds the primary when no explicit
1040    /// mount_ids are given — the core promise of RFC-025.
1041    #[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}