Skip to main content

aptu_coder/
metrics.rs

1// SPDX-FileCopyrightText: 2026 aptu-coder contributors
2// SPDX-License-Identifier: Apache-2.0
3//! Metrics collection and daily-rotating JSONL emission.
4//!
5//! Provides a channel-based pipeline: callers emit [`MetricEvent`] values via [`MetricsSender`],
6//! and [`MetricsWriter`] drains the channel and appends events to a daily-rotated JSONL file
7//! under the XDG data directory (`~/.local/share/aptu-coder/metrics-YYYY-MM-DD.jsonl`).
8//! Files older than 30 days are deleted on startup.
9
10use serde::{Deserialize, Serialize};
11use std::path::{Path, PathBuf};
12use std::time::{SystemTime, UNIX_EPOCH};
13use tokio::io::AsyncWriteExt;
14use tokio::sync::mpsc;
15
16/// A single metric event emitted by a tool invocation.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct MetricEvent {
19    pub ts: u64,
20    pub tool: &'static str,
21    pub duration_ms: u64,
22    pub output_chars: usize,
23    pub param_path_depth: usize,
24    pub max_depth: Option<u32>,
25    pub result: &'static str,
26    pub error_type: Option<String>,
27    #[serde(default)]
28    pub session_id: Option<String>,
29    #[serde(default)]
30    pub seq: Option<u32>,
31    #[serde(default)]
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub cache_hit: Option<bool>,
34}
35
36/// Sender half of the metrics channel; cloned and passed to tools for event emission.
37#[derive(Clone)]
38pub struct MetricsSender(pub tokio::sync::mpsc::UnboundedSender<MetricEvent>);
39
40impl MetricsSender {
41    pub fn send(&self, event: MetricEvent) {
42        let _ = self.0.send(event);
43    }
44}
45
46/// Receiver half of the metrics channel; drains events and writes them to daily-rotated JSONL files.
47pub struct MetricsWriter {
48    rx: tokio::sync::mpsc::UnboundedReceiver<MetricEvent>,
49    base_dir: PathBuf,
50    dir_created: bool,
51}
52
53impl MetricsWriter {
54    pub fn new(
55        rx: tokio::sync::mpsc::UnboundedReceiver<MetricEvent>,
56        base_dir: Option<PathBuf>,
57    ) -> Self {
58        let dir = base_dir.unwrap_or_else(xdg_metrics_dir);
59        Self {
60            rx,
61            base_dir: dir,
62            dir_created: false,
63        }
64    }
65
66    /// Accumulate a metric event into tool_counts and export_session_id.
67    fn accumulate_event(
68        tool_counts: &mut std::collections::HashMap<&'static str, (u64, u64)>,
69        export_session_id: &mut Option<String>,
70        event: &MetricEvent,
71    ) {
72        let entry = tool_counts.entry(event.tool).or_insert((0, 0));
73        entry.0 += 1;
74        entry.1 += event.duration_ms;
75        if export_session_id.is_none() {
76            *export_session_id = event.session_id.clone();
77        }
78    }
79
80    pub async fn run(mut self) {
81        cleanup_old_files(&self.base_dir).await;
82        let mut current_date = current_date_str();
83        let mut current_file: Option<PathBuf> = None;
84
85        // Accumulate per-tool metrics for export on shutdown (issue #773)
86        let mut tool_counts: std::collections::HashMap<&'static str, (u64, u64)> =
87            std::collections::HashMap::new();
88        let mut export_session_id: Option<String> = None;
89
90        loop {
91            let mut batch = Vec::new();
92            if let Some(event) = self.rx.recv().await {
93                Self::accumulate_event(&mut tool_counts, &mut export_session_id, &event);
94                batch.push(event);
95                for _ in 0..99 {
96                    match self.rx.try_recv() {
97                        Ok(e) => {
98                            Self::accumulate_event(&mut tool_counts, &mut export_session_id, &e);
99                            batch.push(e);
100                        }
101                        Err(
102                            mpsc::error::TryRecvError::Empty
103                            | mpsc::error::TryRecvError::Disconnected,
104                        ) => break,
105                    }
106                }
107            } else {
108                break;
109            }
110
111            let new_date = current_date_str();
112            if new_date != current_date {
113                current_date = new_date;
114                current_file = None;
115                self.dir_created = false;
116            }
117
118            if current_file.is_none() {
119                current_file = Some(
120                    self.base_dir
121                        .join(format!("metrics-{}.jsonl", current_date)),
122                );
123            }
124
125            let path = current_file.as_ref().unwrap();
126
127            // Create directory once per day
128            if !self.dir_created
129                && let Some(parent) = path.parent()
130                && !parent.as_os_str().is_empty()
131            {
132                match tokio::fs::create_dir_all(parent).await {
133                    Ok(()) => {
134                        self.dir_created = true;
135                    }
136                    Err(e) => {
137                        tracing::warn!(
138                            error = %e,
139                            path = %parent.display(),
140                            "metrics: failed to create directory; will retry next batch"
141                        );
142                    }
143                }
144            }
145
146            // Open file once per batch
147            let file = tokio::fs::OpenOptions::new()
148                .create(true)
149                .append(true)
150                .open(path)
151                .await;
152
153            if let Ok(mut file) = file {
154                for event in batch {
155                    if let Ok(mut json) = serde_json::to_string(&event) {
156                        json.push('\n');
157                        let _ = file.write_all(json.as_bytes()).await;
158                    }
159                }
160                let _ = file.flush().await;
161            }
162        }
163
164        // Export metrics summary on shutdown (issue #773)
165        if let Ok(export_path) = std::env::var("APTU_CODER_METRICS_EXPORT_FILE") {
166            if !std::path::Path::new(&export_path).is_absolute() {
167                tracing::warn!(
168                    path = %export_path,
169                    "metrics: APTU_CODER_METRICS_EXPORT_FILE must be an absolute path; skipping export"
170                );
171            } else {
172                let mut tool_calls = Vec::new();
173                let mut total_duration_ms = 0u64;
174                for (tool_name, (count, duration)) in tool_counts {
175                    tool_calls.push(serde_json::json!({
176                        "tool": tool_name,
177                        "call_count": count,
178                        "total_duration_ms": duration
179                    }));
180                    total_duration_ms += duration;
181                }
182                let summary = serde_json::json!({
183                    "session_id": export_session_id.unwrap_or_default(),
184                    "tool_calls": tool_calls,
185                    "total_duration_ms": total_duration_ms
186                });
187                if let Ok(json_str) = serde_json::to_string(&summary)
188                    && let Err(e) = tokio::fs::write(&export_path, json_str).await
189                {
190                    tracing::warn!(
191                        error = %e,
192                        path = %export_path,
193                        "metrics: failed to write export file"
194                    );
195                }
196            }
197        }
198    }
199}
200
201/// Returns the current UNIX timestamp in milliseconds.
202#[must_use]
203pub fn unix_ms() -> u64 {
204    SystemTime::now()
205        .duration_since(UNIX_EPOCH)
206        .unwrap_or_default()
207        .as_millis()
208        .try_into()
209        .unwrap_or(u64::MAX)
210}
211
212/// Counts the number of path segments in a file path.
213#[must_use]
214pub fn path_component_count(path: &str) -> usize {
215    Path::new(path).components().count()
216}
217
218fn xdg_metrics_dir() -> PathBuf {
219    if let Ok(xdg_data_home) = std::env::var("XDG_DATA_HOME")
220        && !xdg_data_home.is_empty()
221    {
222        return PathBuf::from(xdg_data_home).join("aptu-coder");
223    }
224
225    if let Ok(home) = std::env::var("HOME") {
226        PathBuf::from(home)
227            .join(".local")
228            .join("share")
229            .join("aptu-coder")
230    } else {
231        PathBuf::from(".")
232    }
233}
234
235async fn cleanup_old_files(base_dir: &Path) {
236    let now_days = u32::try_from(unix_ms() / 86_400_000).unwrap_or(u32::MAX);
237
238    let Ok(mut entries) = tokio::fs::read_dir(base_dir).await else {
239        return;
240    };
241
242    loop {
243        match entries.next_entry().await {
244            Ok(Some(entry)) => {
245                let path = entry.path();
246                let file_name = match path.file_name() {
247                    Some(n) => n.to_string_lossy().into_owned(),
248                    None => continue,
249                };
250
251                // Expected format: metrics-YYYY-MM-DD.jsonl
252                if !file_name.starts_with("metrics-")
253                    || std::path::Path::new(&*file_name)
254                        .extension()
255                        .is_none_or(|e| !e.eq_ignore_ascii_case("jsonl"))
256                {
257                    continue;
258                }
259                let date_part = &file_name[8..file_name.len() - 6];
260                if date_part.len() != 10
261                    || date_part.as_bytes().get(4) != Some(&b'-')
262                    || date_part.as_bytes().get(7) != Some(&b'-')
263                {
264                    continue;
265                }
266                let Ok(year) = date_part[0..4].parse::<u32>() else {
267                    continue;
268                };
269                let Ok(month) = date_part[5..7].parse::<u32>() else {
270                    continue;
271                };
272                let Ok(day) = date_part[8..10].parse::<u32>() else {
273                    continue;
274                };
275                if month == 0 || month > 12 || day == 0 || day > 31 {
276                    continue;
277                }
278
279                let file_days = date_to_days_since_epoch(year, month, day);
280                if now_days > file_days && (now_days - file_days) > 30 {
281                    let _ = tokio::fs::remove_file(&path).await;
282                }
283            }
284            Ok(None) => break,
285            Err(e) => {
286                tracing::warn!("error reading metrics directory entry: {e}");
287            }
288        }
289    }
290}
291
292fn date_to_days_since_epoch(y: u32, m: u32, d: u32) -> u32 {
293    // Shift year so March is month 0
294    let (y, m) = if m <= 2 { (y - 1, m + 9) } else { (y, m - 3) };
295    let era = y / 400;
296    let yoe = y - era * 400;
297    let doy = (153 * m + 2) / 5 + d - 1;
298    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
299    // Compute the proleptic Gregorian day number, then subtract the Unix epoch offset.
300    // The subtraction must wrap the full expression; applying .saturating_sub to `doe`
301    // alone would underflow for recent dates where doe < 719_468.
302    (era * 146_097 + doe).saturating_sub(719_468)
303}
304
305/// Returns the current UTC date as a string in YYYY-MM-DD format.
306#[must_use]
307pub fn current_date_str() -> String {
308    let days = u32::try_from(unix_ms() / 86_400_000).unwrap_or(u32::MAX);
309    let z = days + 719_468;
310    let era = z / 146_097;
311    let doe = z - era * 146_097;
312    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
313    let y = yoe + era * 400;
314    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
315    let mp = (5 * doy + 2) / 153;
316    let d = doy - (153 * mp + 2) / 5 + 1;
317    let m = if mp < 10 { mp + 3 } else { mp - 9 };
318    let y = if m <= 2 { y + 1 } else { y };
319    format!("{y:04}-{m:02}-{d:02}")
320}
321
322/// Migrate legacy metrics directory from `code-analyze-mcp` to `aptu-coder`.
323///
324/// - If the old directory exists and the new one does not, rename it and log info.
325/// - If both exist, log a warning and do nothing.
326/// - If neither exists, do nothing.
327///
328/// Returns `Ok(())` on success, propagating any I/O errors.
329pub fn migrate_legacy_metrics_dir() -> std::io::Result<()> {
330    let home =
331        std::env::var("HOME").map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
332    migrate_legacy_metrics_dir_impl(&home)
333}
334
335#[allow(dead_code)]
336fn migrate_legacy_metrics_dir_impl(home: &str) -> std::io::Result<()> {
337    let old_dir = PathBuf::from(home).join(".local/share/code-analyze-mcp");
338    let new_dir = PathBuf::from(home).join(".local/share/aptu-coder");
339
340    let old_exists = old_dir.is_dir();
341    let new_exists = new_dir.is_dir();
342
343    if old_exists && !new_exists {
344        std::fs::rename(&old_dir, &new_dir)?;
345        tracing::info!(
346            "Migrated legacy metrics directory from {:?} to {:?}",
347            old_dir,
348            new_dir
349        );
350    } else if old_exists && new_exists {
351        tracing::warn!("Both legacy and new metrics directories exist; not migrating");
352    }
353    // If old does not exist, nothing to do.
354    Ok(())
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360    use std::fs;
361    use std::sync::{Mutex, OnceLock};
362    use tempfile::TempDir;
363
364    /// Serializes tests that mutate `APTU_CODER_METRICS_EXPORT_FILE` to prevent parallel
365    /// pollution. Recovers from poison caused by panicking tests.
366    fn metrics_export_lock() -> std::sync::MutexGuard<'static, ()> {
367        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
368        let m = LOCK.get_or_init(|| Mutex::new(()));
369        m.lock().unwrap_or_else(|e| e.into_inner())
370    }
371
372    #[test]
373    fn test_migrate_legacy_only_old_exists() {
374        // Arrange
375        let tmp_home = TempDir::new().unwrap();
376        let home_str = tmp_home.path().to_str().unwrap();
377        let old_path = tmp_home.path().join(".local/share/code-analyze-mcp");
378        let new_path = tmp_home.path().join(".local/share/aptu-coder");
379        fs::create_dir_all(&old_path).unwrap();
380        assert!(!new_path.exists());
381
382        // Act
383        let result = migrate_legacy_metrics_dir_impl(home_str);
384
385        // Assert
386        assert!(result.is_ok());
387        assert!(!old_path.exists(), "old dir should be moved");
388        assert!(new_path.is_dir(), "new dir should exist");
389    }
390
391    #[test]
392    fn test_migrate_legacy_both_exist() {
393        // Arrange
394        let tmp_home = TempDir::new().unwrap();
395        let home_str = tmp_home.path().to_str().unwrap();
396        let old_path = tmp_home.path().join(".local/share/code-analyze-mcp");
397        let new_path = tmp_home.path().join(".local/share/aptu-coder");
398        fs::create_dir_all(&old_path).unwrap();
399        fs::create_dir_all(&new_path).unwrap();
400
401        // Act
402        let result = migrate_legacy_metrics_dir_impl(home_str);
403
404        // Assert
405        assert!(result.is_ok());
406        assert!(old_path.is_dir(), "old dir should remain");
407        assert!(new_path.is_dir(), "new dir should remain");
408    }
409
410    #[test]
411    fn test_migrate_legacy_neither_exists() {
412        // Arrange
413        let tmp_home = TempDir::new().unwrap();
414        let home_str = tmp_home.path().to_str().unwrap();
415        let old_path = tmp_home.path().join(".local/share/code-analyze-mcp");
416        let new_path = tmp_home.path().join(".local/share/aptu-coder");
417
418        // Act
419        let result = migrate_legacy_metrics_dir_impl(home_str);
420
421        // Assert
422        assert!(result.is_ok());
423        assert!(!old_path.exists(), "old dir should not exist");
424        assert!(!new_path.exists(), "new dir should not exist");
425    }
426
427    #[test]
428    fn test_date_to_days_since_epoch_known_dates() {
429        assert_eq!(date_to_days_since_epoch(1970, 1, 1), 0);
430        assert_eq!(date_to_days_since_epoch(2020, 1, 1), 18_262);
431        assert_eq!(date_to_days_since_epoch(2000, 2, 29), 11_016);
432    }
433
434    #[test]
435    fn test_current_date_str_format() {
436        let s = current_date_str();
437        assert_eq!(s.len(), 10);
438        assert_eq!(s.as_bytes()[4], b'-');
439        assert_eq!(s.as_bytes()[7], b'-');
440        let year: u32 = s[0..4].parse().expect("year must be numeric");
441        assert!(year >= 2020 && year <= 2100);
442    }
443
444    #[tokio::test]
445    async fn test_metrics_writer_batching() {
446        let dir = TempDir::new().unwrap();
447        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<MetricEvent>();
448        let writer = MetricsWriter::new(rx, Some(dir.path().to_path_buf()));
449        let make_event = || MetricEvent {
450            ts: unix_ms(),
451            tool: "analyze_directory",
452            duration_ms: 1,
453            output_chars: 10,
454            param_path_depth: 1,
455            max_depth: None,
456            result: "ok",
457            error_type: None,
458            session_id: None,
459            seq: None,
460            cache_hit: None,
461        };
462        tx.send(make_event()).unwrap();
463        tx.send(make_event()).unwrap();
464        tx.send(make_event()).unwrap();
465        drop(tx);
466        writer.run().await;
467        let entries: Vec<_> = std::fs::read_dir(dir.path())
468            .unwrap()
469            .filter_map(|e| e.ok())
470            .filter(|e| {
471                e.path()
472                    .extension()
473                    .and_then(|x| x.to_str())
474                    .map(|x| x.eq_ignore_ascii_case("jsonl"))
475                    .unwrap_or(false)
476            })
477            .collect();
478        assert_eq!(entries.len(), 1);
479        let content = std::fs::read_to_string(entries[0].path()).unwrap();
480        let lines: Vec<&str> = content.lines().collect();
481        assert_eq!(lines.len(), 3);
482    }
483
484    #[tokio::test]
485    async fn test_cleanup_old_files_deletes_old_keeps_recent() {
486        let dir = TempDir::new().unwrap();
487        let old_file = dir.path().join("metrics-1970-01-01.jsonl");
488        let today = current_date_str();
489        let recent_file = dir.path().join(format!("metrics-{}.jsonl", today));
490        std::fs::write(&old_file, "old\n").unwrap();
491        std::fs::write(&recent_file, "recent\n").unwrap();
492        cleanup_old_files(dir.path()).await;
493        assert!(!old_file.exists());
494        assert!(recent_file.exists());
495    }
496
497    #[test]
498    fn test_metric_event_serialization() {
499        let event = MetricEvent {
500            ts: 1_700_000_000_000,
501            tool: "analyze_directory",
502            duration_ms: 42,
503            output_chars: 100,
504            param_path_depth: 3,
505            max_depth: Some(2),
506            result: "ok",
507            error_type: None,
508            session_id: None,
509            seq: None,
510            cache_hit: None,
511        };
512        let json = serde_json::to_string(&event).unwrap();
513        assert!(json.contains("analyze_directory"));
514        assert!(json.contains(r#""result":"ok""#));
515        assert!(json.contains(r#""output_chars":100"#));
516    }
517
518    #[test]
519    fn test_metric_event_serialization_error() {
520        let event = MetricEvent {
521            ts: 1_700_000_000_000,
522            tool: "analyze_directory",
523            duration_ms: 5,
524            output_chars: 0,
525            param_path_depth: 3,
526            max_depth: Some(3),
527            result: "error",
528            error_type: Some("invalid_params".to_string()),
529            session_id: None,
530            seq: None,
531            cache_hit: None,
532        };
533        let json = serde_json::to_string(&event).unwrap();
534        assert!(json.contains(r#""result":"error""#));
535        assert!(json.contains(r#""error_type":"invalid_params""#));
536        assert!(json.contains(r#""output_chars":0"#));
537        assert!(json.contains(r#""max_depth":3"#));
538    }
539
540    #[test]
541    fn test_metric_event_new_fields_round_trip() {
542        let event = MetricEvent {
543            ts: 1_700_000_000_000,
544            tool: "analyze_file",
545            duration_ms: 100,
546            output_chars: 500,
547            param_path_depth: 2,
548            max_depth: Some(3),
549            result: "ok",
550            error_type: None,
551            session_id: Some("1742468880123-42".to_string()),
552            seq: Some(5),
553            cache_hit: None,
554        };
555        let serialized = serde_json::to_string(&event).unwrap();
556        let json_str = r#"{"ts":1700000000000,"tool":"analyze_file","duration_ms":100,"output_chars":500,"param_path_depth":2,"max_depth":3,"result":"ok","error_type":null,"session_id":"1742468880123-42","seq":5}"#;
557        assert_eq!(serialized, json_str);
558    }
559
560    #[tokio::test]
561    async fn test_metrics_export_file_created() {
562        let _guard = metrics_export_lock();
563        // Arrange: create temp dir and set export env var
564        let dir = TempDir::new().unwrap();
565        let export_file = dir.path().join("metrics_export.json");
566        let export_path_str = export_file.to_string_lossy().to_string();
567
568        unsafe {
569            std::env::set_var("APTU_CODER_METRICS_EXPORT_FILE", &export_path_str);
570        }
571
572        // Create metrics writer and send events
573        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<MetricEvent>();
574        let writer = MetricsWriter::new(rx, Some(dir.path().to_path_buf()));
575
576        // Act: send a few events with session_id
577        tx.send(MetricEvent {
578            ts: unix_ms(),
579            tool: "analyze_directory",
580            duration_ms: 100,
581            output_chars: 50,
582            param_path_depth: 1,
583            max_depth: None,
584            result: "ok",
585            error_type: None,
586            session_id: Some("test-session-123".to_string()),
587            seq: None,
588            cache_hit: None,
589        })
590        .unwrap();
591        tx.send(MetricEvent {
592            ts: unix_ms(),
593            tool: "analyze_file",
594            duration_ms: 50,
595            output_chars: 100,
596            param_path_depth: 2,
597            max_depth: Some(3),
598            result: "ok",
599            error_type: None,
600            session_id: Some("test-session-123".to_string()),
601            seq: None,
602            cache_hit: None,
603        })
604        .unwrap();
605        drop(tx);
606        writer.run().await;
607
608        // Assert: export file should exist with correct JSON structure
609        assert!(
610            export_file.exists(),
611            "export file should be created at {:?}",
612            export_file
613        );
614        let content = std::fs::read_to_string(&export_file).unwrap();
615        let json: serde_json::Value = serde_json::from_str(&content).unwrap();
616
617        assert_eq!(
618            json["session_id"], "test-session-123",
619            "export should contain correct session_id"
620        );
621        assert!(
622            json["tool_calls"].is_array(),
623            "export should contain tool_calls array"
624        );
625        let tool_calls = json["tool_calls"].as_array().unwrap();
626        assert_eq!(tool_calls.len(), 2, "should have 2 tool calls");
627        assert!(
628            json["total_duration_ms"].is_number(),
629            "export should contain total_duration_ms"
630        );
631        assert_eq!(
632            json["total_duration_ms"], 150,
633            "total_duration_ms should be sum of all durations"
634        );
635
636        // Cleanup
637        unsafe {
638            std::env::remove_var("APTU_CODER_METRICS_EXPORT_FILE");
639        }
640    }
641
642    #[tokio::test]
643    async fn test_metrics_export_env_var_unset() {
644        let _guard = metrics_export_lock();
645        // Arrange: ensure env var is not set
646        unsafe {
647            std::env::remove_var("APTU_CODER_METRICS_EXPORT_FILE");
648        }
649        let dir = TempDir::new().unwrap();
650        // Use a unique marker to ensure we don't pick up files from other tests
651        let marker = "metrics_export_unset_test";
652
653        // Create metrics writer and send events
654        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<MetricEvent>();
655        let writer = MetricsWriter::new(rx, Some(dir.path().to_path_buf()));
656
657        // Act: send events and run writer
658        tx.send(MetricEvent {
659            ts: unix_ms(),
660            tool: "analyze_directory",
661            duration_ms: 100,
662            output_chars: 50,
663            param_path_depth: 1,
664            max_depth: None,
665            result: "ok",
666            error_type: None,
667            session_id: Some("test-session-456".to_string()),
668            seq: None,
669            cache_hit: None,
670        })
671        .unwrap();
672        drop(tx);
673        writer.run().await;
674
675        // Assert: no export file should be created
676        let entries: Vec<_> = std::fs::read_dir(dir.path())
677            .unwrap()
678            .filter_map(|e| e.ok())
679            .filter(|e| {
680                e.path()
681                    .file_name()
682                    .and_then(|n| n.to_str())
683                    .map(|n| n.contains(marker))
684                    .unwrap_or(false)
685            })
686            .collect();
687        assert_eq!(
688            entries.len(),
689            0,
690            "no export file should be created when env var is unset"
691        );
692    }
693
694    #[tokio::test]
695    async fn test_metrics_export_relative_path_rejected() {
696        let _guard = metrics_export_lock();
697        // Arrange: set export env var to a relative path
698        let relative_path = "relative/path/metrics.json";
699        unsafe {
700            std::env::set_var("APTU_CODER_METRICS_EXPORT_FILE", relative_path);
701        }
702
703        let dir = TempDir::new().unwrap();
704        // Use a unique marker to ensure we don't pick up files from other tests
705        let marker = "metrics_export_relative_test";
706
707        // Create metrics writer and send events
708        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<MetricEvent>();
709        let writer = MetricsWriter::new(rx, Some(dir.path().to_path_buf()));
710
711        // Act: send events and run writer
712        tx.send(MetricEvent {
713            ts: unix_ms(),
714            tool: "analyze_directory",
715            duration_ms: 100,
716            output_chars: 50,
717            param_path_depth: 1,
718            max_depth: None,
719            result: "ok",
720            error_type: None,
721            session_id: Some(marker.to_string()),
722            seq: None,
723            cache_hit: None,
724        })
725        .unwrap();
726        drop(tx);
727        writer.run().await;
728
729        // Assert: no export file should be created for relative path
730        let entries: Vec<_> = std::fs::read_dir(dir.path())
731            .unwrap()
732            .filter_map(|e| e.ok())
733            .filter(|e| {
734                e.path()
735                    .file_name()
736                    .and_then(|n| n.to_str())
737                    .map(|n| n.contains("metrics.json"))
738                    .unwrap_or(false)
739            })
740            .collect();
741        assert_eq!(
742            entries.len(),
743            0,
744            "no export file should be created for relative path"
745        );
746
747        // Cleanup
748        unsafe {
749            std::env::remove_var("APTU_CODER_METRICS_EXPORT_FILE");
750        }
751    }
752}