Skip to main content

cmtraceopen_parser/parser/
ccm.rs

1//! CCM/SCCM format parser.
2//!
3//! Parses log lines in the format:
4//!   <![LOG[message text]LOG]!><time="HH:mm:ss.fff+TZO" date="MM-dd-yyyy"
5//!     component="Name" context="" type="N" thread="N" file="source.cpp">
6//!
7//! The regex patterns are derived directly from the scanf format strings
8//! extracted from the CMTrace.exe binary (see REVERSE_ENGINEERING.md).
9
10use chrono::{FixedOffset, TimeZone};
11use regex::Regex;
12
13use super::severity::detect_severity_from_text;
14use crate::models::log_entry::{LogEntry, LogFormat, ParserSpecialization, Severity};
15use std::sync::OnceLock;
16
17/// Compiled regex matching a complete CCM log line.
18///
19/// Based on the binary's scanf pattern:
20///   <time="%02u:%02u:%02u.%03u%d" date="%02u-%02u-%04u"
21///    component="%100[^"]" context="" type="%u" thread="%u" file="%100[^"]"
22fn ccm_re() -> &'static Regex {
23    static CELL: OnceLock<Regex> = OnceLock::new();
24    CELL.get_or_init(|| {
25        Regex::new(concat!(
26            r#"<!\[LOG\[(?P<msg>[\s\S]*?)\]LOG\]!>"#,
27            r#"<time="(?P<h>\d{1,2}):(?P<m>\d{1,2}):(?P<s>\d{1,2})\.(?P<ms>\d+)(?P<tz>[+-]*\d+)""#,
28            r#"\s+date="(?P<mon>\d{1,2})-(?P<day>\d{1,2})-(?P<yr>\d{4})""#,
29            r#"\s+component="(?P<comp>[^"]*)""#,
30            r#"\s+context="[^"]*""#,
31            r#"\s+type="(?P<typ>\d)?""#,
32            r#"\s+thread="(?P<thr>\d+)?""#,
33            r#"(?:\s+file="(?P<file>[^"]*)")?>"#,
34        ))
35        .expect("CCM regex must compile")
36    })
37}
38
39/// Parse a single CCM-format log line.
40/// Returns None if the line doesn't match the CCM format.
41fn parse_line(line: &str) -> Option<CcmParsed> {
42    let caps = ccm_re().captures(line)?;
43    parse_captures(&caps)
44}
45
46struct CcmParsed {
47    message: String,
48    component: Option<String>,
49    timestamp: Option<i64>,
50    timestamp_display: Option<String>,
51    severity: Severity,
52    thread: u32,
53    thread_display: Option<String>,
54    source_file: Option<String>,
55    timezone_offset: i32,
56}
57
58pub(crate) fn truncate_subsecond_to_millis(value: &str) -> Option<u32> {
59    if value.len() > 3 {
60        value[..3].parse().ok()
61    } else {
62        value.parse().ok()
63    }
64}
65
66/// Convert a naive local datetime + optional timezone offset (in minutes) to UTC epoch millis.
67/// Falls back to treating naive as UTC if the offset is invalid or overflows.
68pub(crate) fn naive_to_utc_millis(
69    naive: chrono::NaiveDateTime,
70    offset_minutes: Option<i32>,
71) -> i64 {
72    if let Some(offset_minutes) = offset_minutes {
73        offset_minutes
74            .checked_mul(60)
75            .and_then(FixedOffset::east_opt)
76            .and_then(|offset| offset.from_local_datetime(&naive).single())
77            .map(|dt| dt.timestamp_millis())
78            .unwrap_or_else(|| naive.and_utc().timestamp_millis())
79    } else {
80        naive.and_utc().timestamp_millis()
81    }
82}
83
84#[allow(clippy::too_many_arguments)]
85pub(crate) fn build_timestamp(
86    month: u32,
87    day: u32,
88    year: i32,
89    hour: u32,
90    minute: u32,
91    second: u32,
92    millis: u32,
93    timezone_offset: Option<i32>,
94) -> (Option<i64>, Option<String>) {
95    let timestamp = chrono::NaiveDate::from_ymd_opt(year, month, day)
96        .and_then(|date| date.and_hms_milli_opt(hour, minute, second, millis))
97        .map(|naive| naive_to_utc_millis(naive, timezone_offset));
98
99    let timestamp_display = Some(format!(
100        "{:02}-{:02}-{:04} {:02}:{:02}:{:02}.{:03}",
101        month, day, year, hour, minute, second, millis
102    ));
103
104    (timestamp, timestamp_display)
105}
106
107pub(crate) fn severity_from_type_field(type_value: Option<u32>, message: &str) -> Severity {
108    match type_value {
109        Some(0) => Severity::Success, // CCM/PSADT type="0" — successful operation (OneTrace green tick)
110        Some(2) => Severity::Warning,
111        Some(3) => Severity::Error,
112        Some(_) => Severity::Info, // includes type="1" and any unknown numeric type
113        None => detect_severity_from_text(message), // type absent/empty — infer from message text
114    }
115}
116
117/// Cache for thread display strings. Thread IDs repeat heavily in log files
118/// (typically 5-20 unique threads across thousands of entries), so caching
119/// avoids a `format!()` allocation per line.
120pub(crate) fn format_thread_display(thread: u32) -> String {
121    use std::cell::RefCell;
122    use std::collections::HashMap;
123
124    thread_local! {
125        static CACHE: RefCell<HashMap<u32, String>> = RefCell::new(HashMap::new());
126    }
127
128    CACHE.with(|cache| {
129        let mut map = cache.borrow_mut();
130        map.entry(thread)
131            .or_insert_with(|| format!("{} (0x{:04X})", thread, thread))
132            .clone()
133    })
134}
135
136pub fn parse_content(
137    content: &str,
138    file_path: &str,
139    specialization: Option<ParserSpecialization>,
140) -> (Vec<LogEntry>, u32) {
141    match specialization {
142        Some(ParserSpecialization::Ime) => {
143            crate::intune::ime_parser::parse_ime_entries(content, file_path)
144        }
145        None => parse_content_multiline(content, file_path),
146    }
147}
148
149/// Content-based multi-line CCM parser.
150///
151/// Runs the CCM regex over the entire file content so that records spanning
152/// multiple physical lines (e.g. `<![LOG[line1\nline2]LOG]!><attrs>`) are
153/// matched as a single logical record.  Text between matched records is
154/// emitted as individual plain-text entries, preserving line numbers.
155fn parse_content_multiline(content: &str, file_path: &str) -> (Vec<LogEntry>, u32) {
156    let line_starts = build_line_starts(content);
157    let mut entries: Vec<LogEntry> = Vec::new();
158    let mut errors = 0u32;
159    let mut id_counter = 0u64;
160    let mut cursor = 0usize;
161    let mut matched_any = false;
162
163    for caps in ccm_re().captures_iter(content) {
164        let Some(full_match) = caps.get(0) else {
165            continue;
166        };
167
168        // Emit unmatched text between the previous match and this one
169        push_unmatched_plain(
170            &content[cursor..full_match.start()],
171            cursor,
172            &line_starts,
173            file_path,
174            &mut entries,
175            &mut id_counter,
176            &mut errors,
177        );
178
179        // Parse the matched CCM record
180        let line_number = line_number_for_offset(&line_starts, full_match.start());
181        if let Some(parsed) = parse_captures(&caps) {
182            entries.push(LogEntry {
183                id: id_counter,
184                line_number,
185                message: parsed.message,
186                component: parsed.component,
187                timestamp: parsed.timestamp,
188                timestamp_display: parsed.timestamp_display,
189                severity: parsed.severity,
190                thread: Some(parsed.thread),
191                thread_display: parsed.thread_display,
192                source_file: parsed.source_file,
193                format: LogFormat::Ccm,
194                file_path: file_path.to_string(),
195                timezone_offset: Some(parsed.timezone_offset),
196                error_code_spans: Vec::new(),
197                ip_address: None,
198                host_name: None,
199                mac_address: None,
200                result_code: None,
201                gle_code: None,
202                setup_phase: None,
203                operation_name: None,
204                http_method: None,
205                uri_stem: None,
206                uri_query: None,
207                status_code: None,
208                sub_status: None,
209                time_taken_ms: None,
210                client_ip: None,
211                server_ip: None,
212                user_agent: None,
213                server_port: None,
214                username: None,
215                win32_status: None,
216                query_name: None,
217                query_type: None,
218                response_code: None,
219                dns_direction: None,
220                dns_protocol: None,
221                source_ip: None,
222                dns_flags: None,
223                dns_event_id: None,
224                zone_name: None,
225                entry_kind: None,
226                whatif: None,
227                section_name: None,
228                section_color: None,
229                iteration: None,
230                tags: None,
231            });
232            id_counter += 1;
233        } else {
234            push_unmatched_plain(
235                full_match.as_str(),
236                full_match.start(),
237                &line_starts,
238                file_path,
239                &mut entries,
240                &mut id_counter,
241                &mut errors,
242            );
243        }
244
245        cursor = full_match.end();
246        matched_any = true;
247    }
248
249    // Trailing unmatched text
250    push_unmatched_plain(
251        &content[cursor..],
252        cursor,
253        &line_starts,
254        file_path,
255        &mut entries,
256        &mut id_counter,
257        &mut errors,
258    );
259
260    if !matched_any {
261        // No CCM records found at all — fall back to line-by-line
262        let lines: Vec<&str> = content.lines().collect();
263        return parse_lines(&lines, file_path);
264    }
265
266    (entries, errors)
267}
268
269/// Parse named captures from a CCM regex match into a CcmParsed struct.
270fn parse_captures(caps: &regex::Captures<'_>) -> Option<CcmParsed> {
271    let msg = caps.name("msg").map(|m| m.as_str().to_string())?;
272    let h: u32 = caps.name("h")?.as_str().parse().ok()?;
273    let m: u32 = caps.name("m")?.as_str().parse().ok()?;
274    let s: u32 = caps.name("s")?.as_str().parse().ok()?;
275    let ms_str = caps.name("ms")?.as_str();
276    let ms = truncate_subsecond_to_millis(ms_str)?;
277    let tz: i32 = caps.name("tz")?.as_str().parse().ok()?;
278    let mon: u32 = caps.name("mon")?.as_str().parse().ok()?;
279    let day: u32 = caps.name("day")?.as_str().parse().ok()?;
280    let yr: i32 = caps.name("yr")?.as_str().parse().ok()?;
281    let comp = caps.name("comp").map(|m| m.as_str().to_string());
282    // Preserve absent/empty/unparseable type as `None` so it falls back to
283    // text-based detection. Coercing to `Some(0)` would misclassify neutral
284    // lines as Success now that type="0" maps to Severity::Success.
285    let typ: Option<u32> = caps.name("typ").and_then(|m| m.as_str().parse().ok());
286    let thr: u32 = caps
287        .name("thr")
288        .and_then(|m| m.as_str().parse().ok())
289        .unwrap_or(0);
290    let file = caps.name("file").map(|m| m.as_str().to_string());
291
292    let severity = severity_from_type_field(typ, &msg);
293    let (timestamp, timestamp_display) = build_timestamp(mon, day, yr, h, m, s, ms, Some(tz));
294    let thread_display = Some(format_thread_display(thr));
295
296    Some(CcmParsed {
297        message: msg,
298        component: comp,
299        timestamp,
300        timestamp_display,
301        severity,
302        thread: thr,
303        thread_display,
304        source_file: file,
305        timezone_offset: tz,
306    })
307}
308
309fn build_line_starts(content: &str) -> Vec<usize> {
310    let mut starts = vec![0];
311    for (index, byte) in content.bytes().enumerate() {
312        if byte == b'\n' {
313            starts.push(index + 1);
314        }
315    }
316    starts
317}
318
319fn line_number_for_offset(line_starts: &[usize], offset: usize) -> u32 {
320    match line_starts.binary_search(&offset) {
321        Ok(index) => (index + 1) as u32,
322        Err(index) => index as u32,
323    }
324}
325
326/// Emit each non-empty physical line in `segment` as a plain-text LogEntry.
327fn push_unmatched_plain(
328    segment: &str,
329    base_offset: usize,
330    line_starts: &[usize],
331    file_path: &str,
332    entries: &mut Vec<LogEntry>,
333    id_counter: &mut u64,
334    errors: &mut u32,
335) {
336    let mut local_offset = 0usize;
337    for piece in segment.split_inclusive('\n') {
338        let line = piece.trim_end_matches(['\r', '\n']);
339        let trimmed = line.trim();
340        if !trimmed.is_empty() {
341            entries.push(LogEntry {
342                id: *id_counter,
343                line_number: line_number_for_offset(line_starts, base_offset + local_offset),
344                message: trimmed.to_string(),
345                component: None,
346                timestamp: None,
347                timestamp_display: None,
348                severity: detect_severity_from_text(trimmed),
349                thread: None,
350                thread_display: None,
351                source_file: None,
352                format: LogFormat::Plain,
353                file_path: file_path.to_string(),
354                timezone_offset: None,
355                error_code_spans: Vec::new(),
356                ip_address: None,
357                host_name: None,
358                mac_address: None,
359                result_code: None,
360                gle_code: None,
361                setup_phase: None,
362                operation_name: None,
363                http_method: None,
364                uri_stem: None,
365                uri_query: None,
366                status_code: None,
367                sub_status: None,
368                time_taken_ms: None,
369                client_ip: None,
370                server_ip: None,
371                user_agent: None,
372                server_port: None,
373                username: None,
374                win32_status: None,
375                query_name: None,
376                query_type: None,
377                response_code: None,
378                dns_direction: None,
379                dns_protocol: None,
380                source_ip: None,
381                dns_flags: None,
382                dns_event_id: None,
383                zone_name: None,
384                entry_kind: None,
385                whatif: None,
386                section_name: None,
387                section_color: None,
388                iteration: None,
389                tags: None,
390            });
391            *id_counter += 1;
392            *errors += 1;
393        }
394        local_offset += piece.len();
395    }
396}
397
398pub fn parse_lines_with_specialization(
399    lines: &[&str],
400    file_path: &str,
401    specialization: Option<ParserSpecialization>,
402) -> (Vec<LogEntry>, u32) {
403    // Always join lines and use content-based parsing for multi-line support
404    parse_content(&lines.join("\n"), file_path, specialization)
405}
406
407/// Parse all lines as CCM format.
408/// Returns (entries, parse_error_count).
409pub fn parse_lines(lines: &[&str], file_path: &str) -> (Vec<LogEntry>, u32) {
410    let mut entries = Vec::with_capacity(lines.len());
411    let mut errors = 0u32;
412    let mut id_counter = 0u64;
413
414    for (i, line) in lines.iter().enumerate() {
415        if line.trim().is_empty() {
416            continue;
417        }
418
419        match parse_line(line) {
420            Some(parsed) => {
421                entries.push(LogEntry {
422                    id: id_counter,
423                    line_number: (i + 1) as u32,
424                    message: parsed.message,
425                    component: parsed.component,
426                    timestamp: parsed.timestamp,
427                    timestamp_display: parsed.timestamp_display,
428                    severity: parsed.severity,
429                    thread: Some(parsed.thread),
430                    thread_display: parsed.thread_display,
431                    source_file: parsed.source_file,
432                    format: LogFormat::Ccm,
433                    file_path: file_path.to_string(),
434                    timezone_offset: Some(parsed.timezone_offset),
435                    error_code_spans: Vec::new(),
436                    ip_address: None,
437                    host_name: None,
438                    mac_address: None,
439                    result_code: None,
440                    gle_code: None,
441                    setup_phase: None,
442                    operation_name: None,
443                    http_method: None,
444                    uri_stem: None,
445                    uri_query: None,
446                    status_code: None,
447                    sub_status: None,
448                    time_taken_ms: None,
449                    client_ip: None,
450                    server_ip: None,
451                    user_agent: None,
452                    server_port: None,
453                    username: None,
454                    win32_status: None,
455                    query_name: None,
456                    query_type: None,
457                    response_code: None,
458                    dns_direction: None,
459                    dns_protocol: None,
460                    source_ip: None,
461                    dns_flags: None,
462                    dns_event_id: None,
463                    zone_name: None,
464                    entry_kind: None,
465                    whatif: None,
466                    section_name: None,
467                    section_color: None,
468                    iteration: None,
469                    tags: None,
470                });
471                id_counter += 1;
472            }
473            None => {
474                // Line didn't match CCM format — treat as plain text continuation
475                // or standalone plain text entry
476                entries.push(LogEntry {
477                    id: id_counter,
478                    line_number: (i + 1) as u32,
479                    message: line.to_string(),
480                    component: None,
481                    timestamp: None,
482                    timestamp_display: None,
483                    severity: detect_severity_from_text(line),
484                    thread: None,
485                    thread_display: None,
486                    source_file: None,
487                    format: LogFormat::Plain,
488                    file_path: file_path.to_string(),
489                    timezone_offset: None,
490                    error_code_spans: Vec::new(),
491                    ip_address: None,
492                    host_name: None,
493                    mac_address: None,
494                    result_code: None,
495                    gle_code: None,
496                    setup_phase: None,
497                    operation_name: None,
498                    http_method: None,
499                    uri_stem: None,
500                    uri_query: None,
501                    status_code: None,
502                    sub_status: None,
503                    time_taken_ms: None,
504                    client_ip: None,
505                    server_ip: None,
506                    user_agent: None,
507                    server_port: None,
508                    username: None,
509                    win32_status: None,
510                    query_name: None,
511                    query_type: None,
512                    response_code: None,
513                    dns_direction: None,
514                    dns_protocol: None,
515                    source_ip: None,
516                    dns_flags: None,
517                    dns_event_id: None,
518                    zone_name: None,
519                    entry_kind: None,
520                    whatif: None,
521                    section_name: None,
522                    section_color: None,
523                    iteration: None,
524                    tags: None,
525                });
526                id_counter += 1;
527                errors += 1;
528            }
529        }
530    }
531
532    (entries, errors)
533}
534
535#[cfg(test)]
536mod tests {
537    use super::*;
538
539    #[test]
540    fn test_parse_ccm_line() {
541        let line = r#"<![LOG[Successfully connected to \\server\share]LOG]!><time="08:06:34.590-060" date="09-02-2016" component="ContentTransferManager" context="" type="1" thread="3692" file="datatransfer.cpp">"#;
542        let parsed = parse_line(line).expect("should parse");
543        assert_eq!(parsed.message, r"Successfully connected to \\server\share");
544        assert_eq!(parsed.component.as_deref(), Some("ContentTransferManager"));
545        assert_eq!(parsed.severity, Severity::Info);
546        assert_eq!(parsed.thread, 3692);
547        assert_eq!(parsed.source_file.as_deref(), Some("datatransfer.cpp"));
548        assert_eq!(parsed.timezone_offset, -60);
549        assert_eq!(
550            parsed.timestamp_display.as_deref(),
551            Some("09-02-2016 08:06:34.590")
552        );
553        // 08:06:34.590 in UTC-1 == 09:06:34.590 UTC
554        let expected_ts = FixedOffset::east_opt(-60 * 60)
555            .unwrap()
556            .from_local_datetime(
557                &chrono::NaiveDate::from_ymd_opt(2016, 9, 2)
558                    .unwrap()
559                    .and_hms_milli_opt(8, 6, 34, 590)
560                    .unwrap(),
561            )
562            .single()
563            .unwrap()
564            .timestamp_millis();
565        assert_eq!(parsed.timestamp, Some(expected_ts));
566    }
567
568    #[test]
569    fn test_build_timestamp_utc_offset() {
570        // +000 offset: naive time equals UTC
571        let (ts_utc, _) = build_timestamp(1, 1, 2024, 10, 0, 0, 0, Some(0));
572        let expected_utc = chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
573            .unwrap()
574            .and_hms_milli_opt(10, 0, 0, 0)
575            .unwrap()
576            .and_utc()
577            .timestamp_millis();
578        assert_eq!(ts_utc, Some(expected_utc));
579
580        // -240 offset (UTC-4 / EST): 10:00 local == 14:00 UTC
581        let (ts_est, _) = build_timestamp(1, 1, 2024, 10, 0, 0, 0, Some(-240));
582        let expected_est = chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
583            .unwrap()
584            .and_hms_milli_opt(14, 0, 0, 0)
585            .unwrap()
586            .and_utc()
587            .timestamp_millis();
588        assert_eq!(ts_est, Some(expected_est));
589
590        // +240 offset (UTC+4): 10:00 local == 06:00 UTC
591        let (ts_plus4, _) = build_timestamp(1, 1, 2024, 10, 0, 0, 0, Some(240));
592        let expected_plus4 = chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
593            .unwrap()
594            .and_hms_milli_opt(6, 0, 0, 0)
595            .unwrap()
596            .and_utc()
597            .timestamp_millis();
598        assert_eq!(ts_plus4, Some(expected_plus4));
599    }
600
601    #[test]
602    fn test_parse_ccm_error() {
603        let line = r#"<![LOG[Failed to download content. Error 0x80070005]LOG]!><time="14:30:45.123+000" date="11-15-2023" component="ContentAccess" context="" type="3" thread="4480" file="contentaccess.cpp">"#;
604        let parsed = parse_line(line).expect("should parse");
605        assert_eq!(parsed.severity, Severity::Error);
606        assert_eq!(parsed.component.as_deref(), Some("ContentAccess"));
607    }
608
609    #[test]
610    fn test_parse_ccm_warning() {
611        let line = r#"<![LOG[Retrying request]LOG]!><time="10:00:00.000+000" date="01-01-2024" component="Test" context="" type="2" thread="100" file="">"#;
612        let parsed = parse_line(line).expect("should parse");
613        assert_eq!(parsed.severity, Severity::Warning);
614    }
615
616    #[test]
617    fn test_parse_ccm_empty_type_and_thread_default_to_zero() {
618        let line = r#"<![LOG[Performing Install steps...]LOG]!><time="10:28:53.264+000" date="04-05-2026" component="install_config.ps1:103" context="" type="" thread="" file="test.ps1">"#;
619
620        let (entries, parse_errors) = parse_lines(&[line], "example.log");
621
622        assert_eq!(parse_errors, 0);
623        assert_eq!(entries.len(), 1);
624        assert_eq!(entries[0].format, LogFormat::Ccm);
625        assert_eq!(entries[0].severity, Severity::Info);
626        assert_eq!(entries[0].thread, Some(0));
627        assert_eq!(entries[0].thread_display.as_deref(), Some("0 (0x0000)"));
628        assert_eq!(entries[0].source_file.as_deref(), Some("test.ps1"));
629    }
630
631    #[test]
632    fn test_parse_ccm_type_0_maps_to_success() {
633        let line = r#"<![LOG[Installation completed successfully]LOG]!><time="10:28:53.264+000" date="04-05-2026" component="install.ps1:10" context="" type="0" thread="42" file="install.ps1">"#;
634
635        let (entries, parse_errors) = parse_lines(&[line], "example.log");
636
637        assert_eq!(parse_errors, 0);
638        assert_eq!(entries.len(), 1);
639        assert_eq!(entries[0].severity, Severity::Success);
640    }
641
642    #[test]
643    fn test_severity_from_type_field_mapping() {
644        // Explicit CCM type values map directly.
645        assert_eq!(
646            severity_from_type_field(Some(0), "anything"),
647            Severity::Success
648        );
649        assert_eq!(
650            severity_from_type_field(Some(1), "anything"),
651            Severity::Info
652        );
653        assert_eq!(
654            severity_from_type_field(Some(2), "anything"),
655            Severity::Warning
656        );
657        assert_eq!(
658            severity_from_type_field(Some(3), "anything"),
659            Severity::Error
660        );
661        // Unknown numeric type falls back to Info.
662        assert_eq!(
663            severity_from_type_field(Some(99), "anything"),
664            Severity::Info
665        );
666        // Absent type infers from message text — a neutral message must NOT
667        // be coerced to Success (the latent unwrap_or(0) bug).
668        assert_eq!(
669            severity_from_type_field(None, "Performing install steps"),
670            Severity::Info
671        );
672        assert_eq!(
673            severity_from_type_field(None, "Operation failed"),
674            Severity::Error
675        );
676    }
677
678    #[test]
679    fn test_severity_from_text() {
680        assert_eq!(
681            detect_severity_from_text("An error occurred"),
682            Severity::Error
683        );
684        assert_eq!(
685            detect_severity_from_text("Connection failed"),
686            Severity::Error
687        );
688        assert_eq!(
689            detect_severity_from_text("Failover to backup"),
690            Severity::Info
691        );
692        assert_eq!(
693            detect_severity_from_text("Warning: low disk"),
694            Severity::Warning
695        );
696        assert_eq!(detect_severity_from_text("All good"), Severity::Info);
697    }
698
699    #[test]
700    fn test_parse_lines_with_ime_specialization_preserves_logical_records() {
701        let lines = [
702            r#"<![LOG[Powershell execution is done, exitCode = 1]LOG]!><time="11:16:37.3093207" date="3-12-2026" component="HealthScripts" context="" type="1" thread="50" file="">"#,
703            r#"<![LOG[[HS] err output = Downloaded profile payload is not valid JSON."#,
704            r#"At C:\Windows\IMECache\HealthScripts\script.ps1:457 char:9"#,
705            r#"]LOG]!><time="11:16:42.3322734" date="3-12-2026" component="HealthScripts" context="" type="3" thread="50" file="">"#,
706        ];
707
708        let (entries, parse_errors) = parse_lines_with_specialization(
709            &lines,
710            "HealthScripts.log",
711            Some(ParserSpecialization::Ime),
712        );
713
714        assert_eq!(parse_errors, 0);
715        assert_eq!(entries.len(), 2);
716        assert_eq!(entries[0].format, LogFormat::Ccm);
717        assert_eq!(entries[1].line_number, 2);
718        assert!(entries[1]
719            .message
720            .contains("Downloaded profile payload is not valid JSON"));
721        assert!(entries[1]
722            .message
723            .contains("At C:\\Windows\\IMECache\\HealthScripts\\script.ps1:457 char:9"));
724    }
725
726    #[test]
727    fn test_build_timestamp_none_offset_treats_as_utc() {
728        let (ts, _) = build_timestamp(1, 1, 2024, 10, 0, 0, 0, None);
729        let expected = chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
730            .unwrap()
731            .and_hms_milli_opt(10, 0, 0, 0)
732            .unwrap()
733            .and_utc()
734            .timestamp_millis();
735        assert_eq!(ts, Some(expected));
736    }
737
738    #[test]
739    fn test_build_timestamp_midnight_crossing_offset() {
740        // 01:00 local at UTC+3 = 22:00 UTC on the previous day
741        let (ts, _) = build_timestamp(1, 2, 2024, 1, 0, 0, 0, Some(180));
742        let expected = chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
743            .unwrap()
744            .and_hms_milli_opt(22, 0, 0, 0)
745            .unwrap()
746            .and_utc()
747            .timestamp_millis();
748        assert_eq!(ts, Some(expected));
749    }
750
751    #[test]
752    fn test_build_timestamp_extreme_offset_falls_back_to_utc() {
753        // Offset of 99999 minutes would overflow FixedOffset range.
754        // Should fall back to treating naive as UTC, not return None.
755        let (ts, display) = build_timestamp(1, 1, 2024, 10, 0, 0, 0, Some(99999));
756        let expected_utc = chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
757            .unwrap()
758            .and_hms_milli_opt(10, 0, 0, 0)
759            .unwrap()
760            .and_utc()
761            .timestamp_millis();
762        assert_eq!(
763            ts,
764            Some(expected_utc),
765            "extreme offset should fall back to UTC"
766        );
767        assert!(display.is_some(), "display should always be present");
768    }
769}