Skip to main content

git_iris/agents/
debug.rs

1//! Debug observability module for Iris agent operations
2//!
3//! All debug output goes through tracing. Use `-l <file>` to log to file,
4//! `--debug` to enable debug-level output.
5
6use std::fs::{self, OpenOptions};
7use std::io::{self, Write};
8use std::path::PathBuf;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::time::{Duration, Instant};
11
12#[cfg(unix)]
13use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
14
15const DEBUG_DIR_ENV: &str = "GIT_IRIS_DEBUG_DIR";
16
17/// Global debug mode flag
18static DEBUG_MODE: AtomicBool = AtomicBool::new(false);
19
20/// Enable debug mode
21pub fn enable_debug_mode() {
22    DEBUG_MODE.store(true, Ordering::SeqCst);
23}
24
25/// Disable debug mode
26pub fn disable_debug_mode() {
27    DEBUG_MODE.store(false, Ordering::SeqCst);
28}
29
30/// Check if debug mode is enabled
31pub fn is_debug_enabled() -> bool {
32    DEBUG_MODE.load(Ordering::SeqCst)
33}
34
35/// Resolve the directory used for storing debug artifacts (LLM dumps, extracted JSON)
36fn debug_artifacts_dir() -> io::Result<PathBuf> {
37    let base = std::env::var_os(DEBUG_DIR_ENV)
38        .map(PathBuf::from)
39        .or_else(|| {
40            dirs::cache_dir().map(|mut dir| {
41                dir.push("git-iris");
42                dir.push("debug-artifacts");
43                dir
44            })
45        })
46        .unwrap_or_else(|| {
47            std::env::temp_dir()
48                .join("git-iris")
49                .join("debug-artifacts")
50        });
51
52    if !base.exists() {
53        fs::create_dir_all(&base)?;
54    }
55
56    #[cfg(unix)]
57    {
58        let _ = fs::set_permissions(&base, fs::Permissions::from_mode(0o700));
59    }
60
61    Ok(base)
62}
63
64/// Write debug artifact with restrictive permissions and return the file path.
65///
66/// # Errors
67///
68/// Returns an error when the artifact directory or file cannot be created.
69pub fn write_debug_artifact(filename: &str, contents: &str) -> io::Result<PathBuf> {
70    let mut path = debug_artifacts_dir()?;
71    path.push(filename);
72
73    write_secure_file(&path, contents)?;
74    Ok(path)
75}
76
77fn write_secure_file(path: &PathBuf, contents: &str) -> io::Result<()> {
78    #[cfg(unix)]
79    {
80        let mut options = OpenOptions::new();
81        options.write(true).create(true).truncate(true).mode(0o600);
82        let mut file = options.open(path)?;
83        file.write_all(contents.as_bytes())?;
84        Ok(())
85    }
86
87    #[cfg(not(unix))]
88    {
89        let mut file = OpenOptions::new()
90            .write(true)
91            .create(true)
92            .truncate(true)
93            .open(path)?;
94        file.write_all(contents.as_bytes())
95    }
96}
97
98/// Format duration in a human-readable way
99fn format_duration(duration: Duration) -> String {
100    if duration.as_secs() > 0 {
101        format!("{:.2}s", duration.as_secs_f64())
102    } else if duration.as_millis() > 0 {
103        format!("{}ms", duration.as_millis())
104    } else {
105        format!("{}μs", duration.as_micros())
106    }
107}
108
109/// Safely truncate a string at a character boundary
110fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> &str {
111    if s.len() <= max_bytes {
112        return s;
113    }
114    let mut end = max_bytes;
115    while end > 0 && !s.is_char_boundary(end) {
116        end -= 1;
117    }
118    &s[..end]
119}
120
121/// Print a debug header
122pub fn debug_header(title: &str) {
123    if !is_debug_enabled() {
124        return;
125    }
126    tracing::debug!(target: "iris", "══════════════════════════════════════════════════════════════════════════════");
127    tracing::debug!(target: "iris", "◆ {} ◆", title);
128    tracing::debug!(target: "iris", "══════════════════════════════════════════════════════════════════════════════");
129}
130
131/// Print a debug section
132pub fn debug_section(title: &str) {
133    if !is_debug_enabled() {
134        return;
135    }
136    tracing::debug!(target: "iris", "▸ {}", title);
137    tracing::debug!(target: "iris", "──────────────────────────────────────────────────────────────────────────────");
138}
139
140/// Print tool call information
141pub fn debug_tool_call(tool_name: &str, args: &str) {
142    if !is_debug_enabled() {
143        return;
144    }
145
146    tracing::debug!(target: "iris", "🔧 Tool Call: {}", tool_name);
147
148    if !args.is_empty() {
149        let truncated = if args.len() > 200 {
150            format!("{}...", truncate_at_char_boundary(args, 200))
151        } else {
152            args.to_string()
153        };
154        tracing::debug!(target: "iris", "   Args: {}", truncated);
155    }
156}
157
158/// Print tool response information
159pub fn debug_tool_response(tool_name: &str, response: &str, duration: Duration) {
160    if !is_debug_enabled() {
161        return;
162    }
163
164    let truncated = if response.len() > 500 {
165        format!("{}...", truncate_at_char_boundary(response, 500))
166    } else {
167        response.to_string()
168    };
169
170    tracing::debug!(target: "iris", "✓ Tool Response: {} ({})", tool_name, format_duration(duration));
171    tracing::debug!(target: "iris", "   {}", truncated);
172}
173
174/// Print LLM request information
175pub fn debug_llm_request(prompt: &str, max_tokens: Option<usize>) {
176    if !is_debug_enabled() {
177        return;
178    }
179
180    let char_count = prompt.chars().count();
181    let word_count = prompt.split_whitespace().count();
182
183    tracing::debug!(target: "iris", "🧠 LLM Request: {} chars, {} words {}",
184        char_count,
185        word_count,
186        max_tokens.map(|t| format!("(max {} tokens)", t)).unwrap_or_default()
187    );
188
189    // Show first few lines of prompt
190    for line in prompt.lines().take(5) {
191        let truncated = if line.len() > 120 {
192            format!("{}...", truncate_at_char_boundary(line, 120))
193        } else {
194            line.to_string()
195        };
196        tracing::debug!(target: "iris", "   {}", truncated);
197    }
198    if prompt.lines().count() > 5 {
199        tracing::debug!(target: "iris", "   ... ({} more lines)", prompt.lines().count() - 5);
200    }
201
202    // Save full prompt to debug artifact
203    if let Ok(path) = write_debug_artifact("iris_last_prompt.txt", prompt) {
204        tracing::debug!(target: "iris", "   Full prompt saved to: {}", path.display());
205    }
206}
207
208/// Print streaming chunk
209pub fn debug_stream_chunk(_chunk: &str, chunk_number: usize) {
210    if !is_debug_enabled() {
211        return;
212    }
213
214    // Only print every 10th chunk to avoid overwhelming output
215    if chunk_number.is_multiple_of(10) {
216        tracing::debug!(target: "iris", "▹ chunk #{}", chunk_number);
217    }
218}
219
220/// Print complete LLM response
221pub fn debug_llm_response(response: &str, duration: Duration, tokens_used: Option<usize>) {
222    if !is_debug_enabled() {
223        return;
224    }
225
226    let char_count = response.chars().count();
227    let word_count = response.split_whitespace().count();
228
229    tracing::debug!(target: "iris", "✨ LLM Response: {} chars, {} words ({})",
230        char_count,
231        word_count,
232        format_duration(duration)
233    );
234
235    if let Some(tokens) = tokens_used {
236        tracing::debug!(target: "iris", "   Tokens: {}", tokens);
237    }
238
239    // Save full response to file for deep debugging
240    if let Ok(path) = write_debug_artifact("iris_last_response.txt", response) {
241        tracing::debug!(target: "iris", "   Full response saved to: {}", path.display());
242    }
243
244    // Show response (truncated if too long)
245    let truncated = if response.len() > 1000 {
246        format!(
247            "{}...\n\n... ({} more characters)",
248            truncate_at_char_boundary(response, 1000),
249            response.len() - 1000
250        )
251    } else {
252        response.to_string()
253    };
254    for line in truncated.lines() {
255        tracing::debug!(target: "iris", "{}", line);
256    }
257}
258
259/// Print JSON parsing attempt
260pub fn debug_json_parse_attempt(json_str: &str) {
261    if !is_debug_enabled() {
262        return;
263    }
264
265    tracing::debug!(target: "iris", "📝 JSON Parse Attempt: {} chars", json_str.len());
266
267    // Show first 500 chars
268    let head = if json_str.len() > 500 {
269        format!("{}...", truncate_at_char_boundary(json_str, 500))
270    } else {
271        json_str.to_string()
272    };
273    tracing::debug!(target: "iris", "{}", head);
274
275    // Show last 200 chars to see where it got cut off
276    if json_str.len() > 700 {
277        tracing::debug!(target: "iris", "... truncated ...");
278        let mut tail_start = json_str.len().saturating_sub(200);
279        while tail_start < json_str.len() && !json_str.is_char_boundary(tail_start) {
280            tail_start += 1;
281        }
282        tracing::debug!(target: "iris", "{}", &json_str[tail_start..]);
283    }
284}
285
286/// Print JSON parse success
287pub fn debug_json_parse_success(type_name: &str) {
288    if !is_debug_enabled() {
289        return;
290    }
291    tracing::debug!(target: "iris", "✓ JSON Parsed: {}", type_name);
292}
293
294/// Print JSON parse error
295pub fn debug_json_parse_error(error: &str) {
296    if !is_debug_enabled() {
297        return;
298    }
299    tracing::warn!(target: "iris", "✗ JSON Parse Error: {}", error);
300}
301
302/// Print context management decision
303pub fn debug_context_management(action: &str, details: &str) {
304    if !is_debug_enabled() {
305        return;
306    }
307    tracing::debug!(target: "iris", "🔍 {} {}", action, details);
308}
309
310/// Print an error
311pub fn debug_error(error: &str) {
312    if !is_debug_enabled() {
313        return;
314    }
315    tracing::error!(target: "iris", "✗ Error: {}", error);
316}
317
318/// Print a warning
319pub fn debug_warning(warning: &str) {
320    if !is_debug_enabled() {
321        return;
322    }
323    tracing::warn!(target: "iris", "⚠ {}", warning);
324}
325
326/// Print agent phase change
327pub fn debug_phase_change(phase: &str) {
328    if !is_debug_enabled() {
329        return;
330    }
331    tracing::debug!(target: "iris", "◆ {}", phase);
332    tracing::debug!(target: "iris", "──────────────────────────────────────────────────────────────────────────────");
333}
334
335/// Timer for measuring operation duration
336pub struct DebugTimer {
337    start: Instant,
338    operation: String,
339}
340
341impl DebugTimer {
342    pub fn start(operation: &str) -> Self {
343        if is_debug_enabled() {
344            tracing::debug!(target: "iris", "⏱ Started: {}", operation);
345        }
346
347        Self {
348            start: Instant::now(),
349            operation: operation.to_string(),
350        }
351    }
352
353    pub fn finish(self) {
354        if is_debug_enabled() {
355            let duration = self.start.elapsed();
356            tracing::debug!(target: "iris", "✓ Completed: {} ({})", self.operation, format_duration(duration));
357        }
358    }
359}