Skip to main content

cmtraceopen_parser/intune/
models.rs

1use std::collections::HashMap;
2
3use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
4
5use super::guid_registry::GuidRegistryEntry;
6
7/// Artifact count summary retained from an evidence bundle manifest.
8#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
9#[serde(rename_all = "camelCase")]
10pub struct EvidenceBundleArtifactCounts {
11    pub collected: u64,
12    pub missing: u64,
13    pub failed: u64,
14    pub skipped: u64,
15}
16
17/// Metadata retained when Intune analysis is sourced from a collected evidence bundle.
18#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
19#[serde(rename_all = "camelCase")]
20pub struct EvidenceBundleMetadata {
21    pub manifest_path: String,
22    pub notes_path: Option<String>,
23    pub evidence_root: Option<String>,
24    #[serde(default)]
25    pub primary_entry_points: Vec<String>,
26    #[serde(default)]
27    pub available_primary_entry_points: Vec<String>,
28    pub bundle_id: Option<String>,
29    pub bundle_label: Option<String>,
30    pub created_utc: Option<String>,
31    pub case_reference: Option<String>,
32    pub summary: Option<String>,
33    pub collector_profile: Option<String>,
34    pub collector_version: Option<String>,
35    pub collected_utc: Option<String>,
36    pub device_name: Option<String>,
37    pub primary_user: Option<String>,
38    pub platform: Option<String>,
39    pub os_version: Option<String>,
40    pub tenant: Option<String>,
41    pub artifact_counts: Option<EvidenceBundleArtifactCounts>,
42}
43
44/// Severity level for generated diagnostic guidance.
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46pub enum IntuneDiagnosticSeverity {
47    Info,
48    Warning,
49    Error,
50}
51
52/// Diagnostic category used to group related remediation guidance.
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
54pub enum IntuneDiagnosticCategory {
55    Download,
56    Install,
57    Timeout,
58    Script,
59    Policy,
60    State,
61    General,
62}
63
64/// Priority used to order remediation guidance.
65#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
66pub enum IntuneRemediationPriority {
67    Monitor,
68    Medium,
69    High,
70    Immediate,
71}
72
73/// Deterministic diagnostic guidance derived from Intune analysis results.
74#[derive(Debug, Clone, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76pub struct IntuneDiagnosticInsight {
77    pub id: String,
78    pub severity: IntuneDiagnosticSeverity,
79    pub category: IntuneDiagnosticCategory,
80    pub remediation_priority: IntuneRemediationPriority,
81    pub title: String,
82    pub summary: String,
83    pub likely_cause: Option<String>,
84    pub evidence: Vec<String>,
85    pub next_checks: Vec<String>,
86    #[serde(default)]
87    pub suggested_fixes: Vec<String>,
88    #[serde(default)]
89    pub focus_areas: Vec<String>,
90    #[serde(default)]
91    pub affected_source_files: Vec<String>,
92    #[serde(default)]
93    pub related_error_codes: Vec<String>,
94}
95
96/// Type of Intune event detected from log analysis.
97#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
98pub enum IntuneEventType {
99    Win32App,
100    WinGetApp,
101    PowerShellScript,
102    Remediation,
103    Esp,
104    SyncSession,
105    PolicyEvaluation,
106    ContentDownload,
107    Other,
108}
109
110/// Status of an Intune operation.
111#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
112pub enum IntuneStatus {
113    Success,
114    Failed,
115    InProgress,
116    Pending,
117    Timeout,
118    Unknown,
119}
120
121/// A single Intune event extracted from log analysis.
122#[derive(Debug, Clone, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124pub struct IntuneEvent {
125    /// Unique identifier for this event
126    pub id: u64,
127    /// Event type category
128    pub event_type: IntuneEventType,
129    /// Display name (resolved from GUID or extracted from context)
130    pub name: String,
131    /// GUID identifier if available
132    pub guid: Option<String>,
133    /// Status of the operation
134    pub status: IntuneStatus,
135    /// Timestamp of event start (ISO 8601 string)
136    pub start_time: Option<String>,
137    /// Timestamp of event end (ISO 8601 string)
138    pub end_time: Option<String>,
139    /// Duration in seconds
140    pub duration_secs: Option<f64>,
141    /// Error code if failed
142    pub error_code: Option<String>,
143    /// Additional detail message
144    pub detail: String,
145    /// Source log file path
146    pub source_file: String,
147    /// Line number in source file
148    pub line_number: u32,
149    /// Start time as milliseconds since Unix epoch (pre-computed for fast frontend sorting)
150    pub start_time_epoch: Option<i64>,
151    /// End time as milliseconds since Unix epoch (pre-computed for fast frontend sorting)
152    pub end_time_epoch: Option<i64>,
153    /// Decoded PowerShell script body (for script detection events)
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub script_body: Option<String>,
156    /// GUID of the parent Win32App this script detection belongs to
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub parent_app_guid: Option<String>,
159}
160
161impl IntuneEvent {
162    /// Is this event in a failed state?
163    pub fn status_is_failed(&self) -> bool {
164        matches!(self.status, IntuneStatus::Failed)
165    }
166
167    /// Start time as epoch milliseconds, if known.
168    pub fn start_time_epoch_ms(&self) -> Option<i64> {
169        self.start_time_epoch
170    }
171
172    /// GUID anchoring this event (app/policy ID), if known.
173    pub fn anchor_guid(&self) -> Option<&str> {
174        self.guid.as_deref()
175    }
176
177    /// Human-readable display label (app/script name).
178    pub fn display_name(&self) -> Option<&str> {
179        if self.name.is_empty() {
180            None
181        } else {
182            Some(self.name.as_str())
183        }
184    }
185
186    /// Short label describing the kind of Intune operation this event represents.
187    pub fn event_kind_label(&self) -> Option<&str> {
188        Some(match self.event_type {
189            IntuneEventType::Win32App => "App Install",
190            IntuneEventType::WinGetApp => "WinGet Install",
191            IntuneEventType::PowerShellScript => "Script",
192            IntuneEventType::Remediation => "Remediation",
193            IntuneEventType::Esp => "ESP",
194            IntuneEventType::SyncSession => "Sync",
195            IntuneEventType::PolicyEvaluation => "Policy",
196            IntuneEventType::ContentDownload => "Download",
197            IntuneEventType::Other => "Operation",
198        })
199    }
200}
201
202/// Metadata for an app policy extracted from "Get policies" JSON payloads.
203#[derive(Debug, Clone, Serialize, Deserialize)]
204#[serde(rename_all = "camelCase")]
205pub struct AppPolicyMetadata {
206    pub id: String,
207    pub name: String,
208    pub intent: Option<i32>,
209    pub target_type: Option<i32>,
210    pub install_command_line: Option<String>,
211    pub uninstall_command_line: Option<String>,
212    pub detection_rules: Vec<DetectionRuleMetadata>,
213    pub return_codes: Vec<ReturnCodeEntry>,
214    pub requirement_rules: Option<String>,
215    pub install_behavior: Option<i32>,
216}
217
218/// A single detection rule from app policy metadata.
219#[derive(Debug, Clone, Serialize, Deserialize)]
220#[serde(rename_all = "camelCase")]
221pub struct DetectionRuleMetadata {
222    /// 0=Registry, 1=MSI, 2=File, 3=Script
223    pub detection_type: i32,
224    /// Base64-decoded PowerShell script (type 3 only)
225    #[serde(skip_serializing_if = "Option::is_none")]
226    pub script_body: Option<String>,
227    #[serde(skip_serializing_if = "Option::is_none")]
228    pub enforce_signature_check: Option<bool>,
229    #[serde(skip_serializing_if = "Option::is_none")]
230    pub run_as_32_bit: Option<bool>,
231}
232
233/// A return code mapping from app policy metadata.
234#[derive(Debug, Clone, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct ReturnCodeEntry {
237    pub return_code: i32,
238    /// 0=Failed, 1=Success, 2=SoftReboot, 3=HardReboot, 4=Retry
239    #[serde(rename = "type")]
240    pub code_type: i32,
241}
242
243/// Download statistics for a content download event.
244#[derive(Debug, Clone, Serialize, Deserialize)]
245#[serde(rename_all = "camelCase")]
246pub struct DownloadStat {
247    /// Name or ID of the content
248    pub content_id: String,
249    /// Display name
250    pub name: String,
251    /// Total size in bytes
252    pub size_bytes: u64,
253    /// Download speed in bytes per second
254    pub speed_bps: f64,
255    /// Percentage downloaded via Delivery Optimization
256    pub do_percentage: f64,
257    /// Download duration in seconds
258    pub duration_secs: f64,
259    /// Whether download succeeded
260    pub success: bool,
261    /// Timestamp
262    pub timestamp: Option<String>,
263    /// Timestamp as milliseconds since Unix epoch (pre-computed for fast frontend sorting)
264    pub timestamp_epoch: Option<i64>,
265}
266
267/// Inclusive timestamp bounds captured from analyzed content.
268#[derive(Debug, Clone, Serialize, Deserialize, Default)]
269#[serde(rename_all = "camelCase")]
270pub struct IntuneTimestampBounds {
271    pub first_timestamp: Option<String>,
272    pub last_timestamp: Option<String>,
273}
274
275/// Coverage metrics for a single analyzed source file.
276#[derive(Debug, Clone, Serialize, Deserialize, Default)]
277#[serde(rename_all = "camelCase")]
278pub struct IntuneDiagnosticsFileCoverage {
279    pub file_path: String,
280    pub event_count: u32,
281    pub download_count: u32,
282    pub timestamp_bounds: Option<IntuneTimestampBounds>,
283    #[serde(default)]
284    pub is_rotated_segment: bool,
285    pub rotation_group: Option<String>,
286}
287
288/// Summary of which files and time ranges contributed to diagnostics.
289#[derive(Debug, Clone, Serialize, Deserialize, Default)]
290#[serde(rename_all = "camelCase")]
291pub struct IntuneDiagnosticsCoverage {
292    #[serde(default)]
293    pub files: Vec<IntuneDiagnosticsFileCoverage>,
294    pub timestamp_bounds: Option<IntuneTimestampBounds>,
295    #[serde(default)]
296    pub has_rotated_logs: bool,
297    pub dominant_source: Option<IntuneDominantSource>,
298}
299
300/// Primary source contributing to the current diagnostics result.
301#[derive(Debug, Clone, Serialize, Deserialize, Default)]
302#[serde(rename_all = "camelCase")]
303pub struct IntuneDominantSource {
304    pub file_path: String,
305    pub event_count: u32,
306    pub event_share: Option<f64>,
307}
308
309/// Confidence bucket for the generated diagnostics result.
310#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
311pub enum IntuneDiagnosticsConfidenceLevel {
312    #[default]
313    Unknown,
314    Low,
315    Medium,
316    High,
317}
318
319/// Confidence metadata for the generated diagnostics result.
320#[derive(Debug, Clone, Serialize, Deserialize, Default)]
321#[serde(rename_all = "camelCase")]
322pub struct IntuneDiagnosticsConfidence {
323    pub level: IntuneDiagnosticsConfidenceLevel,
324    pub score: Option<f64>,
325    #[serde(default)]
326    pub reasons: Vec<String>,
327}
328
329/// Grouped repeated failures for follow-on diagnostics phases.
330#[derive(Debug, Clone, Serialize, Deserialize)]
331#[serde(rename_all = "camelCase")]
332pub struct IntuneRepeatedFailureGroup {
333    pub id: String,
334    pub name: String,
335    pub event_type: IntuneEventType,
336    pub error_code: Option<String>,
337    pub occurrences: u32,
338    pub timestamp_bounds: Option<IntuneTimestampBounds>,
339    #[serde(default)]
340    pub source_files: Vec<String>,
341    #[serde(default)]
342    pub sample_event_ids: Vec<u64>,
343}
344
345// ---------------------------------------------------------------------------
346// Windows Event Log (EVTX) models
347// ---------------------------------------------------------------------------
348
349/// Severity level from a Windows Event Log record (`System.Level`).
350#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
351pub enum EventLogSeverity {
352    Critical,
353    Error,
354    Warning,
355    Information,
356    Verbose,
357    Unknown,
358}
359
360impl EventLogSeverity {
361    /// Map the numeric `Level` value from an EVTX record to a severity.
362    pub fn from_level(level: u8) -> Self {
363        match level {
364            1 => Self::Critical,
365            2 => Self::Error,
366            3 => Self::Warning,
367            4 => Self::Information,
368            5 => Self::Verbose,
369            _ => Self::Unknown,
370        }
371    }
372
373    pub fn is_error_or_warning(&self) -> bool {
374        matches!(self, Self::Critical | Self::Error | Self::Warning)
375    }
376}
377
378/// Typed Windows Event Log channel corresponding to the curated channels
379/// collected by the evidence profile.
380#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
381pub enum EventLogChannel {
382    DeviceManagementAdmin,
383    DeviceManagementOperational,
384    Autopilot,
385    AadOperational,
386    DeliveryOptimizationOperational,
387    ManagementService,
388    ProvisioningDiagnosticsAdmin,
389    ShellCoreOperational,
390    TimeServiceOperational,
391    UserDeviceRegistrationAdmin,
392    CryptoDpapiOperational,
393    KerberosOperational,
394    SystemLog,
395    Other(String),
396}
397
398impl EventLogChannel {
399    /// Map the full channel name string from an EVTX record to a typed variant.
400    pub fn from_channel_string(raw: &str) -> Self {
401        let lower = raw.to_ascii_lowercase();
402        if lower.contains("devicemanagement")
403            && lower.contains("/admin")
404            && !lower.contains("/operational")
405        {
406            Self::DeviceManagementAdmin
407        } else if lower.contains("devicemanagement") && lower.contains("/operational") {
408            Self::DeviceManagementOperational
409        } else if lower.contains("moderndeployment") && lower.contains("autopilot") {
410            Self::Autopilot
411        } else if lower.contains("-aad/operational") {
412            Self::AadOperational
413        } else if lower.contains("deliveryoptimization") && lower.contains("/operational") {
414            Self::DeliveryOptimizationOperational
415        } else if lower.contains("moderndeployment") && lower.contains("managementservice") {
416            Self::ManagementService
417        } else if lower.contains("provisioning-diagnostics") && lower.contains("/admin") {
418            Self::ProvisioningDiagnosticsAdmin
419        } else if lower.contains("shell-core") && lower.contains("/operational") {
420            Self::ShellCoreOperational
421        } else if lower.contains("time-service") && lower.contains("/operational") {
422            Self::TimeServiceOperational
423        } else if lower.contains("user device registration") && lower.contains("/admin") {
424            Self::UserDeviceRegistrationAdmin
425        } else if lower.contains("crypto-dpapi") && lower.contains("/operational") {
426            Self::CryptoDpapiOperational
427        } else if lower.contains("kerberos") && lower.contains("/operational") {
428            Self::KerberosOperational
429        } else if lower == "system" || lower.contains("system log") {
430            Self::SystemLog
431        } else if raw.is_empty() {
432            Self::Other("Unknown".to_string())
433        } else {
434            Self::Other(raw.to_string())
435        }
436    }
437
438    /// Short display name for UI badges and labels.
439    pub fn display_name(&self) -> &str {
440        match self {
441            Self::DeviceManagementAdmin => "MDM Admin",
442            Self::DeviceManagementOperational => "MDM Operational",
443            Self::Autopilot => "Autopilot",
444            Self::AadOperational => "AAD Operational",
445            Self::DeliveryOptimizationOperational => "DO Operational",
446            Self::ManagementService => "Management Service",
447            Self::ProvisioningDiagnosticsAdmin => "Provisioning Admin",
448            Self::ShellCoreOperational => "Shell Core",
449            Self::TimeServiceOperational => "Time Service",
450            Self::UserDeviceRegistrationAdmin => "User Device Reg",
451            Self::CryptoDpapiOperational => "Crypto DPAPI",
452            Self::KerberosOperational => "Kerberos",
453            Self::SystemLog => "System",
454            Self::Other(name) => name.as_str(),
455        }
456    }
457}
458
459/// A single parsed record from a Windows Event Log (.evtx) file.
460#[derive(Debug, Clone, Serialize, Deserialize)]
461#[serde(rename_all = "camelCase")]
462pub struct EventLogEntry {
463    /// Sequential ID across all parsed entries (chronological after sorting).
464    pub id: u64,
465    /// Typed channel enum.
466    pub channel: EventLogChannel,
467    /// Human-readable channel display name.
468    pub channel_display: String,
469    /// Provider name from `System.Provider`.
470    pub provider: String,
471    /// Windows Event ID.
472    pub event_id: u32,
473    /// Severity mapped from `System.Level`.
474    pub severity: EventLogSeverity,
475    /// ISO 8601 UTC timestamp.
476    pub timestamp: String,
477    /// Computer name from `System.Computer`.
478    pub computer: Option<String>,
479    /// Extracted message from EventData/UserData.
480    pub message: String,
481    /// Correlation activity ID from `System.Correlation`.
482    pub correlation_activity_id: Option<String>,
483    /// Path to the .evtx source file.
484    pub source_file: String,
485}
486
487/// Per-channel summary rollup for the UI.
488#[derive(Debug, Clone, Serialize, Deserialize)]
489#[serde(rename_all = "camelCase")]
490pub struct EventLogChannelSummary {
491    pub channel: EventLogChannel,
492    pub channel_display: String,
493    pub entry_count: u32,
494    pub error_count: u32,
495    pub warning_count: u32,
496    pub timestamp_bounds: Option<IntuneTimestampBounds>,
497    pub source_file: String,
498}
499
500/// The kind of deterministic correlation between an event log entry
501/// and an IME-derived Intune event or diagnostic.
502#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
503pub enum EventLogCorrelationKind {
504    /// Temporal proximity within a contextually relevant channel.
505    TimeWindowChannelMatch,
506    /// Error code from an IME event appears in the event log message.
507    ErrorCodeMatch,
508    /// Enrollment/registration activity near ESP or sync events.
509    EnrollmentContextMatch,
510}
511
512/// A deterministic link between an event log entry and an IME event or diagnostic.
513#[derive(Debug, Clone, Serialize, Deserialize)]
514#[serde(rename_all = "camelCase")]
515pub struct EventLogCorrelationLink {
516    /// Points to `EventLogEntry.id`.
517    pub event_log_entry_id: u64,
518    /// Points to `IntuneEvent.id` when this is an event-level link.
519    pub linked_intune_event_id: Option<u64>,
520    /// Points to `IntuneDiagnosticInsight.id` when this is a diagnostic-level link.
521    pub linked_diagnostic_id: Option<String>,
522    /// Which correlation strategy produced this link.
523    pub correlation_kind: EventLogCorrelationKind,
524    /// Time gap in seconds between the linked items (for display/sorting).
525    pub time_delta_secs: Option<f64>,
526}
527
528/// Source category for the current event log analysis payload.
529#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
530pub enum EventLogAnalysisSource {
531    #[default]
532    Bundle,
533    Live,
534}
535
536/// Per-channel outcome status for a live Windows Event Log query.
537#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
538pub enum EventLogLiveQueryStatus {
539    #[default]
540    Success,
541    Empty,
542    Failed,
543}
544
545/// Per-channel metadata retained for a live Windows Event Log query attempt.
546#[derive(Debug, Clone, Serialize, Deserialize)]
547#[serde(rename_all = "camelCase")]
548pub struct EventLogLiveQueryChannelResult {
549    pub channel: EventLogChannel,
550    pub channel_display: String,
551    pub channel_path: String,
552    pub source_file: String,
553    pub status: EventLogLiveQueryStatus,
554    pub entry_count: u32,
555    pub error_message: Option<String>,
556}
557
558/// Live Windows Event Log query summary for UI status and empty-state behavior.
559#[derive(Debug, Clone, Serialize, Deserialize, Default)]
560#[serde(rename_all = "camelCase")]
561pub struct EventLogLiveQueryMetadata {
562    pub attempted_channel_count: u32,
563    pub successful_channel_count: u32,
564    pub channels_with_results_count: u32,
565    pub failed_channel_count: u32,
566    pub per_channel_entry_limit: u32,
567    #[serde(default)]
568    pub channels: Vec<EventLogLiveQueryChannelResult>,
569}
570
571/// Top-level container for all parsed and correlated Windows Event Log data.
572#[derive(Debug, Clone, Serialize, Deserialize, Default)]
573#[serde(rename_all = "camelCase")]
574pub struct EventLogAnalysis {
575    pub source_kind: EventLogAnalysisSource,
576    pub entries: Vec<EventLogEntry>,
577    pub channel_summaries: Vec<EventLogChannelSummary>,
578    pub correlation_links: Vec<EventLogCorrelationLink>,
579    pub parsed_file_count: u32,
580    pub total_entry_count: u32,
581    pub error_entry_count: u32,
582    pub warning_entry_count: u32,
583    pub timestamp_bounds: Option<IntuneTimestampBounds>,
584    pub live_query: Option<EventLogLiveQueryMetadata>,
585}
586
587// ---------------------------------------------------------------------------
588// Intune analysis result
589// ---------------------------------------------------------------------------
590
591/// Complete result of Intune log analysis.
592#[derive(Debug, Clone, Deserialize)]
593#[serde(rename_all = "camelCase")]
594pub struct IntuneAnalysisResult {
595    /// All detected events
596    pub events: Vec<IntuneEvent>,
597    /// Download statistics
598    pub downloads: Vec<DownloadStat>,
599    /// Summary counts
600    pub summary: IntuneSummary,
601    /// Deterministic diagnostic guidance.
602    #[serde(default)]
603    pub diagnostics: Vec<IntuneDiagnosticInsight>,
604    /// Source path analyzed (file path or directory path)
605    pub source_file: String,
606    /// Expanded source files included in this result.
607    #[serde(default)]
608    pub source_files: Vec<String>,
609    /// Coverage metadata behind the diagnostics contract.
610    #[serde(default)]
611    pub diagnostics_coverage: IntuneDiagnosticsCoverage,
612    /// Confidence metadata behind the diagnostics contract.
613    #[serde(default)]
614    pub diagnostics_confidence: IntuneDiagnosticsConfidence,
615    /// Grouped repeated failures behind the diagnostics contract.
616    #[serde(default)]
617    pub repeated_failures: Vec<IntuneRepeatedFailureGroup>,
618    /// Bundle metadata retained when the analyzed path is an evidence bundle root.
619    #[serde(default)]
620    pub evidence_bundle: Option<EvidenceBundleMetadata>,
621    /// Parsed and correlated Windows Event Log data from evidence bundle .evtx files.
622    #[serde(default)]
623    pub event_log_analysis: Option<EventLogAnalysis>,
624    /// Global GUID→app-name registry for frontend display (tooltips, lookup panel).
625    #[serde(default)]
626    pub guid_registry: HashMap<String, GuidRegistryEntry>,
627    /// Per-app policy metadata extracted from "Get policies" JSON payloads.
628    #[serde(default)]
629    pub policy_metadata: HashMap<String, AppPolicyMetadata>,
630}
631
632impl Serialize for IntuneAnalysisResult {
633    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
634    where
635        S: Serializer,
636    {
637        let mut state = serializer.serialize_struct("IntuneAnalysisResult", 13)?;
638        state.serialize_field("events", &self.events)?;
639        state.serialize_field("downloads", &self.downloads)?;
640        state.serialize_field("summary", &self.summary)?;
641        state.serialize_field("diagnostics", &self.diagnostics)?;
642        state.serialize_field("sourceFile", &self.source_file)?;
643        state.serialize_field("sourceFiles", &self.source_files)?;
644        state.serialize_field("diagnosticsCoverage", &self.diagnostics_coverage)?;
645        state.serialize_field("diagnosticsConfidence", &self.diagnostics_confidence)?;
646        state.serialize_field("repeatedFailures", &self.repeated_failures)?;
647        state.serialize_field("evidenceBundle", &self.evidence_bundle)?;
648        state.serialize_field("eventLogAnalysis", &self.event_log_analysis)?;
649        state.serialize_field("guidRegistry", &self.guid_registry)?;
650        state.serialize_field("policyMetadata", &self.policy_metadata)?;
651        state.end()
652    }
653}
654
655/// Summary statistics from Intune analysis.
656#[derive(Debug, Clone, Serialize, Deserialize)]
657#[serde(rename_all = "camelCase")]
658pub struct IntuneSummary {
659    pub total_events: u32,
660    pub win32_apps: u32,
661    pub winget_apps: u32,
662    pub scripts: u32,
663    pub remediations: u32,
664    pub succeeded: u32,
665    pub failed: u32,
666    pub in_progress: u32,
667    pub pending: u32,
668    pub timed_out: u32,
669    pub total_downloads: u32,
670    pub successful_downloads: u32,
671    pub failed_downloads: u32,
672    pub failed_scripts: u32,
673    pub log_time_span: Option<String>,
674}
675
676#[cfg(test)]
677mod tests {
678    use std::collections::HashMap;
679
680    use super::{
681        EvidenceBundleArtifactCounts, EvidenceBundleMetadata, IntuneAnalysisResult,
682        IntuneDiagnosticsConfidence, IntuneDiagnosticsCoverage, IntuneSummary,
683    };
684
685    #[test]
686    fn intune_analysis_result_serializes_evidence_bundle_metadata() {
687        let result = IntuneAnalysisResult {
688            events: Vec::new(),
689            downloads: Vec::new(),
690            summary: IntuneSummary {
691                total_events: 0,
692                win32_apps: 0,
693                winget_apps: 0,
694                scripts: 0,
695                remediations: 0,
696                succeeded: 0,
697                failed: 0,
698                in_progress: 0,
699                pending: 0,
700                timed_out: 0,
701                total_downloads: 0,
702                successful_downloads: 0,
703                failed_downloads: 0,
704                failed_scripts: 0,
705                log_time_span: None,
706            },
707            diagnostics: Vec::new(),
708            source_file: "bundle-root".to_string(),
709            source_files: Vec::new(),
710            diagnostics_coverage: IntuneDiagnosticsCoverage::default(),
711            diagnostics_confidence: IntuneDiagnosticsConfidence::default(),
712            repeated_failures: Vec::new(),
713            event_log_analysis: None,
714            guid_registry: HashMap::new(),
715            policy_metadata: HashMap::new(),
716            evidence_bundle: Some(EvidenceBundleMetadata {
717                manifest_path: "bundle-root/manifest.json".to_string(),
718                notes_path: Some("bundle-root/notes.md".to_string()),
719                evidence_root: Some("bundle-root/evidence".to_string()),
720                primary_entry_points: vec!["bundle-root/evidence/logs".to_string()],
721                available_primary_entry_points: vec!["bundle-root/evidence/logs".to_string()],
722                bundle_id: Some("CMTRACE-123".to_string()),
723                bundle_label: Some("intune-endpoint-evidence".to_string()),
724                created_utc: Some("2026-03-12T16:00:54Z".to_string()),
725                case_reference: Some("case-123".to_string()),
726                summary: Some("Collected bundle".to_string()),
727                collector_profile: Some("intune-windows-endpoint-v1".to_string()),
728                collector_version: Some("1.1.0".to_string()),
729                collected_utc: Some("2026-03-12T16:00:54Z".to_string()),
730                device_name: Some("GELL-VM-5879648".to_string()),
731                primary_user: Some("AzureAD\\AdamGell".to_string()),
732                platform: Some("Windows".to_string()),
733                os_version: Some("Windows 11".to_string()),
734                tenant: Some("CDWWorkspaceLab".to_string()),
735                artifact_counts: Some(EvidenceBundleArtifactCounts {
736                    collected: 55,
737                    missing: 7,
738                    failed: 2,
739                    skipped: 0,
740                }),
741            }),
742        };
743
744        let value = serde_json::to_value(&result).expect("serialize result");
745
746        assert_eq!(
747            value["evidenceBundle"]["bundleId"].as_str(),
748            Some("CMTRACE-123")
749        );
750        assert_eq!(
751            value["evidenceBundle"]["artifactCounts"]["collected"].as_u64(),
752            Some(55)
753        );
754    }
755}