1use 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
17static DEBUG_MODE: AtomicBool = AtomicBool::new(false);
19
20pub fn enable_debug_mode() {
22 DEBUG_MODE.store(true, Ordering::SeqCst);
23}
24
25pub fn disable_debug_mode() {
27 DEBUG_MODE.store(false, Ordering::SeqCst);
28}
29
30pub fn is_debug_enabled() -> bool {
32 DEBUG_MODE.load(Ordering::SeqCst)
33}
34
35fn 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
64pub 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
98fn 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
109fn 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
121pub 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
131pub 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
140pub 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
158pub 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
174pub 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 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 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
208pub fn debug_stream_chunk(_chunk: &str, chunk_number: usize) {
210 if !is_debug_enabled() {
211 return;
212 }
213
214 if chunk_number.is_multiple_of(10) {
216 tracing::debug!(target: "iris", "▹ chunk #{}", chunk_number);
217 }
218}
219
220pub 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 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 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
259pub 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 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 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
286pub 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
294pub 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
302pub 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
310pub fn debug_error(error: &str) {
312 if !is_debug_enabled() {
313 return;
314 }
315 tracing::error!(target: "iris", "✗ Error: {}", error);
316}
317
318pub fn debug_warning(warning: &str) {
320 if !is_debug_enabled() {
321 return;
322 }
323 tracing::warn!(target: "iris", "⚠ {}", warning);
324}
325
326pub 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
335pub 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}