rch-common 1.0.26

Shared types and utilities for Remote Compilation Helper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
//! E2E Test Logging Library
//!
//! Provides comprehensive logging infrastructure for end-to-end tests.
//!
//! - Real-time console output (human-readable)
//! - Per-test JSONL log files under `target/test-logs/` (machine-readable)

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::fmt;
use std::fs::{self, File};
use std::io::{BufWriter, Write as IoWrite};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};

/// Find the workspace root by walking up from a path until we find a Cargo.toml
/// that contains `[workspace]` or has a `target/` subdirectory with actual builds.
fn find_workspace_root(start: &Path) -> Option<PathBuf> {
    let mut current = start.to_path_buf();
    // Handle case where start is a file (e.g., manifest path)
    if current.is_file() {
        current = current.parent()?.to_path_buf();
    }

    // First pass: look for workspace root marker
    let mut candidate = current.clone();
    loop {
        let cargo_toml = candidate.join("Cargo.toml");
        if cargo_toml.exists() {
            // Check if this is the workspace root by looking for [workspace]
            if let Ok(contents) = std::fs::read_to_string(&cargo_toml)
                && contents.contains("[workspace]")
            {
                return Some(candidate);
            }
            // Also check if target/debug or target/release exists (indicates build root)
            let target = candidate.join("target");
            if target.join("debug").exists() || target.join("release").exists() {
                return Some(candidate);
            }
        }
        // Move up one level
        match candidate.parent() {
            Some(parent) if parent != candidate => candidate = parent.to_path_buf(),
            _ => break,
        }
    }

    // Fallback: walk up and find first directory with target/
    loop {
        if current.join("target").exists() {
            return Some(current);
        }
        match current.parent() {
            Some(parent) if parent != current => current = parent.to_path_buf(),
            _ => break,
        }
    }

    // Last resort: just use the start directory
    start.parent().map(|p| p.to_path_buf())
}

/// Log severity levels for E2E tests
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    /// Very fine-grained diagnostic information
    Trace,
    /// Detailed diagnostic information
    Debug,
    /// Normal operational information
    Info,
    /// Potential issues that don't prevent operation
    Warn,
    /// Errors that may cause test failure
    Error,
}

impl fmt::Display for LogLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            LogLevel::Trace => "TRACE",
            LogLevel::Debug => "DEBUG",
            LogLevel::Info => "INFO",
            LogLevel::Warn => "WARN",
            LogLevel::Error => "ERROR",
        };
        write!(f, "{s}")
    }
}

impl LogLevel {
    /// Returns the ANSI color code for this log level
    pub fn color_code(&self) -> &'static str {
        match self {
            LogLevel::Trace => "\x1b[90m", // Gray
            LogLevel::Debug => "\x1b[36m", // Cyan
            LogLevel::Info => "\x1b[32m",  // Green
            LogLevel::Warn => "\x1b[33m",  // Yellow
            LogLevel::Error => "\x1b[31m", // Red
        }
    }
}

/// Source of a log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LogSource {
    /// Log from the test harness itself
    Harness,
    /// Stdout from a spawned process
    ProcessStdout { name: String, pid: u32 },
    /// Stderr from a spawned process
    ProcessStderr { name: String, pid: u32 },
    /// Log from the daemon process
    Daemon,
    /// Log from a worker process
    Worker { id: String },
    /// Log from the hook process
    Hook,
    /// Custom source
    Custom(String),
}

impl fmt::Display for LogSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LogSource::Harness => write!(f, "harness"),
            LogSource::ProcessStdout { name, pid } => write!(f, "{name}:{pid}:stdout"),
            LogSource::ProcessStderr { name, pid } => write!(f, "{name}:{pid}:stderr"),
            LogSource::Daemon => write!(f, "daemon"),
            LogSource::Worker { id } => write!(f, "worker:{id}"),
            LogSource::Hook => write!(f, "hook"),
            LogSource::Custom(s) => write!(f, "{s}"),
        }
    }
}

/// A single log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
    /// Timestamp when the log was created
    pub timestamp: DateTime<Utc>,
    /// Elapsed time since test start
    pub elapsed_ms: u64,
    /// Severity level
    pub level: LogLevel,
    /// Source of the log
    pub source: LogSource,
    /// Log message
    pub message: String,
    /// Optional context key-value pairs
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub context: Vec<(String, String)>,
}

impl fmt::Display for LogEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{:>6}ms] [{:<5}] [{}] {}",
            self.elapsed_ms, self.level, self.source, self.message
        )?;
        if !self.context.is_empty() {
            write!(f, " {{")?;
            for (i, (k, v)) in self.context.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{k}={v}")?;
            }
            write!(f, "}}")?;
        }
        Ok(())
    }
}

impl LogEntry {
    /// Format the log entry with ANSI colors
    pub fn format_colored(&self) -> String {
        let reset = "\x1b[0m";
        let color = self.level.color_code();
        let dim = "\x1b[2m";

        let ctx = if self.context.is_empty() {
            String::new()
        } else {
            let pairs: Vec<_> = self
                .context
                .iter()
                .map(|(k, v)| format!("{k}={v}"))
                .collect();
            format!(" {dim}{{{}}}{reset}", pairs.join(", "))
        };

        format!(
            "{dim}[{:>6}ms]{reset} {color}[{:<5}]{reset} {dim}[{}]{reset} {}{ctx}",
            self.elapsed_ms, self.level, self.source, self.message
        )
    }
}

/// Stable schema version for reliability phase events.
pub const RELIABILITY_EVENT_SCHEMA_VERSION: &str = "1.0.0";

/// Reliability test phase used for lifecycle-oriented logging.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReliabilityPhase {
    Setup,
    Execute,
    Verify,
    Cleanup,
}

impl fmt::Display for ReliabilityPhase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let phase = match self {
            Self::Setup => "setup",
            Self::Execute => "execute",
            Self::Verify => "verify",
            Self::Cleanup => "cleanup",
        };
        write!(f, "{phase}")
    }
}

/// Context payload attached to each reliability phase event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReliabilityContext {
    pub worker_id: Option<String>,
    pub repo_set: Vec<String>,
    pub pressure_state: Option<String>,
    pub triage_actions: Vec<String>,
    pub decision_code: String,
    pub fallback_reason: Option<String>,
}

impl ReliabilityContext {
    /// Build a context with required decision code and no optional fields.
    pub fn decision_only(decision_code: impl Into<String>) -> Self {
        Self {
            worker_id: None,
            repo_set: Vec::new(),
            pressure_state: None,
            triage_actions: Vec::new(),
            decision_code: decision_code.into(),
            fallback_reason: None,
        }
    }
}

/// Machine-readable reliability phase event schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReliabilityPhaseEvent {
    pub schema_version: String,
    pub timestamp: DateTime<Utc>,
    pub elapsed_ms: u64,
    pub level: LogLevel,
    pub phase: ReliabilityPhase,
    pub scenario_id: String,
    pub message: String,
    pub context: ReliabilityContext,
    pub artifact_paths: Vec<String>,
}

/// Input contract for emitting reliability phase events.
#[derive(Debug, Clone)]
pub struct ReliabilityEventInput {
    pub level: LogLevel,
    pub phase: ReliabilityPhase,
    pub scenario_id: String,
    pub message: String,
    pub context: ReliabilityContext,
    pub artifact_paths: Vec<String>,
}

impl ReliabilityEventInput {
    /// Convenience constructor for phase+scenario+decision-only events.
    pub fn with_decision(
        phase: ReliabilityPhase,
        scenario_id: impl Into<String>,
        message: impl Into<String>,
        decision_code: impl Into<String>,
    ) -> Self {
        Self {
            level: LogLevel::Info,
            phase,
            scenario_id: scenario_id.into(),
            message: message.into(),
            context: ReliabilityContext::decision_only(decision_code),
            artifact_paths: Vec::new(),
        }
    }
}

/// Configuration for the test logger
#[derive(Debug, Clone)]
pub struct LoggerConfig {
    /// Minimum log level to capture
    pub min_level: LogLevel,
    /// Whether to print logs to stdout in real-time
    pub print_realtime: bool,
    /// Whether to use ANSI colors when printing
    pub use_colors: bool,
    /// Maximum number of entries to keep in memory (0 = unlimited)
    pub max_entries: usize,
    /// Directory for persisting logs
    pub log_dir: Option<PathBuf>,
}

impl Default for LoggerConfig {
    fn default() -> Self {
        Self {
            min_level: LogLevel::Debug,
            print_realtime: true,
            use_colors: true,
            max_entries: 10_000,
            log_dir: None,
        }
    }
}

/// Thread-safe test logger that captures logs during E2E tests
#[derive(Clone)]
pub struct TestLogger {
    config: Arc<RwLock<LoggerConfig>>,
    entries: Arc<Mutex<VecDeque<LogEntry>>>,
    start_time: Instant,
    test_name: Arc<String>,
    file_writer: Arc<Mutex<Option<BufWriter<File>>>>,
    reliability_writer: Arc<Mutex<Option<BufWriter<File>>>>,
    reliability_log_path: Arc<Option<PathBuf>>,
    artifact_root: Arc<Option<PathBuf>>,
}

impl TestLogger {
    /// Create a new test logger with the given configuration
    pub fn new(test_name: &str, config: LoggerConfig) -> Self {
        let mut file_writer = None;
        let mut reliability_writer = None;
        let mut reliability_log_path = None;
        let mut artifact_root = None;

        if let Some(ref dir) = config.log_dir
            && fs::create_dir_all(dir).is_ok()
        {
            let sanitized_test_name = test_name.replace("::", "_").replace(' ', "_");
            let timestamp = Utc::now().format("%Y%m%d_%H%M%S");

            let log_path = dir.join(format!("{sanitized_test_name}_{timestamp}.jsonl"));
            match File::create(&log_path) {
                Ok(file) => file_writer = Some(BufWriter::new(file)),
                Err(error) => {
                    eprintln!(
                        "Warning: Failed to create log file {}: {error}",
                        log_path.display()
                    );
                }
            }

            let reliability_path = dir.join(format!(
                "reliability_{sanitized_test_name}_{timestamp}.jsonl"
            ));
            match File::create(&reliability_path) {
                Ok(file) => {
                    reliability_writer = Some(BufWriter::new(file));
                    reliability_log_path = Some(reliability_path);
                }
                Err(error) => {
                    eprintln!(
                        "Warning: Failed to create reliability log file {}: {error}",
                        reliability_path.display()
                    );
                }
            }

            let artifacts_dir = dir.join("artifacts");
            if fs::create_dir_all(&artifacts_dir).is_ok() {
                artifact_root = Some(artifacts_dir);
            }
        }

        Self {
            config: Arc::new(RwLock::new(config)),
            entries: Arc::new(Mutex::new(VecDeque::new())),
            start_time: Instant::now(),
            test_name: Arc::new(test_name.to_string()),
            file_writer: Arc::new(Mutex::new(file_writer)),
            reliability_writer: Arc::new(Mutex::new(reliability_writer)),
            reliability_log_path: Arc::new(reliability_log_path),
            artifact_root: Arc::new(artifact_root),
        }
    }

    /// Create a logger with default configuration
    pub fn default_for_test(test_name: &str) -> Self {
        Self::new(test_name, LoggerConfig::default())
    }

    /// Get the test name
    pub fn test_name(&self) -> &str {
        &self.test_name
    }

    /// Get elapsed time since logger creation
    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Log an entry with the given level and source
    pub fn log(&self, level: LogLevel, source: LogSource, message: impl Into<String>) {
        self.log_with_context(level, source, message, Vec::new());
    }

    /// Log an entry with context key-value pairs
    pub fn log_with_context(
        &self,
        level: LogLevel,
        source: LogSource,
        message: impl Into<String>,
        context: Vec<(String, String)>,
    ) {
        let config = self.config.read().unwrap();
        if level < config.min_level {
            return;
        }

        let entry = LogEntry {
            timestamp: Utc::now(),
            elapsed_ms: self.start_time.elapsed().as_millis() as u64,
            level,
            source,
            message: message.into(),
            context,
        };

        // Print to stdout if configured
        if config.print_realtime {
            if config.use_colors {
                println!("{}", entry.format_colored());
            } else {
                println!("{entry}");
            }
        }

        // Write JSONL to file if configured
        if let Ok(mut writer) = self.file_writer.lock()
            && let Some(ref mut w) = *writer
            && let Ok(json) = serde_json::to_string(&entry)
        {
            let _ = writeln!(w, "{json}");
            let _ = w.flush();
        }

        // Store in memory
        let mut entries = self.entries.lock().unwrap();
        entries.push_back(entry);
        if config.max_entries > 0 && entries.len() > config.max_entries {
            entries.pop_front();
        }
    }

    /// Returns the reliability JSONL path if reliability logging is enabled.
    pub fn reliability_log_path(&self) -> Option<&Path> {
        self.reliability_log_path.as_deref()
    }

    /// Emit a structured reliability event using the stable schema contract.
    pub fn log_reliability_event(&self, input: ReliabilityEventInput) -> ReliabilityPhaseEvent {
        let event = ReliabilityPhaseEvent {
            schema_version: RELIABILITY_EVENT_SCHEMA_VERSION.to_string(),
            timestamp: Utc::now(),
            elapsed_ms: self.start_time.elapsed().as_millis() as u64,
            level: input.level,
            phase: input.phase,
            scenario_id: input.scenario_id,
            message: input.message,
            context: input.context,
            artifact_paths: input.artifact_paths,
        };

        let mut log_context = vec![
            ("schema_version".to_string(), event.schema_version.clone()),
            ("phase".to_string(), event.phase.to_string()),
            ("scenario_id".to_string(), event.scenario_id.clone()),
            (
                "decision_code".to_string(),
                event.context.decision_code.clone(),
            ),
        ];
        if let Some(worker_id) = event.context.worker_id.as_ref() {
            log_context.push(("worker_id".to_string(), worker_id.clone()));
        }
        if !event.context.repo_set.is_empty() {
            log_context.push(("repo_set".to_string(), event.context.repo_set.join(",")));
        }
        if let Some(pressure_state) = event.context.pressure_state.as_ref() {
            log_context.push(("pressure_state".to_string(), pressure_state.clone()));
        }
        if !event.context.triage_actions.is_empty() {
            log_context.push((
                "triage_actions".to_string(),
                event.context.triage_actions.join(","),
            ));
        }
        if let Some(fallback_reason) = event.context.fallback_reason.as_ref() {
            log_context.push(("fallback_reason".to_string(), fallback_reason.clone()));
        }
        if !event.artifact_paths.is_empty() {
            log_context.push(("artifact_paths".to_string(), event.artifact_paths.join(",")));
        }

        self.log_with_context(
            event.level,
            LogSource::Harness,
            format!("[{}] {}", event.phase, event.message),
            log_context,
        );

        if let Ok(mut writer_guard) = self.reliability_writer.lock()
            && let Some(ref mut writer) = *writer_guard
            && let Ok(serialized) = serde_json::to_string(&event)
        {
            let _ = writeln!(writer, "{serialized}");
            let _ = writer.flush();
        }

        event
    }

    /// Persist a text artifact for replay/postmortem analysis.
    pub fn capture_artifact_text(
        &self,
        scenario_id: &str,
        artifact_name: &str,
        content: &str,
    ) -> std::io::Result<PathBuf> {
        let Some(artifact_root) = self.artifact_root.as_deref() else {
            return Err(std::io::Error::other(
                "artifact capture requires logger log_dir to be configured",
            ));
        };

        let scenario_dir = artifact_root.join(Self::sanitize_artifact_component(scenario_id));
        fs::create_dir_all(&scenario_dir)?;
        let artifact_path = scenario_dir.join(format!(
            "{}.txt",
            Self::sanitize_artifact_component(artifact_name)
        ));
        fs::write(&artifact_path, content)?;
        Ok(artifact_path)
    }

    /// Persist a JSON artifact for replay/postmortem analysis.
    pub fn capture_artifact_json<T: Serialize>(
        &self,
        scenario_id: &str,
        artifact_name: &str,
        value: &T,
    ) -> std::io::Result<PathBuf> {
        let serialized = serde_json::to_string_pretty(value).map_err(|error| {
            std::io::Error::other(format!("failed to serialize artifact json: {error}"))
        })?;
        let Some(artifact_root) = self.artifact_root.as_deref() else {
            return Err(std::io::Error::other(
                "artifact capture requires logger log_dir to be configured",
            ));
        };

        let scenario_dir = artifact_root.join(Self::sanitize_artifact_component(scenario_id));
        fs::create_dir_all(&scenario_dir)?;
        let artifact_path = scenario_dir.join(format!(
            "{}.json",
            Self::sanitize_artifact_component(artifact_name)
        ));
        fs::write(&artifact_path, serialized)?;
        Ok(artifact_path)
    }

    fn sanitize_artifact_component(raw: &str) -> String {
        let mut cleaned = String::with_capacity(raw.len());
        for ch in raw.chars() {
            if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.' {
                cleaned.push(ch);
            } else {
                cleaned.push('_');
            }
        }
        if cleaned.is_empty() {
            "artifact".to_string()
        } else {
            cleaned
        }
    }

    /// Log a trace message from the harness
    pub fn trace(&self, message: impl Into<String>) {
        self.log(LogLevel::Trace, LogSource::Harness, message);
    }

    /// Log a debug message from the harness
    pub fn debug(&self, message: impl Into<String>) {
        self.log(LogLevel::Debug, LogSource::Harness, message);
    }

    /// Log an info message from the harness
    pub fn info(&self, message: impl Into<String>) {
        self.log(LogLevel::Info, LogSource::Harness, message);
    }

    /// Log a warning message from the harness
    pub fn warn(&self, message: impl Into<String>) {
        self.log(LogLevel::Warn, LogSource::Harness, message);
    }

    /// Log an error message from the harness
    pub fn error(&self, message: impl Into<String>) {
        self.log(LogLevel::Error, LogSource::Harness, message);
    }

    /// Log process stdout
    pub fn log_stdout(&self, process_name: &str, pid: u32, message: impl Into<String>) {
        self.log(
            LogLevel::Debug,
            LogSource::ProcessStdout {
                name: process_name.to_string(),
                pid,
            },
            message,
        );
    }

    /// Log process stderr
    pub fn log_stderr(&self, process_name: &str, pid: u32, message: impl Into<String>) {
        self.log(
            LogLevel::Warn,
            LogSource::ProcessStderr {
                name: process_name.to_string(),
                pid,
            },
            message,
        );
    }

    /// Log a daemon message
    pub fn log_daemon(&self, level: LogLevel, message: impl Into<String>) {
        self.log(level, LogSource::Daemon, message);
    }

    /// Log a worker message
    pub fn log_worker(&self, worker_id: &str, level: LogLevel, message: impl Into<String>) {
        self.log(
            level,
            LogSource::Worker {
                id: worker_id.to_string(),
            },
            message,
        );
    }

    /// Log a hook message
    pub fn log_hook(&self, level: LogLevel, message: impl Into<String>) {
        self.log(level, LogSource::Hook, message);
    }

    /// Get all log entries
    pub fn entries(&self) -> Vec<LogEntry> {
        self.entries.lock().unwrap().iter().cloned().collect()
    }

    /// Get entries filtered by level
    pub fn entries_by_level(&self, min_level: LogLevel) -> Vec<LogEntry> {
        self.entries
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.level >= min_level)
            .cloned()
            .collect()
    }

    /// Get entries filtered by source
    pub fn entries_by_source(&self, source_prefix: &str) -> Vec<LogEntry> {
        let prefix = source_prefix.to_lowercase();
        self.entries
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.source.to_string().to_lowercase().starts_with(&prefix))
            .cloned()
            .collect()
    }

    /// Search entries by message content
    pub fn search(&self, pattern: &str) -> Vec<LogEntry> {
        let pattern_lower = pattern.to_lowercase();
        self.entries
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.message.to_lowercase().contains(&pattern_lower))
            .cloned()
            .collect()
    }

    /// Check if any errors were logged
    pub fn has_errors(&self) -> bool {
        self.entries
            .lock()
            .unwrap()
            .iter()
            .any(|e| e.level == LogLevel::Error)
    }

    /// Get error count
    pub fn error_count(&self) -> usize {
        self.entries
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.level == LogLevel::Error)
            .count()
    }

    /// Get warning count
    pub fn warn_count(&self) -> usize {
        self.entries
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.level == LogLevel::Warn)
            .count()
    }

    /// Clear all entries
    pub fn clear(&self) {
        self.entries.lock().unwrap().clear();
    }

    /// Export logs to JSON
    pub fn export_json(&self) -> String {
        let entries = self.entries();
        serde_json::to_string_pretty(&entries).unwrap_or_else(|_| "[]".to_string())
    }

    /// Export logs to a JSON file
    pub fn export_json_to_file(&self, path: &Path) -> std::io::Result<()> {
        let json = self.export_json();
        fs::write(path, json)
    }

    /// Generate a test summary
    pub fn summary(&self) -> TestLogSummary {
        let entries = self.entries.lock().unwrap();
        let mut summary = TestLogSummary {
            test_name: self.test_name.to_string(),
            total_entries: entries.len(),
            duration_ms: self.elapsed().as_millis() as u64,
            counts_by_level: [
                (LogLevel::Trace, 0),
                (LogLevel::Debug, 0),
                (LogLevel::Info, 0),
                (LogLevel::Warn, 0),
                (LogLevel::Error, 0),
            ]
            .into_iter()
            .collect(),
            first_error: None,
            last_error: None,
        };

        for entry in entries.iter() {
            *summary.counts_by_level.entry(entry.level).or_insert(0) += 1;
            if entry.level == LogLevel::Error {
                if summary.first_error.is_none() {
                    summary.first_error = Some(entry.message.clone());
                }
                summary.last_error = Some(entry.message.clone());
            }
        }

        summary
    }

    /// Print a formatted summary to stdout
    pub fn print_summary(&self) {
        let summary = self.summary();
        println!("\n{}", "=".repeat(60));
        println!("Test Log Summary: {}", summary.test_name);
        println!("{}", "=".repeat(60));
        println!("Duration: {}ms", summary.duration_ms);
        println!("Total entries: {}", summary.total_entries);
        println!(
            "  TRACE: {}",
            summary.counts_by_level.get(&LogLevel::Trace).unwrap_or(&0)
        );
        println!(
            "  DEBUG: {}",
            summary.counts_by_level.get(&LogLevel::Debug).unwrap_or(&0)
        );
        println!(
            "  INFO:  {}",
            summary.counts_by_level.get(&LogLevel::Info).unwrap_or(&0)
        );
        println!(
            "  WARN:  {}",
            summary.counts_by_level.get(&LogLevel::Warn).unwrap_or(&0)
        );
        println!(
            "  ERROR: {}",
            summary.counts_by_level.get(&LogLevel::Error).unwrap_or(&0)
        );
        if let Some(ref err) = summary.first_error {
            println!("First error: {err}");
        }
        if let Some(ref err) = summary.last_error
            && summary.first_error.as_ref() != Some(err)
        {
            println!("Last error: {err}");
        }
        println!("{}", "=".repeat(60));
    }
}

/// Summary of test logs
#[derive(Debug, Clone, Serialize)]
pub struct TestLogSummary {
    pub test_name: String,
    pub total_entries: usize,
    pub duration_ms: u64,
    pub counts_by_level: std::collections::HashMap<LogLevel, usize>,
    pub first_error: Option<String>,
    pub last_error: Option<String>,
}

/// Builder for creating a TestLogger with custom configuration
pub struct TestLoggerBuilder {
    test_name: String,
    config: LoggerConfig,
}

impl TestLoggerBuilder {
    /// Create a new builder for the given test name.
    ///
    /// By default, logs are written to `target/test-logs/` relative to the
    /// workspace root (auto-detected via CARGO_MANIFEST_DIR) as JSONL (one
    /// JSON object per line).
    pub fn new(test_name: &str) -> Self {
        // Auto-set log directory for standardized JSONL output
        let config = LoggerConfig {
            log_dir: Self::auto_detect_log_dir(),
            ..Default::default()
        };
        Self {
            test_name: test_name.to_string(),
            config,
        }
    }

    /// Auto-detect the log directory based on cargo workspace.
    /// Returns `target/test-logs/` relative to workspace root.
    fn auto_detect_log_dir() -> Option<PathBuf> {
        // Try CARGO_MANIFEST_DIR first (set during cargo test)
        if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
            let manifest_path = PathBuf::from(&manifest_dir);
            // Walk up to find workspace root (has target/ directory)
            let workspace_root = find_workspace_root(&manifest_path)?;
            let log_dir = workspace_root.join("target").join("test-logs");
            // Create directory if it doesn't exist
            let _ = fs::create_dir_all(&log_dir);
            return Some(log_dir);
        }
        // Fallback: try current directory
        if let Ok(cwd) = std::env::current_dir() {
            let log_dir = cwd.join("target").join("test-logs");
            if log_dir.parent().map(|p| p.exists()).unwrap_or(false) {
                let _ = fs::create_dir_all(&log_dir);
                return Some(log_dir);
            }
        }
        None
    }

    /// Set the minimum log level
    pub fn min_level(mut self, level: LogLevel) -> Self {
        self.config.min_level = level;
        self
    }

    /// Enable or disable real-time printing
    pub fn print_realtime(mut self, enabled: bool) -> Self {
        self.config.print_realtime = enabled;
        self
    }

    /// Enable or disable ANSI colors
    pub fn use_colors(mut self, enabled: bool) -> Self {
        self.config.use_colors = enabled;
        self
    }

    /// Set the maximum number of entries to keep in memory
    pub fn max_entries(mut self, max: usize) -> Self {
        self.config.max_entries = max;
        self
    }

    /// Set the log directory for file persistence
    pub fn log_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.config.log_dir = Some(dir.into());
        self
    }

    /// Build the TestLogger
    pub fn build(self) -> TestLogger {
        TestLogger::new(&self.test_name, self.config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_log_levels_order() {
        assert!(LogLevel::Trace < LogLevel::Debug);
        assert!(LogLevel::Debug < LogLevel::Info);
        assert!(LogLevel::Info < LogLevel::Warn);
        assert!(LogLevel::Warn < LogLevel::Error);
    }

    #[test]
    fn test_logger_basic() {
        let logger = TestLoggerBuilder::new("test_basic")
            .print_realtime(false)
            .build();

        logger.info("Test message");
        logger.warn("Warning message");
        logger.error("Error message");

        assert_eq!(logger.entries().len(), 3);
        assert!(logger.has_errors());
        assert_eq!(logger.error_count(), 1);
        assert_eq!(logger.warn_count(), 1);
    }

    #[test]
    fn test_logger_filtering() {
        let logger = TestLoggerBuilder::new("test_filtering")
            .print_realtime(false)
            .min_level(LogLevel::Info)
            .build();

        logger.trace("Trace message");
        logger.debug("Debug message");
        logger.info("Info message");

        // Only info should be captured (trace and debug filtered out)
        assert_eq!(logger.entries().len(), 1);
    }

    #[test]
    fn test_logger_search() {
        let logger = TestLoggerBuilder::new("test_search")
            .print_realtime(false)
            .build();

        logger.info("Starting daemon");
        logger.info("Daemon ready");
        logger.info("Worker connected");

        let daemon_logs = logger.search("daemon");
        assert_eq!(daemon_logs.len(), 2);
    }

    #[test]
    fn test_logger_context() {
        let logger = TestLoggerBuilder::new("test_context")
            .print_realtime(false)
            .build();

        logger.log_with_context(
            LogLevel::Info,
            LogSource::Harness,
            "Worker selected",
            vec![
                ("worker_id".to_string(), "css".to_string()),
                ("slots".to_string(), "4".to_string()),
            ],
        );

        let entries = logger.entries();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].context.len(), 2);
    }

    #[test]
    fn test_logger_max_entries() {
        let logger = TestLoggerBuilder::new("test_max_entries")
            .print_realtime(false)
            .max_entries(5)
            .build();

        for i in 0..10 {
            logger.info(format!("Message {i}"));
        }

        let entries = logger.entries();
        assert_eq!(entries.len(), 5);
        // Should keep the most recent entries
        assert!(entries[0].message.contains("5"));
        assert!(entries[4].message.contains("9"));
    }

    #[test]
    fn test_logger_summary() {
        let logger = TestLoggerBuilder::new("test_summary")
            .print_realtime(false)
            .build();

        logger.debug("Debug 1");
        logger.debug("Debug 2");
        logger.info("Info 1");
        logger.warn("Warn 1");
        logger.error("First error");
        logger.error("Last error");

        let summary = logger.summary();
        assert_eq!(summary.test_name, "test_summary");
        assert_eq!(summary.total_entries, 6);
        assert_eq!(summary.counts_by_level.get(&LogLevel::Debug), Some(&2));
        assert_eq!(summary.counts_by_level.get(&LogLevel::Error), Some(&2));
        assert_eq!(summary.first_error, Some("First error".to_string()));
        assert_eq!(summary.last_error, Some("Last error".to_string()));
    }

    #[test]
    fn test_log_entry_display() {
        let entry = LogEntry {
            timestamp: Utc::now(),
            elapsed_ms: 123,
            level: LogLevel::Info,
            source: LogSource::Harness,
            message: "Test message".to_string(),
            context: vec![("key".to_string(), "value".to_string())],
        };

        let s = entry.to_string();
        assert!(s.contains("123ms"));
        assert!(s.contains("INFO"));
        assert!(s.contains("harness"));
        assert!(s.contains("Test message"));
        assert!(s.contains("key=value"));
    }

    #[test]
    fn test_auto_detect_log_dir() {
        // Verify auto-detection finds a log directory
        let log_dir = TestLoggerBuilder::auto_detect_log_dir();
        eprintln!("Auto-detected log_dir: {:?}", log_dir);

        // Should find something when running in cargo test context
        if std::env::var("CARGO_MANIFEST_DIR").is_ok() {
            assert!(
                log_dir.is_some(),
                "Should auto-detect log_dir with CARGO_MANIFEST_DIR set"
            );
            let dir = log_dir.unwrap();
            eprintln!("Log directory: {}", dir.display());
            assert!(dir.ends_with("test-logs"), "Should end with test-logs");
        }
    }

    #[test]
    fn test_logger_writes_to_file() {
        // Create logger with explicit temp directory
        let temp_dir = tempfile::tempdir().expect("temp dir should be creatable");
        let temp_dir_path = temp_dir.path();

        let logger = TestLoggerBuilder::new("test_file_write")
            .log_dir(temp_dir_path)
            .print_realtime(false)
            .build();

        logger.info("Test file write message");
        logger.warn("Another message");

        // Drop logger to flush file
        drop(logger);

        // Check for log file
        let entries: Vec<_> = fs::read_dir(temp_dir_path)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.file_name()
                    .to_string_lossy()
                    .starts_with("test_file_write")
            })
            .collect();

        assert!(
            !entries.is_empty(),
            "Should have created a log file in {:?}",
            temp_dir_path
        );

        // Read and verify contents
        let log_path = &entries[0].path();
        let contents = fs::read_to_string(log_path).expect("Should read log file");
        assert!(
            contents.contains("Test file write message"),
            "Log should contain message"
        );
    }

    #[test]
    fn test_reliability_event_schema_contract() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be creatable");
        let logger = TestLoggerBuilder::new("test_reliability_schema")
            .log_dir(temp_dir.path())
            .print_realtime(false)
            .build();

        let event = logger.log_reliability_event(ReliabilityEventInput {
            level: LogLevel::Info,
            phase: ReliabilityPhase::Execute,
            scenario_id: "scenario-path-deps".to_string(),
            message: "remote execution complete".to_string(),
            context: ReliabilityContext {
                worker_id: Some("worker-a".to_string()),
                repo_set: vec!["/data/projects/repo-a".to_string()],
                pressure_state: Some("disk:normal,memory:normal".to_string()),
                triage_actions: vec!["none".to_string()],
                decision_code: "REMOTE_OK".to_string(),
                fallback_reason: None,
            },
            artifact_paths: vec!["/tmp/a.json".to_string()],
        });

        assert_eq!(event.schema_version, RELIABILITY_EVENT_SCHEMA_VERSION);
        assert_eq!(event.phase, ReliabilityPhase::Execute);
        assert_eq!(event.scenario_id, "scenario-path-deps");
        assert_eq!(event.context.decision_code, "REMOTE_OK");

        let reliability_path = logger
            .reliability_log_path()
            .expect("reliability log path should exist")
            .to_path_buf();
        let reliability_contents =
            fs::read_to_string(&reliability_path).expect("should read reliability log");
        let first_line = reliability_contents
            .lines()
            .next()
            .expect("reliability log should contain one event");
        let parsed: ReliabilityPhaseEvent =
            serde_json::from_str(first_line).expect("reliability event should parse");
        assert_eq!(parsed.schema_version, RELIABILITY_EVENT_SCHEMA_VERSION);
        assert_eq!(parsed.phase, ReliabilityPhase::Execute);
        assert_eq!(parsed.context.worker_id, Some("worker-a".to_string()));
        assert_eq!(parsed.context.repo_set, vec!["/data/projects/repo-a"]);
    }

    #[test]
    fn test_reliability_event_parser_compatibility() {
        let json = r#"{
            "schema_version":"1.0.0",
            "timestamp":"2026-02-16T00:00:00Z",
            "elapsed_ms":42,
            "level":"info",
            "phase":"verify",
            "scenario_id":"scenario-x",
            "message":"verify finished",
            "context":{
                "worker_id":"worker-1",
                "repo_set":["/data/projects/repo-x","/dp/repo-y"],
                "pressure_state":"disk:high",
                "triage_actions":["trim-cache","kill-stuck-procs"],
                "decision_code":"VERIFY_OK",
                "fallback_reason":null
            },
            "artifact_paths":["/tmp/trace.json"]
        }"#;

        let event: ReliabilityPhaseEvent =
            serde_json::from_str(json).expect("contract payload should deserialize");
        assert_eq!(event.schema_version, "1.0.0");
        assert_eq!(event.phase, ReliabilityPhase::Verify);
        assert_eq!(event.context.decision_code, "VERIFY_OK");
        assert_eq!(event.context.triage_actions.len(), 2);
    }

    #[test]
    fn test_reliability_artifact_capture_text_and_json() {
        let temp_dir = tempfile::tempdir().expect("temp dir should be creatable");
        let logger = TestLoggerBuilder::new("test_reliability_artifacts")
            .log_dir(temp_dir.path())
            .print_realtime(false)
            .build();

        let text_path = logger
            .capture_artifact_text("scenario-alpha", "stdout_capture", "hello world")
            .expect("text artifact capture should succeed");
        assert!(text_path.exists());
        let text_contents = fs::read_to_string(&text_path).expect("read text artifact");
        assert_eq!(text_contents, "hello world");

        let json_path = logger
            .capture_artifact_json(
                "scenario-alpha",
                "command_trace",
                &serde_json::json!({ "cmd": "cargo test", "exit_code": 0 }),
            )
            .expect("json artifact capture should succeed");
        assert!(json_path.exists());
        let json_contents = fs::read_to_string(&json_path).expect("read json artifact");
        assert!(json_contents.contains("\"cmd\""));
        assert!(json_contents.contains("\"cargo test\""));
    }
}