Skip to main content

algocline_app/service/
logging.rs

1use super::hub_dist_preset::PRESET_CATALOG_VERSION;
2use super::path::ContainedPath;
3use super::transcript::append_note;
4use super::AppService;
5
6impl AppService {
7    /// Append a note to a session's log file.
8    pub async fn add_note(
9        &self,
10        session_id: &str,
11        content: &str,
12        title: Option<&str>,
13    ) -> Result<String, String> {
14        let count = append_note(self.require_log_dir()?, session_id, content, title)?;
15        Ok(serde_json::json!({
16            "session_id": session_id,
17            "notes_count": count,
18        })
19        .to_string())
20    }
21
22    /// Default max response size for detail mode (100 KB).
23    const DEFAULT_MAX_CHARS: usize = 100_000;
24
25    /// View session logs.
26    pub async fn log_view(
27        &self,
28        session_id: Option<&str>,
29        limit: Option<usize>,
30        max_chars: Option<usize>,
31    ) -> Result<String, String> {
32        match session_id {
33            Some(sid) => self.log_read(sid, max_chars.unwrap_or(Self::DEFAULT_MAX_CHARS)),
34            None => self.log_list(limit.unwrap_or(50)),
35        }
36    }
37
38    fn log_read(&self, session_id: &str, max_chars: usize) -> Result<String, String> {
39        let log_dir = self.require_log_dir()?;
40        let path = ContainedPath::child(log_dir, &format!("{session_id}.json"))?;
41        if !path.as_ref().exists() {
42            return Err(format!("Log file not found for session '{session_id}'"));
43        }
44        let raw = std::fs::read_to_string(&path).map_err(|e| format!("Failed to read log: {e}"))?;
45
46        // 0 means unlimited
47        if max_chars == 0 || raw.len() <= max_chars {
48            return Ok(raw);
49        }
50
51        // Parse and truncate transcript (oldest rounds first) to fit within max_chars
52        let mut doc: serde_json::Value =
53            serde_json::from_str(&raw).map_err(|e| format!("Failed to parse log: {e}"))?;
54
55        let original_rounds = doc
56            .get("transcript")
57            .and_then(|t| t.as_array())
58            .map(|a| a.len())
59            .unwrap_or(0);
60
61        if original_rounds == 0 {
62            // No transcript to truncate; return as-is
63            return Ok(raw);
64        }
65
66        // Binary-search: keep the maximum number of newest rounds that fit
67        let transcript = doc
68            .get("transcript")
69            .and_then(|t| t.as_array())
70            .cloned()
71            .unwrap_or_default();
72
73        let mut kept = original_rounds;
74        loop {
75            if kept == 0 {
76                // Even with empty transcript it might still be too large (unlikely)
77                doc["transcript"] = serde_json::json!([]);
78                break;
79            }
80            // Keep the newest `kept` rounds
81            let slice = &transcript[original_rounds - kept..];
82            doc["transcript"] = serde_json::Value::Array(slice.to_vec());
83            let serialized =
84                serde_json::to_string(&doc).map_err(|e| format!("Failed to serialize: {e}"))?;
85            if serialized.len() <= max_chars {
86                break;
87            }
88            // Halve for speed, then linear scan
89            if kept > 8 {
90                kept /= 2;
91            } else {
92                kept -= 1;
93            }
94        }
95
96        let returned_rounds = doc
97            .get("transcript")
98            .and_then(|t| t.as_array())
99            .map(|a| a.len())
100            .unwrap_or(0);
101
102        doc["truncated"] = serde_json::json!(true);
103        doc["original_rounds"] = serde_json::json!(original_rounds);
104        doc["returned_rounds"] = serde_json::json!(returned_rounds);
105
106        serde_json::to_string_pretty(&doc).map_err(|e| format!("Failed to serialize: {e}"))
107    }
108
109    pub(super) fn log_list(&self, limit: usize) -> Result<String, String> {
110        let dir = match self.log_config.log_dir.as_deref() {
111            Some(d) if d.is_dir() => d,
112            _ => return Ok(serde_json::json!({ "sessions": [] }).to_string()),
113        };
114
115        let entries = std::fs::read_dir(dir).map_err(|e| format!("Failed to read log dir: {e}"))?;
116
117        // Collect .meta.json files first; fall back to .json for legacy logs
118        let mut files: Vec<(std::path::PathBuf, std::time::SystemTime)> = entries
119            .flatten()
120            .filter_map(|entry| {
121                let path = entry.path();
122                let name = path.file_name()?.to_str()?;
123                // Skip non-json and meta files in this pass
124                if !name.ends_with(".json") || name.ends_with(".meta.json") {
125                    return None;
126                }
127                let mtime = entry.metadata().ok()?.modified().ok()?;
128                Some((path, mtime))
129            })
130            .collect();
131
132        // Sort by modification time descending (newest first), take limit
133        files.sort_by_key(|b| std::cmp::Reverse(b.1));
134        files.truncate(limit);
135
136        let mut sessions = Vec::new();
137        for (path, _) in &files {
138            // Try .meta.json first (lightweight), fall back to full log
139            let meta_path = path.with_extension("meta.json");
140            let doc: serde_json::Value = if meta_path.exists() {
141                // Meta file: already flat summary (~200 bytes)
142                match std::fs::read_to_string(&meta_path)
143                    .ok()
144                    .and_then(|r| serde_json::from_str(&r).ok())
145                {
146                    Some(d) => d,
147                    None => continue,
148                }
149            } else {
150                // Legacy fallback: read full log and extract fields
151                let raw = match std::fs::read_to_string(path) {
152                    Ok(r) => r,
153                    Err(_) => continue,
154                };
155                match serde_json::from_str::<serde_json::Value>(&raw) {
156                    Ok(d) => {
157                        let stats = d.get("stats");
158                        serde_json::json!({
159                            "session_id": d.get("session_id").and_then(|v| v.as_str()).unwrap_or("unknown"),
160                            "task_hint": d.get("task_hint").and_then(|v| v.as_str()),
161                            "elapsed_ms": stats.and_then(|s| s.get("elapsed_ms")),
162                            "rounds": stats.and_then(|s| s.get("rounds")),
163                            "llm_calls": stats.and_then(|s| s.get("llm_calls")),
164                            "notes_count": d.get("notes").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0),
165                        })
166                    }
167                    Err(_) => continue,
168                }
169            };
170
171            sessions.push(doc);
172        }
173
174        Ok(serde_json::json!({ "sessions": sessions }).to_string())
175    }
176
177    // ─── Stats ──────────────────────────────────────────────────
178
179    /// Return diagnostic info about the current configuration (mise doctor style).
180    pub fn info(&self) -> String {
181        let mut info = serde_json::json!({
182            "version": env!("CARGO_PKG_VERSION"),
183            "preset_catalog_version": PRESET_CATALOG_VERSION,
184            "log_dir": {
185                "resolved": self.log_config.log_dir.as_ref().map(|p| p.display().to_string()),
186                "source": self.log_config.log_dir_source.to_string(),
187            },
188            "log_enabled": self.log_config.log_enabled,
189            "tracing": if self.log_config.log_dir.is_some() { "file + stderr" } else { "stderr only" },
190        });
191
192        // search paths (package resolution chain, priority order)
193        let search_paths_json: Vec<serde_json::Value> = self
194            .search_paths
195            .iter()
196            .map(|sp| {
197                serde_json::json!({
198                    "path": sp.path.display().to_string(),
199                    "source": sp.source.to_string(),
200                })
201            })
202            .collect();
203        info["search_paths"] = serde_json::json!(search_paths_json);
204
205        // packages dir (kept for backward compatibility)
206        let packages = self.log_config.app_dir().packages_dir();
207        if packages.is_dir() {
208            info["packages_dir"] = serde_json::json!(packages.display().to_string());
209        }
210
211        // Settings — resolve all [setting.*] layers in one call.
212        // resolve_setting is synchronous; info() is also synchronous, so no
213        // spawn_blocking is needed.
214        // On error, surface a warning string under settings_error rather than
215        // failing info() entirely — info() is used as a doctor/diagnostics tool
216        // and must return a useful response even when config files are corrupt
217        // (CLAUDE.md §Service 層 Error 伝播規律, warning-field pattern).
218        let app_dir = self.log_config.app_dir();
219        match crate::service::setting::resolve_setting(&app_dir, None, None) {
220            Ok(resolved) => match serde_json::to_value(&resolved) {
221                Ok(v) => {
222                    info["settings"] = v;
223                }
224                Err(e) => {
225                    info["settings_error"] = serde_json::json!(e.to_string());
226                }
227            },
228            Err(e) => {
229                info["settings_error"] = serde_json::json!(e.to_string());
230            }
231        }
232
233        serde_json::to_string_pretty(&info).unwrap_or_else(|_| "{}".to_string())
234    }
235
236    /// Aggregate stats across all logged sessions.
237    ///
238    /// Scans `.meta.json` files (with `.json` fallback for legacy logs).
239    /// Optional filters: `strategy` (exact match), `days` (last N days).
240    ///
241    /// # Legacy log compatibility
242    ///
243    /// Token fields (`prompt_tokens`, `response_tokens`) were introduced in v0.12.
244    /// Logs written by earlier versions lack these fields entirely. When absent,
245    /// the aggregation treats them as **0** (via `unwrap_or(0)`) — the same
246    /// pattern used for other numeric fields (`elapsed_ms`, `total_prompt_chars`,
247    /// etc.). This means per-strategy `total_tokens` may under-report if the
248    /// dataset includes pre-v0.12 sessions.
249    pub fn stats(
250        &self,
251        strategy_filter: Option<&str>,
252        days: Option<u64>,
253    ) -> Result<String, String> {
254        let dir = match self.log_config.log_dir.as_deref() {
255            Some(d) if d.is_dir() => d,
256            _ => {
257                let card_sinks = algocline_engine::card::subscriber_stats_snapshot();
258                return Ok(serde_json::json!({
259                    "total_sessions": 0,
260                    "strategies": {},
261                    "card_sinks": card_sinks,
262                })
263                .to_string());
264            }
265        };
266
267        let cutoff = days.map(|d| {
268            std::time::SystemTime::now()
269                .duration_since(std::time::UNIX_EPOCH)
270                .unwrap_or_default()
271                .as_millis() as u64
272                - d * 86_400_000
273        });
274
275        let entries = std::fs::read_dir(dir).map_err(|e| format!("Failed to read log dir: {e}"))?;
276
277        #[derive(Default)]
278        struct StrategyAcc {
279            count: u64,
280            sum_elapsed_ms: u64,
281            sum_llm_calls: u64,
282            sum_rounds: u64,
283            sum_prompt_chars: u64,
284            sum_response_chars: u64,
285            sum_prompt_tokens: u64,
286            sum_response_tokens: u64,
287        }
288
289        let mut acc: std::collections::HashMap<String, StrategyAcc> =
290            std::collections::HashMap::new();
291        let mut total: u64 = 0;
292
293        for entry in entries.flatten() {
294            let path = entry.path();
295            let name = match path.file_name().and_then(|n| n.to_str()) {
296                Some(n) => n.to_string(),
297                None => continue,
298            };
299
300            // Read meta from .meta.json or fall back to .json
301            let doc: serde_json::Value = if name.ends_with(".meta.json") {
302                match std::fs::read_to_string(&path)
303                    .ok()
304                    .and_then(|r| serde_json::from_str(&r).ok())
305                {
306                    Some(d) => d,
307                    None => continue,
308                }
309            } else if name.ends_with(".json") && !name.ends_with(".meta.json") {
310                // Skip full logs if meta exists
311                let meta_name =
312                    format!("{}.meta.json", name.strip_suffix(".json").unwrap_or(&name));
313                let meta_path = dir.join(meta_name);
314                if meta_path.exists() {
315                    continue;
316                }
317                // Legacy fallback
318                match std::fs::read_to_string(&path)
319                    .ok()
320                    .and_then(|r| serde_json::from_str::<serde_json::Value>(&r).ok())
321                {
322                    Some(d) => {
323                        let stats = d.get("stats");
324                        serde_json::json!({
325                            "strategy": d.get("strategy").and_then(|v| v.as_str()),
326                            "elapsed_ms": stats.and_then(|s| s.get("elapsed_ms")),
327                            "llm_calls": stats.and_then(|s| s.get("llm_calls")),
328                            "rounds": stats.and_then(|s| s.get("rounds")),
329                            "total_prompt_chars": stats.and_then(|s| s.get("total_prompt_chars")),
330                            "total_response_chars": stats.and_then(|s| s.get("total_response_chars")),
331                        })
332                    }
333                    None => continue,
334                }
335            } else {
336                continue;
337            };
338
339            // Apply time filter via elapsed_ms proxy (file mtime would be better but
340            // meta files don't store timestamps; use mtime as approximation)
341            if let Some(cutoff_ms) = cutoff {
342                let mtime = entry
343                    .metadata()
344                    .ok()
345                    .and_then(|m| m.modified().ok())
346                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
347                    .map(|d| d.as_millis() as u64)
348                    .unwrap_or(0);
349                if mtime < cutoff_ms {
350                    continue;
351                }
352            }
353
354            let strat = doc
355                .get("strategy")
356                .and_then(|v| v.as_str())
357                .unwrap_or("unknown")
358                .to_string();
359
360            // Apply strategy filter
361            if let Some(filter) = strategy_filter {
362                if strat != filter {
363                    continue;
364                }
365            }
366
367            let elapsed = doc.get("elapsed_ms").and_then(|v| v.as_u64()).unwrap_or(0);
368            let llm = doc.get("llm_calls").and_then(|v| v.as_u64()).unwrap_or(0);
369            let rounds = doc.get("rounds").and_then(|v| v.as_u64()).unwrap_or(0);
370            let prompt_chars = doc
371                .get("total_prompt_chars")
372                .and_then(|v| v.as_u64())
373                .unwrap_or(0);
374            let response_chars = doc
375                .get("total_response_chars")
376                .and_then(|v| v.as_u64())
377                .unwrap_or(0);
378
379            // Token counts: nested {"tokens": N, "source": "..."} or legacy absent
380            let prompt_tokens = doc
381                .get("prompt_tokens")
382                .and_then(|v| v.get("tokens"))
383                .and_then(|v| v.as_u64())
384                .unwrap_or(0);
385            let response_tokens = doc
386                .get("response_tokens")
387                .and_then(|v| v.get("tokens"))
388                .and_then(|v| v.as_u64())
389                .unwrap_or(0);
390
391            let a = acc.entry(strat).or_default();
392            a.count += 1;
393            a.sum_elapsed_ms += elapsed;
394            a.sum_llm_calls += llm;
395            a.sum_rounds += rounds;
396            a.sum_prompt_chars += prompt_chars;
397            a.sum_response_chars += response_chars;
398            a.sum_prompt_tokens += prompt_tokens;
399            a.sum_response_tokens += response_tokens;
400            total += 1;
401        }
402
403        // Build response
404        let mut strategies = serde_json::Map::new();
405        for (strat, a) in &acc {
406            let c = a.count.max(1); // avoid division by zero
407            strategies.insert(
408                strat.clone(),
409                serde_json::json!({
410                    "count": a.count,
411                    "avg_elapsed_ms": (a.sum_elapsed_ms + c / 2) / c,
412                    "avg_llm_calls": (a.sum_llm_calls + c / 2) / c,
413                    "avg_rounds": (a.sum_rounds + c / 2) / c,
414                    "total_prompt_chars": a.sum_prompt_chars,
415                    "total_response_chars": a.sum_response_chars,
416                    "total_prompt_tokens": a.sum_prompt_tokens,
417                    "total_response_tokens": a.sum_response_tokens,
418                    "total_tokens": a.sum_prompt_tokens + a.sum_response_tokens,
419                }),
420            );
421        }
422
423        let card_sinks = algocline_engine::card::subscriber_stats_snapshot();
424        Ok(serde_json::json!({
425            "total_sessions": total,
426            "strategies": strategies,
427            "card_sinks": card_sinks,
428        })
429        .to_string())
430    }
431}