This repository has been archived on 2026-09-16. You can view files and clone it, but cannot push or open issues or pull requests.
typst_reporter/diagnostics-normalize.typ

653 lines
32 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Pure-Typst normalizer for WinDiagnostics schema_version 1 JSON reports.
//
// The collector now emits structured JSON. This file intentionally does not
// reconstruct tables or parse presentation text. It only performs reporting
// work: classification, correlation, scoring, evidence selection and shaping
// the collector schema for diagnostics-model.typ.
// The legacy converter used snake_case for CIM fields; native JSON preserves case.
#let get(dict, key, default) = {
if type(dict) != dictionary { default } else {
let matched = if key in dict { key } else {
dict.keys().find(candidate => lower(candidate.replace("_", "")) == lower(key.replace("_", "")))
}
if matched == none or dict.at(matched) == none { default } else { dict.at(matched) }
}
}
#let enabled(value) = value == true or value == 1
#let legacy-incomplete(report, name) = {
let value = get(get(report, "sections", (:)), name, (:))
get(report, "legacy", none) != none and (
name == "" or name == "storage" or
get(value, "data", ()).any(item => get(item, "text", none) != none)
)
}
#let first(values, default: (:)) = {
if values == none or values.len() == 0 { default } else { values.at(0) }
}
#let section(report, name) = {
let sections = get(report, "sections", (:))
get(sections, name, (status: "missing", count: 0, data: (), error: none))
}
#let section-data(report, name) = get(section(report, name), "data", ()).filter(item => get(item, "text", none) == none)
#let section-first(report, name) = first(section-data(report, name))
#let section-count(report, name) = if legacy-incomplete(report, name) { "Unavailable" } else { get(section(report, name), "count", 0) }
#let section-status(report, name) = get(section(report, name), "status", "missing")
#let number(value, default: 0.0) = {
if value == none { default }
else if type(value) == int or type(value) == float { value }
else {
let found = str(value).replace(",", ".").match(regex("-?\\d+(?:\\.\\d+)?"))
if found == none { default } else { float(found.text) }
}
}
#let bool-text(value) = if value == true { "Yes" } else if value == false { "No" } else { str(value) }
#let is-leap-year(year) = calc.rem(year, 4) == 0 and (calc.rem(year, 100) != 0 or calc.rem(year, 400) == 0)
#let date-index(year, month, day) = {
let before-month = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
let completed-year = year - 1
365 * completed-year + int(calc.floor(completed-year / 4)) - int(calc.floor(completed-year / 100)) + int(calc.floor(completed-year / 400)) + before-month.at(month - 1) + day + if month > 2 and is-leap-year(year) { 1 } else { 0 }
}
#let datetime-day(value) = {
let text = str(value)
let iso = text.match(regex("^(\\d{4})-(\\d{2})-(\\d{2})"))
if iso != none {
date-index(int(iso.captures.at(0)), int(iso.captures.at(1)), int(iso.captures.at(2)))
} else {
// Windows PowerShell 5.1 may serialize DateTime values as /Date(ms)/.
let ms = text.match(regex("^/Date\\((-?\\d+)"))
if ms == none { none } else {
date-index(1970, 1, 1) + int(calc.floor(float(ms.captures.at(0)) / 86400000))
}
}
}
#let datetime-second(value) = {
let text = str(value)
let day = datetime-day(text)
if day == none { none } else {
let iso-clock = text.match(regex("T(\\d{2}):(\\d{2}):(\\d{2})"))
if iso-clock != none {
let offset = text.match(regex("([+-])(\\d{2}):(\\d{2})$"))
let shift = if offset == none { 0 } else { (if offset.captures.at(0) == "-" { -1 } else { 1 }) * (int(offset.captures.at(1)) * 3600 + int(offset.captures.at(2)) * 60) }
(day - date-index(1970, 1, 1)) * 86400 + int(iso-clock.captures.at(0)) * 3600 + int(iso-clock.captures.at(1)) * 60 + int(iso-clock.captures.at(2)) - shift
} else {
let ms = text.match(regex("^/Date\\((-?\\d+)"))
if ms == none { none } else { int(calc.floor(float(ms.captures.at(0)) / 1000)) }
}
}
}
// Display absolute event times in UTC; retain raw values for correlation/fading.
#let display-time(value) = {
let raw = str(value)
let seconds = datetime-second(raw)
if seconds == none { raw } else {
let instant = datetime(year: 1970, month: 1, day: 1, hour: 0, minute: 0, second: 0) + duration(seconds: seconds)
instant.display("[year]-[month]-[day] [hour]:[minute]:[second]") + " UTC"
}
}
#let display-date(value) = {
let text = str(value)
let iso = text.match(regex("^(\\d{4}-\\d{2}-\\d{2})"))
if iso == none { text } else { iso.captures.at(0) }
}
#let fade-weight(rule, event-time, reference-day) = {
if rule == none or not get(rule, "fading", false) or reference-day == none {
(factor: 1.0, age_days: none)
} else {
let observed-day = datetime-day(event-time)
if observed-day == none {
(factor: 1.0, age_days: none)
} else {
let age = calc.max(0, reference-day - observed-day)
let starts = get(rule, "fade_after_days", 7)
let reaches-half = calc.max(starts + 1, get(rule, "fade_to_half_days", 90))
let factor = if age <= starts { 1.0 } else { calc.max(0.5, 1.0 - 0.5 * (age - starts) / (reaches-half - starts)) }
(factor: factor, age_days: age)
}
}
}
#let event-rule(rules, event) = get(rules, "event_rules", ()).find(
rule => get(rule, "provider", "") == event.provider and str(get(rule, "id", "")) == event.id,
)
#let capture(text, pattern, default: "Unknown") = {
let found = str(text).match(regex(pattern))
if found == none { default } else { found.captures.at(0) }
}
#let event-summary(event) = {
if event.provider == "Microsoft-Windows-WER-SystemErrorReporting" and event.id == "1001" and lower(event.message).contains("0x00000133") {
"DPC_WATCHDOG_VIOLATION (0x133): Windows detected excessive time in a DPC/ISR or at elevated interrupt level. Analyze the saved dump to identify the responsible component. " + event.message
} else if event.provider == "MsiInstaller" {
let product = capture(event.message, "Product: (.*?) --", default: "Unknown product")
let error = capture(event.message, "Error (\\d+)", default: "unknown")
let description = capture(event.message, "-- Error \\d+\\. (.*?)(?:[ \\t]+Action[ \\t]|$)", default: "Windows Installer did not complete the transaction.")
product + " installation failed with MSI error " + error + ". " + description
} else if event.provider == "Application Error" and event.id == "1000" {
let application = capture(event.message, "(?:Faulting application name|Nom de l’application défaillante|Nom de l'application défaillante) *: ([^,]+)", default: "Unknown application")
let module = capture(event.message, "(?:Faulting module name|faulting module name|Nom du module défaillant) *: ([^,]+)", default: "unknown module")
let exception = capture(event.message, "(?:Exception code|exception code): ([^ ]+)", default: "unknown code")
application + " terminated unexpectedly in " + module + " (exception " + exception + ")."
} else {
event.message
}
}
#let raw-events(report) = {
let events = ()
for (section-name, log-name) in (
("recent_system_errors", "System"),
("recent_application_errors", "Application"),
) {
for item in section-data(report, section-name) {
events.push((
time: str(get(item, "TimeCreated", "Unknown")),
id: str(get(item, "Id", "?")),
provider: str(get(item, "ProviderName", "Unknown")),
message: str(get(item, "Message", "No message")) + if get(report, "legacy", none) != none {
item.pairs().filter(pair => not (pair.at(0) in ("time_created", "id", "provider_name", "message"))).map(pair => " " + pair.at(0).replace("_", " ") + ": " + str(if pair.at(1) == none { "" } else { pair.at(1) })).join("")
} else { "" },
log: log-name,
))
}
}
events
}
#let group-events(events, rules, reference-day: none) = {
let groups = ()
for event in events {
let index = groups.position(group => group.provider == event.provider and group.id == event.id)
if index == none {
let item = event
item.message = event-summary(event)
item.insert("count", 1)
item.insert("messages", (item.message,))
let rule = event-rule(rules, event)
let fading = fade-weight(rule, event.time, reference-day)
item.insert("severity", if rule == none { get(rules, "unknown_event_severity", "unanalysed") } else { get(rule, "severity", "unanalysed") })
item.insert("rationale", if rule == none { "FAIL TO ANALYSE — no matching rule in diagnostics-rules.yaml." } else { get(rule, "rationale", "") })
item.insert("remediation", if rule == none { "Add a reviewed provider/ID rule before attempting cleanup." } else { get(rule, "remediation", "") })
item.insert("resolution_steps", if rule == none { ("Review the raw event and add a rule to diagnostics-rules.yaml.", "Re-run the report after the rule has been reviewed.") } else { get(rule, "resolution_steps", ()) })
item.insert("reference_url", if rule == none { "" } else { get(rule, "reference_url", "") })
item.insert("reference_label", if rule == none { "" } else { get(rule, "reference_label", "Microsoft guidance") })
item.insert("confidence", if rule == none { 20 } else { get(rule, "confidence", 70) })
item.insert("weight_factor", fading.factor)
item.insert("age_days", fading.age_days)
item.insert("fading", rule != none and get(rule, "fading", false))
groups.push(item)
} else {
let item = groups.at(index)
item.count += 1
let summary = event-summary(event)
if not (summary in item.messages) {
item.messages.push(summary)
item.message = item.messages.join(" / ")
}
// Keep the latest parseable event timestamp for display/fading context.
let old-time = datetime-second(item.time)
let new-time = datetime-second(event.time)
if new-time != none and (old-time == none or new-time > old-time) {
item.time = event.time
let fading = fade-weight(event-rule(rules, event), event.time, reference-day)
item.weight_factor = fading.factor
item.age_days = fading.age_days
}
groups.at(index) = item
}
}
groups
}
// Correlate original records before provider/ID grouping loses timestamps.
#let catalog-correlation(events) = {
let checksums = events.filter(event => event.provider == "ESENT" and event.id == "474" and lower(event.message).contains("catroot2") and event.message.contains("-1018"))
checksums.find(anchor => {
let time = datetime-second(anchor.time)
let nearby = events.filter(event => {
let other = datetime-second(event.time)
time != none and other != none and calc.abs(time - other) <= 120
})
nearby.any(event => event.provider == "Application Error" and event.id == "1000" and lower(event.message).contains("cryptsvc") and lower(event.message).contains("esent.dll")) and nearby.any(event => event.provider == "Microsoft-Windows-WindowsUpdateClient" and event.id == "20")
})
}
#let command-output(report, name) = {
let item = section-first(report, name)
let output = get(item, "output", get(section(report, name), "legacy_raw", ()))
let text = if type(output) == array { output.map(value => str(value)).join("\n", default: "") } else { str(output) }
text.replace("\r", "\n").split("\n").filter(line => line.trim() != "" and not lower(line).contains("% complete")).join("\n", default: "")
}
#let object-lines(item, fields) = {
fields.map(pair => pair.at(0) + ": " + str(get(item, pair.at(1), "Unknown"))).join("\n", default: "")
}
#let normalize(report, rules: (:), source-name: "WinDiagnostics JSON") = {
let schema = get(report, "schema_version", 0)
if schema != 1 { panic("Unsupported WinDiagnostics schema_version: " + str(schema)) }
let generated-raw = get(report, "generated_at", "Unknown")
let generated = if generated-raw == "Unknown" { "Unknown" } else { display-date(generated-raw) }
let reference-day = datetime-day(generated-raw)
let host = get(report, "host", (:))
let mode = str(get(report, "mode", "Unknown"))
let administrator = get(host, "administrator", false)
// Full/Mid reports use sections. Compact reports use summary.
let compact = lower(mode) == "compact"
let summary = get(report, "summary", (:))
let os = if compact { get(summary, "operating_system", (:)) } else { section-first(report, "operating_system") }
let system = if compact { get(summary, "system", (:)) } else { section-first(report, "computer_system") }
let cpu = if compact { get(summary, "cpu", (:)) } else { section-first(report, "cpu") }
let uptime = if compact { get(summary, "uptime", (:)) } else { section-first(report, "uptime") }
let defender = if compact { get(summary, "defender", (:)) } else { section-first(report, "defender") }
let battery = if compact { (:) } else { section-first(report, "battery") }
let storage-root = if compact { get(summary, "storage", (:)) } else { section-first(report, "storage") }
let logical-volumes = if compact { get(storage-root, "logical_volumes", ()) } else { get(storage-root, "logical_volumes", ()) }
let raw = if compact { () } else { raw-events(report) }
let events = group-events(raw, rules, reference-day: reference-day)
let findings = ()
if get(report, "legacy", none) != none {
findings.push((severity: "warning", title: "Legacy conversion has incomplete evidence", detail: "This report was converted from formatted text. Table rows and event-message formatting may have been lost. Unrecoverable inventories and device/firewall states are unavailable; empty converted storage is not evidence that no disks exist. Legacy event dates retain their original format and receive no age discount.", confidence: 100, weight_factor: 0, resolution_steps: ("Collect a new native JSON report with WinDiagnostics Full to replace incomplete evidence.",)))
}
for warning in get(report, "warnings", ()) {
findings.push((severity: "warning", title: "Collector warning", detail: str(warning), confidence: 100, weight_factor: 0))
}
for (name, value) in get(report, "sections", (:)).pairs() {
if get(value, "status", "") in ("error", "skipped") {
findings.push((severity: "warning", title: "Collector coverage: " + name, detail: get(value, "status", "") + ": " + str(get(value, "error", "No result collected")), confidence: 100, weight_factor: 0))
}
}
let catalog-cluster = catalog-correlation(raw)
if catalog-cluster != none {
findings.push((
severity: "critical",
title: "Catalog corruption coincides with Cryptographic Services and update failures",
detail: "Around " + display-time(catalog-cluster.time) + ", CatRoot2 checksum failure (-1018), a CryptSvc crash in ESENT.dll, and Windows Update failure occur within two minutes of the checksum event. This supports a related failure sequence, but does not establish which hardware or software component caused the corruption.",
confidence: 90,
weight_factor: 0,
resolution_steps: (
"Back up important data and preserve event logs before resetting update components.",
"Investigate storage and memory stability. Retest at stock CPU/RAM settings and review firmware guidance for the captured motherboard and CPU.",
"Run Full diagnostics as administrator to obtain DISM and SFC results, then use those results to guide supported Windows component repair.",
"Retry the failed update and verify Cryptographic Services remains stable with no new database checksum failures.",
),
))
}
if not administrator {
findings.push((
severity: "warning",
title: "Diagnostic coverage is incomplete",
detail: "The collector was not elevated. Administrator-only checks, including DISM and SFC, may be skipped and are not evidence of healthy system files.",
confidence: 100,
resolution_steps: (
"Run WinDiagnostics Full from an elevated PowerShell session.",
"Review the new DISM, SFC, and other previously skipped results before closing the investigation.",
),
))
}
let dism = if compact { "" } else { command-output(report, "component_store") }
let sfc = if compact { "" } else { command-output(report, "system_file_check") }
if lower(dism).contains("repairable") and not lower(dism).contains("non-repairable") {
findings.push((
severity: "warning",
title: "Windows component store is repairable",
detail: "DISM found component-store corruption and classified the image as repairable with RestoreHealth.",
confidence: 98,
resolution_steps: (
"Open an elevated terminal and run DISM.exe /Online /Cleanup-Image /RestoreHealth.",
"After DISM succeeds, run sfc /scannow.",
"Re-run diagnostics and confirm both checks are healthy.",
),
reference_url: "https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/repair-a-windows-image?view=windows-11",
reference_label: "Microsoft Windows image repair guidance",
))
}
if lower(sfc).contains("integrity violations") and not lower(sfc).contains("did not find any integrity violations") {
findings.push((
severity: "critical",
title: "System-file integrity violations",
detail: "SFC verification found integrity violations; review CBS.log and repair after DISM.",
confidence: 98,
resolution_steps: (
"Repair the component store with DISM.exe /Online /Cleanup-Image /RestoreHealth.",
"Run sfc /scannow after DISM completes.",
"Re-run verification and confirm that no integrity violations remain.",
),
reference_url: "https://support.microsoft.com/en-us/windows/experience/backup-recovery/using-system-file-checker-in-windows",
reference_label: "Microsoft SFC and DISM guidance",
))
}
for event in events {
if event.severity in ("critical", "warning", "unanalysed") {
findings.push((
severity: event.severity,
title: event.provider + " · Event " + event.id,
detail: event.message + " " + event.rationale,
remediation: event.remediation,
resolution_steps: event.resolution_steps,
reference_url: event.reference_url,
reference_label: event.reference_label,
confidence: event.confidence,
count: event.count,
weight_factor: event.weight_factor,
age_days: event.age_days,
fading: event.fading,
))
}
}
let problem-devices = if compact { () } else { section-data(report, "problem_devices") }
for device in problem-devices {
if get(device, "Class", "") == "Display" and (get(device, "ConfigManagerErrorCode", 0) == 22 or str(get(device, "Problem", "")).contains("CM_PROB_DISABLED")) {
findings.push((severity: "warning", title: str(get(device, "FriendlyName", get(device, "Name", "Display adapter"))) + " is disabled (Code 22)", detail: "The device is disabled. This does not establish GPU hardware failure or who disabled it.", confidence: 99, resolution_steps: ("Inspect the adapter status and Events tab in Device Manager.", "If it should be active, enable it, restart, and verify acceleration and workload stability.")))
}
}
if problem-devices.len() > 0 or (compact and get(get(summary, "devices", (:)), "problem_count", 0) > 0) {
findings.push((
severity: "warning",
title: "Devices report problems",
detail: str(if compact { get(get(summary, "devices", (:)), "problem_count", 0) } else { problem-devices.len() }) + " present device(s) did not report a healthy state.",
confidence: 90,
resolution_steps: (
"Identify every reported device in Device Manager.",
"Update, repair, enable, or remove the associated driver or disconnected hardware as appropriate.",
"Re-run diagnostics and confirm that no present device reports a problem.",
),
))
}
let disk-free = logical-volumes.map(disk => (
drive: str(get(disk, "drive", get(disk, "DeviceID", "Disk"))),
size_gb: number(get(disk, "size_gb", 0)),
free_gb: number(get(disk, "free_gb", 0)),
free_percent: number(get(disk, "free_percent", 0)),
))
let low-disk = disk-free.filter(disk => disk.free_percent < 10)
if low-disk.len() > 0 {
findings.push((
severity: "warning",
title: "Low storage headroom",
detail: low-disk.map(disk => disk.drive + " has " + str(disk.free_percent) + "% free space").join("; ") + ".",
confidence: 100,
resolution_steps: (
"Review large or temporary files on the affected volume.",
"Preserve sufficient free space for Windows servicing, updates, paging, and application workloads.",
"Re-run diagnostics after cleanup and confirm storage headroom has recovered.",
),
))
}
let firewall = if compact { () } else { section-data(report, "firewall_profiles") }
let firewall-ok = firewall.len() == 0 or firewall.all(item => enabled(get(item, "Enabled", none)))
if firewall.len() > 0 and not firewall-ok {
findings.push((
severity: "critical",
title: "Windows Firewall protection is incomplete",
detail: "At least one captured firewall profile is disabled.",
confidence: 95,
resolution_steps: (
"Confirm that organization policy does not intentionally disable the profile.",
"Otherwise enable the required Domain, Private, and Public profiles in elevated PowerShell.",
"Verify the resulting profile state and re-run diagnostics.",
),
reference_url: "https://learn.microsoft.com/en-us/windows/security/operating-system-security/network-security/windows-firewall/configure-with-command-line",
reference_label: "Microsoft firewall command guidance",
))
}
let defender-ok = defender != (:) and (
get(defender, "AntivirusEnabled", false) == true and
get(defender, "AntispywareEnabled", false) == true and
get(defender, "RealTimeProtectionEnabled", false) == true and
get(defender, "BehaviorMonitorEnabled", false) == true and
get(defender, "IoavProtectionEnabled", false) == true and
get(defender, "NISEnabled", false) == true
)
let battery-charge = number(get(battery, "EstimatedChargeRemaining", 0))
let battery-present = battery != (:)
let battery-ok = not battery-present or (str(get(battery, "Status", "Unknown")) == "OK" and battery-charge >= 20)
let inventory = if compact {
let software = get(summary, "software", (:))
let startup = get(summary, "startup", (:))
let services = get(summary, "services", (:))
(
(label: "Desktop programs", count: get(software, "desktop_program_count", 0)),
(label: "Store packages", count: get(software, "appx_package_count", 0)),
(label: "Startup commands", count: get(startup, "command_count", 0)),
(label: "Automatic services", count: get(services, "automatic_count", 0)),
)
} else {
(
(label: "Desktop programs", count: section-count(report, "installed_programs")),
(label: "Store packages", count: section-count(report, "appx_packages")),
(label: "Automatic services", count: section-count(report, "automatic_services")),
(label: "Signed drivers", count: section-count(report, "signed_drivers")),
(label: "Hotfixes", count: section-count(report, "hotfixes")),
(label: "Scheduled tasks", count: section-count(report, "non_microsoft_scheduled_tasks")),
(label: "Startup programs", count: section-count(report, "startup_programs")),
(label: "Listening endpoints", count: section-count(report, "active_tcp_listeners")),
)
}
let excerpts = ()
for (name, title, fields) in (
("bios", "BIOS", (("Manufacturer", "Manufacturer"), ("Version", "Name"))),
("motherboard", "MOTHERBOARD", (("Manufacturer", "Manufacturer"), ("Product", "Product"))),
("memory_modules", "MEMORY MODULES", (("Capacity GB", "capacity_gb"), ("Configured clock", "ConfiguredClockSpeed"), ("Part number", "PartNumber"))),
("gpus", "GPU / DISPLAY ADAPTERS", (("Name", "Name"), ("Driver", "DriverVersion"))),
) {
let records = section-data(report, name)
if records.len() > 0 {
excerpts.push((title: title, severity: "info", text: records.map(item => object-lines(item, fields)).join("\n\n")))
}
}
let storage-health = get(storage-root, "storage_health", ())
let unhealthy-storage = storage-health.filter(item => lower(str(get(item, "HealthStatus", "Healthy"))) != "healthy")
if unhealthy-storage.len() > 0 {
excerpts.push((
title: "STORAGE HEALTH",
severity: "warning",
text: unhealthy-storage.map(item => object-lines(item, (("Disk", "FriendlyName"), ("Health", "HealthStatus"), ("Operational", "OperationalStatus")))).join("\n\n"),
))
}
if problem-devices.len() > 0 {
excerpts.push((
title: "DEVICES WITH PROBLEMS",
severity: "warning",
text: problem-devices.map(item => object-lines(item, (("Status", "Status"), ("Class", "Class"), ("Device", "FriendlyName"), ("Instance", "InstanceId")))).join("\n\n"),
))
}
if dism != "" and (lower(dism).contains("repairable") or lower(dism).contains("corrupt") or lower(dism).contains("error")) {
excerpts.push((title: "WINDOWS COMPONENT STORE STATUS", text: dism, severity: "warning"))
}
if sfc != "" {
let sfc-level = if lower(sfc).contains("integrity violations") and not lower(sfc).contains("did not find any integrity violations") { "critical" } else { "info" }
excerpts.push((title: "SYSTEM FILE CHECK - VERIFY ONLY", text: sfc, severity: sfc-level))
}
if firewall.len() > 0 and not firewall-ok {
excerpts.push((
title: "FIREWALL PROFILES",
severity: "warning",
text: firewall.map(item => object-lines(item, (("Profile", "Name"), ("Enabled", "Enabled"), ("Inbound", "DefaultInboundAction"), ("Outbound", "DefaultOutboundAction")))).join("\n\n"),
))
}
if defender != (:) and not defender-ok {
excerpts.push((
title: "WINDOWS DEFENDER STATUS",
severity: "warning",
text: object-lines(defender, (
("Antivirus", "AntivirusEnabled"),
("Antispyware", "AntispywareEnabled"),
("Real-time", "RealTimeProtectionEnabled"),
("Behavior monitor", "BehaviorMonitorEnabled"),
("IOAV", "IoavProtectionEnabled"),
("NIS", "NISEnabled"),
)),
))
}
if battery-present and not battery-ok {
excerpts.push((
title: "BATTERY",
severity: if battery-charge < 10 { "critical" } else { "warning" },
text: object-lines(battery, (("Name", "Name"), ("Status", "Status"), ("Charge", "EstimatedChargeRemaining"), ("Battery status", "BatteryStatus"))),
))
}
let inventory-sections = (
"installed_programs", "appx_packages", "automatic_services", "signed_drivers",
"hotfixes", "non_microsoft_scheduled_tasks", "startup_programs", "active_tcp_listeners",
)
let sensitive-sections = ("ip_configuration", "important_directories", "startup_folders", "dns_servers")
let routine-sections = ("automatic_services_not_running", "power_plan", "top_processes_by_memory")
let detailed-sections = (
"storage", "problem_devices", "component_store", "system_file_check", "firewall_profiles", "defender", "battery",
)
let coverage = ()
if compact {
coverage.push((section: "summary", use: "Compact structured summary", records: 1, severity: "info"))
} else {
for (name, value) in get(report, "sections", (:)).pairs() {
let status = get(value, "status", "missing")
let count = section-count(report, name)
let use = if legacy-incomplete(report, name) { "Legacy conversion incomplete; recollect JSON" } else if status == "skipped" { "Skipped by collector" }
else if status == "error" { "Collector error retained" }
else if name in ("recent_system_errors", "recent_application_errors") { "Deduplicated findings" }
else if name in inventory-sections { "Inventory count" }
else if name in sensitive-sections { "Reviewed; sensitive/noise-heavy values omitted" }
else if name in routine-sections { "Reviewed; routine snapshot omitted" }
else if name in detailed-sections { "Structured health evidence" }
else { "Retained in source; no specific analysis" }
let severity = if legacy-incomplete(report, name) { "warning" } else if status == "error" { "warning" }
else if status == "skipped" { "warning" }
else if name in ("recent_system_errors", "recent_application_errors") and events.any(event => event.severity == "critical") { "critical" }
else { "success" }
coverage.push((section: name, use: use, records: count, severity: severity))
}
}
findings = findings.filter(item => item.severity == "critical") + findings.filter(item => item.severity == "warning") + findings.filter(item => item.severity == "unanalysed")
let critical = findings.filter(item => item.severity == "critical").len()
let warnings = findings.filter(item => item.severity == "warning").len()
let unanalysed = findings.filter(item => item.severity == "unanalysed").len()
let penalty = 0.0
for finding in findings {
let base = if finding.severity == "critical" { 8 } else if finding.severity == "warning" { 2 } else if finding.severity == "unanalysed" { 1 } else { 0 }
penalty += base * get(finding, "weight_factor", 1.0)
}
let health-score = calc.round(calc.max(0, calc.min(100, 100 - penalty)))
let confidence-total = 0
for finding in findings { confidence-total += get(finding, "confidence", 50) }
let analysis-confidence = if findings.len() == 0 { 80 } else { calc.round(confidence-total / findings.len()) }
let uptime-value = if uptime == (:) {
"Unanalysed"
} else {
str(get(uptime, "days", get(uptime, "Days", "?"))) + "d " + str(get(uptime, "hours", get(uptime, "Hours", "?"))) + "h " + str(get(uptime, "minutes", get(uptime, "Minutes", "?"))) + "m"
}
let os-name = str(get(os, "caption", get(os, "Caption", "Unknown")))
let os-version = str(get(os, "version", get(os, "Version", "Unknown")))
let os-build = str(get(os, "build_number", get(os, "BuildNumber", "Unknown")))
let manufacturer = str(get(system, "manufacturer", get(system, "Manufacturer", "Unknown")))
let model = str(get(system, "model", get(system, "Model", "Unknown")))
let cpu-name = str(get(cpu, "name", get(cpu, "Name", "Unknown")))
let cores = get(cpu, "cores", get(cpu, "NumberOfCores", "?"))
let threads = get(cpu, "logical_processors", get(cpu, "NumberOfLogicalProcessors", "?"))
let ram-total = if compact {
number(get(get(summary, "memory", (:)), "total_gb", 0))
} else {
number(get(system, "total_physical_memory_gb", 0))
}
let ram-free = if compact {
number(get(get(summary, "memory", (:)), "free_gb", 0))
} else {
number(get(os, "free_memory_gb", 0))
}
(
source: source-name,
schema_version: schema,
mode: mode,
generated: generated,
computer: str(get(host, "computer_name", "Unknown")),
administrator: bool-text(administrator),
health: if critical > 0 { "Attention required" } else if warnings > 0 or unanalysed > 0 { "Review recommended" } else { "No actionable issue detected" },
health_score: health-score,
analysis_confidence: analysis-confidence,
system: (
os: os-name,
version: os-version,
build: os-build,
manufacturer: manufacturer,
model: model,
cpu: cpu-name,
cores: cores,
threads: threads,
ram_total_gb: ram-total,
ram_free_gb: ram-free,
uptime: uptime-value,
),
security: (
antivirus: bool-text(get(defender, "AntivirusEnabled", "Unavailable")),
realtime: bool-text(get(defender, "RealTimeProtectionEnabled", "Unavailable")),
signatures: display-time(get(defender, "AntivirusSignatureLastUpdated", "Unavailable")),
),
battery: (
charge: battery-charge,
status: str(get(battery, "Status", "Unavailable")),
),
disk_free: disk-free,
inventory: inventory,
findings: findings,
issue_counts: (critical: critical, warning: warnings, unanalysed: unanalysed),
event_groups: events.map(event => {
event.insert("display_time", display-time(event.time))
event
}),
excerpts: excerpts,
coverage: coverage,
)
}