fix(intelligence): 精确化 dead_code 标注并实现 LLM 上下文压缩
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled

- 将 intelligence/llm/memory/browser 模块的 dead_code 注释从模糊的
  "reserved for future" 改为明确说明 Tauri invoke_handler 运行时注册机制
- 为 identity.rs 中 3 个真正未使用的方法添加 #[allow(dead_code)]
- 实现 compactor use_llm: true 功能:新增 compact_with_llm 方法和
  compactor_compact_llm Tauri 命令,支持 LLM 驱动的对话摘要生成
- 将 pipeline_commands.rs 中 40+ 处 println!/eprintln! 调试输出替换为
  tracing::debug!/warn!/error! 结构化日志
- 移除 intelligence/mod.rs 中不必要的 #[allow(unused_imports)]
This commit is contained in:
iven
2026-03-27 00:43:14 +08:00
parent c3996573aa
commit 9a77fd4645
14 changed files with 433 additions and 265 deletions

View File

@@ -49,21 +49,21 @@ impl LlmActionDriver for RuntimeLlmAdapter {
max_tokens: Option<u32>,
json_mode: bool,
) -> Result<Value, String> {
println!("[DEBUG RuntimeLlmAdapter] generate called with prompt length: {}", prompt.len());
println!("[DEBUG RuntimeLlmAdapter] input HashMap contents:");
tracing::debug!("[RuntimeLlmAdapter] generate called with prompt length: {}", prompt.len());
tracing::debug!("[RuntimeLlmAdapter] input HashMap contents:");
for (k, v) in &input {
println!(" {} => {}", k, v);
}
// Build user content from prompt and input
let user_content = if input.is_empty() {
println!("[DEBUG RuntimeLlmAdapter] WARNING: input is empty, using raw prompt");
tracing::debug!("[RuntimeLlmAdapter] WARNING: input is empty, using raw prompt");
prompt.clone()
} else {
// Inject input values into prompt
// Support multiple placeholder formats: {{key}}, {{ key }}, ${key}, ${inputs.key}
let mut rendered = prompt.clone();
println!("[DEBUG RuntimeLlmAdapter] Original prompt (first 500 chars): {}", &prompt[..prompt.len().min(500)]);
tracing::debug!("[RuntimeLlmAdapter] Original prompt (first 500 chars): {}", &prompt[..prompt.len().min(500)]);
for (key, value) in &input {
let str_value = if let Some(s) = value.as_str() {
s.to_string()
@@ -71,7 +71,7 @@ impl LlmActionDriver for RuntimeLlmAdapter {
value.to_string()
};
println!("[DEBUG RuntimeLlmAdapter] Replacing '{}' with '{}'", key, str_value);
tracing::debug!("[RuntimeLlmAdapter] Replacing '{}' with '{}'", key, str_value);
// Replace all common placeholder formats
rendered = rendered.replace(&format!("{{{{{key}}}}}"), &str_value); // {{key}}
@@ -79,7 +79,7 @@ impl LlmActionDriver for RuntimeLlmAdapter {
rendered = rendered.replace(&format!("${{{key}}}"), &str_value); // ${key}
rendered = rendered.replace(&format!("${{inputs.{key}}}"), &str_value); // ${inputs.key}
}
println!("[DEBUG RuntimeLlmAdapter] Rendered prompt (first 500 chars): {}", &rendered[..rendered.len().min(500)]);
tracing::debug!("[RuntimeLlmAdapter] Rendered prompt (first 500 chars): {}", &rendered[..rendered.len().min(500)]);
rendered
};
@@ -111,7 +111,7 @@ impl LlmActionDriver for RuntimeLlmAdapter {
// Safe truncation for UTF-8 strings
let truncated: String = text.chars().take(1000).collect();
println!("[DEBUG RuntimeLlmAdapter] LLM response text (first 1000 chars): {}", truncated);
tracing::debug!("[RuntimeLlmAdapter] LLM response text (first 1000 chars): {}", truncated);
// Parse as JSON if json_mode, otherwise return as string
if json_mode {
@@ -132,11 +132,11 @@ impl LlmActionDriver for RuntimeLlmAdapter {
// Safe truncation for UTF-8 strings
let truncated_json: String = json_text.chars().take(500).collect();
println!("[DEBUG RuntimeLlmAdapter] JSON text to parse (first 500 chars): {}", truncated_json);
tracing::debug!("[RuntimeLlmAdapter] JSON text to parse (first 500 chars): {}", truncated_json);
serde_json::from_str(&json_text)
.map_err(|e| {
println!("[DEBUG RuntimeLlmAdapter] JSON parse error: {}", e);
tracing::debug!("[RuntimeLlmAdapter] JSON parse error: {}", e);
format!("Failed to parse LLM response as JSON: {}\nResponse: {}", e, json_text)
})
} else {
@@ -269,22 +269,22 @@ pub async fn pipeline_list(
// Get pipelines directory
let pipelines_dir = get_pipelines_directory()?;
println!("[DEBUG pipeline_list] Scanning directory: {:?}", pipelines_dir);
println!("[DEBUG pipeline_list] Filters - category: {:?}, industry: {:?}", category, industry);
tracing::debug!("[pipeline_list] Scanning directory: {:?}", pipelines_dir);
tracing::debug!("[pipeline_list] Filters - category: {:?}, industry: {:?}", category, industry);
// Scan for pipeline files (returns both info and paths)
let mut pipelines_with_paths: Vec<(PipelineInfo, PathBuf)> = Vec::new();
if pipelines_dir.exists() {
scan_pipelines_with_paths(&pipelines_dir, category.as_deref(), industry.as_deref(), &mut pipelines_with_paths)?;
} else {
eprintln!("[WARN pipeline_list] Pipelines directory does not exist: {:?}", pipelines_dir);
tracing::warn!("[WARN pipeline_list] Pipelines directory does not exist: {:?}", pipelines_dir);
}
println!("[DEBUG pipeline_list] Found {} pipelines", pipelines_with_paths.len());
tracing::debug!("[pipeline_list] Found {} pipelines", pipelines_with_paths.len());
// Debug: log all pipelines with their industry values
for (info, _) in &pipelines_with_paths {
println!("[DEBUG pipeline_list] Pipeline: {} -> category: {}, industry: '{}'", info.id, info.category, info.industry);
tracing::debug!("[pipeline_list] Pipeline: {} -> category: {}, industry: '{}'", info.id, info.category, info.industry);
}
// Update state
@@ -328,15 +328,15 @@ pub async fn pipeline_run(
kernel_state: State<'_, KernelState>,
request: RunPipelineRequest,
) -> Result<RunPipelineResponse, String> {
println!("[DEBUG pipeline_run] Received request for pipeline_id: {}", request.pipeline_id);
tracing::debug!("[pipeline_run] Received request for pipeline_id: {}", request.pipeline_id);
// Get pipeline
let pipelines = state.pipelines.read().await;
println!("[DEBUG pipeline_run] State has {} pipelines loaded", pipelines.len());
tracing::debug!("[pipeline_run] State has {} pipelines loaded", pipelines.len());
// Debug: list all loaded pipeline IDs
for (id, _) in pipelines.iter() {
println!("[DEBUG pipeline_run] Loaded pipeline: {}", id);
tracing::debug!("[pipeline_run] Loaded pipeline: {}", id);
}
let pipeline = pipelines.get(&request.pipeline_id)
@@ -353,13 +353,13 @@ pub async fn pipeline_run(
let llm_driver = {
let kernel_lock = kernel_state.lock().await;
if let Some(kernel) = kernel_lock.as_ref() {
println!("[DEBUG pipeline_run] Got LLM driver from Kernel");
tracing::debug!("[pipeline_run] Got LLM driver from Kernel");
Some(Arc::new(RuntimeLlmAdapter::new(
kernel.driver(),
Some(kernel.config().llm.model.clone()),
)) as Arc<dyn LlmActionDriver>)
} else {
println!("[DEBUG pipeline_run] Kernel not initialized, no LLM driver available");
tracing::debug!("[pipeline_run] Kernel not initialized, no LLM driver available");
None
}
};
@@ -382,10 +382,10 @@ pub async fn pipeline_run(
// Run pipeline in background with the known run_id
tokio::spawn(async move {
println!("[DEBUG pipeline_run] Starting execution with run_id: {}", run_id_for_spawn);
tracing::debug!("[pipeline_run] Starting execution with run_id: {}", run_id_for_spawn);
let result = executor.execute_with_id(&pipeline, inputs, &run_id_for_spawn).await;
println!("[DEBUG pipeline_run] Execution completed for run_id: {}, status: {:?}",
tracing::debug!("[pipeline_run] Execution completed for run_id: {}, status: {:?}",
run_id_for_spawn,
result.as_ref().map(|r| r.status.clone()).unwrap_or(RunStatus::Failed));
@@ -411,7 +411,7 @@ pub async fn pipeline_run(
});
// Return immediately with the known run ID
println!("[DEBUG pipeline_run] Returning run_id: {} to caller", run_id);
tracing::debug!("[pipeline_run] Returning run_id: {} to caller", run_id);
Ok(RunPipelineResponse {
run_id,
pipeline_id: request.pipeline_id,
@@ -576,7 +576,7 @@ fn scan_pipelines_with_paths(
industry_filter: Option<&str>,
pipelines: &mut Vec<(PipelineInfo, PathBuf)>,
) -> Result<(), String> {
println!("[DEBUG scan] Entering directory: {:?}", dir);
tracing::debug!("[scan] Entering directory: {:?}", dir);
let entries = std::fs::read_dir(dir)
.map_err(|e| format!("Failed to read pipelines directory: {}", e))?;
@@ -589,9 +589,9 @@ fn scan_pipelines_with_paths(
scan_pipelines_with_paths(&path, category_filter, industry_filter, pipelines)?;
} else if path.extension().map(|e| e == "yaml" || e == "yml").unwrap_or(false) {
// Try to parse pipeline file
println!("[DEBUG scan] Found YAML file: {:?}", path);
tracing::debug!("[scan] Found YAML file: {:?}", path);
if let Ok(content) = std::fs::read_to_string(&path) {
println!("[DEBUG scan] File content length: {} bytes", content.len());
tracing::debug!("[scan] File content length: {} bytes", content.len());
match parse_pipeline_yaml(&content) {
Ok(pipeline) => {
// Debug: log parsed pipeline metadata
@@ -620,7 +620,7 @@ fn scan_pipelines_with_paths(
pipelines.push((pipeline_to_info(&pipeline), path));
}
Err(e) => {
eprintln!("[ERROR scan] Failed to parse pipeline at {:?}: {}", path, e);
tracing::error!("[scan] Failed to parse pipeline at {:?}: {}", path, e);
}
}
}
@@ -701,10 +701,10 @@ fn pipeline_to_info(pipeline: &Pipeline) -> PipelineInfo {
pub fn create_pipeline_state() -> Arc<PipelineState> {
// Try to create an LLM driver from environment/config
let action_registry = if let Some(driver) = create_llm_driver_from_config() {
println!("[DEBUG create_pipeline_state] LLM driver configured successfully");
tracing::debug!("[create_pipeline_state] LLM driver configured successfully");
Arc::new(ActionRegistry::new().with_llm_driver(driver))
} else {
println!("[DEBUG create_pipeline_state] No LLM driver configured - pipelines requiring LLM will fail");
tracing::debug!("[create_pipeline_state] No LLM driver configured - pipelines requiring LLM will fail");
Arc::new(ActionRegistry::new())
};
Arc::new(PipelineState::new(action_registry))
@@ -767,7 +767,7 @@ pub async fn route_intent(
) -> Result<RouteResultResponse, String> {
use zclaw_pipeline::{TriggerParser, Trigger, TriggerParam, compile_trigger};
println!("[DEBUG route_intent] Routing user input: {}", user_input);
tracing::debug!("[route_intent] Routing user input: {}", user_input);
// Build trigger parser from loaded pipelines
let pipelines = state.pipelines.read().await;
@@ -810,7 +810,7 @@ pub async fn route_intent(
) {
Ok(compiled) => parser.register(compiled),
Err(e) => {
eprintln!("[WARN route_intent] Failed to compile trigger for {}: {}", id, e);
tracing::warn!("[WARN route_intent] Failed to compile trigger for {}: {}", id, e);
}
}
}
@@ -883,7 +883,7 @@ fn create_llm_driver_from_config() -> Option<Arc<dyn LlmActionDriver>> {
.map(|p| p.join("zclaw").join("config.toml"))?;
if !config_path.exists() {
println!("[DEBUG create_llm_driver] Config file not found at {:?}", config_path);
tracing::debug!("[create_llm_driver] Config file not found at {:?}", config_path);
return None;
}
@@ -899,7 +899,7 @@ fn create_llm_driver_from_config() -> Option<Arc<dyn LlmActionDriver>> {
let base_url = llm_config.get("base_url").and_then(|v| v.as_str()).map(|s| s.to_string());
let model = llm_config.get("model").and_then(|v| v.as_str()).map(|s| s.to_string());
println!("[DEBUG create_llm_driver] Found LLM config: provider={}, model={:?}", provider, model);
tracing::debug!("[create_llm_driver] Found LLM config: provider={}, model={:?}", provider, model);
// Convert api_key to SecretString
let secret_key = SecretString::new(api_key);
@@ -920,7 +920,7 @@ fn create_llm_driver_from_config() -> Option<Arc<dyn LlmActionDriver>> {
Arc::new(zclaw_runtime::LocalDriver::new(&url))
}
_ => {
eprintln!("[WARN create_llm_driver] Unknown provider: {}", provider);
tracing::warn!("[WARN create_llm_driver] Unknown provider: {}", provider);
return None;
}
};