Skip to main content

cmtraceopen_parser/intune/
event_tracker.rs

1use std::collections::{HashMap, HashSet};
2use std::path::Path;
3use std::sync::OnceLock;
4
5use regex::Regex;
6
7use super::guid_registry::{self, guid_re, GuidRegistry};
8use super::ime_parser::ImeLine;
9use super::models::{IntuneEvent, IntuneEventType, IntuneStatus};
10
11fn win32_app_re() -> &'static Regex {
12    static CELL: OnceLock<Regex> = OnceLock::new();
13    CELL.get_or_init(|| {
14        Regex::new(
15        r#"(?i)\[Win32App\].*(?:processing|executing|installing|detected|not detected|evaluating)"#,
16    )
17    .unwrap()
18    })
19}
20fn win32_result_re() -> &'static Regex {
21    static CELL: OnceLock<Regex> = OnceLock::new();
22    CELL.get_or_init(|| {
23        Regex::new(r#"(?i)\[Win32App\].*(?:result|completed|success|failed|error)"#).unwrap()
24    })
25}
26fn win32_guid_re() -> &'static Regex {
27    static CELL: OnceLock<Regex> = OnceLock::new();
28    CELL.get_or_init(|| {
29    Regex::new(r#"(?i)(?:app|application)\s+(?:id|with\s+id)[:\s]+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"#).unwrap()
30})
31}
32/// Matches "for app <GUID>" — common in StatusReport lines where a user GUID precedes the app GUID.
33fn for_app_guid_re() -> &'static Regex {
34    static CELL: OnceLock<Regex> = OnceLock::new();
35    CELL.get_or_init(|| {
36        Regex::new(
37            r#"(?i)for\s+app\s+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"#,
38        )
39        .unwrap()
40    })
41}
42fn winget_re() -> &'static Regex {
43    static CELL: OnceLock<Regex> = OnceLock::new();
44    CELL.get_or_init(|| {
45        Regex::new(r#"(?i)WinGetApp.*(?:processing|installing|detected|evaluating)"#).unwrap()
46    })
47}
48fn winget_token_re() -> &'static Regex {
49    static CELL: OnceLock<Regex> = OnceLock::new();
50    CELL.get_or_init(|| Regex::new(r#"(?i)(?:winget|microsoft\.winget)"#).unwrap())
51}
52fn appworkload_download_re() -> &'static Regex {
53    static CELL: OnceLock<Regex> = OnceLock::new();
54    CELL.get_or_init(|| {
55    Regex::new(
56        r#"(?i)(?:download(?:ing|ed)?|delivery\s+optimization|content\s+download|bytes\s+downloaded|download\s+progress|download\s+session|content\s+retrieval)"#,
57    )
58    .unwrap()
59})
60}
61fn appworkload_staging_re() -> &'static Regex {
62    static CELL: OnceLock<Regex> = OnceLock::new();
63    CELL.get_or_init(|| {
64    Regex::new(
65        r#"(?i)(?:staging\s+(?:file|content)|hash\s+validation|content\s+cached|cache\s+location|expanded\s+content|extract(?:ed|ing))"#,
66    )
67    .unwrap()
68})
69}
70fn appworkload_hash_re() -> &'static Regex {
71    static CELL: OnceLock<Regex> = OnceLock::new();
72    CELL.get_or_init(|| {
73        Regex::new(r#"(?i)(?:hash\s+validation|hash\s+mismatch|hash\s+check)"#).unwrap()
74    })
75}
76fn appworkload_install_re() -> &'static Regex {
77    static CELL: OnceLock<Regex> = OnceLock::new();
78    CELL.get_or_init(|| {
79    Regex::new(
80        r#"(?i)(?:install(?:ing|ation)?|execution|enforcement|installer|launching\s+install|handoff\s+to\s+install|processdetectionrules|detection\s+rule)"#,
81    )
82    .unwrap()
83})
84}
85fn appworkload_retry_re() -> &'static Regex {
86    static CELL: OnceLock<Regex> = OnceLock::new();
87    CELL.get_or_init(|| {
88        Regex::new(r#"(?i)(?:retry|retrying|reattempt|will\s+retry|attempt\s+\d+\s+of\s+\d+)"#)
89            .unwrap()
90    })
91}
92fn appworkload_stall_re() -> &'static Regex {
93    static CELL: OnceLock<Regex> = OnceLock::new();
94    CELL.get_or_init(|| {
95    Regex::new(
96        r#"(?i)(?:stalled|not\s+progressing|no\s+progress|timed?\s*out|timeout|hung|retry\s+exhausted)"#,
97    )
98    .unwrap()
99})
100}
101fn appworkload_queue_re() -> &'static Regex {
102    static CELL: OnceLock<Regex> = OnceLock::new();
103    CELL.get_or_init(|| {
104    Regex::new(
105        r#"(?i)(?:queued|queueing|requesting\s+download|waiting\s+for\s+download|waiting\s+for\s+content|pending\s+download)"#,
106    )
107    .unwrap()
108})
109}
110fn appworkload_failure_re() -> &'static Regex {
111    static CELL: OnceLock<Regex> = OnceLock::new();
112    CELL.get_or_init(|| {
113    Regex::new(
114        r#"(?i)(?:download\s+failed|failed\s+to\s+download|hash\s+validation\s+failed|hash\s+mismatch|staging\s+failed|unable\s+to\s+download|content\s+not\s+found|cancelled|aborted|retry\s+exhausted)"#,
115    )
116    .unwrap()
117})
118}
119fn appworkload_success_re() -> &'static Regex {
120    static CELL: OnceLock<Regex> = OnceLock::new();
121    CELL.get_or_init(|| {
122    Regex::new(
123        r#"(?i)(?:download\s+completed|download\s+succeeded|staging\s+completed|content\s+cached|hash\s+validation\s+succeeded|install\s+completed|completed\s+successfully)"#,
124    )
125    .unwrap()
126})
127}
128fn sidecar_script_start_re() -> &'static Regex {
129    static CELL: OnceLock<Regex> = OnceLock::new();
130    CELL.get_or_init(|| {
131        Regex::new(r#"(?i)start\s+detectionmanager\s+sidecarscriptdetectionmanager"#).unwrap()
132    })
133}
134fn sidecar_script_complete_re() -> &'static Regex {
135    static CELL: OnceLock<Regex> = OnceLock::new();
136    CELL.get_or_init(|| {
137        Regex::new(r#"(?i)completed\s+detectionmanager\s+sidecarscriptdetectionmanager"#).unwrap()
138    })
139}
140fn sidecar_script_mid_re() -> &'static Regex {
141    static CELL: OnceLock<Regex> = OnceLock::new();
142    CELL.get_or_init(|| {
143    Regex::new(
144        r#"(?i)sidecarscriptdetectionmanager\s+(?:launch|process\s+id|powershell\s+exitcode|powershell\s+execution|create\s+proxy|execution\s+is\s+done|create\s+files)"#,
145    )
146    .unwrap()
147})
148}
149fn sidecar_exitcode_re() -> &'static Regex {
150    static CELL: OnceLock<Regex> = OnceLock::new();
151    CELL.get_or_init(|| Regex::new(r#"(?i)powershell\s+exitcode:\s*(\d+)"#).unwrap())
152}
153fn policy_eval_re() -> &'static Regex {
154    static CELL: OnceLock<Regex> = OnceLock::new();
155    CELL.get_or_init(|| {
156    Regex::new(
157        r#"(?i)(?:assignment\s+evaluation|targeted\s+intent|applicability\s*=|\bapplicable\b|not\s+applicable|requirement\s+rule|detection\s+rule|local\s+deadline|grs\s+expired|grs\s+not\s+expired|enforcement\s+classification|will\s+not\s+be\s+enforced)"#,
158    )
159    .unwrap()
160})
161}
162fn app_action_re() -> &'static Regex {
163    static CELL: OnceLock<Regex> = OnceLock::new();
164    CELL.get_or_init(|| {
165        Regex::new(r#"(?i)(?:app\s+with\s+id:|application\s+action|managed\s+app)"#).unwrap()
166    })
167}
168fn applicability_re() -> &'static Regex {
169    static CELL: OnceLock<Regex> = OnceLock::new();
170    CELL.get_or_init(|| {
171    Regex::new(r#"(?i)(?:applicability|applicable|not\s+applicable|requirement\s+rule|detection\s+rule|will\s+not\s+be\s+enforced)"#)
172        .unwrap()
173})
174}
175fn applicability_block_re() -> &'static Regex {
176    static CELL: OnceLock<Regex> = OnceLock::new();
177    CELL.get_or_init(|| {
178    Regex::new(
179        r#"(?i)(?:not\s+applicable|applicability\s*(?:=|:)\s*false|will\s+not\s+be\s+enforced|requirement\s+rule.*(?:not\s+satisfied|failed|false)|assignment.*(?:not\s+applicable|not\s+targeted)|enforcement\s+classification.*not\s+applicable)"#,
180    )
181    .unwrap()
182})
183}
184fn applicability_success_re() -> &'static Regex {
185    static CELL: OnceLock<Regex> = OnceLock::new();
186    CELL.get_or_init(|| {
187    Regex::new(
188        r#"(?i)(?:applicability\s*(?:=|:)\s*true|requirement\s+rule.*(?:passed|satisfied|true)|assignment\s+evaluation\s+completed|applicable\s*=\s*true)"#,
189    )
190    .unwrap()
191})
192}
193fn policy_pending_re() -> &'static Regex {
194    static CELL: OnceLock<Regex> = OnceLock::new();
195    CELL.get_or_init(|| {
196        Regex::new(r#"(?i)(?:local\s+deadline|grs\s+not\s+expired|scheduled|queued|pending)"#)
197            .unwrap()
198    })
199}
200fn script_re() -> &'static Regex {
201    static CELL: OnceLock<Regex> = OnceLock::new();
202    CELL.get_or_init(|| {
203        Regex::new(r#"(?i)(?:PowerShell\s+script|script\s+execution|running\s+script)"#).unwrap()
204    })
205}
206fn script_result_re() -> &'static Regex {
207    static CELL: OnceLock<Regex> = OnceLock::new();
208    CELL.get_or_init(|| {
209        Regex::new(r#"(?i)script.*(?:completed|exit\s+code|result|output|failed|success)"#).unwrap()
210    })
211}
212fn agentexecutor_script_re() -> &'static Regex {
213    static CELL: OnceLock<Regex> = OnceLock::new();
214    CELL.get_or_init(|| {
215    Regex::new(
216        r#"(?i)(?:powershell\s+script\s+is\s+successfully\s+executed|detection\s+script|remediation\s+script|exit\s+code|script\s+(?:completed|failed|timed?\s*out|execution)|stdout|stderr)"#,
217    )
218    .unwrap()
219})
220}
221fn detection_script_re() -> &'static Regex {
222    static CELL: OnceLock<Regex> = OnceLock::new();
223    CELL.get_or_init(|| {
224        Regex::new(r#"(?i)\b(?:pre-)?detection\s+script\b|\bpre-detect\b"#).unwrap()
225    })
226}
227fn remediation_script_re() -> &'static Regex {
228    static CELL: OnceLock<Regex> = OnceLock::new();
229    CELL.get_or_init(|| {
230        Regex::new(r#"(?i)\b(?:post-)?remediation\s+script\b|\bpost-detect\b|\bremediation\b"#)
231            .unwrap()
232    })
233}
234fn script_failure_re() -> &'static Regex {
235    static CELL: OnceLock<Regex> = OnceLock::new();
236    CELL.get_or_init(|| {
237    Regex::new(
238        r#"(?i)(?:access\s+is\s+denied|unauthorized|permission\s+denied|term\s+'.+'\s+is\s+not\s+recognized|cannot\s+find\s+path|path\s+not\s+found|file\s+not\s+found|module\s+.*\s+not\s+found|parsererror|syntax\s+error|execution\s+policy|digitally\s+signed|failed\s+to\s+execute|exception|stderr)"#,
239    )
240    .unwrap()
241})
242}
243fn remediation_re() -> &'static Regex {
244    static CELL: OnceLock<Regex> = OnceLock::new();
245    CELL.get_or_init(|| {
246        Regex::new(r#"(?i)(?:Remediation|HealthScript|proactive\s+remediation)"#).unwrap()
247    })
248}
249fn healthscript_re() -> &'static Regex {
250    static CELL: OnceLock<Regex> = OnceLock::new();
251    CELL.get_or_init(|| {
252    Regex::new(
253        r#"(?i)(?:healthscript|health\s+script|detection\s+script|remediation\s+script|pre-detect|post-detect|schedule(?:d|ing)?|compliance\s+result)"#,
254    )
255    .unwrap()
256})
257}
258fn esp_re() -> &'static Regex {
259    static CELL: OnceLock<Regex> = OnceLock::new();
260    CELL.get_or_init(|| {
261        Regex::new(r#"(?i)(?:ESP|EspBody|EnrollmentStatusPage|enrollment\s+status)"#).unwrap()
262    })
263}
264fn sync_re() -> &'static Regex {
265    static CELL: OnceLock<Regex> = OnceLock::new();
266    CELL.get_or_init(|| Regex::new(r#"(?i)(?:sync\s+session|check-in|SyncSession)"#).unwrap())
267}
268// GUID_RE imported from guid_registry
269fn error_code_re() -> &'static Regex {
270    static CELL: OnceLock<Regex> = OnceLock::new();
271    CELL.get_or_init(|| {
272    Regex::new(
273        r#"(?i)(?:error\s*(?:code)?|exit\s*code(?:\s+of\s+the\s+script)?|hresult|hr|result|return\s*code)\s*(?:is|[=:])\s*(0x[0-9a-fA-F]+|-?\d+)"#,
274    )
275    .unwrap()
276})
277}
278fn exit_code_re() -> &'static Regex {
279    static CELL: OnceLock<Regex> = OnceLock::new();
280    CELL.get_or_init(|| {
281        Regex::new(r#"(?i)exit\s*code(?:\s+of\s+the\s+script)?\s*(?:is|[=:])\s*(-?\d+)"#).unwrap()
282    })
283}
284fn pending_re() -> &'static Regex {
285    static CELL: OnceLock<Regex> = OnceLock::new();
286    CELL.get_or_init(|| {
287        Regex::new(r#"(?i)(?:pending|queued|waiting|scheduled|requesting)"#).unwrap()
288    })
289}
290fn timeout_re() -> &'static Regex {
291    static CELL: OnceLock<Regex> = OnceLock::new();
292    CELL.get_or_init(|| {
293        Regex::new(r#"(?i)(?:timed?\s*out|timeout|stalled|hung|not\s+progressing|no\s+progress)"#)
294            .unwrap()
295    })
296}
297fn compliance_true_re() -> &'static Regex {
298    static CELL: OnceLock<Regex> = OnceLock::new();
299    CELL.get_or_init(|| Regex::new(r#"(?i)compliance\s+result.*\bis\s+true\b"#).unwrap())
300}
301fn compliance_false_re() -> &'static Regex {
302    static CELL: OnceLock<Regex> = OnceLock::new();
303    CELL.get_or_init(|| Regex::new(r#"(?i)compliance\s+result.*\bis\s+false\b"#).unwrap())
304}
305fn client_health_rule_summary_re() -> &'static Regex {
306    static CELL: OnceLock<Regex> = OnceLock::new();
307    CELL.get_or_init(|| {
308    Regex::new(
309        r#"(?i)summary:\s*rule\s+(.+?)\s+with\s+ID\s+[0-9a-f-]{36},\s*result\s*=\s*(pass|fail),\s*details\s*=\s*(.+)$"#,
310    )
311    .unwrap()
312})
313}
314fn client_health_heartbeat_success_re() -> &'static Regex {
315    static CELL: OnceLock<Regex> = OnceLock::new();
316    CELL.get_or_init(|| {
317        Regex::new(r#"(?i)the client health report was sent successfully\. done\."#).unwrap()
318    })
319}
320fn client_health_heartbeat_failure_re() -> &'static Regex {
321    static CELL: OnceLock<Regex> = OnceLock::new();
322    CELL.get_or_init(|| {
323    Regex::new(
324        r#"(?i)(?:failed to send heartbeat report|exception occurred while sending heartbeat report|clienthealthruleengine\]\(sendheartbeatreport\).*(?:failed|unauthorized|exception)|found webexception in aggregateexception)"#,
325    )
326    .unwrap()
327})
328}
329fn client_cert_local_machine_count_re() -> &'static Regex {
330    static CELL: OnceLock<Regex> = OnceLock::new();
331    CELL.get_or_init(|| {
332        Regex::new(r#"(?i)MDM certs found in LocalMachine count:\s*(\d+)"#).unwrap()
333    })
334}
335fn client_cert_failure_re() -> &'static Regex {
336    static CELL: OnceLock<Regex> = OnceLock::new();
337    CELL.get_or_init(|| {
338    Regex::new(
339        r#"(?i)(?:certificate.*(?:invalid|error|fail)|private key|correct oid|expired|client cert check.*exception|exception.*certificate)"#,
340    )
341    .unwrap()
342})
343}
344fn device_health_app_crash_re() -> &'static Regex {
345    static CELL: OnceLock<Regex> = OnceLock::new();
346    CELL.get_or_init(|| {
347    Regex::new(
348        r#"(?is)received application event.*?<Data Name="AppName">([^<]+)</Data>.*?<Data Name="ExceptionCode">([^<]+)</Data>"#,
349    )
350    .unwrap()
351})
352}
353fn sensor_memory_failure_re() -> &'static Regex {
354    static CELL: OnceLock<Regex> = OnceLock::new();
355    CELL.get_or_init(|| {
356    Regex::new(
357        r#"(?i)(?:error getting physically installed system memory|GetPhysicallyInstalledSystemMemory failed)"#,
358    )
359    .unwrap()
360})
361}
362fn win32_app_inventory_full_re() -> &'static Regex {
363    static CELL: OnceLock<Regex> = OnceLock::new();
364    CELL.get_or_init(|| Regex::new(r#"(?i)\[Win32AppInventory\]\s*report type is 1\b"#).unwrap())
365}
366fn win32_app_inventory_no_change_re() -> &'static Regex {
367    static CELL: OnceLock<Regex> = OnceLock::new();
368    CELL.get_or_init(|| {
369        Regex::new(r#"(?i)no change detected in win32 app inventory delta update"#).unwrap()
370    })
371}
372fn win32_app_inventory_delta_re() -> &'static Regex {
373    static CELL: OnceLock<Regex> = OnceLock::new();
374    CELL.get_or_init(|| {
375    Regex::new(
376        r#"(?i)computing delta inventory\.\.\.done\.\s*add count\s*=\s*(\d+),\s*modify count\s*=\s*(\d+),\s*delete count\s*=\s*(\d+)"#,
377    )
378    .unwrap()
379})
380}
381fn success_re() -> &'static Regex {
382    static CELL: OnceLock<Regex> = OnceLock::new();
383    CELL.get_or_init(|| {
384    Regex::new(
385        r#"(?i)(?:success|succeeded|completed\s+successfully|installed|detected|compliant|validated|passed)"#,
386    )
387    .unwrap()
388})
389}
390fn failed_re() -> &'static Regex {
391    static CELL: OnceLock<Regex> = OnceLock::new();
392    CELL.get_or_init(|| {
393    Regex::new(
394        r#"(?i)(?:fail|error|not\s+detected|not\s+installed|non-compliant|cancelled|aborted|exception)"#,
395    )
396    .unwrap()
397})
398}
399
400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
401enum ImeSourceKind {
402    PrimaryIme,
403    AppWorkload,
404    AppActionProcessor,
405    AgentExecutor,
406    HealthScripts,
407    ClientHealth,
408    ClientCertCheck,
409    DeviceHealthMonitoring,
410    Sensor,
411    Win32AppInventory,
412    Other,
413}
414
415#[derive(Debug, Default, Clone, Copy)]
416struct AppWorkloadMatchFlags {
417    winget_token: bool,
418    winget: bool,
419    download: bool,
420    staging: bool,
421    hash: bool,
422    install: bool,
423    retry: bool,
424    stall: bool,
425    failure: bool,
426    success: bool,
427    queue: bool,
428    pending: bool,
429    timeout: bool,
430    sidecar_script_start: bool,
431    sidecar_script_complete: bool,
432    sidecar_script_mid: bool,
433}
434
435impl AppWorkloadMatchFlags {
436    fn from_message(msg: &str) -> Self {
437        Self {
438            winget_token: winget_token_re().is_match(msg),
439            winget: winget_re().is_match(msg),
440            download: appworkload_download_re().is_match(msg),
441            staging: appworkload_staging_re().is_match(msg),
442            hash: appworkload_hash_re().is_match(msg),
443            install: appworkload_install_re().is_match(msg),
444            retry: appworkload_retry_re().is_match(msg),
445            stall: appworkload_stall_re().is_match(msg),
446            failure: appworkload_failure_re().is_match(msg),
447            success: appworkload_success_re().is_match(msg),
448            queue: appworkload_queue_re().is_match(msg),
449            pending: pending_re().is_match(msg),
450            timeout: timeout_re().is_match(msg),
451            sidecar_script_start: sidecar_script_start_re().is_match(msg),
452            sidecar_script_complete: sidecar_script_complete_re().is_match(msg),
453            sidecar_script_mid: sidecar_script_mid_re().is_match(msg),
454        }
455    }
456
457    fn is_candidate(self) -> bool {
458        self.download
459            || self.staging
460            || self.install
461            || self.retry
462            || self.stall
463            || self.winget_token
464            || self.winget
465            || self.sidecar_script_start
466            || self.sidecar_script_complete
467            || self.sidecar_script_mid
468    }
469}
470
471pub fn extract_events(
472    lines: &[ImeLine],
473    source_file: &str,
474    registry: &GuidRegistry,
475) -> Vec<IntuneEvent> {
476    let mut events = Vec::new();
477    let mut next_id = 0u64;
478    let source_kind = classify_source_kind(source_file);
479
480    for (index, line) in lines.iter().enumerate() {
481        if source_kind == ImeSourceKind::AppWorkload {
482            if let Some(event) =
483                extract_appworkload_event(lines, index, line, source_file, next_id, registry)
484            {
485                events.push(event);
486                next_id += 1;
487            }
488            continue;
489        }
490
491        let Some(event_type) = detect_event_type(&line.message, source_kind) else {
492            continue;
493        };
494
495        // Try primary extract_guid, fall back to guid_registry::extract_app_id
496        let guid =
497            extract_guid(&line.message).or_else(|| guid_registry::extract_app_id(&line.message));
498        let status = determine_status(&line.message, source_kind);
499        let raw_name = build_event_name(&event_type, &guid, &line.message, source_kind);
500
501        // Inline enrichment: resolve GUID suffix immediately if possible
502        let name = match guid.as_deref() {
503            Some(g) => registry.enrich_event_name(&raw_name, g).unwrap_or(raw_name),
504            None => raw_name,
505        };
506
507        let detail = line.message.clone();
508
509        events.push(IntuneEvent {
510            id: next_id,
511            event_type,
512            name,
513            guid,
514            status,
515            start_time: line
516                .timestamp_utc
517                .clone()
518                .or_else(|| line.timestamp.clone()),
519            end_time: None,
520            duration_secs: None,
521            error_code: extract_error_code(&line.message),
522            detail,
523            source_file: source_file.to_string(),
524            line_number: line.line_number,
525            start_time_epoch: None,
526            end_time_epoch: None,
527            script_body: None,
528            parent_app_guid: None,
529        });
530        next_id += 1;
531    }
532
533    pair_events(&mut events);
534    events
535}
536
537fn extract_appworkload_event(
538    lines: &[ImeLine],
539    index: usize,
540    line: &ImeLine,
541    source_file: &str,
542    next_id: u64,
543    registry: &GuidRegistry,
544) -> Option<IntuneEvent> {
545    let msg = line.message.as_str();
546    if contains_any_ascii_case_insensitive(
547        msg,
548        &[
549            "reportingmanager",
550            "reportingcachemanager",
551            "reporting state initialized",
552            "sending reports",
553            "writeabletostorage",
554            "cangenerate",
555            "isappreportable",
556            "get policies",
557        ],
558    ) {
559        return None;
560    }
561
562    let flags = AppWorkloadMatchFlags::from_message(msg);
563    if !flags.is_candidate() {
564        return None;
565    }
566
567    // Determine event type from flags
568    let is_sidecar =
569        flags.sidecar_script_start || flags.sidecar_script_complete || flags.sidecar_script_mid;
570
571    let event_type = if flags.winget_token || flags.winget {
572        IntuneEventType::WinGetApp
573    } else if is_sidecar {
574        IntuneEventType::PowerShellScript
575    } else if flags.download || flags.staging || flags.retry || flags.stall {
576        IntuneEventType::ContentDownload
577    } else if flags.install {
578        IntuneEventType::Win32App
579    } else {
580        return None;
581    };
582
583    // Try primary extract_guid, fall back to guid_registry::extract_app_id
584    let guid = extract_guid(msg).or_else(|| guid_registry::extract_app_id(msg));
585
586    if is_sidecar {
587        let status = determine_sidecar_script_status(msg, flags);
588        let error_code = sidecar_exitcode_re()
589            .captures(msg)
590            .and_then(|cap| cap.get(1))
591            .map(|m| m.as_str().to_string());
592        let short = guid
593            .as_deref()
594            .map(|g| &g[..8.min(g.len())])
595            .unwrap_or("unknown");
596        let phase = if flags.sidecar_script_complete {
597            "Complete"
598        } else if flags.sidecar_script_start {
599            "Start"
600        } else {
601            "Running"
602        };
603        let raw_name = format!("Script Detection {phase} ({short})");
604
605        let name = match guid.as_deref() {
606            Some(g) => registry.enrich_event_name(&raw_name, g).unwrap_or(raw_name),
607            None => raw_name,
608        };
609
610        return Some(IntuneEvent {
611            id: next_id,
612            event_type,
613            name,
614            guid: guid.clone(),
615            status,
616            start_time: line
617                .timestamp_utc
618                .clone()
619                .or_else(|| line.timestamp.clone()),
620            end_time: None,
621            duration_secs: None,
622            error_code,
623            detail: msg.to_string(),
624            source_file: source_file.to_string(),
625            line_number: line.line_number,
626            start_time_epoch: None,
627            end_time_epoch: None,
628            script_body: None,
629            parent_app_guid: guid,
630        });
631    }
632
633    let status = determine_appworkload_status(msg, flags);
634    let raw_name = build_appworkload_name(&event_type, &guid, msg, flags);
635
636    // Inline enrichment: resolve GUID suffix immediately if possible
637    let name = match guid.as_deref() {
638        Some(g) => registry.enrich_event_name(&raw_name, g).unwrap_or(raw_name),
639        None => raw_name,
640    };
641    let detail = build_appworkload_detail(lines, index, guid.as_deref(), msg, status);
642
643    Some(IntuneEvent {
644        id: next_id,
645        event_type,
646        name,
647        guid,
648        status,
649        start_time: line
650            .timestamp_utc
651            .clone()
652            .or_else(|| line.timestamp.clone()),
653        end_time: None,
654        duration_secs: None,
655        error_code: extract_error_code(msg),
656        detail,
657        source_file: source_file.to_string(),
658        line_number: line.line_number,
659        start_time_epoch: None,
660        end_time_epoch: None,
661        script_body: None,
662        parent_app_guid: None,
663    })
664}
665
666fn determine_appworkload_status(msg: &str, flags: AppWorkloadMatchFlags) -> IntuneStatus {
667    if flags.stall || flags.timeout {
668        IntuneStatus::Timeout
669    } else if flags.retry || flags.failure {
670        IntuneStatus::Failed
671    } else if flags.success {
672        IntuneStatus::Success
673    } else if flags.queue || flags.pending || contains_ascii_case_insensitive(msg, "pending") {
674        IntuneStatus::Pending
675    } else {
676        IntuneStatus::InProgress
677    }
678}
679
680fn determine_sidecar_script_status(msg: &str, flags: AppWorkloadMatchFlags) -> IntuneStatus {
681    if flags.sidecar_script_start {
682        return IntuneStatus::InProgress;
683    }
684    if flags.sidecar_script_complete {
685        // Detection complete — both detected and not-detected are successful detection runs.
686        return IntuneStatus::Success;
687    }
688    // Mid-event: check exit code
689    if let Some(cap) = sidecar_exitcode_re().captures(msg) {
690        let code = cap.get(1).map_or("", |m| m.as_str());
691        return if code == "0" {
692            IntuneStatus::Success
693        } else {
694            IntuneStatus::Failed
695        };
696    }
697    IntuneStatus::InProgress
698}
699
700fn build_appworkload_name(
701    event_type: &IntuneEventType,
702    guid: &Option<String>,
703    msg: &str,
704    flags: AppWorkloadMatchFlags,
705) -> String {
706    if *event_type == IntuneEventType::WinGetApp {
707        return match guid.as_deref().map(short_guid) {
708            Some(short) => format!("AppWorkload WinGet ({short})"),
709            None => "AppWorkload WinGet".to_string(),
710        };
711    }
712
713    let phase = if flags.stall {
714        "Download Stall"
715    } else if flags.retry {
716        "Download Retry"
717    } else if flags.hash {
718        "Hash Validation"
719    } else if flags.staging {
720        "Staging"
721    } else if flags.install {
722        "Install"
723    } else if flags.download {
724        "Download"
725    } else {
726        return build_event_name(event_type, guid, msg, ImeSourceKind::AppWorkload);
727    };
728
729    match guid.as_deref().map(short_guid) {
730        Some(short) => format!("AppWorkload {phase} ({short})"),
731        None => format!("AppWorkload {phase}"),
732    }
733}
734
735// When AppWorkload failures do not have clean subgraph markers nearby, fall back to a
736// compact local window so the row still shows useful surrounding evidence.
737const APPWORKLOAD_CONTEXT_RADIUS: usize = 10;
738// Search a wider neighborhood for same-GUID lines because AppWorkload often emits
739// reporting state or policy payload records well before the failure line itself.
740const APPWORKLOAD_CONTEXT_LOOKAROUND: usize = 120;
741// Cap the rendered context bundle so failed rows stay readable and the copied payload
742// remains shareable without dragging in the entire file.
743const APPWORKLOAD_CONTEXT_MAX_LINES: usize = 48;
744
745fn build_appworkload_detail(
746    lines: &[ImeLine],
747    index: usize,
748    guid: Option<&str>,
749    msg: &str,
750    status: IntuneStatus,
751) -> String {
752    if !matches!(status, IntuneStatus::Failed | IntuneStatus::Timeout) {
753        return msg.to_string();
754    }
755
756    let context = collect_appworkload_context(lines, index, guid);
757    if context.is_empty() {
758        return msg.to_string();
759    }
760
761    format!("{msg}\n\nAppWorkload context:\n{}", context.join("\n"))
762}
763
764fn collect_appworkload_context(lines: &[ImeLine], index: usize, guid: Option<&str>) -> Vec<String> {
765    if lines.is_empty() || index >= lines.len() {
766        return Vec::new();
767    }
768
769    let (block_start, block_end) = find_appworkload_subgraph_bounds(lines, index);
770    let mut selected = HashSet::new();
771    for selected_index in block_start..=block_end {
772        selected.insert(selected_index);
773    }
774
775    if let Some(guid) = guid {
776        let lookaround_start = index.saturating_sub(APPWORKLOAD_CONTEXT_LOOKAROUND);
777        let lookaround_end =
778            (index + APPWORKLOAD_CONTEXT_LOOKAROUND).min(lines.len().saturating_sub(1));
779        for (i, line) in lines[lookaround_start..=lookaround_end].iter().enumerate() {
780            if contains_ascii_case_insensitive(&line.message, guid) {
781                selected.insert(lookaround_start + i);
782            }
783        }
784    }
785
786    if selected.is_empty() {
787        let fallback_start = index.saturating_sub(APPWORKLOAD_CONTEXT_RADIUS);
788        let fallback_end = (index + APPWORKLOAD_CONTEXT_RADIUS).min(lines.len().saturating_sub(1));
789        for selected_index in fallback_start..=fallback_end {
790            selected.insert(selected_index);
791        }
792    }
793
794    let mut indices = selected.into_iter().collect::<Vec<_>>();
795    indices.sort_unstable();
796
797    if indices.len() > APPWORKLOAD_CONTEXT_MAX_LINES {
798        // Keep the lines closest to the failure first so trimmed bundles preserve the
799        // immediate error context before more distant same-GUID references. For equally
800        // distant lines, the lower line number wins so the final output stays chronological.
801        indices.sort_by_key(|selected_index| (selected_index.abs_diff(index), *selected_index));
802        indices.truncate(APPWORKLOAD_CONTEXT_MAX_LINES);
803        indices.sort_unstable();
804    }
805
806    let mut formatted = Vec::with_capacity(indices.len());
807    let mut previous_index = None;
808    for selected_index in indices {
809        if let Some(previous_index_value) = previous_index {
810            if selected_index > previous_index_value + 1 {
811                formatted.push(format!(
812                    "… {} line(s) omitted …",
813                    selected_index - previous_index_value - 1
814                ));
815            }
816        }
817        formatted.push(format_appworkload_context_line(
818            &lines[selected_index],
819            selected_index == index,
820        ));
821        previous_index = Some(selected_index);
822    }
823
824    formatted
825}
826
827fn find_appworkload_subgraph_bounds(lines: &[ImeLine], index: usize) -> (usize, usize) {
828    if lines.is_empty() {
829        return (0, 0);
830    }
831
832    let safe_index = index.min(lines.len() - 1);
833    let mut start = safe_index;
834    while start > 0 {
835        let candidate = start - 1;
836        let message = lines[candidate].message.as_str();
837        if is_appworkload_subgraph_end(message) {
838            break;
839        }
840        start = candidate;
841        if is_appworkload_subgraph_start(message) {
842            break;
843        }
844    }
845
846    let mut end = safe_index;
847    while end + 1 < lines.len() {
848        let candidate = end + 1;
849        let message = lines[candidate].message.as_str();
850        if is_appworkload_subgraph_start(message) {
851            break;
852        }
853        end = candidate;
854        if is_appworkload_subgraph_end(message) {
855            break;
856        }
857    }
858
859    (start, end)
860}
861
862fn is_appworkload_subgraph_start(msg: &str) -> bool {
863    contains_ascii_case_insensitive(msg, "processing subgraph with app ids:")
864}
865
866fn is_appworkload_subgraph_end(msg: &str) -> bool {
867    contains_ascii_case_insensitive(msg, "done processing subgraph")
868}
869
870fn format_appworkload_context_line(line: &ImeLine, is_selected: bool) -> String {
871    let marker = if is_selected { ">" } else { " " };
872    let timestamp = line
873        .timestamp_utc
874        .as_deref()
875        .or(line.timestamp.as_deref())
876        .unwrap_or("No timestamp");
877    format!(
878        "{marker} L{} {timestamp} {}",
879        line.line_number, line.message
880    )
881}
882
883fn classify_source_kind(source_file: &str) -> ImeSourceKind {
884    let file_name = Path::new(source_file)
885        .file_name()
886        .map(|name| name.to_string_lossy().to_ascii_lowercase())
887        .unwrap_or_else(|| source_file.to_ascii_lowercase());
888
889    if file_name.contains("appworkload") {
890        ImeSourceKind::AppWorkload
891    } else if file_name.contains("appactionprocessor") {
892        ImeSourceKind::AppActionProcessor
893    } else if file_name.contains("agentexecutor") {
894        ImeSourceKind::AgentExecutor
895    } else if file_name.contains("healthscripts") {
896        ImeSourceKind::HealthScripts
897    } else if file_name.contains("clienthealth") {
898        ImeSourceKind::ClientHealth
899    } else if file_name.contains("clientcertcheck") {
900        ImeSourceKind::ClientCertCheck
901    } else if file_name.contains("devicehealthmonitoring") {
902        ImeSourceKind::DeviceHealthMonitoring
903    } else if file_name.contains("sensor") {
904        ImeSourceKind::Sensor
905    } else if file_name.contains("win32appinventory") {
906        ImeSourceKind::Win32AppInventory
907    } else if file_name.contains("intunemanagementextension") {
908        ImeSourceKind::PrimaryIme
909    } else {
910        ImeSourceKind::Other
911    }
912}
913
914fn detect_event_type(msg: &str, source_kind: ImeSourceKind) -> Option<IntuneEventType> {
915    match source_kind {
916        ImeSourceKind::AppWorkload => {
917            if !is_appworkload_event_candidate(msg) {
918                return None;
919            }
920            if winget_token_re().is_match(msg) || winget_re().is_match(msg) {
921                return Some(IntuneEventType::WinGetApp);
922            }
923            if appworkload_download_re().is_match(msg)
924                || appworkload_staging_re().is_match(msg)
925                || appworkload_retry_re().is_match(msg)
926                || appworkload_stall_re().is_match(msg)
927            {
928                return Some(IntuneEventType::ContentDownload);
929            }
930            if appworkload_install_re().is_match(msg) {
931                return Some(IntuneEventType::Win32App);
932            }
933        }
934        ImeSourceKind::AppActionProcessor => {
935            if is_app_action_processor_event_candidate(msg)
936                && (policy_eval_re().is_match(msg)
937                    || app_action_re().is_match(msg)
938                    || applicability_re().is_match(msg))
939            {
940                return Some(IntuneEventType::PolicyEvaluation);
941            }
942        }
943        ImeSourceKind::AgentExecutor => {
944            if !is_agent_executor_event_candidate(msg) {
945                return None;
946            }
947            if remediation_script_re().is_match(msg) || remediation_re().is_match(msg) {
948                return Some(IntuneEventType::Remediation);
949            }
950            if agentexecutor_script_re().is_match(msg)
951                || script_re().is_match(msg)
952                || script_result_re().is_match(msg)
953            {
954                return Some(IntuneEventType::PowerShellScript);
955            }
956        }
957        ImeSourceKind::HealthScripts => {
958            if is_healthscripts_event_candidate(msg)
959                && (healthscript_re().is_match(msg) || remediation_re().is_match(msg))
960            {
961                return Some(IntuneEventType::Remediation);
962            }
963        }
964        ImeSourceKind::ClientHealth => {
965            if is_client_health_event_candidate(msg) {
966                return Some(IntuneEventType::Other);
967            }
968        }
969        ImeSourceKind::ClientCertCheck => {
970            if is_client_cert_check_event_candidate(msg) {
971                return Some(IntuneEventType::Other);
972            }
973        }
974        ImeSourceKind::DeviceHealthMonitoring => {
975            if device_health_app_crash_re().is_match(msg) {
976                return Some(IntuneEventType::Other);
977            }
978        }
979        ImeSourceKind::Sensor => {
980            if sensor_memory_failure_re().is_match(msg) {
981                return Some(IntuneEventType::Other);
982            }
983        }
984        ImeSourceKind::Win32AppInventory => {
985            if is_win32_app_inventory_event_candidate(msg) {
986                return Some(IntuneEventType::Other);
987            }
988        }
989        ImeSourceKind::PrimaryIme | ImeSourceKind::Other => {}
990    }
991
992    if win32_app_re().is_match(msg) || win32_result_re().is_match(msg) {
993        Some(IntuneEventType::Win32App)
994    } else if winget_re().is_match(msg) {
995        Some(IntuneEventType::WinGetApp)
996    } else if script_re().is_match(msg) || script_result_re().is_match(msg) {
997        Some(IntuneEventType::PowerShellScript)
998    } else if remediation_re().is_match(msg) {
999        Some(IntuneEventType::Remediation)
1000    } else if esp_re().is_match(msg) {
1001        Some(IntuneEventType::Esp)
1002    } else if sync_re().is_match(msg) {
1003        Some(IntuneEventType::SyncSession)
1004    } else {
1005        None
1006    }
1007}
1008
1009fn is_agent_executor_event_candidate(msg: &str) -> bool {
1010    if ends_with_ascii_case_insensitive(msg, ".timeout")
1011        || ends_with_ascii_case_insensitive(msg, "quotedtimeoutfilepath.txt")
1012        || contains_any_ascii_case_insensitive(
1013            msg,
1014            &[
1015                "prepare to run powershell script",
1016                "remediation script option gets invoked",
1017                "creating command line parser",
1018                "adding argument",
1019                "powershell path is",
1020            ],
1021        )
1022    {
1023        return false;
1024    }
1025
1026    contains_any_ascii_case_insensitive(
1027        msg,
1028        &[
1029            "powershell exit code",
1030            "powershell script is successfully executed",
1031            "detection script",
1032            "remediation script",
1033            "script completed",
1034            "script failed",
1035            "script execution",
1036            "timed out",
1037            "timeout",
1038            "stdout",
1039            "stderr",
1040            "exit code",
1041        ],
1042    )
1043}
1044
1045fn is_appworkload_event_candidate(msg: &str) -> bool {
1046    if contains_any_ascii_case_insensitive(
1047        msg,
1048        &[
1049            "reportingmanager",
1050            "reportingcachemanager",
1051            "reporting state initialized",
1052            "sending reports",
1053            "writeabletostorage",
1054            "cangenerate",
1055            "isappreportable",
1056        ],
1057    ) {
1058        return false;
1059    }
1060
1061    appworkload_download_re().is_match(msg)
1062        || appworkload_staging_re().is_match(msg)
1063        || appworkload_install_re().is_match(msg)
1064        || appworkload_retry_re().is_match(msg)
1065        || appworkload_stall_re().is_match(msg)
1066        || winget_token_re().is_match(msg)
1067}
1068
1069fn is_app_action_processor_event_candidate(msg: &str) -> bool {
1070    !(contains_ascii_case_insensitive(msg, "processor initializing")
1071        || (contains_ascii_case_insensitive(msg, "found:")
1072            && contains_ascii_case_insensitive(msg, "apps with intent"))
1073        || contains_ascii_case_insensitive(
1074            msg,
1075            "evaluating install enforcement actions for app with id",
1076        )
1077        || contains_ascii_case_insensitive(msg, "no action required for app with id"))
1078        && contains_any_ascii_case_insensitive(
1079            msg,
1080            &[
1081                "app with id:",
1082                "assignment evaluation",
1083                "targeted intent",
1084                "applicability =",
1085                "not applicable",
1086                "local deadline",
1087                "grs expired",
1088                "grs not expired",
1089                "requirement rule",
1090                "detection rule",
1091                "will not be enforced",
1092            ],
1093        )
1094}
1095
1096fn is_healthscripts_event_candidate(msg: &str) -> bool {
1097    if contains_any_ascii_case_insensitive(
1098        msg,
1099        &[
1100            "inspect hourly schedule",
1101            "job is queued and will be scheduled",
1102            "completed user session",
1103        ],
1104    ) {
1105        return false;
1106    }
1107
1108    contains_any_ascii_case_insensitive(
1109        msg,
1110        &[
1111            "detection script",
1112            "remediation script",
1113            "exit code of the script",
1114            "compliance result",
1115            "pre-detect",
1116            "post-detect",
1117            "timed out",
1118            "timeout",
1119            "failed",
1120            "schedule",
1121        ],
1122    )
1123}
1124
1125fn is_client_health_event_candidate(msg: &str) -> bool {
1126    client_health_heartbeat_success_re().is_match(msg)
1127        || client_health_heartbeat_failure_re().is_match(msg)
1128        || matches!(
1129            parse_client_health_summary(msg),
1130            Some((_, IntuneStatus::Failed, _))
1131        )
1132}
1133
1134fn is_client_cert_check_event_candidate(msg: &str) -> bool {
1135    parse_client_cert_local_machine_count(msg) == Some(0) || client_cert_failure_re().is_match(msg)
1136}
1137
1138fn is_win32_app_inventory_event_candidate(msg: &str) -> bool {
1139    win32_app_inventory_full_re().is_match(msg)
1140        || win32_app_inventory_no_change_re().is_match(msg)
1141        || matches!(parse_win32_app_inventory_delta(msg), Some((add, modify, delete)) if add > 0 || modify > 0 || delete > 0)
1142}
1143
1144fn extract_guid(msg: &str) -> Option<String> {
1145    // 1. Specific "app id" / "application with id" pattern
1146    win32_guid_re()
1147        .captures(msg)
1148        .and_then(|cap| cap.get(1))
1149        .map(|value| value.as_str().to_string())
1150        // 2. "for app <GUID>" — avoids grabbing a user GUID that precedes the app GUID
1151        .or_else(|| {
1152            for_app_guid_re()
1153                .captures(msg)
1154                .and_then(|cap| cap.get(1))
1155                .map(|value| value.as_str().to_string())
1156        })
1157        // 3. PolicyId from JSON payloads (HealthScripts, script results)
1158        .or_else(|| extract_policy_id(msg))
1159        // 4. Generic first GUID fallback
1160        .or_else(|| {
1161            guid_re()
1162                .captures(msg)
1163                .and_then(|cap| cap.get(1))
1164                .map(|value| value.as_str().to_string())
1165        })
1166}
1167
1168/// Extract PolicyId from JSON payloads in HealthScripts/script result messages.
1169/// Handles lines like: `"PolicyId":"79880037-a3c4-489a-a7e6-a6a705b52b78"`
1170fn extract_policy_id(msg: &str) -> Option<String> {
1171    static RE: OnceLock<Regex> = OnceLock::new();
1172    let re = RE.get_or_init(|| {
1173        Regex::new(r#"(?i)"PolicyId"\s*:\s*\\?"([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\\?""#).unwrap()
1174    });
1175    re.captures(msg)
1176        .and_then(|cap| cap.get(1))
1177        .map(|m| m.as_str().to_string())
1178}
1179
1180fn extract_error_code(msg: &str) -> Option<String> {
1181    error_code_re()
1182        .captures(msg)
1183        .and_then(|cap| cap.get(1))
1184        .map(|value| value.as_str().to_string())
1185}
1186
1187fn determine_status(msg: &str, source_kind: ImeSourceKind) -> IntuneStatus {
1188    if compliance_true_re().is_match(msg) {
1189        return IntuneStatus::Success;
1190    }
1191    if compliance_false_re().is_match(msg) {
1192        return IntuneStatus::Failed;
1193    }
1194    if let Some(exit_code) = exit_code_re()
1195        .captures(msg)
1196        .and_then(|cap| cap.get(1))
1197        .and_then(|value| value.as_str().parse::<i32>().ok())
1198    {
1199        return if exit_code == 0 {
1200            IntuneStatus::Success
1201        } else {
1202            IntuneStatus::Failed
1203        };
1204    }
1205
1206    match source_kind {
1207        ImeSourceKind::AppWorkload => {
1208            if appworkload_stall_re().is_match(msg) || timeout_re().is_match(msg) {
1209                IntuneStatus::Timeout
1210            } else if appworkload_retry_re().is_match(msg) || appworkload_failure_re().is_match(msg)
1211            {
1212                IntuneStatus::Failed
1213            } else if appworkload_success_re().is_match(msg) {
1214                IntuneStatus::Success
1215            } else if appworkload_queue_re().is_match(msg) || pending_re().is_match(msg) {
1216                IntuneStatus::Pending
1217            } else {
1218                IntuneStatus::InProgress
1219            }
1220        }
1221        ImeSourceKind::AppActionProcessor => {
1222            if applicability_block_re().is_match(msg) {
1223                IntuneStatus::Failed
1224            } else if applicability_success_re().is_match(msg) {
1225                IntuneStatus::Success
1226            } else if policy_pending_re().is_match(msg) {
1227                IntuneStatus::Pending
1228            } else {
1229                IntuneStatus::InProgress
1230            }
1231        }
1232        ImeSourceKind::AgentExecutor | ImeSourceKind::HealthScripts => {
1233            if timeout_re().is_match(msg) {
1234                IntuneStatus::Timeout
1235            } else if script_failure_re().is_match(msg) || failed_re().is_match(msg) {
1236                IntuneStatus::Failed
1237            } else if success_re().is_match(msg) {
1238                IntuneStatus::Success
1239            } else if pending_re().is_match(msg) {
1240                IntuneStatus::Pending
1241            } else {
1242                IntuneStatus::InProgress
1243            }
1244        }
1245        ImeSourceKind::ClientHealth => {
1246            if let Some((_, status, _)) = parse_client_health_summary(msg) {
1247                status
1248            } else if client_health_heartbeat_failure_re().is_match(msg) {
1249                IntuneStatus::Failed
1250            } else if client_health_heartbeat_success_re().is_match(msg) {
1251                IntuneStatus::Success
1252            } else {
1253                IntuneStatus::Unknown
1254            }
1255        }
1256        ImeSourceKind::ClientCertCheck => {
1257            if parse_client_cert_local_machine_count(msg) == Some(0)
1258                || client_cert_failure_re().is_match(msg)
1259            {
1260                IntuneStatus::Failed
1261            } else {
1262                IntuneStatus::Unknown
1263            }
1264        }
1265        ImeSourceKind::DeviceHealthMonitoring | ImeSourceKind::Sensor => IntuneStatus::Failed,
1266        ImeSourceKind::Win32AppInventory => IntuneStatus::Success,
1267        ImeSourceKind::PrimaryIme | ImeSourceKind::Other => {
1268            if timeout_re().is_match(msg) {
1269                IntuneStatus::Timeout
1270            } else if failed_re().is_match(msg) {
1271                IntuneStatus::Failed
1272            } else if success_re().is_match(msg) {
1273                IntuneStatus::Success
1274            } else if pending_re().is_match(msg) {
1275                IntuneStatus::Pending
1276            } else {
1277                IntuneStatus::InProgress
1278            }
1279        }
1280    }
1281}
1282
1283fn build_event_name(
1284    event_type: &IntuneEventType,
1285    guid: &Option<String>,
1286    msg: &str,
1287    source_kind: ImeSourceKind,
1288) -> String {
1289    if let Some(name) = build_source_specific_name(event_type, guid, msg, source_kind) {
1290        return name;
1291    }
1292
1293    let label = match event_type {
1294        IntuneEventType::Win32App => "Win32 App",
1295        IntuneEventType::WinGetApp => "WinGet App",
1296        IntuneEventType::PowerShellScript => "PowerShell Script",
1297        IntuneEventType::Remediation => "Remediation",
1298        IntuneEventType::Esp => "ESP",
1299        IntuneEventType::SyncSession => "Sync Session",
1300        IntuneEventType::PolicyEvaluation => "Policy Evaluation",
1301        IntuneEventType::ContentDownload => "Content Download",
1302        IntuneEventType::Other => "Other",
1303    };
1304
1305    if let Some(guid) = guid {
1306        let short = short_guid(guid);
1307        format!("{label} ({short})")
1308    } else {
1309        format!("{label}: {msg}")
1310    }
1311}
1312
1313fn build_source_specific_name(
1314    event_type: &IntuneEventType,
1315    guid: &Option<String>,
1316    msg: &str,
1317    source_kind: ImeSourceKind,
1318) -> Option<String> {
1319    let short_guid = guid.as_deref().map(short_guid);
1320
1321    match source_kind {
1322        ImeSourceKind::AppWorkload => {
1323            let phase = if appworkload_stall_re().is_match(msg) {
1324                "Download Stall"
1325            } else if appworkload_retry_re().is_match(msg) {
1326                "Download Retry"
1327            } else if appworkload_hash_re().is_match(msg) {
1328                "Hash Validation"
1329            } else if appworkload_staging_re().is_match(msg) {
1330                "Staging"
1331            } else if appworkload_install_re().is_match(msg) {
1332                "Install"
1333            } else if appworkload_download_re().is_match(msg) {
1334                "Download"
1335            } else {
1336                return None;
1337            };
1338            Some(match short_guid {
1339                Some(short) => format!("AppWorkload {phase} ({short})"),
1340                None => format!("AppWorkload {phase}"),
1341            })
1342        }
1343        ImeSourceKind::AppActionProcessor => {
1344            let area = if applicability_block_re().is_match(msg) || applicability_re().is_match(msg)
1345            {
1346                "Applicability"
1347            } else if contains_case_insensitive(msg, "requirement rule") {
1348                "Requirement Rule"
1349            } else if contains_case_insensitive(msg, "detection rule") {
1350                "Detection Rule"
1351            } else if policy_eval_re().is_match(msg) {
1352                "Policy Evaluation"
1353            } else {
1354                return None;
1355            };
1356            Some(match short_guid {
1357                Some(short) => format!("AppActionProcessor {area} ({short})"),
1358                None => format!("AppActionProcessor {area}"),
1359            })
1360        }
1361        ImeSourceKind::AgentExecutor => {
1362            let area = if remediation_script_re().is_match(msg)
1363                || *event_type == IntuneEventType::Remediation
1364            {
1365                "Remediation Script"
1366            } else if detection_script_re().is_match(msg) {
1367                "Detection Script"
1368            } else if timeout_re().is_match(msg) {
1369                "Script Timeout"
1370            } else {
1371                "PowerShell Script"
1372            };
1373            Some(match short_guid {
1374                Some(short) => format!("AgentExecutor {area} ({short})"),
1375                None => format!("AgentExecutor {area}"),
1376            })
1377        }
1378        ImeSourceKind::HealthScripts => {
1379            let area = if remediation_script_re().is_match(msg) {
1380                "Remediation"
1381            } else if detection_script_re().is_match(msg)
1382                || contains_case_insensitive(msg, "compliance result")
1383            {
1384                "Detection"
1385            } else {
1386                "Schedule"
1387            };
1388            Some(match short_guid {
1389                Some(short) => format!("HealthScripts {area} ({short})"),
1390                None => format!("HealthScripts {area}"),
1391            })
1392        }
1393        ImeSourceKind::ClientHealth => {
1394            if let Some((rule, status, details)) = parse_client_health_summary(msg) {
1395                let status_label = match status {
1396                    IntuneStatus::Success => "Passed",
1397                    IntuneStatus::Failed => "Failed",
1398                    IntuneStatus::Pending => "Pending",
1399                    IntuneStatus::InProgress => "In Progress",
1400                    IntuneStatus::Timeout => "Timed Out",
1401                    IntuneStatus::Unknown => "Unknown",
1402                };
1403                let suffix = if details.eq_ignore_ascii_case("N/A") {
1404                    String::new()
1405                } else {
1406                    format!(": {}", details.chars().take(40).collect::<String>())
1407                };
1408                return Some(format!("ClientHealth Rule {status_label}: {rule}{suffix}"));
1409            }
1410            if client_health_heartbeat_failure_re().is_match(msg) {
1411                Some("ClientHealth Heartbeat Failed".to_string())
1412            } else if client_health_heartbeat_success_re().is_match(msg) {
1413                Some("ClientHealth Heartbeat Sent".to_string())
1414            } else {
1415                None
1416            }
1417        }
1418        ImeSourceKind::ClientCertCheck => {
1419            if parse_client_cert_local_machine_count(msg) == Some(0) {
1420                Some("ClientCertCheck Missing MDM Certificate".to_string())
1421            } else if client_cert_failure_re().is_match(msg) {
1422                Some("ClientCertCheck Validation Failure".to_string())
1423            } else {
1424                None
1425            }
1426        }
1427        ImeSourceKind::DeviceHealthMonitoring => {
1428            parse_device_health_app_crash(msg).map(|(app_name, exception_code)| {
1429                format!(
1430                    "DeviceHealthMonitoring App Crash: {} ({})",
1431                    app_name, exception_code
1432                )
1433            })
1434        }
1435        ImeSourceKind::Sensor => {
1436            if sensor_memory_failure_re().is_match(msg) {
1437                Some("Sensor Hardware Readiness Memory Failure".to_string())
1438            } else {
1439                None
1440            }
1441        }
1442        ImeSourceKind::Win32AppInventory => {
1443            if win32_app_inventory_full_re().is_match(msg) {
1444                Some("Win32AppInventory Full Inventory".to_string())
1445            } else if win32_app_inventory_no_change_re().is_match(msg) {
1446                Some("Win32AppInventory No Delta".to_string())
1447            } else if let Some((add, modify, delete)) = parse_win32_app_inventory_delta(msg) {
1448                Some(format!(
1449                    "Win32AppInventory Delta (+{add} ~{modify} -{delete})"
1450                ))
1451            } else {
1452                None
1453            }
1454        }
1455        ImeSourceKind::PrimaryIme | ImeSourceKind::Other => None,
1456    }
1457}
1458
1459fn parse_client_health_summary(msg: &str) -> Option<(String, IntuneStatus, String)> {
1460    let captures = client_health_rule_summary_re().captures(msg)?;
1461    let rule = captures.get(1)?.as_str().trim().to_string();
1462    let status = match captures.get(2)?.as_str().to_ascii_lowercase().as_str() {
1463        "pass" => IntuneStatus::Success,
1464        "fail" => IntuneStatus::Failed,
1465        _ => IntuneStatus::Unknown,
1466    };
1467    let details = captures.get(3)?.as_str().trim().to_string();
1468    Some((rule, status, details))
1469}
1470
1471fn parse_client_cert_local_machine_count(msg: &str) -> Option<u32> {
1472    client_cert_local_machine_count_re()
1473        .captures(msg)
1474        .and_then(|cap| cap.get(1))
1475        .and_then(|value| value.as_str().parse::<u32>().ok())
1476}
1477
1478fn parse_device_health_app_crash(msg: &str) -> Option<(String, String)> {
1479    let captures = device_health_app_crash_re().captures(msg)?;
1480    let app_name = captures.get(1)?.as_str().trim().to_string();
1481    let exception_code = captures.get(2)?.as_str().trim().to_string();
1482    Some((app_name, exception_code))
1483}
1484
1485fn parse_win32_app_inventory_delta(msg: &str) -> Option<(u32, u32, u32)> {
1486    let captures = win32_app_inventory_delta_re().captures(msg)?;
1487    let add = captures.get(1)?.as_str().parse::<u32>().ok()?;
1488    let modify = captures.get(2)?.as_str().parse::<u32>().ok()?;
1489    let delete = captures.get(3)?.as_str().parse::<u32>().ok()?;
1490    Some((add, modify, delete))
1491}
1492
1493fn short_guid(value: &str) -> &str {
1494    value
1495}
1496
1497fn contains_case_insensitive(value: &str, needle: &str) -> bool {
1498    contains_ascii_case_insensitive(value, needle)
1499}
1500
1501fn contains_any_ascii_case_insensitive(value: &str, needles: &[&str]) -> bool {
1502    needles
1503        .iter()
1504        .copied()
1505        .any(|needle| contains_ascii_case_insensitive(value, needle))
1506}
1507
1508fn contains_ascii_case_insensitive(value: &str, needle: &str) -> bool {
1509    if needle.is_empty() {
1510        return true;
1511    }
1512    if needle.len() > value.len() {
1513        return false;
1514    }
1515
1516    value
1517        .as_bytes()
1518        .windows(needle.len())
1519        .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
1520}
1521
1522fn ends_with_ascii_case_insensitive(value: &str, suffix: &str) -> bool {
1523    value
1524        .get(value.len().saturating_sub(suffix.len())..)
1525        .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix))
1526}
1527
1528fn pair_events(events: &mut Vec<IntuneEvent>) {
1529    let mut consumed_end_indices: HashSet<usize> = HashSet::new();
1530    let mut open_events: HashMap<String, Vec<usize>> = HashMap::new();
1531
1532    for index in 0..events.len() {
1533        let status = events[index].status;
1534        let Some(identity_key) = event_identity_key(&events[index]) else {
1535            continue;
1536        };
1537
1538        if status == IntuneStatus::InProgress {
1539            open_events.entry(identity_key).or_default().push(index);
1540            continue;
1541        }
1542        if !(status == IntuneStatus::Success
1543            || status == IntuneStatus::Failed
1544            || status == IntuneStatus::Timeout)
1545        {
1546            continue;
1547        }
1548
1549        let Some(start_index) = open_events
1550            .get_mut(&identity_key)
1551            .and_then(|indices| indices.pop())
1552        else {
1553            continue;
1554        };
1555        if consumed_end_indices.contains(&index) {
1556            continue;
1557        }
1558
1559        events[start_index].end_time = events[index].start_time.clone();
1560        events[start_index].status = events[index].status;
1561        events[start_index].error_code = events[index]
1562            .error_code
1563            .clone()
1564            .or_else(|| events[start_index].error_code.clone());
1565
1566        if let (Some(start), Some(end)) = (
1567            &events[start_index].start_time,
1568            &events[start_index].end_time,
1569        ) {
1570            events[start_index].duration_secs = estimate_duration(start, end);
1571        }
1572
1573        consumed_end_indices.insert(index);
1574    }
1575
1576    if consumed_end_indices.is_empty() {
1577        return;
1578    }
1579
1580    let mut index = 0usize;
1581    events.retain(|_| {
1582        let keep = !consumed_end_indices.contains(&index);
1583        index += 1;
1584        keep
1585    });
1586}
1587
1588fn event_identity_key(event: &IntuneEvent) -> Option<String> {
1589    if let Some(guid) = &event.guid {
1590        return Some(format!(
1591            "{}|{}|{}",
1592            event.source_file,
1593            event_type_identity(&event.event_type),
1594            guid
1595        ));
1596    }
1597
1598    let normalized_name = normalize_identity_fragment(&event.name);
1599    if normalized_name.is_empty() {
1600        None
1601    } else {
1602        Some(format!(
1603            "{}|{}|{}",
1604            event.source_file,
1605            event_type_identity(&event.event_type),
1606            normalized_name
1607        ))
1608    }
1609}
1610
1611fn event_type_identity(event_type: &IntuneEventType) -> &'static str {
1612    match event_type {
1613        IntuneEventType::Win32App => "win32",
1614        IntuneEventType::WinGetApp => "winget",
1615        IntuneEventType::PowerShellScript => "script",
1616        IntuneEventType::Remediation => "remediation",
1617        IntuneEventType::Esp => "esp",
1618        IntuneEventType::SyncSession => "sync",
1619        IntuneEventType::PolicyEvaluation => "policy",
1620        IntuneEventType::ContentDownload => "download",
1621        IntuneEventType::Other => "other",
1622    }
1623}
1624
1625fn normalize_identity_fragment(value: &str) -> String {
1626    value
1627        .chars()
1628        .map(|ch| {
1629            if ch.is_ascii_alphanumeric() {
1630                ch.to_ascii_lowercase()
1631            } else {
1632                ' '
1633            }
1634        })
1635        .collect::<String>()
1636        .split_whitespace()
1637        .take(6)
1638        .collect::<Vec<_>>()
1639        .join(" ")
1640}
1641
1642fn estimate_duration(start: &str, end: &str) -> Option<f64> {
1643    if let (Some(start_dt), Some(end_dt)) =
1644        (parse_event_timestamp(start), parse_event_timestamp(end))
1645    {
1646        return Some((end_dt - start_dt).num_milliseconds().abs() as f64 / 1000.0);
1647    }
1648
1649    let parse_seconds = |ts: &str| -> Option<f64> {
1650        let time_part = ts.split_whitespace().last()?;
1651        let parts: Vec<&str> = time_part.split(':').collect();
1652        if parts.len() >= 3 {
1653            let h: f64 = parts[0].parse().ok()?;
1654            let m: f64 = parts[1].parse().ok()?;
1655            let s: f64 = parts[2].parse().ok()?;
1656            Some(h * 3600.0 + m * 60.0 + s)
1657        } else {
1658            None
1659        }
1660    };
1661
1662    let start_secs = parse_seconds(start)?;
1663    let end_secs = parse_seconds(end)?;
1664    let diff = end_secs - start_secs;
1665    if diff >= 0.0 {
1666        Some(diff)
1667    } else {
1668        Some(diff + 86400.0)
1669    }
1670}
1671
1672fn parse_event_timestamp(value: &str) -> Option<chrono::DateTime<chrono::Utc>> {
1673    if let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(value) {
1674        return Some(parsed.with_timezone(&chrono::Utc));
1675    }
1676
1677    let naive = chrono::NaiveDateTime::parse_from_str(value, "%m-%d-%Y %H:%M:%S%.f").ok()?;
1678    Some(chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
1679        naive,
1680        chrono::Utc,
1681    ))
1682}
1683
1684#[cfg(test)]
1685mod tests {
1686    use super::*;
1687
1688    fn empty_registry() -> GuidRegistry {
1689        GuidRegistry::new()
1690    }
1691
1692    fn line(message: &str, timestamp: &str, line_number: u32) -> ImeLine {
1693        ImeLine {
1694            line_number,
1695            timestamp: Some(timestamp.to_string()),
1696            timestamp_utc: Some(timestamp.to_string()),
1697            message: message.to_string(),
1698            component: None,
1699        }
1700    }
1701
1702    #[test]
1703    fn extract_events_prefers_utc_normalized_timestamp() {
1704        let events = extract_events(
1705            &[ImeLine {
1706                line_number: 1,
1707                timestamp: Some("03-12-2026 11:16:42.332".to_string()),
1708                timestamp_utc: Some("2026-03-12T11:16:42.332Z".to_string()),
1709                message: "Assignment evaluation failed for app with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890".to_string(),
1710                component: None,
1711            }],
1712            "C:/Logs/AppActionProcessor.log",
1713            &empty_registry(),
1714        );
1715
1716        assert_eq!(events.len(), 1);
1717        assert_eq!(
1718            events[0].start_time.as_deref(),
1719            Some("2026-03-12T11:16:42.332Z")
1720        );
1721    }
1722
1723    #[test]
1724    fn estimate_duration_supports_iso_timestamps() {
1725        assert_eq!(
1726            estimate_duration("2026-03-12T11:16:42.332Z", "2026-03-12T11:16:47.332Z"),
1727            Some(5.0)
1728        );
1729    }
1730
1731    #[test]
1732    fn appworkload_extracts_stalled_download_events() {
1733        let events = extract_events(
1734            &[line(
1735                "AppWorkload download stalled with no progress for app id: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1736                "01-15-2024 10:00:05.000",
1737                1,
1738            )],
1739            "C:/Logs/AppWorkload.log",
1740            &empty_registry(),
1741        );
1742
1743        assert_eq!(events.len(), 1);
1744        assert_eq!(events[0].event_type, IntuneEventType::ContentDownload);
1745        assert_eq!(events[0].status, IntuneStatus::Timeout);
1746    }
1747
1748    #[test]
1749    fn app_action_processor_marks_not_applicable_as_failed() {
1750        let events = extract_events(
1751            &[line(
1752                "Assignment evaluation found app is not applicable and will not be enforced for app with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1753                "01-15-2024 10:00:05.000",
1754                1,
1755            )],
1756            "C:/Logs/AppActionProcessor.log",
1757            &empty_registry(),
1758        );
1759
1760        assert_eq!(events.len(), 1);
1761        assert_eq!(events[0].event_type, IntuneEventType::PolicyEvaluation);
1762        assert_eq!(events[0].status, IntuneStatus::Failed);
1763    }
1764
1765    #[test]
1766    fn agent_executor_extracts_remediation_timeout() {
1767        let events = extract_events(
1768            &[line(
1769                "AgentExecutor remediation script timed out for package a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1770                "01-15-2024 10:00:05.000",
1771                1,
1772            )],
1773            "C:/Logs/AgentExecutor.log",
1774            &empty_registry(),
1775        );
1776
1777        assert_eq!(events.len(), 1);
1778        assert_eq!(events[0].event_type, IntuneEventType::Remediation);
1779        assert_eq!(events[0].status, IntuneStatus::Timeout);
1780    }
1781
1782    #[test]
1783    fn agent_executor_skips_argument_parsing_noise() {
1784        let events = extract_events(
1785            &[
1786                line(
1787                    "Creating command line parser, name delimiter is - and value separator is .",
1788                    "01-15-2024 10:00:05.000",
1789                    1,
1790                ),
1791                line(
1792                    "Adding argument remediationScript with value C:\\Windows\\IMECache\\HealthScripts\\abc\\detect.ps1 to the named argument list.",
1793                    "01-15-2024 10:00:06.000",
1794                    2,
1795                ),
1796            ],
1797            "C:/Logs/AgentExecutor.log",
1798            &empty_registry(),
1799        );
1800
1801        assert!(events.is_empty());
1802    }
1803
1804    #[test]
1805    fn client_health_extracts_heartbeat_failure() {
1806        let events = extract_events(
1807            &[line(
1808                "Failed to send heartbeat report, exception = System.NullReferenceException: Object reference not set to an instance of an object.",
1809                "01-15-2024 10:00:05.000",
1810                1,
1811            )],
1812            "C:/Logs/ClientHealth.log",
1813            &empty_registry(),
1814        );
1815
1816        assert_eq!(events.len(), 1);
1817        assert_eq!(events[0].event_type, IntuneEventType::Other);
1818        assert_eq!(events[0].status, IntuneStatus::Failed);
1819        assert_eq!(events[0].name, "ClientHealth Heartbeat Failed");
1820    }
1821
1822    #[test]
1823    fn client_health_ignores_passing_rule_summaries() {
1824        let events = extract_events(
1825            &[line(
1826                "Summary: rule Verify Intune Management Extension service exists. with ID b862e7a7-fe34-47f3-a648-edd4803f781a, result = Pass, details = N/A",
1827                "01-15-2024 10:00:05.000",
1828                1,
1829            )],
1830            "C:/Logs/ClientHealth.log",
1831            &empty_registry(),
1832        );
1833
1834        assert!(events.is_empty());
1835    }
1836
1837    #[test]
1838    fn client_cert_check_detects_missing_local_machine_certificate() {
1839        let events = extract_events(
1840            &[line(
1841                "MDM certs found in LocalMachine count: 0",
1842                "01-15-2024 10:00:05.000",
1843                1,
1844            )],
1845            "C:/Logs/ClientCertCheck.log",
1846            &empty_registry(),
1847        );
1848
1849        assert_eq!(events.len(), 1);
1850        assert_eq!(events[0].event_type, IntuneEventType::Other);
1851        assert_eq!(events[0].status, IntuneStatus::Failed);
1852        assert_eq!(events[0].name, "ClientCertCheck Missing MDM Certificate");
1853    }
1854
1855    #[test]
1856    fn device_health_monitoring_extracts_app_crash_event() {
1857        let events = extract_events(
1858            &[line(
1859                "[datasensor] received application event, RecordId: 19583, 1000 , <![CDATA[<EventData xmlns=\"http://schemas.microsoft.com/win/2004/08/events/event\">\n  <Data Name=\"AppName\">SenseNdr.exe</Data>\n  <Data Name=\"ExceptionCode\">c0000409</Data>\n</EventData>]]>",
1860                "01-15-2024 10:00:05.000",
1861                1,
1862            )],
1863            "C:/Logs/DeviceHealthMonitoring.log",
1864            &empty_registry(),
1865        );
1866
1867        assert_eq!(events.len(), 1);
1868        assert_eq!(events[0].event_type, IntuneEventType::Other);
1869        assert_eq!(events[0].status, IntuneStatus::Failed);
1870        assert_eq!(
1871            events[0].name,
1872            "DeviceHealthMonitoring App Crash: SenseNdr.exe (c0000409)"
1873        );
1874    }
1875
1876    #[test]
1877    fn sensor_extracts_memory_failure() {
1878        let events = extract_events(
1879            &[line(
1880                "Win32Exception occurred. Error: 0; Message: Call to GetPhysicallyInstalledSystemMemory failed.; Stacktrace:",
1881                "01-15-2024 10:00:05.000",
1882                1,
1883            )],
1884            "C:/Logs/Sensor.log",
1885            &empty_registry(),
1886        );
1887
1888        assert_eq!(events.len(), 1);
1889        assert_eq!(events[0].event_type, IntuneEventType::Other);
1890        assert_eq!(events[0].status, IntuneStatus::Failed);
1891        assert_eq!(events[0].name, "Sensor Hardware Readiness Memory Failure");
1892    }
1893
1894    #[test]
1895    fn win32_app_inventory_extracts_non_zero_delta() {
1896        let events = extract_events(
1897            &[line(
1898                "[Win32AppInventory] Computing delta inventory...Done. Add count = 2, Modify count = 0, Delete count = 2",
1899                "01-15-2024 10:00:05.000",
1900                1,
1901            )],
1902            "C:/Logs/Win32AppInventory.log",
1903            &empty_registry(),
1904        );
1905
1906        assert_eq!(events.len(), 1);
1907        assert_eq!(events[0].event_type, IntuneEventType::Other);
1908        assert_eq!(events[0].status, IntuneStatus::Success);
1909        assert_eq!(events[0].name, "Win32AppInventory Delta (+2 ~0 -2)");
1910    }
1911
1912    #[test]
1913    fn win32_app_inventory_ignores_no_user_skip_noise() {
1914        let events = extract_events(
1915            &[line(
1916                "[Win32AppInventory] OnAppInventoryCollecting There is no any AAD User logged in, skip this round of inventory collection.",
1917                "01-15-2024 10:00:05.000",
1918                1,
1919            )],
1920            "C:/Logs/Win32AppInventory.log",
1921            &empty_registry(),
1922        );
1923
1924        assert!(events.is_empty());
1925    }
1926
1927    #[test]
1928    fn paired_completion_events_are_collapsed() {
1929        let events = extract_events(
1930            &[
1931                line(
1932                    "[Win32App] Processing app with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1933                    "01-15-2024 10:00:00.000",
1934                    1,
1935                ),
1936                line(
1937                    "[Win32App] Completed successfully for app with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1938                    "01-15-2024 10:01:00.000",
1939                    2,
1940                ),
1941            ],
1942            "C:/Logs/IntuneManagementExtension.log",
1943            &empty_registry(),
1944        );
1945
1946        assert_eq!(events.len(), 1);
1947        assert_eq!(events[0].status, IntuneStatus::Success);
1948        assert_eq!(events[0].duration_secs, Some(60.0));
1949    }
1950
1951    #[test]
1952    fn appworkload_request_payload_events_are_paired() {
1953        let events = extract_events(
1954            &[
1955                line(
1956                    r#"Starting content download RequestPayload: {\"AppId\":\"a1b2c3d4-e5f6-7890-abcd-ef1234567890\",\"ApplicationName\":\"Contoso App\"}"#,
1957                    "01-15-2024 10:00:00.000",
1958                    1,
1959                ),
1960                line(
1961                    r#"Download completed successfully RequestPayload: {\"AppId\":\"a1b2c3d4-e5f6-7890-abcd-ef1234567890\",\"ApplicationName\":\"Contoso App\"}"#,
1962                    "01-15-2024 10:00:05.000",
1963                    2,
1964                ),
1965            ],
1966            "C:/Logs/AppWorkload.log",
1967            &empty_registry(),
1968        );
1969
1970        assert_eq!(events.len(), 1);
1971        assert_eq!(events[0].event_type, IntuneEventType::ContentDownload);
1972        assert_eq!(events[0].status, IntuneStatus::Success);
1973        assert_eq!(
1974            events[0].guid.as_deref(),
1975            Some("a1b2c3d4-e5f6-7890-abcd-ef1234567890")
1976        );
1977        assert_eq!(events[0].duration_secs, Some(5.0));
1978    }
1979
1980    #[test]
1981    fn appworkload_failed_events_include_guid_context() {
1982        let events = extract_events(
1983            &[
1984                line(
1985                    "[Win32App][ReportingManager] App with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890 has been loaded.",
1986                    "01-15-2024 10:00:00.000",
1987                    10,
1988                ),
1989                line(
1990                    "[Win32App][V3Processor] Processing subgraph with app ids: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
1991                    "01-15-2024 10:00:01.000",
1992                    11,
1993                ),
1994                line(
1995                    "Download failed for app id: a1b2c3d4-e5f6-7890-abcd-ef1234567890 with error code = 0x87D30067",
1996                    "01-15-2024 10:00:02.000",
1997                    12,
1998                ),
1999                line(
2000                    "[Win32App][V3Processor] Done processing subgraph.",
2001                    "01-15-2024 10:00:03.000",
2002                    13,
2003                ),
2004            ],
2005            "C:/Logs/AppWorkload.log",
2006            &empty_registry(),
2007        );
2008
2009        assert_eq!(events.len(), 1);
2010        assert_eq!(events[0].status, IntuneStatus::Failed);
2011        assert!(events[0].detail.contains("AppWorkload context:"));
2012        assert!(events[0].detail.contains("L10 01-15-2024 10:00:00.000"));
2013        assert!(events[0].detail.contains("L11 01-15-2024 10:00:01.000"));
2014        assert!(events[0].detail.contains("> L12 01-15-2024 10:00:02.000"));
2015        assert!(events[0].detail.contains("L13 01-15-2024 10:00:03.000"));
2016    }
2017
2018    #[test]
2019    fn appworkload_success_events_keep_single_line_detail() {
2020        let message =
2021            "Download completed successfully for app id: a1b2c3d4-e5f6-7890-abcd-ef1234567890";
2022        let events = extract_events(
2023            &[line(message, "01-15-2024 10:00:05.000", 20)],
2024            "C:/Logs/AppWorkload.log",
2025            &empty_registry(),
2026        );
2027
2028        assert_eq!(events.len(), 1);
2029        assert_eq!(events[0].status, IntuneStatus::Success);
2030        assert_eq!(events[0].detail, message);
2031    }
2032}