Skip to main content

algocline_app/service/
logging.rs

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