Skip to main content

oxios_kernel/
agent_runtime.rs

1//! Agent runtime: wraps oxi-sdk's Agent for directive execution.
2//!
3//! The AgentRuntime uses `OxiosEngine.oxi().agent()` (AgentBuilder pattern)
4//! to construct agents with full middleware, observability, and security
5//! integration from oxi-sdk 0.24.0.
6//!
7//! # Architecture
8//!
9//! All tool access goes through `KernelHandle` — the single syscall-table-like
10//! path for agent OS control. The runtime:
11//!
12//! 1. Resolves the agent's CSpace from persona/role/hint
13//! 2. Registers tools via `register_tools_from_cspace()`
14//! 3. Optionally queries `ToolRetriever` for semantic capability hints
15//! 4. Builds an `Agent` via `AgentBuilder` with middleware pipeline
16//! 5. Runs via `Agent::run_streaming()` for real-time event processing
17//!
18//! # oxi-sdk 0.23.0 Integration
19//!
20//! Uses `AgentBuilder` for agent construction with:
21//! - `.with_rate_limit()` — tool call rate limiting
22//! - `.with_token_budget()` — per-execution token caps
23//! - `.tracer()` / `.cost_tracker()` — observability hooks
24//! ## Routing integration (RFC-011)
25//!
26//! Model usage events (`AgentEvent::Usage`) are recorded to the shared
27//! `RoutingStats` so the Web dashboard can display per-model call counts
28//! and estimated costs.
29
30use anyhow::Result;
31use oxi_sdk::observability::AuditTrail;
32use oxi_sdk::{
33    Agent, AgentConfig, AgentEvent, CompactionEvent, CompactionStrategy, ProviderResolver,
34};
35use oxi_sdk::{SearchCache, ToolExecutionMode, ToolRegistry};
36use parking_lot::Mutex;
37use std::collections::HashMap;
38use std::sync::Arc;
39// RFC-014 Phase D: `ToolRegistry::register_arc` is used in the AgentBuilder
40// path to attach CSpace tools after `builder.build()` returns.
41
42use crate::access_manager::{AccessGate, AgentContext, TracingAuditSink, TrailAuditSink};
43use crate::capability::resolve::resolve_cspace;
44use crate::engine::OxiosEngine;
45use crate::memory::{MemoryEntry, MemoryManager, MemoryType};
46use crate::persona::PersonaManager;
47use crate::tools::registration::register_tools_from_cspace_gated;
48
49use crate::KernelHandle;
50use crate::event_bus::KernelEvent;
51use crate::session_context::SessionContext;
52use crate::types::AgentId;
53use oxios_ouroboros::{Directive, ExecEnv, ExecutionResult};
54
55/// Global LLM circuit breaker instance — delegates to oxi-sdk's ProviderCircuitBreaker.
56static LLM_CIRCUIT_BREAKER: std::sync::OnceLock<oxi_sdk::ProviderCircuitBreaker> =
57    std::sync::OnceLock::new();
58
59/// Get the global LLM circuit breaker.
60fn get_llm_circuit_breaker() -> &'static oxi_sdk::ProviderCircuitBreaker {
61    LLM_CIRCUIT_BREAKER.get_or_init(|| {
62        oxi_sdk::ProviderCircuitBreaker::new(
63            "global".to_string(),
64            oxi_sdk::CircuitBreakerConfig::default(),
65        )
66    })
67}
68
69/// Streaming delta emitted by the runtime's `AgentEvent` callback.
70///
71/// P1 wires only `Text` (one `AgentEvent::TextChunk { text }` → one delta).
72/// P4 adds `Thinking` / `ThinkingDelta` for the live 추론 panel. The enum
73/// is `#[non_exhaustive]` so adding variants later doesn't break collectors.
74#[derive(Debug, Clone)]
75#[non_exhaustive]
76pub enum StreamDelta {
77    /// One-shot model announcement. Emitted exactly once at the start of a
78    /// streaming turn so the chat UI can mark the response with the actual
79    /// model after fallback resolution.
80    Model(String),
81    /// One text chunk from the model.
82    Text(String),
83
84    /// The model has entered extended thinking (no payload — signal only).
85    /// Used by the LiveActivityBar to transition into "추론 중" state.
86    Thinking,
87    /// One batched chunk of reasoning text. The runtime coalesces
88    /// `AgentEvent::ThinkingDelta { text }` into ~50ms batches before
89    /// emitting this delta to avoid flooding the mpsc.
90    ThinkingDelta(String),
91}
92
93/// Connection-scoped streaming sink sender.
94///
95/// Wrapped in `Arc` so it can be cloned cheaply across the
96/// orchestrator → lifecycle → runtime boundary. The receiver lives in a
97/// collector task owned by the gateway dispatch layer; see the design doc
98/// §8.1 for the conn_id scoping rationale.
99pub type StreamingSinkTx = std::sync::Arc<tokio::sync::mpsc::UnboundedSender<StreamDelta>>;
100
101/// Configuration for creating AgentRuntime instances.
102#[derive(Debug, Clone)]
103pub struct AgentRuntimeConfig {
104    /// Model ID in `provider/model` format (e.g. `anthropic/claude-sonnet-4-20250514`).
105    pub model_id: String,
106    /// How to execute tool calls within a single turn.
107    pub tool_execution: ToolExecutionMode,
108    /// Whether auto-retry is enabled for retryable LLM errors.
109    pub auto_retry_enabled: bool,
110    /// Scratch workspace directory for temp files.
111    pub workspace_dir: Option<std::path::PathBuf>,
112    /// API key resolved from CredentialStore at build time.
113    pub api_key: Option<String>,
114    /// Per-provider options for fine-grained control.
115    pub provider_options: Option<oxi_sdk::ProviderOptions>,
116    /// Rate limit for tool calls (requests per minute). 0 = unlimited.
117    pub rate_limit_per_minute: usize,
118    /// Token budget per agent execution. 0 = unlimited.
119    pub token_budget: usize,
120    /// Enable audit logging for all tool executions.
121    pub audit_tool_calls: bool,
122    /// Provider-level RPM for rate-limited provider pool. 0 = no pooling.
123    /// When set, uses `OxiosEngine::pooled_provider()` instead of `create_provider()`.
124    pub provider_rpm: u32,
125    /// Maximum bytes of a tool result before truncation (RFC-035 gap 1).
126    /// When set, tool results exceeding this are truncated in the message
127    /// history with a `"... [truncated: N bytes omitted]"` marker.
128    /// `None` = unlimited (opt-in). Threaded to `AgentConfig::max_tool_result_bytes`.
129    pub max_tool_result_bytes: Option<usize>,
130    // NOTE: subagent_max_depth was removed — oxi-agent hardcodes the
131    // in-process recursion cap to 3 (subagent.rs:649). `AgentConfig.subagent_depth`
132    // is the CURRENT depth (always 0 for top-level agents), not a max.
133}
134
135impl Default for AgentRuntimeConfig {
136    fn default() -> Self {
137        Self {
138            model_id: String::new(),
139            tool_execution: ToolExecutionMode::Parallel,
140            auto_retry_enabled: true,
141            workspace_dir: None,
142            api_key: None,
143            provider_options: None,
144            rate_limit_per_minute: 0,
145            token_budget: 0,
146            audit_tool_calls: false,
147            provider_rpm: 0,
148            max_tool_result_bytes: None,
149        }
150    }
151}
152
153/// Mutable state shared between the event callback and the main execute flow.
154#[derive(Default)]
155struct ExecuteState {
156    final_content: String,
157    steps_completed: usize,
158    success: bool,
159    /// Collected trajectory steps for SONA learning (RFC-020 Phase 2).
160    /// P4 (§7 persistence): concatenated reasoning text from
161    /// `AgentEvent::ThinkingDelta { text }`. Surfaced via `ExecutionResult`
162    /// metadata on turn completion, capped at ~4 KB to bound storage.
163    reasoning_text: String,
164    /// Ordered by insertion — parallel tools get their final position
165    /// resolved when they complete, preserving approximate execution order.
166    trajectory_steps: Vec<oxios_memory::memory::sona::TrajectoryStep>,
167    /// Map of tool_call_id → (start instant, index into trajectory_steps).
168    /// Used to correlate ToolExecutionEnd with the correct step when
169    /// parallel tool calls complete out of order.
170    pending_tools: std::collections::HashMap<String, (std::time::Instant, usize)>,
171    /// Ordered tool_call_ids matching trajectory_steps indices.
172    /// Pushed in ToolExecutionStart, same order as trajectory_steps.
173    tool_call_ids: Vec<String>,
174    /// Per-step tool args (JSON string) captured from ToolExecutionStart.
175    tool_args_map: std::collections::HashMap<String, String>,
176    /// Per-step error flag from ToolExecutionEnd.
177    tool_error_map: std::collections::HashMap<String, bool>,
178    /// Per-step start timestamp (UTC) from ToolExecutionStart.
179    tool_timestamps: std::collections::HashMap<String, chrono::DateTime<chrono::Utc>>,
180    /// Cumulative input tokens from AgentEvent::Usage.
181    total_input_tokens: u64,
182    /// Cumulative output tokens from AgentEvent::Usage.
183    total_output_tokens: u64,
184}
185
186/// Runtime that wraps an oxi-sdk `Agent` for executing directives.
187///
188/// Each call to [`AgentRuntime::execute_directive`] creates a fresh `Agent`,
189/// builds a ToolRegistry based on the agent's CSpace, and runs it to completion.
190///
191/// All OS-level access goes through `KernelHandle` — the single syscall table
192/// for agent control. Provider/model resolution goes through `EngineHandle`,
193/// which returns the latest `OxiosEngine` (hot-swapped on config change).
194pub struct AgentRuntime {
195    engine_handle: Arc<crate::engine::EngineHandle>,
196    config: AgentRuntimeConfig,
197    /// Single path to all kernel services.
198    kernel_handle: Arc<KernelHandle>,
199    /// Persona manager for system prompt injection.
200    persona_manager: Option<Arc<PersonaManager>>,
201    /// Semantic tool retriever for capability discovery.
202    tool_retriever: Option<Arc<crate::tools::retrieval::ToolRetriever>>,
203    /// Shared routing stats (shared with EngineApi).
204    routing_stats: Option<Arc<crate::kernel_handle::RoutingStats>>,
205    /// Autonomous persistence hook (RFC-016).
206    persistence_hook: Option<Arc<crate::persistence_hook::PersistenceHook>>,
207    /// Per-session assistant message index counter (RFC-016).
208    session_msg_counter: Arc<Mutex<HashMap<String, usize>>>,
209}
210
211impl AgentRuntime {
212    /// Creates a new agent runtime with engine handle and kernel access.
213    ///
214    /// The active model is resolved live from `engine_handle` on each
215    /// `execute()` (reads the post-hot-swap default) — there is no frozen
216    /// model id at construction. Tool access goes through `kernel_handle`.
217    pub fn new(
218        engine_handle: Arc<crate::engine::EngineHandle>,
219        kernel_handle: Arc<KernelHandle>,
220        routing_stats: Option<Arc<crate::kernel_handle::RoutingStats>>,
221    ) -> Self {
222        Self {
223            engine_handle,
224            config: AgentRuntimeConfig::default(),
225            kernel_handle,
226            persona_manager: None,
227            tool_retriever: None,
228            routing_stats,
229            persistence_hook: None,
230            session_msg_counter: Arc::new(Mutex::new(HashMap::new())),
231        }
232    }
233
234    /// Attach a PersonaManager for persona system prompt injection.
235    pub fn with_persona_manager(mut self, pm: Arc<PersonaManager>) -> Self {
236        self.persona_manager = Some(pm);
237        self
238    }
239
240    /// Set the runtime config (overrides defaults).
241    pub fn with_config(mut self, config: AgentRuntimeConfig) -> Self {
242        self.config = config;
243        self
244    }
245
246    /// Attach a ToolRetriever for semantic capability discovery.
247    pub fn with_tool_retriever(
248        mut self,
249        retriever: Arc<crate::tools::retrieval::ToolRetriever>,
250    ) -> Self {
251        self.tool_retriever = Some(retriever);
252        self
253    }
254
255    /// Attach a PersistenceHook for autonomous persistence (RFC-016).
256    pub fn with_persistence_hook(
257        mut self,
258        hook: Arc<crate::persistence_hook::PersistenceHook>,
259    ) -> Self {
260        self.persistence_hook = Some(hook);
261        self
262    }
263
264    /// Execute a Directive with its ExecEnv (RFC-027 unified intent handling).
265    ///
266    /// Maps Directive/ExecEnv fields to the agent's runtime inputs and runs
267    /// the tool-calling loop to completion. The persistence hook (RFC-016)
268    /// runs on this path.
269    pub async fn execute_directive(
270        &self,
271        agent_id: AgentId,
272        directive: &Directive,
273        env: &ExecEnv,
274        session_ctx: &mut SessionContext,
275    ) -> Result<ExecutionResult> {
276        // RFC-033: prefer the chat session id the gateway registered its
277        // streaming sink under (set by the orchestrator from ctx.session_id)
278        // so token/tool/thinking deltas and RFC-015 events correlate with the
279        // live WS sink. Fall back to the agent id for non-chat callers
280        // (token-maxing, A2A) that leave env.session_id unset.
281        let session_id: Option<String> = env
282            .session_id
283            .clone()
284            .or_else(|| Some(agent_id.to_string()));
285        self.execute_directive_with_session(agent_id, directive, env, session_ctx, session_id)
286            .await
287    }
288    /// Like [`execute_directive`](Self::execute_directive) but with an
289    /// explicit session_id for RFC-015 chat transparency event publishing.
290    pub async fn execute_directive_with_session(
291        &self,
292        agent_id: AgentId,
293        directive: &Directive,
294        env: &ExecEnv,
295        session_ctx: &mut SessionContext,
296        session_id: Option<String>,
297    ) -> Result<ExecutionResult> {
298        self.execute_inner(
299            agent_id,
300            &directive.goal,
301            &directive.original_request,
302            &directive.constraints,
303            &directive.acceptance_criteria,
304            env.cspace_hint.as_deref(),
305            &env.mount_paths,
306            env.workspace_context.as_deref(),
307            session_ctx,
308            session_id,
309            Some(directive),
310            env.model_override.as_deref(),
311            env.role.as_deref(),
312            env.restore_state.as_ref(),
313        )
314        .await
315    }
316
317    /// Shared execution body for the directive path.
318    ///
319    /// Performs the full agent-runtime pipeline: prompt assembly, capability
320    /// retrieval, memory + knowledge recall, CSpace tool registration,
321    /// model resolution, agent run, post-execution summary, and the
322    /// autonomous persistence hook (RFC-016).
323    #[allow(clippy::too_many_arguments)]
324    async fn execute_inner(
325        &self,
326        agent_id: AgentId,
327        goal: &str,
328        original_request: &str,
329        constraints: &[String],
330        acceptance_criteria: &[String],
331        cspace_hint: Option<&str>,
332        mount_paths: &[std::path::PathBuf],
333        workspace_context: Option<&str>,
334        session_ctx: &mut SessionContext,
335        session_id: Option<String>,
336        persistence_directive: Option<&Directive>,
337        model_override: Option<&str>,
338        role: Option<&str>,
339        restore_state: Option<&serde_json::Value>,
340    ) -> Result<ExecutionResult> {
341        let prompt = build_user_prompt_inner(goal, acceptance_criteria);
342
343        // Get active persona system prompt.
344        let persona_prompt = self
345            .persona_manager
346            .as_ref()
347            .map(|pm| pm.active_system_prompt())
348            .filter(|s| !s.trim().is_empty());
349
350        // Determine persona role for CSpace resolution.
351        let persona_role = self
352            .persona_manager
353            .as_ref()
354            .and_then(|pm| pm.get_active_persona().map(|p| p.role.clone()));
355
356        // Resolve CSpace from persona role, hint, or default.
357        let cspace = resolve_cspace(
358            cspace_hint,
359            persona_role.as_deref(),
360            Some("worker"),
361            agent_id,
362        );
363
364        // Build system prompt (without SKILL.md injection — capabilities are
365        // surfaced through the CSpace tool set + semantic retrieval instead).
366        let mut system_prompt = build_system_prompt_inner(
367            goal,
368            original_request,
369            constraints,
370            acceptance_criteria,
371            workspace_context,
372            persona_prompt.as_deref(),
373            None,
374            None,
375        );
376
377        // Semantic capability retrieval: find tools relevant to this task's goal.
378        let capabilities_xml = if let Some(ref retriever) = self.tool_retriever {
379            match retriever.embedder().embed(goal).await {
380                Ok(query_vec) => {
381                    let results = retriever.retrieve(&query_vec, 8);
382                    if results.is_empty() {
383                        None
384                    } else {
385                        let xml = crate::tools::retrieval::format_capability_index(&results);
386                        tracing::info!(count = results.len(), "Retrieved relevant capabilities");
387                        Some(xml)
388                    }
389                }
390                Err(e) => {
391                    tracing::warn!(error = %e, "Failed to embed goal for retrieval");
392                    None
393                }
394            }
395        } else {
396            None
397        };
398
399        // Build kernel manifest from CSpace active domains.
400        let kernel_manifest = {
401            let domains = cspace.active_domains();
402            if domains.is_empty() {
403                None
404            } else {
405                Some(crate::tools::retrieval::build_kernel_manifest(&domains))
406            }
407        };
408
409        // Rebuild system prompt with capabilities and manifest if available.
410        if capabilities_xml.is_some() || kernel_manifest.is_some() {
411            system_prompt = build_system_prompt_inner(
412                goal,
413                original_request,
414                constraints,
415                acceptance_criteria,
416                workspace_context,
417                persona_prompt.as_deref(),
418                capabilities_xml.as_deref(),
419                kernel_manifest.as_deref(),
420            );
421        }
422
423        // Blend relevant memories into system prompt.
424        let memory_manager = self.kernel_handle.agents.memory_manager();
425        match memory_manager
426            .recall_with_proactive(goal, &mut session_ctx.recall_timing)
427            .await
428        {
429            Ok(memories) if !memories.is_empty() => {
430                tracing::info!(count = memories.len(), "Recalled memories for task");
431                system_prompt = memory_manager.blend_into_prompt(&memories, &system_prompt);
432            }
433            Ok(_) => tracing::debug!("No memories recalled"),
434            Err(e) => tracing::warn!(error = %e, "Failed to recall memories"),
435        }
436
437        // Inject learned strategy from SONA (RFC-020 Phase 2).
438        if let Some(sona) = memory_manager.sona_engine() {
439            match sona.adapt(goal).await {
440                Ok(Some(pattern)) if pattern.confidence > 0.5 => {
441                    tracing::info!(
442                        domain = %pattern.domain,
443                        confidence = pattern.confidence,
444                        "SONA learned pattern injected"
445                    );
446                    system_prompt.push_str(&format!(
447                        "\n\n## Learned Strategy (confidence: {:.0}%)\n{}\n",
448                        pattern.confidence * 100.0,
449                        pattern.strategy,
450                    ));
451                }
452                Ok(_) => tracing::debug!("No high-confidence SONA pattern found"),
453                Err(e) => tracing::debug!(error = %e, "SONA adapt failed (non-fatal)"),
454            }
455        }
456
457        // Blend relevant knowledge notes into system prompt (KnowledgeLens, RFC-003 Phase 3).
458        match self
459            .kernel_handle
460            .knowledge_lens
461            .recall_for_context(goal, 5)
462            .await
463        {
464            Ok(ctx) if !ctx.notes.is_empty() => {
465                tracing::info!(
466                    notes = ctx.notes.len(),
467                    memories = ctx.memories.len(),
468                    "Recalled knowledge context for task"
469                );
470                let knowledge_blend = ctx
471                    .notes
472                    .iter()
473                    .take(3)
474                    .map(|n| format!("## {}\n\n{}", n.name, n.content))
475                    .collect::<Vec<_>>()
476                    .join("\n\n");
477                system_prompt.push_str("\n\n## Relevant Knowledge\n\n");
478                system_prompt.push_str(&knowledge_blend);
479            }
480            Ok(_) => tracing::debug!("No knowledge recalled"),
481            Err(e) => tracing::warn!(error = %e, "Failed to recall knowledge context"),
482        }
483
484        // RFC-032 + RFC-029 P2: resolve the model. Precedence:
485        //   1.  — set by RecoveryCoordinator during fallback
486        //      retries. MUST win over role routing: if a role-mapped model
487        //      is the one that just failed, letting role override recovery
488        //      would loop the failure.
489        //   2.  — when the WS client supplied a role
490        //      hint, consult  for a role → model
491        //      mapping. Read from  directly (not via the
492        //      EngineApi facade) so the resolution stays on the hot path.
493        //   3.  — the configured default.
494        let engine = self.engine_handle.get();
495        let model_id = model_override
496            .map(|s| s.to_string())
497            .or_else(|| role.and_then(|r| self.kernel_handle.engine.model_for_role(r)))
498            .unwrap_or_else(|| engine.default_model_id().to_string());
499        // Validates fail-fast: a bad model ID is rejected here at execute entry.
500        engine.resolve_model(&model_id)?;
501        // Synthetic per-execution ID for tracing.
502        let exec_id = uuid::Uuid::new_v4();
503
504        // Build the agent. Refresh config.model_id to the live value so every
505        // downstream consumer (AgentConfig, legacy provider path, usage callback)
506        // uses the same model as the interview/crystallize phases — no frozen boot
507        // string that silently diverges from what interview used.
508        let mut config = self.config.clone();
509        config.model_id = model_id;
510        let kernel_handle = Arc::clone(&self.kernel_handle);
511
512        // Extract audit trail from kernel for TrailAuditSink wiring.
513        let audit_trail: Option<Arc<AuditTrail>> =
514            Some(Arc::clone(&self.kernel_handle.security.audit_trail));
515
516        let (
517            mut final_content,
518            steps_completed,
519            success,
520            trajectory_steps,
521            agent,
522            tool_call_ids,
523            tool_args_map,
524            tool_error_map,
525            tool_timestamps,
526            total_input_tokens,
527            total_output_tokens,
528            reasoning_text,
529        ) = {
530            run_agent(
531                &config,
532                &engine,
533                kernel_handle,
534                system_prompt,
535                prompt,
536                exec_id,
537                goal.to_string(),
538                agent_id,
539                cspace,
540                audit_trail,
541                self.routing_stats.clone(),
542                session_id.clone(),
543                mount_paths,
544                restore_state,
545            )
546            .await?
547        };
548
549        // ── Post-execution: safety net for empty final content ──
550        //
551        // oxi 0.32.0 removed max_iterations — the loop now exits naturally
552        // when the LLM produces a text-only response (pi-agent behavior).
553        // This block is kept as a safety net in case the LLM returns empty
554        // text despite a natural exit (rare, but possible).
555        if final_content.is_empty() && !trajectory_steps.is_empty() {
556            let tool_summary: Vec<String> = trajectory_steps
557                .iter()
558                .enumerate()
559                .map(|(i, step)| {
560                    let truncated = if step.output.len() > 800 {
561                        // Char-boundary safe truncation: roll back to the
562                        // nearest UTF-8 boundary so multibyte sequences
563                        // (Korean, CJK, emoji) don't panic on byte slicing.
564                        let mut end = 800;
565                        while end > 0 && !step.output.is_char_boundary(end) {
566                            end -= 1;
567                        }
568                        format!("{}...", &step.output[..end])
569                    } else {
570                        step.output.clone()
571                    };
572                    format!("{}. [{}] {}", i + 1, step.input, truncated)
573                })
574                .collect();
575            let summary_prompt = format!(
576                "도구 실행 결과:\n\n{}\n\n\
577                 위 결과를 바탕으로 사용자의 요청에 대해 자연스럽게 한국어로 답변해주세요. \
578                 도구의 원시 출력을 그대로 복사하지 말고, 의미 있는 내용만 정리해서 전달하세요.",
579                tool_summary.join("\n")
580            );
581            match agent.run(summary_prompt).await {
582                Ok((response, _events)) => {
583                    if !response.content.is_empty() {
584                        tracing::info!(exec_id = %exec_id, "Post-execution summary generated");
585                        final_content = response.content;
586                    }
587                }
588                Err(e) => {
589                    tracing::warn!(error = %e, "Post-execution summary failed");
590                }
591            }
592        }
593
594        // Map trajectory steps to tool call records for the execution result.
595        // tool_call_ids[i] corresponds to trajectory_steps[i].
596        let tool_calls: Vec<oxios_ouroboros::ToolCallRecord> = trajectory_steps
597            .iter()
598            .enumerate()
599            .map(|(i, step)| {
600                let tc_id = tool_call_ids.get(i).cloned().unwrap_or_default();
601                let args_str = tool_call_ids
602                    .get(i)
603                    .and_then(|id| tool_args_map.get(id))
604                    .cloned()
605                    .unwrap_or_default();
606                let is_error = tool_call_ids
607                    .get(i)
608                    .and_then(|id| tool_error_map.get(id))
609                    .copied()
610                    .unwrap_or(false);
611                let timestamp = tool_call_ids
612                    .get(i)
613                    .and_then(|id| tool_timestamps.get(id))
614                    .copied();
615                let input_str = truncate_json_str(&args_str, 500);
616                oxios_ouroboros::ToolCallRecord {
617                    tool: step.input.clone(),
618                    input: input_str,
619                    output: step.output.clone(),
620                    duration_ms: step.duration_ms,
621                    is_error,
622                    tool_call_id: tc_id,
623                    timestamp,
624                }
625            })
626            .collect();
627
628        tracing::info!(
629            exec_id = %exec_id,
630            steps = steps_completed,
631            success,
632            tool_calls = tool_calls.len(),
633            "AgentRuntime finished"
634        );
635
636        let result = ExecutionResult {
637            output: final_content.clone(),
638            steps_completed,
639            success,
640            tool_calls,
641            failure_class: None,
642            restore_state: None,
643            tokens_input: total_input_tokens,
644            tokens_output: total_output_tokens,
645            model_id: self.engine_handle.get().default_model_id().to_string(),
646            reasoning_text,
647        };
648
649        // RFC-016: Autonomous persistence hook.
650        // Runs after successful execution, fire-and-forget.
651        if let Some(directive) = persistence_directive
652            && success
653            && let Some(hook) = &self.persistence_hook
654        {
655            let already_saved_knowledge = trajectory_steps
656                .iter()
657                .any(|s| s.input == "knowledge" && s.output.contains("written successfully"));
658            let hook = hook.clone();
659            let directive_clone = directive.clone();
660            let traj_clone = trajectory_steps.clone();
661            let output_clone = final_content.clone();
662            let sid = session_id.clone();
663            // Compute the assistant message index for this execution.
664            // Increment per-session counter, then use the pre-increment value.
665            let msg_index = {
666                let mut counter = self.session_msg_counter.lock();
667                let idx = counter.entry(sid.clone().unwrap_or_default()).or_insert(0);
668                let current = *idx;
669                *idx += 1;
670                current
671            };
672            tokio::spawn(async move {
673                match hook
674                    .evaluate(
675                        &directive_clone,
676                        &traj_clone,
677                        &output_clone,
678                        already_saved_knowledge,
679                    )
680                    .await
681                {
682                    Ok(plan) => {
683                        if !plan.memory.is_empty() || !plan.knowledge.is_empty() {
684                            tracing::info!(
685                                memory = plan.memory.len(),
686                                knowledge = plan.knowledge.len(),
687                                message_index = msg_index,
688                                "PersistenceHook executing plan"
689                            );
690                            let session_id = sid.unwrap_or_default();
691                            hook.execute_plan(plan, &session_id, msg_index).await;
692                        }
693                    }
694                    Err(e) => tracing::warn!(error = %e, "PersistenceHook evaluate failed"),
695                }
696            });
697        }
698
699        Ok(result)
700    }
701}
702
703/// Create and run an oxi-sdk `Agent` with CSpace-based tool registration.
704///
705/// Uses `engine.oxi().agent()` (AgentBuilder) for full middleware,
706/// observability, and security integration from oxi-sdk 0.23.0.
707#[allow(clippy::too_many_arguments)]
708async fn run_agent(
709    config: &AgentRuntimeConfig,
710    engine: &OxiosEngine,
711    kernel_handle: Arc<KernelHandle>,
712    system_prompt: String,
713    prompt: String,
714    exec_id: uuid::Uuid,
715    goal: String,
716    agent_id: AgentId,
717    cspace: crate::capability::CSpace,
718    audit_trail: Option<Arc<AuditTrail>>,
719    routing_stats: Option<Arc<crate::kernel_handle::RoutingStats>>,
720    session_id: Option<String>,
721    mount_paths: &[std::path::PathBuf],
722    restore_state: Option<&serde_json::Value>,
723) -> Result<(
724    String,
725    usize,
726    bool,
727    Vec<oxios_memory::memory::sona::TrajectoryStep>,
728    Arc<Agent>,
729    Vec<String>,
730    std::collections::HashMap<String, String>,
731    std::collections::HashMap<String, bool>,
732    std::collections::HashMap<String, chrono::DateTime<chrono::Utc>>,
733    u64,
734    u64,
735    String,
736)> {
737    // Extract workspace.
738    // RFC-025: the primary Mount's first path is the CWD; otherwise the
739    // configured workspace_dir, otherwise a per-agent temp dir. Paths now
740    // come only from Mounts — the legacy config.project_paths fallback was
741    // removed when the RFC-025 migration completed.
742    let workspace = if !mount_paths.is_empty() {
743        mount_paths[0].clone()
744    } else if let Some(ws) = &config.workspace_dir {
745        ws.clone()
746    } else {
747        std::env::temp_dir()
748            .join("oxios-agent-workspace")
749            .join(agent_id.to_string())
750    };
751
752    // Ensure workspace exists.
753    let _ = std::fs::create_dir_all(&workspace);
754
755    tracing::debug!(workspace = %workspace.display(), "Agent workspace scoped");
756
757    // Ensure all paths the agent might access are in allowed_paths.
758    //
759    // AgentLifecycleManager::ensure_permissions() adds kernel.workspace (~/.oxios/workspace),
760    // but the agent operates in different directories depending on context:
761    //
762    //   1. Process CWD — oxi-sdk 0.35+ bakes `workspace_dir` into file tools
763    //      via `with_cwd`, so ReadTool/LsTool resolve relatives against the
764    //      workspace, NOT the process CWD. However, oxios's own CSpace tools
765    //      (kernel-bridge tools wrapped in GatedTool) and bash/exec
766    //      subprocesses may still resolve against the process CWD. We grant
767    //      it as a safety net so those tools aren't denied by GatedTool.
768    //   2. The designated workspace — computed from mount_paths / workspace_dir / temp.
769    //   3. Kernel workspace — state store path for sessions, etc.
770    //   4. /tmp -- general temp file access.
771    //
772    // All four must be in allowed_paths before GatedTool wraps any tool.
773    {
774        use crate::access_manager::{Role, Subject};
775        let agent_name = format!("agent-{agent_id}");
776        let mut am = kernel_handle.exec.access_manager().lock();
777        let perms = am.get_or_create_permissions(&agent_name);
778
779        // 1. CWD -- critical: oxi-sdk resolves relative paths here
780        if let Ok(cwd) = std::env::current_dir() {
781            let cwd_pattern = format!("{}/**", cwd.to_string_lossy().trim_end_matches('/'));
782            if !perms.allowed_paths.iter().any(|p| p == &cwd_pattern) {
783                perms.allow_path(&cwd_pattern);
784                tracing::debug!(
785                    agent = %agent_name,
786                    path = %cwd_pattern,
787                    "Added CWD to agent allowed paths"
788                );
789            }
790        }
791
792        // 2. Designated workspace
793        let ws_pattern = format!("{}/**", workspace.to_string_lossy().trim_end_matches('/'));
794        if !perms.allowed_paths.iter().any(|p| p == &ws_pattern) {
795            perms.allow_path(&ws_pattern);
796        }
797
798        // 2b. RFC-025: every bound Mount grants path access.
799        //     This fixes the latent gap where only project_paths[0] was
800        //     accessible — now all Mount paths (multi-path work) are allowed.
801        //     Parent patterns already covering a path are skipped.
802        for mount_path in mount_paths {
803            let pattern = format!("{}/**", mount_path.to_string_lossy().trim_end_matches('/'));
804            if !perms.allowed_paths.iter().any(|p| p == &pattern) {
805                perms.allow_path(&pattern);
806                tracing::debug!(
807                    agent = %agent_name,
808                    path = %pattern,
809                    "Added Mount path to agent allowed paths (RFC-025)"
810                );
811            }
812        }
813
814        // 3. Kernel workspace (state store path)
815        let kernel_ws = kernel_handle
816            .state
817            .workspace_path()
818            .to_string_lossy()
819            .to_string();
820        let kernel_ws_pattern = format!("{}/**", kernel_ws.trim_end_matches('/'));
821        if kernel_ws_pattern != ws_pattern
822            && !perms.allowed_paths.iter().any(|p| p == &kernel_ws_pattern)
823        {
824            perms.allow_path(&kernel_ws_pattern);
825        }
826
827        // 4. /tmp -- for general temp file access
828        if !perms.allowed_paths.iter().any(|p| p == "/tmp/**") {
829            perms.allow_path("/tmp/**");
830        }
831
832        // Ensure RBAC Superuser role so AccessGate Layer 1 passes.
833        let rbac_subject = Subject::Agent(agent_id);
834        am.rbac_manager_mut()
835            .assign_role(rbac_subject, Role::Superuser);
836    }
837
838    // Start distributed trace span for this agent execution.
839    let _trace_guard = crate::observability::tracer().start(
840        format!("exec-{}", &exec_id.to_string()[..8]).as_str(),
841        oxi_sdk::SpanKind::Agent,
842    );
843
844    // ── Register tools based on CSpace (with access gate) ──
845    let registry = ToolRegistry::new();
846    let search_cache = Arc::new(SearchCache::new());
847
848    // Build agent context for security
849    let agent_context = AgentContext {
850        agent_id,
851        agent_name: format!("agent-{agent_id}"),
852        cspace: Arc::new(cspace.clone()),
853    };
854
855    // Build audit sink: TrailAuditSink (Merkle chain + JSONL) when audit_trail
856    // is available, otherwise fall back to TracingAuditSink.
857    let audit_sink: Arc<dyn crate::access_manager::AuditSink> = if let Some(trail) = audit_trail {
858        let audit_path = kernel_handle
859            .state
860            .workspace_path()
861            .join("audit")
862            .join("access.jsonl");
863        Arc::new(TrailAuditSink::new(trail, audit_path))
864    } else {
865        Arc::new(TracingAuditSink)
866    };
867
868    // Build access gate from kernel's security infrastructure
869    let access_gate = Arc::new(AccessGate::new(
870        kernel_handle.exec.access_manager().clone(),
871        Arc::new(kernel_handle.exec.config_snapshot()),
872        audit_sink,
873    ));
874
875    register_tools_from_cspace_gated(
876        &registry,
877        &kernel_handle,
878        &cspace,
879        search_cache,
880        agent_id,
881        access_gate,
882        agent_context,
883    );
884
885    tracing::info!(
886        exec_id = %exec_id,
887        capabilities = cspace.len(),
888        "Tools registered from CSpace"
889    );
890
891    // ── Build AgentConfig ──
892    //
893    // RFC-014 Phase D: `system_prompt` is also passed to the new
894    // `AgentBuilder::system_prompt()` (which overrides the value embedded
895    // in `AgentConfig` at build time). We clone here so the builder path
896    // can consume the value while the legacy `Agent::new_with_resolver`
897    // path still sees it in the config.
898    let agent_config = AgentConfig {
899        name: format!("agent-{agent_id}"),
900        description: None,
901        model_id: config.model_id.clone(),
902        system_prompt: Some(system_prompt.clone()),
903        timeout_seconds: 300,
904        temperature: Some(0.7),
905        max_tokens: Some(8192),
906        compaction_strategy: CompactionStrategy::Threshold(0.8),
907        compaction_instruction: None,
908        context_window: 128_000,
909        api_key: config.api_key.clone(),
910        workspace_dir: Some(workspace.clone()),
911        output_mode: None,
912        provider_options: config.provider_options.clone(),
913        // oxi-sdk 0.37.0+: ownership identity for oxi's built-in ownership-gated
914        // tools (e.g. the `issue` tool's flock). `None` preserves the pre-0.37.1
915        // behavior (ToolContext.session_id == None). Oxios runs its own tool
916        // set, so no ownership identity is needed here; set `Some(...)` only if
917        // oxios agents start using oxi ownership-gated tools.
918        session_id: None,
919        // RFC-035 Phase B/C: pass through gap 1/3 config to oxi-sdk 0.54.0+.
920        max_tool_result_bytes: config.max_tool_result_bytes,
921        // subagent_depth = CURRENT depth (0 = top-level). The in-process
922        // max is hardcoded to 3 in oxi-agent (subagent.rs:649). Do NOT
923        // wire a "max depth" config here — it would make the agent start
924        // at depth N and fail every subagent call immediately.
925        subagent_depth: 0,
926        // RFC-035 Phase C: wire the in-process sub-agent runner so the
927        // `subagent` tool delegates in-process (no CLI subprocess).
928        subagent_runner: Some(
929            crate::subagent_runner::OxiosSubagentRunner::new(engine.oxi().clone())
930                .into_trait_object(),
931        ),
932        ..Default::default()
933    };
934
935    // ── Build Agent (RFC-014 Phase D) ──
936    //
937    // Two paths:
938    //   1. `provider_rpm == 0` (common): use oxi-sdk 0.26.2's new
939    //      `AgentBuilder` API. The builder unifies model resolution, provider
940    //      creation, and (optionally) middleware wiring. Engine-level
941    //      `authorizer` / `tracer` / `cost_tracker` are propagated through
942    //      the new builder methods.
943    //   2. `provider_rpm > 0` (rare): keep the legacy
944    //      `Agent::new_with_resolver` + `set_hooks` path because the
945    //      AgentBuilder does not expose a way to inject a pre-built
946    //      `ProviderPool` for rate-limited access. This is a deliberate
947    //      scope-limit per RFC-014/phase-d-agentbuilder.md §2 "Provider
948    //      선택 로직은 보존".
949    let agent = if config.provider_rpm > 0 {
950        // ── Legacy path: rate-limited provider pool ──
951        let resolver: Arc<dyn ProviderResolver> = Arc::new(engine.oxi().clone());
952        let provider_name = engine.resolve_model(&config.model_id)?.provider;
953        let provider = engine.pooled_provider(&provider_name, config.provider_rpm)?;
954
955        // Build middleware pipeline.
956        let mut pipeline = oxi_sdk::MiddlewarePipeline::new();
957        if config.rate_limit_per_minute > 0 {
958            pipeline = pipeline.push(oxi_sdk::middleware::builtins::RateLimitMiddleware::new(
959                config.rate_limit_per_minute,
960            ));
961        }
962        if config.token_budget > 0 {
963            pipeline = pipeline.push(oxi_sdk::middleware::builtins::TokenBudgetMiddleware::new(
964                config.token_budget,
965            ));
966        }
967        if config.audit_tool_calls {
968            pipeline = pipeline.push(oxi_sdk::middleware::builtins::LoggingMiddleware::new(
969                tracing::Level::INFO,
970            ));
971        }
972
973        // Create Agent with CSpace tool registry and provider resolver.
974        let agent = Arc::new(Agent::new_with_resolver(
975            provider,
976            agent_config,
977            Arc::new(registry),
978            resolver,
979        ));
980
981        // Wire middleware pipeline → AgentHooks.
982        if !pipeline.is_empty() {
983            let terminate_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
984            let agent_id_for_hooks = agent_id.to_string();
985            let hooks = oxi_sdk::middleware::build_hooks(
986                Arc::new(pipeline),
987                agent_id_for_hooks,
988                terminate_flag,
989            );
990            agent.set_hooks(hooks);
991        }
992
993        agent
994    } else {
995        // ── New path: AgentBuilder (RFC-014 Phase D) ──
996        let mut builder = engine
997            .oxi()
998            .agent(agent_config)
999            .workspace(&workspace)
1000            .system_prompt(system_prompt);
1001
1002        // CSpace-based tool registration is oxios-specific and is preserved.
1003        //
1004        // The builder's `.tool()` method takes `impl AgentTool + 'static`
1005        // (a concrete value), but oxios' CSpace tools are `Arc<dyn AgentTool>`.
1006        // The SDK does not expose a way to inject a pre-built `ToolRegistry`
1007        // into the builder, so we register them on the agent's tool registry
1008        // after `build()` returns. This keeps CSpace semantics intact.
1009        //
1010        // We capture the tool names now and apply them once the agent exists.
1011        let cspace_tool_arcs: Vec<Arc<dyn oxi_sdk::AgentTool>> = registry
1012            .names()
1013            .into_iter()
1014            .filter_map(|name| registry.get(&name))
1015            .collect();
1016
1017        // Engine-level observability/security → AgentBuilder (new API).
1018        if let Some(auth) = engine.authorizer() {
1019            builder = builder.authorizer(auth.clone());
1020        }
1021        if let Some(tracer) = engine.tracer() {
1022            builder = builder.tracer(tracer.clone());
1023        }
1024        if let Some(ct) = engine.cost_tracker() {
1025            builder = builder.cost_tracker(ct.clone());
1026        }
1027
1028        // Middleware: AgentBuilder convenience helpers replace the manual
1029        // `MiddlewarePipeline` + `build_hooks()` + `set_hooks()` triple.
1030        if config.rate_limit_per_minute > 0 {
1031            builder = builder.with_rate_limit(config.rate_limit_per_minute);
1032        }
1033        if config.token_budget > 0 {
1034            builder = builder.with_token_budget(config.token_budget);
1035        }
1036        if config.audit_tool_calls {
1037            builder = builder.with_logging();
1038        }
1039
1040        let built = builder.build()?;
1041        let agent = Arc::new(built);
1042
1043        // Attach CSpace tools to the agent's tool registry.
1044        // `Agent::tools()` returns the same `Arc<ToolRegistry>` that
1045        // `AgentBuilder` populated, so `register_arc` is the canonical
1046        // extension point for `Arc<dyn AgentTool>` values.
1047        let agent_tools = agent.tools();
1048        for tool in cspace_tool_arcs {
1049            agent_tools.register_arc(tool);
1050        }
1051
1052        agent
1053    };
1054
1055    // RFC-029 P2b: restore conversation state from a prior failed run
1056    // so the new agent (with a fallback model) continues from the
1057    // checkpoint rather than restarting from scratch.
1058    if let Some(state) = restore_state {
1059        agent.import_state(state.clone()).unwrap_or_else(|e| {
1060            tracing::warn!(agent_id = %agent_id, error = %e, "Failed to restore agent state");
1061        });
1062    }
1063
1064    // Shared mutable state for the event callback.
1065    let exec_state = Arc::new(Mutex::new(ExecuteState::default()));
1066    let exec_state_cb = Arc::clone(&exec_state);
1067    let memory_for_callback: Arc<MemoryManager> = (*kernel_handle.agents.memory_manager()).clone();
1068    let session_id_for_callback = exec_id.to_string();
1069    let model_id_for_callback = config.model_id.clone();
1070    let agent_id_for_callback = agent_id.to_string();
1071    let routing_stats_for_cb = routing_stats.clone();
1072    // RFC-015: real-time event publishing for chat transparency.
1073    // Falls back to None when the caller did not opt in.
1074    let transparency_session: Option<String> = session_id.clone();
1075    let kernel_handle_for_cb: Arc<KernelHandle> = Arc::clone(&kernel_handle);
1076    // P1 chat transparency: per-session streaming sink registry. The
1077    // callback looks up the sink for this session and pushes live text
1078    // deltas. Lookup misses silently (no gateway registered → not a chat).
1079    let streaming_sinks_for_cb: Arc<crate::streaming_sink::StreamingSinkRegistry> =
1080        Arc::clone(&kernel_handle.streaming_sinks);
1081    // Run the agent with streaming events.
1082    let mut sent_model_for_cb: bool = false;
1083    let result =
1084        agent
1085            .run_streaming(prompt, move |event| {
1086                if !sent_model_for_cb
1087                    && let Some(ref sid) = transparency_session
1088                    && !model_id_for_callback.is_empty()
1089                    && let Some(tx) = streaming_sinks_for_cb.lookup(sid)
1090                {
1091                    let _ = tx.send(StreamDelta::Model(model_id_for_callback.clone()));
1092                    sent_model_for_cb = true;
1093                }
1094                let mut s = exec_state_cb.lock();
1095                match event {
1096                    AgentEvent::ToolExecutionStart {
1097                        tool_name,
1098                        tool_call_id,
1099                        args,
1100                        context,
1101                        ..
1102                    } => {
1103                        // Record start time and push a placeholder step.
1104                        let idx = s.trajectory_steps.len();
1105                        s.pending_tools
1106                            .insert(tool_call_id.clone(), (std::time::Instant::now(), idx));
1107                        s.tool_args_map.insert(
1108                            tool_call_id.clone(),
1109                            serde_json::to_string(&args).unwrap_or_default(),
1110                        );
1111                        s.tool_timestamps
1112                            .insert(tool_call_id.clone(), chrono::Utc::now());
1113                        s.tool_call_ids.push(tool_call_id.clone());
1114                        s.trajectory_steps
1115                            .push(oxios_memory::memory::sona::TrajectoryStep {
1116                                input: tool_name.clone(),
1117                                output: String::new(),
1118                                duration_ms: 0,
1119                                confidence: 0.0,
1120                            });
1121                        // RFC-015: broadcast tool start so Web UI can show progress.
1122                        if let Some(ref sid) = transparency_session {
1123                            let context_json = context
1124                                .as_ref()
1125                                .map(serde_json::to_value)
1126                                .transpose()
1127                                .unwrap_or(None);
1128                            let _ = kernel_handle_for_cb.infra.publish(
1129                                KernelEvent::ToolExecutionStarted {
1130                                    session_id: sid.clone(),
1131                                    tool_name: tool_name.clone(),
1132                                    tool_call_id: tool_call_id.clone(),
1133                                    tool_args: args.clone(),
1134                                    context: context_json,
1135                                },
1136                            );
1137                        }
1138                    }
1139                    AgentEvent::ToolExecutionUpdate {
1140                        tool_call_id,
1141                        tool_name,
1142                        partial_result,
1143                        tab_id,
1144                        context,
1145                    } => {
1146                        // RFC-015: forward real-time progress to the event bus
1147                        // so the Web UI can show a spinner and progress text
1148                        // while the tool is still executing. Best-effort —
1149                        // publish failures (e.g. lagged subscribers) are ignored.
1150                        //
1151                        // `tab_id` and `context` come from oxi-agent 0.29+
1152                        // (ToolCallContext: PageVisit, WebSearch, etc.).
1153                        // Older agent versions won't send these — they default
1154                        // to None and the UI gracefully ignores them.
1155                        if let Some(ref sid) = transparency_session {
1156                            let context_json = context
1157                                .as_ref()
1158                                .map(serde_json::to_value)
1159                                .transpose()
1160                                .unwrap_or(None);
1161                            let _ = kernel_handle_for_cb.infra.publish(
1162                                KernelEvent::ToolExecutionProgress {
1163                                    session_id: sid.clone(),
1164                                    tool_call_id: tool_call_id.clone(),
1165                                    tool_name: tool_name.clone(),
1166                                    progress: partial_result,
1167                                    tab_id,
1168                                    context: context_json,
1169                                },
1170                            );
1171                        }
1172                    }
1173                    AgentEvent::ToolExecutionEnd {
1174                        tool_name,
1175                        tool_call_id,
1176                        is_error,
1177                        result,
1178                        ..
1179                    } => {
1180                        if !is_error {
1181                            s.steps_completed += 1;
1182                        }
1183                        // Look up the exact step by tool_call_id.
1184                        let mut duration_ms: u64 = 0;
1185                        let mut summary = String::new();
1186                        if let Some((start, idx)) = s.pending_tools.remove(tool_call_id.as_str()) {
1187                            duration_ms = start.elapsed().as_millis() as u64;
1188                            if let Some(step) = s.trajectory_steps.get_mut(idx) {
1189                                summary = summarize_tool_result(&result.content, 200);
1190                                step.output = summary.clone();
1191                                step.duration_ms = duration_ms;
1192                                step.confidence = if is_error { 0.3 } else { 0.8 };
1193                            }
1194                        }
1195                        s.tool_error_map.insert(tool_call_id.clone(), is_error);
1196                        // RFC-015: broadcast tool completion.
1197                        if let Some(ref sid) = transparency_session {
1198                            let _ = kernel_handle_for_cb.infra.publish(
1199                                KernelEvent::ToolExecutionFinished {
1200                                    session_id: sid.clone(),
1201                                    tool_call_id: tool_call_id.clone(),
1202                                    tool_name: tool_name.clone(),
1203                                    duration_ms,
1204                                    is_error,
1205                                    output_summary: summary,
1206                                },
1207                            );
1208                        }
1209                    }
1210                    AgentEvent::AgentEnd {
1211                        messages,
1212                        stop_reason,
1213                        ..
1214                    } => {
1215                        if let Some(oxi_sdk::Message::Assistant(a)) = messages.last() {
1216                            s.final_content = a.text_content();
1217                        }
1218                        // oxi 0.32.0: loop exits naturally when LLM produces text-only
1219                        // response (StopReason::Stop). Error/Aborted = failure.
1220                        // ToolUse should not occur at AgentEnd in 0.32.0 (the loop
1221                        // continues until text-only), but treat it as non-failure
1222                        // since tool calls were executed successfully.
1223                        s.success =
1224                            matches!(stop_reason.as_deref(), Some("Stop") | Some("ToolUse"));
1225                    }
1226                    AgentEvent::Error { message, .. } => {
1227                        s.final_content = message.clone();
1228                        s.success = false;
1229                    }
1230                    AgentEvent::Usage {
1231                        input_tokens,
1232                        output_tokens,
1233                    } => {
1234                        // Accumulate totals for ExecutionResult.
1235                        s.total_input_tokens += input_tokens as u64;
1236                        s.total_output_tokens += output_tokens as u64;
1237
1238                        // Record token usage to cost tracker (existing).
1239                        let agent_label = format!("agent-{agent_id_for_callback}");
1240                        crate::observability::cost_tracker().record(
1241                            &agent_label,
1242                            &oxi_sdk::Model::new(
1243                                &model_id_for_callback,
1244                                &model_id_for_callback,
1245                                oxi_sdk::Api::OpenAiCompletions,
1246                                "unknown",
1247                                "https://unknown.com",
1248                            ),
1249                            oxi_sdk::TokenUsage {
1250                                input: input_tokens as u64,
1251                                output: output_tokens as u64,
1252                                cache_read: 0,
1253                                cache_write: 0,
1254                            },
1255                        );
1256
1257                        // Record to routing stats (RFC-011).
1258                        if let Some(stats) = &routing_stats_for_cb {
1259                            let cost = crate::kernel_handle::engine_api::estimate_cost(
1260                                &model_id_for_callback,
1261                                input_tokens as u64,
1262                                output_tokens as u64,
1263                            );
1264                            stats.record_model_usage(&model_id_for_callback, cost);
1265                        }
1266                        // RFC-015: publish cumulative token usage.
1267                        if let Some(ref sid) = transparency_session {
1268                            let _ =
1269                                kernel_handle_for_cb
1270                                    .infra
1271                                    .publish(KernelEvent::TokenUsageUpdate {
1272                                        session_id: sid.clone(),
1273                                        input_tokens: input_tokens as u64,
1274                                        output_tokens: output_tokens as u64,
1275                                    });
1276                        }
1277                    }
1278                    AgentEvent::Compaction {
1279                        event: CompactionEvent::Completed { result, .. },
1280                    } => {
1281                        handle_compaction(
1282                            result.summary.clone(),
1283                            session_id_for_callback.clone(),
1284                            memory_for_callback.clone(),
1285                        );
1286                        // RFC-015: compaction is a form of reasoning — expose it.
1287                        if let Some(ref sid) = transparency_session {
1288                            let _ = kernel_handle_for_cb.infra.publish(
1289                                KernelEvent::ReasoningFragment {
1290                                    session_id: sid.clone(),
1291                                    content: result.summary.clone(),
1292                                    source: "compaction".to_string(),
1293                                },
1294                            );
1295                        }
1296                    }
1297                    AgentEvent::Compaction {
1298                        event: CompactionEvent::Triggered { source, .. },
1299                    } => {
1300                        // RFC-035 gap 2: surface the trigger source so the
1301                        // 3-4× heuristic drift (pre-0.53 silent no-op) is
1302                        // observable end-to-end. The match arm itself does
1303                        // not act on compaction — the SDK handles the
1304                        // actual trigger — we only publish a KernelEvent.
1305                        if let Some(ref sid) = transparency_session {
1306                            let _ = kernel_handle_for_cb.infra.publish(
1307                                KernelEvent::CompactionTriggered {
1308                                    session_id: Some(sid.clone()),
1309                                    source,
1310                                },
1311                            );
1312                        } else {
1313                            let _ = kernel_handle_for_cb.infra.publish(
1314                                KernelEvent::CompactionTriggered {
1315                                    session_id: None,
1316                                    source,
1317                                },
1318                            );
1319                        }
1320                    }
1321                    AgentEvent::TextChunk { text } => {
1322                        // P1 chat transparency: push live text delta through the
1323                        // streaming-sink registry. The gateway has already
1324                        // registered a strong sender under `session_id`; the
1325                        // collector there converts each delta into a partial
1326                        // `OutgoingMessage` with `partial = Some(true)` and
1327                        // `target_conn_id = Some(conn_id)` so the WS handler
1328                        // forwards it as a bare `token` chunk (no `done`).
1329                        //
1330                        // Lookup uses `transparency_session` (the same session_id
1331                        // already plumbed for RFC-015 event publishing). A miss
1332                        // here means no gateway has registered for this session —
1333                        // silent skip; non-streaming callers see no behavior
1334                        // change.
1335                        if let Some(ref sid) = transparency_session
1336                            && let Some(tx) = streaming_sinks_for_cb.lookup(sid)
1337                        {
1338                            let _ = tx.send(StreamDelta::Text(text.clone()));
1339                        }
1340                    }
1341                    AgentEvent::Thinking => {
1342                        // P4: signal-only — LiveActivityBar flips to "추론 중".
1343                        // Sent through the same connection-scoped sink so the
1344                        // state change is visible to the live chat only (no
1345                        // EventBus broadcast for a transient UI signal).
1346                        if let Some(ref sid) = transparency_session
1347                            && let Some(tx) = streaming_sinks_for_cb.lookup(sid)
1348                        {
1349                            let _ = tx.send(StreamDelta::Thinking);
1350                        }
1351                    }
1352                    AgentEvent::ThinkingDelta { text } => {
1353                        // P4: each thinking delta goes through the same
1354                        // connection-scoped sink as Text deltas. The collector
1355                        // converts each into a `reasoning` WS chunk (partial,
1356                        // no assign_seq). Frontend appends them to the
1357                        // ThinkingPanel. No batching here — the sink is a
1358                        // per-session mpsc, fan-out is bounded by active turns,
1359                        // and the per-token load is well below 100 Hz in
1360                        // practice (verified empirically with reasoning models).
1361                        // P4 (§7 persistence): append to the accumulator too so
1362                        // the full reasoning text surfaces via ExecutionResult
1363                        // metadata at turn end. Capped at ~4 KB to bound
1364                        // storage — matches the design doc §7 truncation
1365                        // rationale (matches `tool_calls.output_summary`).
1366                        const REASONING_CAP: usize = 4096;
1367                        if s.reasoning_text.len() < REASONING_CAP {
1368                            s.reasoning_text.push_str(&text);
1369                            if s.reasoning_text.len() > REASONING_CAP {
1370                                s.reasoning_text.truncate(REASONING_CAP);
1371                            }
1372                        }
1373                        if let Some(ref sid) = transparency_session
1374                            && let Some(tx) = streaming_sinks_for_cb.lookup(sid)
1375                        {
1376                            let _ = tx.send(StreamDelta::ThinkingDelta(text.clone()));
1377                        }
1378                    }
1379                    _ => {}
1380                }
1381            })
1382            .await;
1383
1384    // Record circuit breaker result after agent execution.
1385    let circuit = get_llm_circuit_breaker();
1386    if result.is_err() {
1387        circuit.record_failure();
1388        crate::metrics::get_metrics()
1389            .llm_circuit_breaker_state
1390            .set(1.0);
1391    } else {
1392        circuit.record_success();
1393        crate::metrics::get_metrics()
1394            .llm_circuit_breaker_state
1395            .set(0.0);
1396    }
1397
1398    if let Err(e) = result {
1399        tracing::error!(exec_id = %exec_id, error = %e, "Agent failed");
1400        // RFC-029 P2b: capture the agent's accumulated conversation state
1401        // before returning. The supervisor's Err arm unwraps AgentRunError
1402        // and populates ExecutionResult.restore_state so the coordinator
1403        // can inject it into a retry with a different model (snapshot→restore).
1404        let restore_state = agent.export_state().ok();
1405        return Err(crate::resilience::AgentRunError::wrap(e, restore_state).into());
1406    }
1407
1408    let s = exec_state.lock();
1409    tracing::info!(
1410        exec_id = %exec_id,
1411        steps = s.steps_completed,
1412        success = s.success,
1413        "Agent completed"
1414    );
1415
1416    // Record trajectory to SONA learning engine (RFC-020 Phase 2).
1417    // Fire-and-forget: don't block the result on learning.
1418    if !s.trajectory_steps.is_empty()
1419        && let Some(sona) = kernel_handle.agents.memory_manager().sona_engine()
1420    {
1421        let steps = s.trajectory_steps.clone();
1422        let success = s.success;
1423        let sona = Arc::clone(sona);
1424        let domain = infer_domain(&goal);
1425        tokio::spawn(async move {
1426            let verdict = if success {
1427                oxios_memory::memory::sona::Verdict::Success
1428            } else {
1429                oxios_memory::memory::sona::Verdict::Failure
1430            };
1431            let trajectory = oxios_memory::memory::sona::Trajectory::new(steps, verdict, &domain);
1432            if let Err(e) = sona.record(trajectory).await {
1433                tracing::debug!(error = %e, "SONA trajectory recording failed (non-fatal)");
1434            }
1435        });
1436    }
1437
1438    Ok((
1439        s.final_content.clone(),
1440        s.steps_completed,
1441        s.success,
1442        s.trajectory_steps.clone(),
1443        agent,
1444        s.tool_call_ids.clone(),
1445        s.tool_args_map.clone(),
1446        s.tool_error_map.clone(),
1447        s.tool_timestamps.clone(),
1448        s.total_input_tokens,
1449        s.total_output_tokens,
1450        s.reasoning_text.clone(),
1451    ))
1452}
1453
1454/// Summarize a tool result string to fit within `max_len` characters.
1455///
1456/// Uses char-aware truncation to avoid panicking on multi-byte UTF-8
1457/// (e.g., Korean, CJK, emoji).
1458fn summarize_tool_result(result: &str, max_len: usize) -> String {
1459    let trimmed = result.trim();
1460    if trimmed.chars().count() <= max_len {
1461        return trimmed.to_string();
1462    }
1463    // Take the first line or truncate.
1464    let first_line = trimmed.lines().next().unwrap_or("");
1465    if first_line.chars().count() <= max_len {
1466        first_line.to_string()
1467    } else {
1468        let take = max_len.saturating_sub(3);
1469        let truncated: String = if take == 0 {
1470            first_line.chars().take(max_len).collect()
1471        } else {
1472            first_line.chars().take(take).collect()
1473        };
1474        format!("{truncated}...")
1475    }
1476}
1477fn truncate_json_str(json_str: &str, max_len: usize) -> String {
1478    if json_str.len() <= max_len {
1479        return json_str.to_string();
1480    }
1481    // Saturating sub avoids underflow panic when max_len < 3; if there
1482    // isn't room for an ellipsis, return as many chars as fit.
1483    let take = max_len.saturating_sub(3);
1484    if take == 0 {
1485        return json_str.chars().take(max_len).collect();
1486    }
1487    let truncated: String = json_str.chars().take(take).collect();
1488    format!("{truncated}...")
1489}
1490
1491/// Infer a domain category from the goal for SONA trajectory grouping.
1492///
1493/// Extracts the core verb + object from the goal to create a meaningful
1494/// domain label. Falls back to "general" for unrecognizable patterns.
1495fn infer_domain(goal: &str) -> String {
1496    let lower = goal.to_lowercase();
1497    let keywords: Vec<&str> = lower.split_whitespace().take(8).collect();
1498
1499    // Check for known domain indicators.
1500    if keywords.iter().any(|k| {
1501        [
1502            "test",
1503            "tests",
1504            "spec",
1505            "testing",
1506            "assert",
1507            "unit test",
1508            "integration",
1509        ]
1510        .contains(k)
1511    }) {
1512        return "testing".to_string();
1513    }
1514    if keywords
1515        .iter()
1516        .any(|k| ["deploy", "release", "publish", "ship"].contains(k))
1517    {
1518        return "deployment".to_string();
1519    }
1520    if keywords
1521        .iter()
1522        .any(|k| ["fix", "bug", "patch", "repair", "debug"].contains(k))
1523    {
1524        return "bugfix".to_string();
1525    }
1526    if keywords
1527        .iter()
1528        .any(|k| ["refactor", "restructure", "reorganize", "rewrite"].contains(k))
1529    {
1530        return "refactoring".to_string();
1531    }
1532    if keywords
1533        .iter()
1534        .any(|k| ["doc", "document", "readme", "guide", "explain"].contains(k))
1535    {
1536        return "documentation".to_string();
1537    }
1538    if keywords
1539        .iter()
1540        .any(|k| ["build", "create", "implement", "add", "make", "new"].contains(k))
1541    {
1542        return "development".to_string();
1543    }
1544    if keywords
1545        .iter()
1546        .any(|k| ["analyze", "review", "audit", "inspect", "check"].contains(k))
1547    {
1548        return "analysis".to_string();
1549    }
1550    if keywords
1551        .iter()
1552        .any(|k| ["config", "setup", "install", "configure", "init"].contains(k))
1553    {
1554        return "configuration".to_string();
1555    }
1556
1557    // Fallback: first 2 meaningful words
1558    let meaningful: Vec<&str> = lower
1559        .split_whitespace()
1560        .filter(|w| w.len() > 2)
1561        .take(2)
1562        .collect();
1563    if meaningful.len() >= 2 {
1564        meaningful.join("_")
1565    } else {
1566        "general".to_string()
1567    }
1568}
1569
1570/// Handle compaction completion by storing the summary as a Warm memory.
1571///
1572/// Extracts the compaction summary from the event and spawns a background
1573/// task to persist it via MemoryManager. This replaces the inline 30-line
1574/// block that was previously in the event callback.
1575fn handle_compaction(summary: String, session_id: String, memory_manager: Arc<MemoryManager>) {
1576    let entry = MemoryEntry {
1577        id: uuid::Uuid::new_v4().to_string(),
1578        memory_type: MemoryType::Conversation,
1579        tier: crate::memory::MemoryTier::Warm,
1580        content: summary,
1581        content_hash: 0,
1582        source: "compaction".to_string(),
1583        session_id: Some(session_id),
1584        tags: vec![],
1585        importance: 0.5,
1586        pinned: false,
1587        protection: crate::memory::ProtectionLevel::None,
1588        auto_classified: false,
1589        session_appearances: 0,
1590        user_corrected: false,
1591        seen_in_sessions: vec![],
1592        created_at: chrono::Utc::now(),
1593        accessed_at: chrono::Utc::now(),
1594        modified_at: chrono::Utc::now(),
1595        access_count: 0,
1596        decay_score: 1.0,
1597        compaction_level: 0,
1598        compacted_from: vec![],
1599        related_ids: vec![],
1600        contradicts: None,
1601    };
1602    tokio::spawn(async move {
1603        if let Err(e) = memory_manager.remember(entry).await {
1604            tracing::warn!(error = %e, "Failed to save compaction summary");
1605        }
1606    });
1607}
1608
1609/// Build a system prompt from a Directive and ExecEnv (RFC-027).
1610///
1611/// Maps [`Directive`] fields (`goal`, `original_request`, `constraints`,
1612/// `acceptance_criteria`) and [`ExecEnv`] fields (`workspace_context`) into
1613#[allow(dead_code)]
1614fn build_directive_system_prompt(
1615    directive: &Directive,
1616    env: &ExecEnv,
1617    persona_prompt: Option<&str>,
1618    capabilities_xml: Option<&str>,
1619    kernel_manifest: Option<&str>,
1620) -> String {
1621    build_system_prompt_inner(
1622        &directive.goal,
1623        &directive.original_request,
1624        &directive.constraints,
1625        &directive.acceptance_criteria,
1626        env.workspace_context.as_deref(),
1627        persona_prompt,
1628        capabilities_xml,
1629        kernel_manifest,
1630    )
1631}
1632
1633/// Shared system-prompt builder for the directive path.
1634///
1635/// Composes the static agent prelude, goal/constraints/criteria sections,
1636/// optional workspace context, persona, capability index, and
1637/// kernel manifest into a single prompt string.
1638#[allow(clippy::too_many_arguments)]
1639fn build_system_prompt_inner(
1640    goal: &str,
1641    original_request: &str,
1642    constraints: &[String],
1643    acceptance_criteria: &[String],
1644    workspace_context: Option<&str>,
1645    persona_prompt: Option<&str>,
1646    capabilities_xml: Option<&str>,
1647    kernel_manifest: Option<&str>,
1648) -> String {
1649    let mut prompt = String::from(
1650        "You are an autonomous agent in the Oxios operating system.\n\
1651         You execute Seeds — immutable specifications with goals, constraints, and\n\
1652         acceptance criteria.\n\n\
1653         ## Available Tools\n\
1654         You have the following tools:\n\
1655         - **File tools**: read, write, edit files; grep, find, ls for searching\n\
1656         - **Web tools**: web_search for searching the web, get_search_results for retrieving cached results\n\
1657         - **Exec**: run shell commands\n\
1658         - **Memory tools**: memory_read, memory_write, memory_search — agent's internal recall\n\
1659         - **Knowledge**: knowledge — personal markdown vault for documents and notes\n\
1660         - **Kernel tools**: agent, project, persona, cron, security, budget, resource\n\n\
1661         **Important**: When the task involves fetching information from the internet,\n\
1662         websites, or online services, use `web_search` first — do NOT search local files.\n\
1663         When the task asks to \"get\", \"fetch\", \"find online\", or \"look up\" something\n\
1664         from the web, use `web_search`.\n",
1665    );
1666    prompt.push_str(&format!("\n## Goal\n{}\n", goal));
1667
1668    // Preserve user's original wording so the agent sees exact language,
1669    // filenames, and nuances that may have been abstracted in the goal.
1670    if !original_request.is_empty() && original_request != goal {
1671        prompt.push_str(&format!(
1672            "\n## User's Original Request\n{}\n",
1673            original_request
1674        ));
1675    }
1676
1677    if !constraints.is_empty() {
1678        prompt.push_str("\n## Constraints\n");
1679        for (i, c) in constraints.iter().enumerate() {
1680            prompt.push_str(&format!("{}. {}\n", i + 1, c));
1681        }
1682    }
1683
1684    if !acceptance_criteria.is_empty() {
1685        prompt.push_str("\n## Acceptance Criteria\n");
1686        for (i, c) in acceptance_criteria.iter().enumerate() {
1687            prompt.push_str(&format!("{}. {}\n", i + 1, c));
1688        }
1689    }
1690
1691    // ── Workspace Context (RFC-025) ──
1692    // Inject active Mounts + project instructions AFTER the goal/constraints
1693    // and BEFORE the persona, so the agent sees its workspace before it acts.
1694    if let Some(ctx) = workspace_context.filter(|s| !s.trim().is_empty()) {
1695        prompt.push_str("\n## Workspace Context\n");
1696        prompt.push_str(ctx);
1697        prompt.push('\n');
1698    }
1699
1700    // Inject persona system prompt
1701    if let Some(pp) = persona_prompt {
1702        prompt.push_str("\n## Persona\n");
1703        prompt.push_str(pp);
1704        prompt.push('\n');
1705    }
1706
1707    // Inject semantic capability index (from ToolRetriever)
1708    if let Some(xml) = capabilities_xml {
1709        prompt.push_str("\n## Available Capabilities\n");
1710        prompt.push_str("The following capabilities are relevant to your goal. ");
1711        prompt.push_str("Use the `read` tool to load SKILL.md for any program.\n\n");
1712        prompt.push_str(xml);
1713        prompt.push('\n');
1714    }
1715
1716    // Inject kernel manifest (from CSpace)
1717    if let Some(manifest) = kernel_manifest {
1718        prompt.push('\n');
1719        prompt.push_str(manifest);
1720        prompt.push('\n');
1721    }
1722
1723    // Execution environment guidance
1724    prompt.push_str(
1725        "\n## Execution Protocol\n\
1726         1. UNDERSTAND — Read the user's request carefully. If it is a simple\n\
1727            greeting, small talk, or a question you can answer from knowledge,\n\
1728            respond naturally and conversationally — no tools needed.\n\
1729         2. PLAN — For complex tasks, outline your approach before acting.\n\
1730         3. EXECUTE — Use tools only when the task actually requires them.\n\
1731            Prefer the simplest approach. Simple requests need no tools.\n\
1732         4. VERIFY — After each action, check the result: created a file? read it back.\n\
1733         5. REPORT — Summarize how each acceptance criterion was met, with evidence.\n\n\
1734         If the request is ambiguous, use the `ask_user` tool (free-text question)\n\
1735         or the `pi-questionnaire` tool (structured choices) to clarify before\n\
1736         executing — do not guess when a single question would resolve the intent.\n\n\
1737         ## Hard Boundaries\n\
1738         - NEVER modify files outside the workspace scope\n\
1739         - NEVER execute destructive commands without confirming scope\n\
1740         - NEVER claim completion without evidence — show the output, not your opinion\n\
1741         - NEVER add features or improvements beyond the goal's scope\n\
1742         - If you cannot complete the task, say so and explain WHY\n\n\
1743         ## Scope Guard\n\
1744         The goal defines your universe. Do not:\n\
1745         - Refactor code the goal didn't mention\n\
1746         - Add tests the goal didn't require\n\
1747         - Change configuration the goal didn't specify\n\
1748         - \"Improve\" anything beyond what the acceptance criteria demand\n\n\
1749         ## Error Handling\n\
1750         - If a tool fails, read the error message carefully before retrying\n\
1751         - If a command fails, do NOT immediately retry with --force or sudo\n\
1752         - If stuck after 3 attempts, report the blocker rather than continuing to fail\n\n\
1753         ## Shape Matching\n\
1754         Match your output to the task: simple task → concise response.\n\
1755         Do not write 50 lines when 5 would do.\n\
1756         Use `exec` for all command execution (git, gh, osascript, etc.).",
1757    );
1758
1759    prompt
1760}
1761#[allow(dead_code)]
1762fn build_directive_user_prompt(directive: &Directive) -> String {
1763    build_user_prompt_inner(&directive.goal, &directive.acceptance_criteria)
1764}
1765
1766/// Shared user-prompt builder for the directive path.
1767fn build_user_prompt_inner(goal: &str, acceptance_criteria: &[String]) -> String {
1768    format!(
1769        "Execute the following goal:\n\n{}\n\nAcceptance criteria:\n{}",
1770        goal,
1771        acceptance_criteria
1772            .iter()
1773            .enumerate()
1774            .map(|(i, c)| format!("{}. {}", i + 1, c))
1775            .collect::<Vec<_>>()
1776            .join("\n")
1777    )
1778}
1779
1780impl std::fmt::Debug for AgentRuntime {
1781    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1782        f.debug_struct("AgentRuntime")
1783            .field("model_id", &self.engine_handle.get().default_model_id())
1784            .finish()
1785    }
1786}
1787
1788#[cfg(test)]
1789mod tests {
1790    use super::*;
1791    use async_trait::async_trait;
1792    use oxi_sdk::{AgentTool, ToolContext, ToolError};
1793    use serde_json::Value;
1794
1795    /// A test tool that does nothing — used to populate the registry.
1796    struct DummyTool {
1797        name: String,
1798    }
1799
1800    #[async_trait]
1801    impl AgentTool for DummyTool {
1802        fn name(&self) -> &str {
1803            &self.name
1804        }
1805        fn label(&self) -> &str {
1806            &self.name
1807        }
1808        fn description(&self) -> &str {
1809            "Test tool"
1810        }
1811        fn parameters_schema(&self) -> Value {
1812            serde_json::json!({"type": "object"})
1813        }
1814
1815        async fn execute(
1816            &self,
1817            _tool_call_id: &str,
1818            _params: Value,
1819            _shutdown: Option<tokio::sync::oneshot::Receiver<()>>,
1820            _ctx: &ToolContext,
1821        ) -> Result<oxi_sdk::AgentToolResult, ToolError> {
1822            Ok(oxi_sdk::AgentToolResult::success("ok"))
1823        }
1824    }
1825
1826    /// Test that requires_tools validation passes when all tools are present.
1827    #[test]
1828    fn test_requires_tools_validation_passes() {
1829        let registry = ToolRegistry::new();
1830
1831        registry.register(DummyTool {
1832            name: "read".into(),
1833        });
1834        registry.register(DummyTool {
1835            name: "exec".into(),
1836        });
1837
1838        let missing = registry.missing(&["read", "exec"]);
1839
1840        assert!(
1841            missing.is_empty(),
1842            "Expected no missing tools, got: {:?}",
1843            missing
1844        );
1845    }
1846
1847    /// Test that requires_tools validation fails when a tool is missing.
1848    #[test]
1849    fn test_requires_tools_validation_fails() {
1850        let registry = ToolRegistry::new();
1851
1852        registry.register(DummyTool {
1853            name: "read".into(),
1854        });
1855
1856        let missing = registry.missing(&["read", "exec", "nonexistent"]);
1857
1858        assert_eq!(missing, vec!["exec", "nonexistent"]);
1859    }
1860
1861    #[test]
1862    fn test_infer_domain_testing() {
1863        assert_eq!(infer_domain("run all unit tests for the kernel"), "testing");
1864    }
1865
1866    #[test]
1867    fn test_infer_domain_deployment() {
1868        assert_eq!(
1869            infer_domain("deploy the web service to production"),
1870            "deployment"
1871        );
1872    }
1873
1874    #[test]
1875    fn test_infer_domain_bugfix() {
1876        assert_eq!(infer_domain("fix the null pointer error in main"), "bugfix");
1877    }
1878
1879    #[test]
1880    fn test_infer_domain_development() {
1881        assert_eq!(
1882            infer_domain("create a new REST API endpoint"),
1883            "development"
1884        );
1885    }
1886
1887    #[test]
1888    fn test_infer_domain_analysis() {
1889        assert_eq!(
1890            infer_domain("review the code for security issues"),
1891            "analysis"
1892        );
1893    }
1894
1895    #[test]
1896    fn test_infer_domain_fallback() {
1897        let domain = infer_domain("optimize performance metrics");
1898        // Should fall back to first 2 meaningful words
1899        assert!(!domain.is_empty());
1900    }
1901}