1use std::fs::{File, OpenOptions};
6use std::io::Write;
7use std::path::PathBuf;
8use std::sync::Mutex;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use crate::truncate::truncate_with_suffix;
13
14static API_CALL_COUNT: AtomicU64 = AtomicU64::new(0);
15static COMPRESSION_COUNT: AtomicU64 = AtomicU64::new(0);
16static MEMORY_SAVE_COUNT: AtomicU64 = AtomicU64::new(0);
17static TOOL_CALL_COUNT: AtomicU64 = AtomicU64::new(0);
18
19pub struct DebugLog {
21 file: Option<Mutex<File>>,
22 verbose: bool,
23}
24
25impl DebugLog {
26 pub fn new(verbose: bool) -> Self {
29 let file = Self::open_log_file().ok().map(Mutex::new);
30 Self { file, verbose }
31 }
32
33 fn open_log_file() -> Result<File, std::io::Error> {
34 let home = std::env::var_os("HOME")
35 .or_else(|| std::env::var_os("USERPROFILE"))
36 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "HOME not set"))?;
37 let mut path = PathBuf::from(home);
38 path.push(".matrix");
39 std::fs::create_dir_all(&path)?;
40 path.push("debug.log");
41 OpenOptions::new().create(true).append(true).open(path)
42 }
43
44 fn timestamp() -> String {
45 let now = SystemTime::now()
46 .duration_since(UNIX_EPOCH)
47 .unwrap_or_default()
48 .as_secs();
49 let secs = now % 60;
50 let mins = (now / 60) % 60;
51 let hours = (now / 3600) % 24;
52 format!("{:02}:{:02}:{:02}", hours, mins, secs)
53 }
54
55 pub fn api_call(&self, model: &str, input_tokens: u32, cached: bool) {
57 let count = API_CALL_COUNT.fetch_add(1, Ordering::Relaxed) + 1;
58 let msg = format!(
59 "[{}] API#{}: model={}, input_tokens={}, cached={}",
60 Self::timestamp(),
61 count,
62 model,
63 input_tokens,
64 cached
65 );
66 self.write(&msg);
67 }
68
69 pub fn compression(&self, original_tokens: u32, compressed_tokens: u32, ratio: f32) {
71 let count = COMPRESSION_COUNT.fetch_add(1, Ordering::Relaxed) + 1;
72 let saved = original_tokens - compressed_tokens;
73 let msg = format!(
74 "[{}] COMPRESSION#{}: original={}, compressed={}, saved={}, ratio={:.1}%",
75 Self::timestamp(),
76 count,
77 original_tokens,
78 compressed_tokens,
79 saved,
80 ratio * 100.0
81 );
82 self.write(&msg);
83 }
84
85 pub fn memory_save(&self, entries: usize, summary_len: usize) {
87 let count = MEMORY_SAVE_COUNT.fetch_add(1, Ordering::Relaxed) + 1;
88 let msg = format!(
89 "[{}] MEMORY#{}: entries={}, summary_len={}chars",
90 Self::timestamp(),
91 count,
92 entries,
93 summary_len
94 );
95 self.write(&msg);
96 }
97
98 pub fn keywords_extracted(&self, keywords: &[String], source: &str) {
100 let msg = format!(
101 "[{}] KEYWORDS: {} extracted from {}chars | keywords: {}",
102 Self::timestamp(),
103 keywords.len(),
104 source.len(),
105 keywords.join(", ")
106 );
107 self.write(&msg);
108 }
109
110 pub fn tool_call(&self, tool: &str, input_preview: &str, result_preview: &str) {
112 let count = TOOL_CALL_COUNT.fetch_add(1, Ordering::Relaxed) + 1;
113 let msg = format!(
114 "[{}] TOOL#{}: {} | input: {} | result: {}",
115 Self::timestamp(),
116 count,
117 tool,
118 truncate(input_preview, 50),
119 truncate(result_preview, 50)
120 );
121 self.write(&msg);
122 }
123
124 pub fn session_save(&self, message_count: usize, total_tokens: u64) {
126 let msg = format!(
127 "[{}] SESSION: messages={}, total_tokens={}",
128 Self::timestamp(),
129 message_count,
130 total_tokens
131 );
132 self.write(&msg);
133 }
134
135 pub fn log(&self, category: &str, message: &str) {
137 let msg = format!("[{}] {}: {}", Self::timestamp(), category, message);
138 self.write(&msg);
139 }
140
141 fn write(&self, msg: &str) {
142 if let Some(ref file) = self.file
144 && let Ok(mut f) = file.lock()
145 {
146 let _ = f.write_all(msg.as_bytes());
147 let _ = f.write_all(b"\n");
148 }
149 if self.verbose {
151 println!("{}", msg);
152 }
153 }
154
155 pub fn stats(&self) -> DebugStats {
157 DebugStats {
158 api_calls: API_CALL_COUNT.load(Ordering::Relaxed),
159 compressions: COMPRESSION_COUNT.load(Ordering::Relaxed),
160 memory_saves: MEMORY_SAVE_COUNT.load(Ordering::Relaxed),
161 tool_calls: TOOL_CALL_COUNT.load(Ordering::Relaxed),
162 }
163 }
164}
165
166fn truncate(s: &str, max: usize) -> String {
167 truncate_with_suffix(s, max)
168}
169
170#[derive(Debug, Clone)]
172pub struct DebugStats {
173 pub api_calls: u64,
174 pub compressions: u64,
175 pub memory_saves: u64,
176 pub tool_calls: u64,
177}
178
179impl DebugStats {
180 pub fn format(&self) -> String {
181 format!(
182 "API: {} │ Compress: {} │ Memory: {} │ Tools: {}",
183 self.api_calls, self.compressions, self.memory_saves, self.tool_calls
184 )
185 }
186}
187
188static DEBUG_LOG: once_cell::sync::Lazy<DebugLog> = once_cell::sync::Lazy::new(|| {
190 let _ = dotenvy::dotenv();
192
193 if let Ok(cwd) = std::env::current_dir() {
195 let matrix_env = cwd.join(".matrix").join(".env");
196 if matrix_env.exists() {
197 let _ = dotenvy::from_path(&matrix_env);
198 }
199 }
200
201 let verbose = std::env::var("MATRIXCODE_DEBUG")
202 .map(|v| v == "1" || v == "true" || v == "verbose")
203 .unwrap_or(false);
204 DebugLog::new(verbose)
205});
206
207pub fn debug_log() -> &'static DebugLog {
209 &DEBUG_LOG
210}
211
212#[macro_export]
214macro_rules! debug_api {
215 ($model:expr, $tokens:expr, $cached:expr) => {
216 $crate::debug::debug_log().api_call($model, $tokens, $cached)
217 };
218}
219
220#[macro_export]
221macro_rules! debug_compress {
222 ($orig:expr, $comp:expr, $ratio:expr) => {
223 $crate::debug::debug_log().compression($orig, $comp, $ratio)
224 };
225}
226
227#[macro_export]
228macro_rules! debug_memory {
229 ($entries:expr, $len:expr) => {
230 $crate::debug::debug_log().memory_save($entries, $len)
231 };
232}
233
234#[macro_export]
235macro_rules! debug_keywords {
236 ($keywords:expr, $source:expr) => {
237 $crate::debug::debug_log().keywords_extracted($keywords, $source)
238 };
239}
240
241#[macro_export]
242macro_rules! debug_tool {
243 ($tool:expr, $input:expr, $result:expr) => {
244 $crate::debug::debug_log().tool_call($tool, $input, $result)
245 };
246}
247
248#[macro_export]
249macro_rules! debug_session {
250 ($msgs:expr, $tokens:expr) => {
251 $crate::debug::debug_log().session_save($msgs, $tokens)
252 };
253}
254
255#[macro_export]
256macro_rules! debug_log_msg {
257 ($cat:expr, $msg:expr) => {
258 $crate::debug::debug_log().log($cat, $msg)
259 };
260}