diff --git a/README.md b/README.md index 478ef77..9724d98 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,27 @@ integration repository or diagnostic tools. The renderer validates the input, loads an optional report-relative logo, and writes the completed PDF. Existing output requires `--force`. +## Render one diagnostic + +```bash +./render-diagnostic.sh capture.json \ + --output diagnostic.pdf \ + --author "Reviewer Name" \ + --logo /path/to/logo.png +``` + +The diagnostic renderer supports the established Windows diagnostic JSON +formats and layout. Select a configured color scheme with `--theme NAME`. + +## Render every diagnostic in a directory + +```bash +./render-diagnostics.sh /path/to/diagnostics \ + --output-dir /path/to/pdfs \ + --author "Reviewer Name" \ + --logo /path/to/logo.png +``` + ## Render every report in a directory ```bash diff --git a/render-diagnostic.sh b/render-diagnostic.sh new file mode 100755 index 0000000..2a29b79 --- /dev/null +++ b/render-diagnostic.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# Render a legacy WinDiagnostics capture with the preserved diagnostic layout. +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) + +usage() { + cat >&2 <&2 + exit 1 +} + +require_value() { + (($# >= 2)) || usage +} + +input=${1:-} +[[ -n "$input" ]] || usage +shift + +output= +author= +logo= +theme=default +source_name= +force=false + +while (($#)); do + case $1 in + --output) + require_value "$@" + output=$2 + shift 2 + ;; + --author) + require_value "$@" + author=$2 + shift 2 + ;; + --logo) + require_value "$@" + logo=$2 + shift 2 + ;; + --theme) + require_value "$@" + theme=$2 + shift 2 + ;; + --source-name) + require_value "$@" + source_name=$2 + shift 2 + ;; + --force) + force=true + shift + ;; + *) + usage + ;; + esac +done + +for value in "$output" "$author" "$logo"; do + [[ -n "$value" ]] || usage +done + +command -v typst >/dev/null 2>&1 || fail "Typst is required" +[[ -f "$input" ]] || fail "$input: diagnostic capture does not exist" +[[ -f "$logo" ]] || fail "$logo: logo does not exist" + +input=$(realpath "$input") +logo=$(realpath "$logo") +source_name=${source_name:-$(basename "$input")} +output_parent=$(dirname "$output") +mkdir -p "$output_parent" +output=$(cd "$output_parent" && pwd -P)/$(basename "$output") + +[[ "$input" != "$output" ]] || fail "input and output paths must differ" +[[ ! -e "$output" || "$force" == true ]] || fail "$output: output exists; use --force to replace it" + +stage=$(mktemp -d "${TMPDIR:-/tmp}/reportist-diagnostic.XXXXXXXX") +trap 'rm -rf "$stage"' EXIT + +mkdir -p "$stage/assets" +cp -R "$root/templates/diagnostics/." "$stage/" +cp "$input" "$stage/diagnostic.json" +cp "$logo" "$stage/assets/beffroi.png" + +typst compile \ + --root "$stage" \ + --input diagnostics=diagnostic.json \ + --input "diagnostics-source=$source_name" \ + --input "author=$author" \ + --input "theme=$theme" \ + "$stage/diagnostics.typ" \ + "$stage/diagnostic.pdf" || fail "diagnostic rendering failed" + +if [[ "$force" == true ]]; then + mv -f "$stage/diagnostic.pdf" "$output" +else + mv "$stage/diagnostic.pdf" "$output" +fi + +echo "Rendered diagnostic PDF: $output" diff --git a/render-diagnostics.sh b/render-diagnostics.sh new file mode 100755 index 0000000..e5db2d5 --- /dev/null +++ b/render-diagnostics.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Render every legacy WinDiagnostics capture while preserving relative paths. +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) + +usage() { + echo "Usage: $0 INPUT_DIR --output-dir DIR --author NAME --logo FILE [--theme NAME] [--force]" >&2 + exit 2 +} + +fail() { + echo "error: $*" >&2 + exit 1 +} + +require_value() { + (($# >= 2)) || usage +} + +input_dir=${1:-} +[[ -n "$input_dir" ]] || usage +shift + +output_dir= +author= +logo= +theme=default +force=false + +while (($#)); do + case $1 in + --output-dir) + require_value "$@" + output_dir=$2 + shift 2 + ;; + --author) + require_value "$@" + author=$2 + shift 2 + ;; + --logo) + require_value "$@" + logo=$2 + shift 2 + ;; + --theme) + require_value "$@" + theme=$2 + shift 2 + ;; + --force) + force=true + shift + ;; + *) + usage + ;; + esac +done + +for value in "$output_dir" "$author" "$logo"; do + [[ -n "$value" ]] || usage +done + +input_dir=$(realpath "$input_dir") +mkdir -p "$output_dir" +output_dir=$(realpath "$output_dir") + +if [[ "$output_dir" == "$input_dir" || "$output_dir" == "$input_dir"/* ]]; then + fail "output directory must be outside the input tree" +fi + +count=0 +while IFS= read -r -d '' input; do + relative=${input#"$input_dir/"} + output="$output_dir/${relative%.json}.pdf" + mkdir -p "$(dirname "$output")" + + arguments=( + --output "$output" + --author "$author" + --logo "$logo" + --theme "$theme" + --source-name "diagnostics/$relative" + ) + [[ "$force" == false ]] || arguments+=(--force) + + "$root/render-diagnostic.sh" "$input" "${arguments[@]}" + ((count += 1)) +done < <(find "$input_dir" -type f -name '*.json' -print0 | sort -z) + +((count > 0)) || fail "$input_dir: no JSON diagnostics found" +echo "Rendered $count diagnostic PDFs into $output_dir" diff --git a/templates/diagnostics/config/diagnostics-rules.yaml b/templates/diagnostics/config/diagnostics-rules.yaml new file mode 100644 index 0000000..be27e02 --- /dev/null +++ b/templates/diagnostics/config/diagnostics-rules.yaml @@ -0,0 +1,384 @@ +# WinDiagnostics interpretation rules. +# Add or revise entries here as new event providers and IDs are understood. +event_rules: + - provider: "Microsoft-Windows-WER-SystemErrorReporting" + id: "1001" + severity: "critical" + confidence: 100 + rationale: "Windows reports a reboot following a kernel bugcheck. The stop code and saved dump are evidence of a crash, but do not identify the responsible driver or hardware on their own." + resolution_steps: + - "Preserve the referenced minidump and the System event log." + - "Open the dump in WinDbg and run !analyze -v; review the bugcheck parameters and stack before attributing the crash to a component." + - "Correlate the crash with nearby storage, device, and driver events. Apply targeted OEM driver or firmware fixes supported by the dump analysis." + - "Reproduce the original workload and verify that no new bugcheck occurs in a subsequent capture." + reference_url: "https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/bug-check-code-reference2" + reference_label: "Microsoft bugcheck reference" + - provider: "volmgr" + id: "162" + severity: "info" + confidence: 100 + rationale: "The collector message records successful crash-dump generation. This is supporting crash evidence, not an additional storage failure." + remediation: "Preserve the dump and investigate the associated bugcheck." + - provider: "stornvme" + id: "11" + severity: "critical" + confidence: 92 + rationale: "Storage controller path reported an I/O controller error." + remediation: "Back up important data first. Identify the disk behind the reported port, then update its firmware and the OEM storage/chipset driver. Recheck disk health and confirm Event 11 does not return under normal load." + - provider: "Microsoft-Windows-TPM-WMI" + id: "1040" + severity: "critical" + confidence: 85 + rationale: "Pre-attestation health checks reported a critical component failure." + remediation: "Inspect the referenced MeasuredBoot JSON and install applicable OEM BIOS or TPM firmware updates. Do not clear the TPM unless recovery keys are backed up and the failed check specifically requires it." + - provider: "Service Control Manager" + id: "7000" + fading: true + severity: "warning" + confidence: 90 + rationale: "A configured service or driver failed to start." + remediation: "Identify the named service, verify that its executable path exists, then repair, update, or remove the owning application or driver. Reboot and confirm the service starts without a new Event 7000." + reference_url: "https://learn.microsoft.com/en-us/troubleshoot/windows-client/setup-upgrade-and-drivers/system-log-event-id-7000-7026" + reference_label: "Microsoft Event 7000 guidance" + - provider: "Service Control Manager" + id: "7009" + fading: true + severity: "warning" + confidence: 82 + rationale: "A service did not connect before the Service Control Manager timeout." + remediation: "Identify and update or repair the named service first. Check its dependencies and startup behavior; only consider changing the service timeout when the service is healthy but consistently needs longer to initialize." + - provider: "Microsoft-Windows-NDIS" + id: "10317" + severity: "warning" + confidence: 78 + rationale: "A network miniport failed a transition to operational power; review the adapter driver and power management if connectivity symptoms correlate." + remediation: "Install the current OEM network driver, reboot, and retest sleep/resume. If the event correlates with connectivity loss, review the adapter's Power Management settings before changing them." + reference_url: "https://learn.microsoft.com/en-us/windows-hardware/drivers/network/how-ndis-sets-the-power-policy-for-a-network-adapter" + reference_label: "Microsoft NDIS power-policy guidance" + - provider: "Application Error" + id: "1000" + fading: true + severity: "warning" + confidence: 75 + rationale: "An application terminated unexpectedly; assess the named application, module, and exception code." + remediation: "Update or repair the named application and its related driver or module, then reproduce the original workflow. Consider it dealt with after the application remains stable and no matching Event 1000 recurs." + - provider: "Microsoft-Windows-WindowsUpdateClient" + id: "20" + fading: true + severity: "warning" + confidence: 88 + rationale: "An update installation failed." + remediation: "Restart Windows, retry the named update, and confirm it installs successfully. If failures persist, repair DISM/SFC findings first and retry Windows Update afterward." + - provider: "Application Hang" + id: "1002" + fading: true + severity: "warning" + confidence: 70 + rationale: "An application stopped responding and was closed." + - provider: "MsiInstaller" + id: "1043" + fading: true + severity: "warning" + confidence: 80 + rationale: "Windows Installer could not finish a transaction." + remediation: "Retry the named installer after a reboot. If it fails again, repair or uninstall the affected application using its supported installer and inspect the installer log for the recorded error code." + - provider: "Volsnap" + id: "36" + severity: "warning" + confidence: 82 + rationale: "A volume shadow-copy operation was aborted." + remediation: "Run vssadmin list shadowstorage from an elevated terminal and check the configured limit and free disk space. Increase the limit only if backups or restore points require it, then verify a new shadow copy succeeds." + - provider: "Service Control Manager" + id: "7043" + fading: true + severity: "warning" + confidence: 75 + rationale: "A service did not shut down cleanly." + remediation: "Update or repair the application that owns the named service, then perform a normal shutdown and confirm the event does not recur." + - provider: "Microsoft-Windows-DistributedCOM" + id: "10010" + severity: "info" + confidence: 65 + rationale: "A DCOM registration timeout is usually contextual unless repeated or correlated with symptoms." + remediation: "No cleanup is normally required for an isolated occurrence. Investigate the referenced component only if the event repeats or matches a user-visible failure." + + - provider: "EventLog" + id: "6008" + severity: "warning" + confidence: 95 + rationale: "Windows recorded that the previous shutdown was unexpected; this confirms an unclean stop but does not identify its cause." + remediation: "Ask whether power was removed or the machine was forcibly restarted. If not, correlate the same timestamp with Kernel-Power Event 41, bug-check Event 1001, hardware errors, thermal history, and recently changed drivers or updates." + reference_url: "https://learn.microsoft.com/en-us/troubleshoot/windows-server/performance/troubleshoot-unexpected-reboots-system-event-logs" + reference_label: "Microsoft unexpected-reboot investigation" + - provider: "Service Control Manager" + id: "7023" + fading: true + severity: "warning" + confidence: 88 + rationale: "A service terminated and returned an error; impact depends on the named service and whether its function is needed." + remediation: "Identify the owning application or driver for the named service, update or repair it, then restart the service or reboot. Confirm the service remains running and Event 7023 does not recur." + - provider: "MsiInstaller" + id: "11704" + fading: true + severity: "warning" + confidence: 92 + rationale: "Windows Installer reported a suspended installation that blocked another product transaction." + remediation: "Finish or roll back the suspended installation, reboot if requested, and retry the affected installer. Confirm that both products complete without another installer event." + - provider: "MsiInstaller" + id: "11722" + fading: true + severity: "warning" + confidence: 92 + rationale: "A program executed by an MSI package did not complete as expected, so the installation was not successful." + remediation: "Reboot and retry the named product's current supported installer. If it fails again, collect a verbose MSI log and repair or remove the affected product before retrying." + - provider: "VSS" + id: "12344" + severity: "warning" + confidence: 82 + rationale: "A Volume Shadow Copy writer failed during its freeze operation; backups or restore points near that time may be incomplete." + remediation: "Run vssadmin list writers from an elevated terminal and identify any failed writer. Reboot or restart the owning service, verify system and registry health, then create and validate a new shadow copy or backup." + - provider: ".NET Runtime" + id: "1022" + severity: "info" + confidence: 80 + rationale: "The process could not initialize profiler-attach support; this is normally contextual unless diagnostics, monitoring, or profiling was expected for that process." + remediation: "No action is normally required. If a profiler or monitoring agent was expected, update or repair that agent and reproduce the attach operation." + - provider: "Waterfox Default Browser Agent" + id: "5" + severity: "info" + confidence: 55 + rationale: "The captured event has no message, so it provides no actionable evidence by itself." + remediation: "No action is recommended from this empty event alone. Update or repair Waterfox only if browser-default handling is visibly failing or the event repeatedly correlates with a symptom." + +# Additional provider/ID pairs observed in the SAURON capture. + - provider: "Microsoft-Windows-Kernel-Boot" + id: "29" + severity: "warning" + confidence: 92 + rationale: "Windows failed Fast Startup; the status and adjacent shutdown events do not establish the underlying cause." + remediation: "Compare a normal Restart with shutdown/startup. Test with Fast Startup disabled through Power Options, then review firmware and drivers if failures recur. Preserve adjacent shutdown and bug-check events." + - provider: "Service Control Manager" + id: "7031" + severity: "warning" + confidence: 95 + rationale: "A service terminated unexpectedly; Windows may schedule a recovery action." + remediation: "Identify each named service and correlate application crashes at the same time. Repair the owning component and verify the service stays running after restart." + - provider: "Microsoft-Windows-DeviceAssociationService" + id: "3505" + severity: "warning" + confidence: 70 + rationale: "Device association failed while enumerating pairing ceremonies; the message does not identify a failed hardware component." + remediation: "Check whether device pairing actually fails. Identify the affected peripheral, retry pairing, and review its driver and device-association logs if reproducible." + - provider: "Microsoft-Windows-HAL" + id: "15" + severity: "warning" + confidence: 90 + rationale: "The IOMMU reported an error. The raw device identifier alone does not identify the graphics adapter or prove physical hardware failure." + remediation: "Preserve the full event XML and map the device to its PCI location before blaming a component. Review OEM firmware and chipset/device drivers and correlate recurrence with device activity. Keep DMA protection enabled." + - provider: "Microsoft-Windows-HAL" + id: "21" + severity: "warning" + confidence: 90 + rationale: "The ACPI time/alarm method failed while Windows attempted to set the hardware real-time clock." + remediation: "Check firmware time and Windows time synchronization after reboot. Review applicable OEM BIOS fixes and retest shutdown/resume. This event alone does not diagnose a dead CMOS battery." + - provider: "usbaudio2" + id: "38" + severity: "warning" + confidence: 90 + rationale: "A USB audio control request failed." + remediation: "Identify the USB audio device, reconnect it directly, and test another port or cable. Review device firmware/drivers and confirm normal playback or recording without recurrence." + - provider: "ESENT" + id: "419" + severity: "critical" + confidence: 95 + rationale: "The database engine could not read a database page. Inspect the recorded error; -1018 indicates a checksum/read-verification failure." + remediation: "Back up important data and preserve the event/database context. Check storage and memory stability, then use the owning application’s supported recovery procedure. Verify that the database can be read and the workload succeeds." + reference_url: "https://learn.microsoft.com/en-us/windows/win32/extensible-storage-engine/jet-err-enumeration" + reference_label: "Microsoft database error definitions" + - provider: "ESENT" + id: "474" + severity: "critical" + confidence: 98 + rationale: "A database page failed checksum verification. This confirms corruption in the read data but does not isolate disk, RAM, CPU, driver, or power as the cause." + remediation: "Back up important data. Check storage health and run memory diagnostics at stock settings. Repair the affected database through its owning component only after investigating stability, then verify the failed workload and absence of new checksum errors." + reference_url: "https://learn.microsoft.com/en-us/windows/win32/extensible-storage-engine/jet-err-enumeration" + reference_label: "Microsoft database error definitions" + - provider: "ESENT" + id: "907" + severity: "critical" + confidence: 95 + rationale: "ESENT detected a transient memory problem; this is a stability signal, not proof that a particular RAM module is defective." + remediation: "Back up data and run Windows Memory Diagnostic or OEM memory tests. Retest at stock CPU/RAM settings and review OEM firmware guidance. Investigate CPU, RAM, storage and drivers if corruption recurs." + reference_url: "https://learn.microsoft.com/en-us/windows/win32/extensible-storage-engine/jet-err-enumeration" + reference_label: "Microsoft database error definitions" + - provider: "ESENT" + id: "908" + severity: "critical" + confidence: 95 + rationale: "The database process terminated because of a fatal error. Inspect its error code and enforcement tag and correlate adjacent ESENT events." + remediation: "Preserve the full message and investigate associated checksum/memory errors before retrying the workload. Verify stability and repair the owning component through its supported recovery procedure." + reference_url: "https://learn.microsoft.com/en-us/windows/win32/extensible-storage-engine/jet-err-enumeration" + reference_label: "Microsoft database error definitions" + - provider: "Microsoft-Windows-Defrag" + id: "264" + severity: "warning" + confidence: 92 + rationale: "Storage optimization did not complete; the message supplies the reason. An unsupported filesystem is not evidence of a failing disk." + remediation: "Check the named volume and error. For 0x8900002F on exFAT, review optimization scheduling; do not format or convert the volume just to remove this event. Investigate other errors according to their actual cause." + +# Reviewed against the native schema 2 capture and linked vendor guidance. +# Entries without a URL interpret the captured message only; no root cause is inferred. + - provider: "Microsoft-Windows-WLAN-AutoConfig" + id: "10002" + severity: "info" + confidence: 85 + rationale: "A WLAN extension stopped. This can accompany adapter shutdown or reset; it does not establish a driver defect." + remediation: "Investigate only if wireless loss coincides with this timestamp. Review adjacent adapter errors before changing software." + - provider: "Microsoft-Windows-DistributedCOM" + id: "10016" + severity: "info" + confidence: 90 + rationale: "DCOM denied an activation request. Common Windows component instances are expected; this event alone does not establish a fault." + remediation: "Leave COM permissions unchanged unless a reproducible application failure and the affected component require targeted investigation." + reference_url: "https://learn.microsoft.com/en-us/troubleshoot/windows-client/application-management/event-10016-logged-when-accessing-dcom" + reference_label: "Vendor guidance" + - provider: "Netwtw10" + id: "6062" + severity: "info" + confidence: 60 + rationale: "The driver logged an LSO trigger. The message alone does not explain its cause or establish adapter failure." + remediation: "Use adjacent error events and actual connection symptoms; do not change offload settings from this notification alone." + - provider: "Microsoft-Windows-Hyper-V-Hypervisor" + id: "167" + severity: "warning" + confidence: 90 + rationale: "The hypervisor reports that VM side-channel mitigations were not enabled with HyperThreading. This is a security configuration signal, not evidence that virtualization caused a crash." + remediation: "Review VM isolation requirements, firmware and applicable Windows mitigation guidance. Verify scheduler and guest settings before deciding whether SMT changes are necessary." + reference_url: "https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/manage/about-hyper-v-scheduler-type-selection" + reference_label: "Vendor guidance" + - provider: "volmgr" + id: "161" + severity: "warning" + confidence: 95 + rationale: "Windows could not create a crash dump. This reduces crash evidence but does not identify the cause of the crash or prove disk failure." + remediation: "Check dump configuration, pagefile and destination capacity. Preserve any other dumps and correlate the associated bugcheck." + reference_url: "https://learn.microsoft.com/en-us/troubleshoot/windows-server/performance/memory-dump-file-options" + reference_label: "Vendor guidance" + - provider: "Microsoft-Windows-WinRM" + id: "10149" + severity: "info" + confidence: 90 + rationale: "WinRM is not listening for remote-management requests. This may be intentional." + remediation: "Check listener and service configuration only if remote management is required; do not enable remote access just to remove this event." + reference_url: "https://learn.microsoft.com/en-us/windows/win32/winrm/installation-and-configuration-for-windows-remote-management" + reference_label: "Vendor guidance" + - provider: "winsrvext" + id: "100" + severity: "info" + confidence: 85 + rationale: "The named process delayed shutdown. A brief delay does not establish system instability." + remediation: "Investigate the application if shutdown delays recur or visibly affect use." + - provider: "Netwtw10" + id: "5005" + severity: "warning" + confidence: 95 + rationale: "The Intel wireless driver reported an internal adapter error and failure." + remediation: "Correlate wireless disconnects, device status and firmware/OEM driver changes. This message does not distinguish driver, firmware and hardware causes." + reference_url: "https://www.intel.com/content/www/us/en/support/articles/000089544/wireless.html" + reference_label: "Vendor guidance" + - provider: "Netwtw10" + id: "5032" + severity: "warning" + confidence: 90 + rationale: "The Intel wireless miniport reset watchdog was triggered." + remediation: "Review nearby adapter failure events and retest connectivity and sleep/resume with the OEM-supported configuration." + - provider: "Netwtw10" + id: "5002" + severity: "warning" + confidence: 95 + rationale: "The Intel driver reported an adapter malfunction." + remediation: "Inspect the adapter status and correlate loss of connectivity. Review OEM driver and firmware guidance before attributing hardware failure." + reference_url: "https://www.intel.com/content/www/us/en/support/articles/000089544/wireless.html" + reference_label: "Vendor guidance" + - provider: "Netwtw10" + id: "5010" + severity: "warning" + confidence: 95 + rationale: "The wireless adapter returned an invalid value to the Intel driver." + remediation: "Preserve recurrent errors and test the OEM-supported wireless configuration. A published fix for another driver version does not prove this capture has that defect." + reference_url: "https://www.intel.com/content/www/us/en/support/articles/000089544/wireless.html" + reference_label: "Vendor guidance" + - provider: "Microsoft-Windows-Perflib" + id: "1008" + severity: "warning" + confidence: 90 + rationale: "A performance-counter provider failed to open; counters for that service may be unavailable. This is not a hardware failure diagnosis." + remediation: "Check the named service and whether monitoring is affected. Repair its counter registration only after identifying the provider and preserving the existing configuration." + reference_url: "https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/lodctr" + reference_label: "Vendor guidance" + - provider: "Microsoft-Windows-WMI" + id: "63" + severity: "info" + confidence: 90 + rationale: "A WMI provider registered with LocalSystem privileges. The warning describes a privilege boundary, not proof of exploitation or repository corruption." + remediation: "Verify that the provider belongs to expected software. Investigate impersonation or access problems only if independently observed." + reference_url: "https://learn.microsoft.com/en-us/windows/win32/wmisdk/hostingmodel" + reference_label: "Vendor guidance" + - provider: "Microsoft-Windows-Winlogon" + id: "6004" + severity: "warning" + confidence: 80 + rationale: "A Winlogon notification subscriber failed a notification. Impact depends on the subscriber and the affected sign-in or servicing operation." + remediation: "Correlate sign-in, shutdown and servicing symptoms with the named subscriber. Preserve adjacent events before attempting repair." + - provider: "Microsoft-Windows-RestartManager" + id: "10010" + severity: "info" + confidence: 85 + rationale: "Restart Manager could not restart an application across the reported security identity boundary." + remediation: "If an installer left an application closed, restart it normally in the intended user session; do not change account permissions from this event alone." + - provider: "Microsoft-Windows-Search" + id: "10024" + severity: "warning" + confidence: 85 + rationale: "Windows Search terminated a filter host that stopped responding. Indexing or a file-format filter may be affected." + remediation: "Check whether search/indexing fails repeatedly. Identify the file or third-party filter involved before rebuilding the index." + - provider: "Microsoft-Windows-CodeIntegrity" + id: "3116" + severity: "info" + confidence: 95 + rationale: "Policy signature metadata was recorded; this message does not report a blocked driver." + remediation: "No repair is indicated by signature metadata alone." + - provider: "Microsoft-Windows-CodeIntegrity" + id: "3099" + severity: "info" + confidence: 95 + rationale: "An App Control policy was loaded; activation is not itself a driver failure." + remediation: "Review the policy details only when diagnosing a related block event." + reference_url: "https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/operations/event-id-explanations" + reference_label: "Vendor guidance" + - provider: "Microsoft-Windows-CodeIntegrity" + id: "3085" + severity: "info" + confidence: 90 + rationale: "WHQL signing requirements were not enforced for this boot. This does not mean all signature checks or memory integrity are disabled." + remediation: "Review intended signing policy if required; this event alone does not justify changing boot security." + reference_url: "https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/operations/event-id-explanations" + reference_label: "Vendor guidance" + - provider: "Microsoft-Windows-CodeIntegrity" + id: "3076" + severity: "warning" + confidence: 95 + rationale: "App Control audit policy would have blocked a file; audit mode did not block it." + remediation: "Identify the file, signer and policy. Review trust and compatibility before changing enforcement." + reference_url: "https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/operations/event-id-explanations" + reference_label: "Vendor guidance" + - provider: "Microsoft-Windows-CodeIntegrity" + id: "3077" + severity: "warning" + confidence: 95 + rationale: "App Control blocked a file that did not satisfy its policy." + remediation: "Identify the file and owning software, verify its signature and obtain a supported replacement. Preserve security enforcement." + reference_url: "https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/operations/event-id-explanations" + reference_label: "Vendor guidance" + +unknown_event_severity: "unanalysed" diff --git a/templates/diagnostics/config/diagnostics-watchlist.yaml b/templates/diagnostics/config/diagnostics-watchlist.yaml new file mode 100644 index 0000000..39ad323 --- /dev/null +++ b/templates/diagnostics/config/diagnostics-watchlist.yaml @@ -0,0 +1,99 @@ +# Curated advisory watchlist, reviewed 2026-09-15. No age-based matching. +# All matchers are exact case-insensitive field values or driver basenames. +# `requires` means all prerequisite matchers must be present. +# Filename matches identify candidates, not cryptographic vulnerability proofs. +reviewed: "2026-09-15" +driver_list_url: "https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/design/microsoft-recommended-driver-block-rules" +entries: + - id: winring0 + title: "WinRing0 low-level driver: documented vulnerability" + category: driver + match: + - section: system_drivers + field: PathName + basename: true + values: [WinRing0.sys, WinRing0x64.sys] + detail: "Microsoft documents WinRing0 as vulnerable. The filename is a candidate match; this inventory cannot verify the binary hash or whether it was exploited." + action: "Identify the owning hardware utility and obtain its supported replacement driver. Check Microsoft Defender and the vendor advisory; retain driver blocking." + reference_url: "https://support.microsoft.com/en-us/windows/security/threat-malware-protection/microsoft-defender-antivirus-alert-vulnerabledriver-winnt-winring0" + - id: dell-dbutil + title: "Dell dbutil_2_3 driver: CVE-2021-21551 candidate" + category: driver + match: + - section: system_drivers + field: PathName + basename: true + values: [dbutil_2_3.sys] + detail: "Dell documents an access-control vulnerability in dbutil_2_3.sys. File identity and remediation state still need verification; this is not proof of exploitation." + action: "Use Dell DSA-2021-088 guidance to verify and remediate the utility driver and its owning update tools." + reference_url: "https://www.dell.com/support/kbdoc/en-us/000186020/additional-information-regarding-dsa-2021-088-dell-client-platform-security-update-for-an-insufficient-access-control-vulnerability-in-the-dell-dbutil-driver" + - id: gigabyte-oc-guru + title: "GIGABYTE OC GURU II 2.08: documented driver vulnerability" + category: software + match: + - section: installed_programs + field: DisplayName + values: [OC GURU II, GIGABYTE OC GURU II] + version_field: DisplayVersion + versions: ["2.08"] + detail: "The vendor lists this exact software version as affected by low-level driver vulnerabilities. Other versions are not inferred to be affected." + action: "Follow the vendor advisory for a supported replacement or removal of the affected utility." + reference_url: "https://www.gigabyte.com/uk/Support/Security/1801" + - id: intel-wifi-observed + title: "Intel wireless driver: repeated failure signals" + category: driver + match: + - section: system_drivers + field: Name + values: [Netwtw10] + events: + provider: Netwtw10 + ids: ["5002", "5005", "5010", "5032"] + minimum: 2 + detail: "The installed driver has repeated adapter-failure events in this capture. Intel documents related firmware/driver failure patterns; its AX210 advisory does not prove the AX200 or this installed version has the same defect." + action: "Check the device status and correlate disconnects. Test the OEM-supported wireless driver and firmware; preserve evidence before changing the adapter configuration." + reference_url: "https://www.intel.com/content/www/us/en/support/articles/000089544/wireless.html" + weight_factor: 0 + - id: obs-overlay + title: "OBS and overlay tools: documented capture conflict" + category: software + match: + - section: installed_programs + field: DisplayName + values: [MSI Afterburner, RivaTuner Statistics Server, EVGA Precision X1, ASUS GPU Tweak II, Overwolf, FRAPS] + requires: + - section: installed_programs + field: DisplayName + values: [OBS Studio] + detail: "OBS lists these overlay tools as possible hook conflicts. Co-installation does not prove simultaneous use or a current capture failure." + action: "If capture fails, test with the overlay closed or disabled. RTSS 7.3.2 and newer offer the Microsoft Detours API hooking compatibility option." + reference_url: "https://obsproject.com/kb/game-capture-troubleshooting" + list_url: "https://obsproject.com/kb/known-conflicts" + - id: obs-audio-hooks + title: "OBS and audio enhancement software: documented conflict" + category: software + match: + - section: installed_programs + field: DisplayName + values: [Nahimic, Nahimic Audio, Sonic Radar, Sonic Studio] + - section: services + field: Name + values: [NahimicService] + requires: + - section: installed_programs + field: DisplayName + values: [OBS Studio] + detail: "OBS lists Nahimic and Sonic Radar among applications that can interfere with it. Installation alone does not establish that a conflict is active." + action: "For reproducible OBS problems, test with the relevant enhancement software closed, using its supported controls." + reference_url: "https://obsproject.com/kb/known-conflicts" + - id: smb1 + title: "SMBv1 enabled: documented security risk" + category: feature + match: + - section: enabled_windows_features + field: FeatureName + values: [SMB1Protocol, SMB1Protocol-Client, SMB1Protocol-Server] + enabled_only: true + detail: "Microsoft documents significant security vulnerabilities in SMBv1. This warning concerns the enabled protocol, not its age or evidence of an attack." + action: "Identify legacy dependencies and migrate them to SMB2/3 before disabling SMBv1 through supported Windows feature management." + reference_url: "https://learn.microsoft.com/en-us/windows-server/storage/file-server/troubleshoot/detect-enable-and-disable-smbv1-v2-v3" diff --git a/templates/diagnostics/config/themes.yaml b/templates/diagnostics/config/themes.yaml new file mode 100644 index 0000000..9376772 --- /dev/null +++ b/templates/diagnostics/config/themes.yaml @@ -0,0 +1,41 @@ +default: + label: "Default" + font: "DejaVu Sans" + mono_font: "DejaVu Sans Mono" + ink: "#22262b" + muted: "#66707a" + line: "#d7dce1" + paper_soft: "#f5f7f8" + accent: "#34495e" + info: "#385f7a" + warning: "#8a671c" + critical: "#7a3030" + success: "#356344" + +cic: + label: "CIC" + font: "DejaVu Sans" + mono_font: "DejaVu Sans Mono" + ink: "#17212b" + muted: "#526777" + line: "#b9d8df" + paper_soft: "#eef7f8" + accent: "#086f83" + info: "#007f95" + warning: "#a86712" + critical: "#a12e4b" + success: "#19765b" + +eridani: + label: "Eridani" + font: "DejaVu Sans" + mono_font: "DejaVu Sans Mono" + ink: "#282c22" + muted: "#68705a" + line: "#c8cbb9" + paper_soft: "#f3f2e8" + accent: "#536b3f" + info: "#526e61" + warning: "#8a6829" + critical: "#813f32" + success: "#49683a" diff --git a/templates/diagnostics/diagnostics.typ b/templates/diagnostics/diagnostics.typ new file mode 100644 index 0000000..d8238cc --- /dev/null +++ b/templates/diagnostics/diagnostics.typ @@ -0,0 +1,65 @@ +#import "modules/diagnostics-model.typ": diagnostics-model +#import "modules/diagnostics-normalize.typ": normalize, datetime-day + +#let diagnostics-file = sys.inputs.at("diagnostics", default: none) +#let diagnostics-source = sys.inputs.at("diagnostics-source", default: diagnostics-file) +#let author = sys.inputs.at("author", default: none) + +#if diagnostics-file == none { + panic( + "Missing diagnostics input.\n" + + "Usage: typst compile --input diagnostics=diagnostics/file.json " + + "--input author=\"Your name\" diagnostics.typ output.pdf" + ) +} + +#if author == none or str.trim(str(author)) == "" { + panic( + "Missing required diagnostics author.\n" + + "Add: --input author=\"Your name\"" + ) +} + +#let source = json(diagnostics-file) + +#if source.at("report_type", default: "") != "windows_system_maintenance" { + panic( + "Unsupported diagnostics JSON.\n" + + "Expected report_type=\"windows_system_maintenance\" in " + diagnostics-file + ) +} + +#if source.at("schema_version", default: 0) not in (1, 2) { + panic( + "Unsupported WinDiagnostics schema version: " + + str(source.at("schema_version", default: "missing")) + + ". This renderer currently supports schema_version 1 and 2." + ) +} + +#let rules = yaml("config/diagnostics-rules.yaml") +#let data = normalize(source, rules: rules, source-name: diagnostics-source) + +#if datetime-day(source.at("generated_at", default: "")) == none { + panic( + "Missing required diagnostics date.\n" + + "The WinDiagnostics JSON must contain generated_at." + ) +} + +#let themes = yaml("config/themes.yaml") +#let theme-name = lower(str(sys.inputs.at("theme", default: "default"))) + +#if theme-name not in themes { + panic( + "Unknown diagnostics theme: \"" + theme-name + "\".\n" + + "Choose one of: " + themes.keys().join(", ") + ) +} + +#show: diagnostics-model.with( + data: data, + author: author, + theme: themes.at(theme-name), + logo: "/assets/beffroi.png", +) diff --git a/templates/diagnostics/modules/diagnostics-model.typ b/templates/diagnostics/modules/diagnostics-model.typ new file mode 100644 index 0000000..1837a7d --- /dev/null +++ b/templates/diagnostics/modules/diagnostics-model.typ @@ -0,0 +1,365 @@ +#import "@preview/primaviz:0.10.0": progress-bar + +#let get(dict, key, default) = if key in dict and dict.at(key) != none { dict.at(key) } else { default } +#let color(theme, key) = rgb(str(get(theme, key, "#000000"))) +#let ink(theme) = color(theme, "ink") +#let muted(theme) = color(theme, "muted") +#let accent(theme) = color(theme, "accent") +#let line-color(theme) = color(theme, "line") +#let soft(theme) = color(theme, "paper_soft") + +#let severity-color(theme, severity) = { + let value = lower(str(severity)) + if value == "critical" or value == "high" { color(theme, "critical") } + else if value == "warning" or value == "medium" { color(theme, "warning") } + else if value == "success" or value == "ok" { color(theme, "success") } + else if value == "unanalysed" { color(theme, "info") } + else { color(theme, "info") } +} + +#let badge(body, fill) = box( + inset: (x: 5pt, y: 2pt), radius: 2pt, + fill: fill.lighten(86%), stroke: .5pt + fill.lighten(50%), + text(size: 7pt, weight: "bold", fill: fill)[#upper(str(body))], +) + +#let heading(theme, body) = block(above: 10pt, below: 5pt, width: 100%)[ + #text(size: 14pt, weight: "bold", fill: accent(theme))[#body] + #v(2pt) + #line(length: 100%, stroke: .7pt + line-color(theme)) +] + +#let part-title(theme, number, body, description: none) = block(width: 100%, below: 10pt)[ + #text(size: 7.5pt, weight: "bold", fill: muted(theme))[SECTION #number] + #v(2pt) + #text(size: 19pt, weight: "bold", fill: accent(theme))[#body] + #if description != none { v(2pt); text(size: 8.5pt, fill: muted(theme))[#description] } + #v(4pt) + #line(length: 100%, stroke: .8pt + line-color(theme)) +] + +#let panel(theme, body, stroke: none, fill: none) = block( + width: 100%, inset: 8pt, radius: 3pt, + fill: if fill == none { soft(theme) } else { fill }, + stroke: .5pt + if stroke == none { line-color(theme) } else { stroke }, + body, +) + +#let metric(theme, title, value, note: none, tone: none) = { + let tone = if tone == none { accent(theme) } else { tone } + block(width: 100%, inset: 7pt, radius: 3pt, fill: tone.lighten(91%), stroke: .5pt + tone.lighten(60%))[ + #text(size: 7pt, weight: "bold", fill: muted(theme))[#upper(title)] + #v(2pt) + #text(size: 16pt, weight: "bold", fill: tone)[#value] + #if note != none { v(1pt); text(size: 7pt, fill: muted(theme))[#note] } + ] +} + +#let header(theme, data, logo) = { + grid(columns: (1fr, auto), align: (left, right + horizon), + text(size: 7.5pt, weight: "bold", fill: muted(theme))[ + Beffroi — Windows diagnostics + ], + image(logo, height: 8mm, fit: "contain"), + ) + v(3pt) + line(length: 100%, stroke: .5pt + line-color(theme)) +} + +#let footer(theme, data) = grid( + columns: (1fr, auto), align: (left, right), + text(size: 7pt, fill: muted(theme))[#get(data, "computer", "Unknown") · #get(data, "generated", "Unknown")], + text(size: 7pt, fill: muted(theme))[Page #context counter(page).display()], +) + +#let short-text(value, limit: 400) = { + let text = str(value) + if text.len() > limit { text.slice(0, limit) + "… [excerpt; full text in source JSON]" } else { text } +} +#let finding-target(index) = label("diagnostic-finding-" + str(index)) + +#let finding-card(theme, finding, show-remediation: true, target-index: none, link-index: none) = { + let tone = severity-color(theme, get(finding, "severity", "info")) + if target-index != none { [#metadata("finding") #finding-target(target-index)] } + block(width: 100%, breakable: true, inset: 7pt, radius: 3pt, + stroke: (left: 2.5pt + tone, top: .5pt + line-color(theme), right: .5pt + line-color(theme), bottom: .5pt + line-color(theme)), + )[ + #grid(columns: (1fr, auto), gutter: 6pt, + text(weight: "bold", fill: ink(theme))[#get(finding, "title", "Finding")], + [#badge(get(finding, "severity", "info"), tone) #h(3pt) #badge(str(get(finding, "confidence", 50)) + "% confidence", tone)], + ) + #v(3pt) + #text(size: 8.5pt, fill: ink(theme))[#get(finding, "detail", "")] + #if show-remediation and get(finding, "evidence", "") != "" { + v(2pt) + text(size: 7.5pt, fill: muted(theme))[Evidence: #short-text(finding.evidence)] + } + #if show-remediation and get(finding, "watch_id", none) != none { + v(2pt) + text(size: 7.5pt, fill: accent(theme))[#link(label("watchlist-" + finding.watch_id))[View known-issue list →]] + } + #if link-index != none { + v(3pt) + text(size: 7.5pt, weight: "bold", fill: accent(theme))[ + #link(finding-target(link-index))[View resolution →] + ] + } + #if get(finding, "fading", false) and get(finding, "weight_factor", 1.0) < 1.0 { + v(2pt) + let pct = calc.round(get(finding, "weight_factor", 1.0) * 100) + text(size: 7pt, style: "italic", fill: muted(theme))[Age-adjusted to #pct% weight at #get(finding, "age_days", 0) days old; never reduced below 50%.] + } + #if show-remediation and (get(finding, "resolution_steps", ()).len() > 0 or get(finding, "remediation", "") != "") { + v(4pt) + text(size: 7.5pt, weight: "bold", fill: tone)[RESOLUTION PATH] + v(2pt) + let steps = get(finding, "resolution_steps", ()) + if steps.len() > 0 { + for (index, step) in steps.enumerate() { + grid(columns: (10pt, 1fr), gutter: 3pt, text(size: 7.8pt, weight: "bold", fill: tone)[#str(index + 1).], text(size: 8pt, fill: ink(theme))[#step]) + v(1.5pt) + } + } else { + grid(columns: (10pt, 1fr), gutter: 3pt, text(size: 7.8pt, weight: "bold", fill: tone)[1.], text(size: 8pt, fill: ink(theme))[#get(finding, "remediation", "")]) + } + let url = get(finding, "reference_url", "") + if url != "" { v(2pt); text(size: 7.5pt, fill: accent(theme))[#link(url)[#get(finding, "reference_label", "Reference guidance") ↗]] } + } + #if get(finding, "count", 0) > 1 { + v(2pt) + text(size: 7.5pt, fill: muted(theme))[Observed #get(finding, "count", 0) times in the captured window.] + } + ] + v(5pt) +} + +#let evidence(theme, item) = block(width: 100%, breakable: get(item, "text", "").len() > 2000, below: 6pt)[ + #let tone = severity-color(theme, get(item, "severity", "info")) + #text(size: 9pt, weight: "bold", fill: tone)[#get(item, "title", "Evidence")] + #v(3pt) + #block(width: 100%, inset: 6pt, radius: 2pt, fill: tone.lighten(94%), stroke: (left: 2pt + tone, top: .4pt + line-color(theme), right: .4pt + line-color(theme), bottom: .4pt + line-color(theme)))[ + #text(font: get(theme, "mono_font", "DejaVu Sans Mono"), size: 6.8pt, fill: ink(theme))[ + #get(item, "text", "") + ] + ] +] + +#let diagnostics-model(data: (:), author: "", theme: (:), logo: "/assets/beffroi.png", body) = { + set page( + paper: "a4", margin: (top: 18mm, bottom: 17mm, left: 18mm, right: 18mm), + header: context header(theme, data, logo), footer: context footer(theme, data), + ) + set text(font: get(theme, "font", "DejaVu Sans"), size: 9pt, fill: ink(theme), lang: "en") + set par(leading: .55em, spacing: .5em) + + let findings = get(data, "findings", ()) + let priority-findings = findings.filter(item => { + let title = get(item, "title", "") + title.contains("System-file") or title.contains("Firewall") + }) + priority-findings += findings.filter(item => { + let title = get(item, "title", "") + not title.contains("System-file") and not title.contains("Firewall") + }) + let counts = get(data, "issue_counts", (:)) + let critical = get(counts, "critical", 0) + let warnings = get(counts, "warning", 0) + let system = get(data, "system", (:)) + let ram-total = get(system, "ram_total_gb", 0) + let ram-free = get(system, "ram_free_gb", 0) + let disks = get(data, "disk_free", ()) + let health-score = get(data, "health_score", 0) + let analysis-confidence = get(data, "analysis_confidence", 50) + let assessment-tone = if critical > 0 { color(theme, "critical") } else if warnings > 0 { color(theme, "warning") } else { color(theme, "success") } + let health-tone = if get(data, "collection_incomplete", false) { color(theme, "warning") } else if health-score < 50 { color(theme, "critical") } else if health-score < 75 { color(theme, "warning") } else { color(theme, "success") } + + // Page 1: deliberately short and decision-oriented. + text(size: 7.5pt, weight: "bold", fill: muted(theme))[SECTION 01 · EXECUTIVE OVERVIEW] + v(3pt) + block(below: 8pt)[ + #text(size: 22pt, weight: "bold", fill: accent(theme))[Windows diagnostic assessment] + #v(3pt) + #text(size: 10.5pt, fill: muted(theme))[ + #get(data, "computer", "Unknown computer") · #get(data, "mode", "Unknown") collection · Administrator: #get(data, "administrator", "Unknown") + ] + ] + + panel(theme, stroke: assessment-tone, fill: assessment-tone.lighten(92%))[ + #text(size: 8pt, weight: "bold", fill: assessment-tone)[OVERALL ASSESSMENT] + #v(3pt) + #text(size: 17pt, weight: "bold", fill: assessment-tone)[#get(data, "health", "Unknown")] + #v(3pt) + #text(size: 8.5pt)[Generated #get(data, "generated", "Unknown") · Reviewed by #author] + ] + + v(7pt) + grid(columns: (1fr, 1fr, 1fr, 1fr), gutter: 5pt, + metric(theme, "Critical", str(critical), tone: color(theme, "critical")), + metric(theme, "Warnings", str(warnings), tone: color(theme, "warning")), + metric(theme, "RAM maximum", str(ram-total) + " GB"), + metric(theme, "Analysis confidence", str(analysis-confidence) + "%"), + ) + + v(5pt) + if get(data, "collection_incomplete", false) { + text(size: 8pt, weight: "bold", fill: color(theme, "warning"))[Collection is partial. The score covers observed signals only; unavailable checks cannot establish health. Confidence is capped at 50%.] + } + v(7pt) + panel(theme, stroke: health-tone)[ + #grid(columns: (1fr, auto), + [#text(size: 8pt, weight: "bold", fill: ink(theme))[#if get(data, "collection_incomplete", false) { [OBSERVED SIGNAL SCORE · PARTIAL COLLECTION] } else { [HEALTH ANALYSIS] }]], + [#text(size: 15pt, weight: "bold", fill: health-tone)[#health-score / 100]], + ) + #v(4pt) + #block(width: 100%, height: 7pt, radius: 3.5pt, fill: line-color(theme))[ + #block(width: health-score * 1%, height: 100%, radius: 3.5pt, fill: health-tone) + ] + #v(3pt) + #text(size: 7pt, fill: muted(theme))[Heuristic score: 100 − 8 per critical − 2 per warning − 1 per unanalysed signal, with approved age fading. Analysis confidence: #analysis-confidence%. Neither value is a failure probability.] + ] + + heading(theme, "Priority findings") + if findings.len() == 0 { + panel(theme)[No actionable exceptions were detected. This is not proof that the system is fault-free.] + } else { + for finding in priority-findings.slice(0, calc.min(4, priority-findings.len())) { + let finding-index = findings.position(item => item == finding) + finding-card(theme, finding, show-remediation: false, link-index: finding-index) + } + } + + if disks.len() > 0 { + heading(theme, "Storage headroom") + block(width: 100%, inset: 7pt, radius: 3pt, fill: soft(theme), stroke: .5pt + line-color(theme))[ + #for disk in disks.slice(0, calc.min(4, disks.len())) { + let free-percent = get(disk, "free_percent", 0) + let disk-tone = if free-percent < 10 { color(theme, "critical") } else if free-percent < 20 { color(theme, "warning") } else { color(theme, "success") } + grid(columns: (15mm, 1fr, 34mm), gutter: 5pt, align: (left + horizon, left + horizon, right + horizon), + text(size: 8pt, weight: "bold")[#get(disk, "drive", "Disk")], + progress-bar(free-percent, width: 100%, height: 7pt, show-value: false, color: disk-tone, background: line-color(theme), theme: (background: soft(theme))), + text(size: 7.5pt, fill: muted(theme))[#str(get(disk, "free_gb", 0)) GB · #str(free-percent)% free], + ) + v(3pt) + } + #text(size: 7pt, fill: muted(theme))[Free capacity is shown rather than used capacity; low headroom is the actionable condition.] + ] + } + + pagebreak() + + part-title(theme, "02", "Findings requiring attention", description: "Actionable exceptions and the event evidence that supports them.") + heading(theme, "Resolution plan") + for (index, finding) in findings.enumerate() { finding-card(theme, finding, target-index: index) } + + pagebreak() + heading(theme, "Correlated event evidence") + [Requested history: #get(get(data, "parameters", (:)), "event_log_days", 7) days; configured maximum: #get(get(data, "parameters", (:)), "max_event_errors", 100) per log. Returned Windows levels: #get(data, "event_counts", (:)).pairs().map(pair => pair.at(0) + ": " + str(pair.at(1))).join(", "). Counts describe captured records; see coverage for truncation and unavailable logs.] + v(5pt) + let event-groups = get(data, "event_groups", ()) + let contextual = event-groups.filter(event => get(event, "severity", "info") == "info") + if contextual.len() > 0 { + text(size: 8pt)[Contextual events are summarized below; full messages remain in the JSON.] + table(columns: (1fr, auto, auto, 1.4fr), inset: 3pt, stroke: .3pt + line-color(theme), + table.header([Provider], [ID], [Count], [Interpretation]), + ..contextual.map(event => ([#event.provider], [#event.id], [#str(event.count)], [#event.rationale])).flatten(), + ) + v(6pt) + } + [Actionable groups show one representative message (up to 600 characters). All occurrence counts and latest timestamps are retained; other message variants remain in source JSON. Reliability history supplements events missing from the bounded logs.] + v(4pt) + for event in event-groups.filter(event => get(event, "severity", "info") != "info") { + let tone = severity-color(theme, get(event, "severity", "info")) + block(width: 100%, breakable: true, below: 5pt, inset: 6pt, fill: tone.lighten(95%), stroke: (left: 2.5pt + tone, top: .4pt + line-color(theme), right: .4pt + line-color(theme), bottom: .4pt + line-color(theme)), radius: 2pt)[ + #grid(columns: (1fr, auto), gutter: 5pt, + [*#get(event, "provider", "Unknown")* · Event #get(event, "id", "?")], + [#badge(get(event, "severity", "info"), tone) #h(3pt) #badge(str(get(event, "count", 1)) + "×", tone)], + ) + #v(2pt) + #text(size: 8pt)[#short-text(get(event, "messages", (get(event, "message", ""),)).first(), limit: 600)] + #if get(event, "rationale", "") != "" { v(2pt); text(size: 7.5pt, style: "italic", fill: tone)[#get(event, "rationale", "")] } + #v(1pt) + #text(size: 7pt, fill: muted(theme))[Log: #get(event, "log", "Unknown") · Windows level: #str(get(event, "level", "Unknown")) (#get(event, "level_display", "Unknown")) · Latest captured: #get(event, "display_time", get(event, "time", "Unknown"))] + ] + } + + pagebreak() + + part-title(theme, "03", "Technical evidence", description: "System context, selected source evidence, and an audit of collector coverage.") + + heading(theme, "System profile") + table( + columns: (32mm, 1fr, 32mm, 1fr), inset: 5pt, stroke: .4pt + line-color(theme), + fill: (x, y) => if calc.rem(y, 2) == 0 { soft(theme) } else { none }, + [Computer], [#get(data, "computer", "Unknown")], [Administrator], [#get(data, "administrator", "Unknown")], + [Operating system], [#get(system, "os", "Unknown")], [Build], [#get(system, "build", "Unknown")], + [CPU], [#get(system, "cpu", "Unknown")], [Cores / threads], [#get(system, "cores", "?") / #get(system, "threads", "?")], + [Memory], [#str(ram-total) GB total], [Free at capture], [#str(ram-free) GB], + ) + + if disks.len() > 0 { + heading(theme, "Storage capacity") + for disk in disks { + let used = 100 - get(disk, "free_percent", 0) + panel(theme)[ + #grid(columns: (1fr, auto), [*#get(disk, "drive", "Disk")*], [#str(get(disk, "free_gb", 0)) GB free of #str(get(disk, "size_gb", 0)) GB]) + #v(4pt) + #block(width: 100%, height: 5pt, radius: 2.5pt, fill: line-color(theme))[ + #block(width: used * 1%, height: 100%, radius: 2.5pt, fill: if used > 90 { color(theme, "critical") } else if used > 80 { color(theme, "warning") } else { accent(theme) }) + ] + ] + v(4pt) + } + } + + heading(theme, "Inventory summary") + let inventory = get(data, "inventory", ()) + table( + columns: (1fr, 22mm), inset: 4pt, stroke: .4pt + line-color(theme), + table.header([Category], [Count]), + ..inventory.map(item => ([#get(item, "label", "")], [#get(item, "count", 0)])).flatten(), + ) + + heading(theme, "Selected source evidence") + [Selected evidence shows up to three records and 1,200 characters per expanded section. Routine service/driver inventories, successful native command dumps and update successes are summarized. Complete data remains in the source JSON.] + v(5pt) + for item in get(data, "excerpts", ()) { evidence(theme, item) } + + heading(theme, "Known-issue watchlist") + let watchlist = get(data, "watchlist", (:)) + text(size: 8pt)[Reviewed #get(watchlist, "reviewed", "Unknown"). Matches raise review warnings; they do not establish crash causation. This curated list is not an exhaustive vulnerability scan. Advisory warnings add no score penalty; observed failures retain their event penalties.] + v(3pt) + text(size: 8pt, fill: accent(theme))[#link(get(watchlist, "driver_list_url", ""))[Microsoft vulnerable driver list ↗]] + v(4pt) + table(columns: (20mm, 1fr, 27mm), inset: 4pt, stroke: .3pt + line-color(theme), + table.header([Type], [Known issue], [Reference]), + ..get(watchlist, "entries", ()).map(entry => ( + [#entry.category], + [#metadata("watchlist") #label("watchlist-" + entry.id) #entry.title], + [#link(get(entry, "list_url", entry.reference_url))[Source ↗]], + )).flatten(), + ) + + pagebreak() + heading(theme, "Analysis coverage") + [Every supplied WinDiagnostics JSON section is accounted for. This table records how each section contributed without reproducing low-value bulk data.] + v(4pt) + table( + columns: (1fr, 1fr, 15mm), inset: 4pt, stroke: none, + fill: (x, y) => if y == 0 { soft(theme) } else { + let item = get(data, "coverage", ()).at(y - 1, default: (:)) + severity-color(theme, get(item, "severity", "info")).lighten(92%) + }, + table.header([Collector section], [Treatment], [Records]), + ..get(data, "coverage", ()).map(item => ( + [#get(item, "section", "")], [#get(item, "use", "")], [#if get(item, "records", 0) == "Unavailable" { [—] } else { get(item, "records", 0) }], + )).flatten(), + ) + + v(3pt) + text(size: 7pt, fill: muted(theme))[— = unavailable record count.] + + v(8pt) + text(size: 7pt, fill: muted(theme))[ + Source: #get(data, "source", "Unknown"). This synthesis is heuristic: it prioritizes exceptions and suppresses routine inventory, but does not replace targeted diagnosis. + ] +} diff --git a/templates/diagnostics/modules/diagnostics-normalize.typ b/templates/diagnostics/modules/diagnostics-normalize.typ new file mode 100644 index 0000000..a48d426 --- /dev/null +++ b/templates/diagnostics/modules/diagnostics-normalize.typ @@ -0,0 +1,845 @@ +// Pure-Typst normalizer for WinDiagnostics schema_version 1 and 2 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 value-text(value) = { + if type(value) == dictionary { + value.pairs().map(pair => pair.at(0) + ": " + value-text(pair.at(1))).join("; ") + } else if type(value) == array { + value.map(value-text).join("\n") + } else if value == none { "Unknown" } + else if value == true { "Yes" } + else if value == false { "No" } + else { str(value) } +} +#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) or get(section(report, name), "status", "missing") != "ok" { "Unavailable" } else { get(section(report, name), "count", "Unknown") } +#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 event-sections(report) = { + let names = get(report, "sections", (:)).keys() + ( + (if "recent_system_events" in names { "recent_system_events" } else { "recent_system_errors" }, "System"), + (if "recent_application_events" in names { "recent_application_events" } else { "recent_application_errors" }, "Application"), + ("code_integrity", "Code Integrity"), + ) +} +#let windows-level(level) = if level == 1 { "Critical" } else if level == 2 { "Error" } else if level == 3 { "Warning" } else if level == 4 { "Information" } else if level == 5 { "Verbose" } else { "Unknown" } + +#let raw-events(report) = { + let events = () + for (section-name, log-name) in event-sections(report) { + 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, + source_section: section-name, + level: get(item, "Level", if section-name.ends-with("_errors") { 2 } else { none }), + level_display: get(item, "LevelDisplayName", "Unknown"), + )) + } + } + 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 and get(group, "log", "") == get(event, "log", "") and get(group, "level", none) == get(event, "level", none)) + if index == none { + let item = event + item.message = event-summary(event) + item.insert("count", 1) + item.insert("messages", (item.message,)) + item.insert("occurrences", (event,)) + let rule = event-rule(rules, event) + let fading = fade-weight(rule, event.time, reference-day) + item.insert("severity", if rule == none and get(event, "level", none) in (4, 5) { "info" } else if rule == none { get(rules, "unknown_event_severity", "unanalysed") } else { get(rule, "severity", "unanalysed") }) + item.insert("rationale", if rule == none and get(event, "level", none) in (4, 5) { "Informational record retained without a reviewed interpretation; no fault inferred." } else if rule == none { "No reviewed interpretation is available for this event." } 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 config/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 + item.occurrences.push(event) + 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) + ": " + if pair.at(1) in ("LastWriteTime", "TimeGenerated", "DriverDate") { display-time(get(item, pair.at(1), "Unknown")) } else { value-text(get(item, pair.at(1), "Unknown")) }).join("\n", default: "") +} + +#let watchlist-catalog = yaml("../config/diagnostics-watchlist.yaml") + +#let watch-matches(report, matcher) = { + let name = matcher.section + // Never interpret incomplete collection as confirmed installation/enabling. + if section-status(report, name) != "ok" { () } else { + section-data(report, name).filter(item => { + let value = lower(value-text(get(item, matcher.field, ""))).trim() + if get(matcher, "basename", false) { + value = value.trim("\"").replace("\\", "/").split("/").last() + } + let identity = matcher.values.any(candidate => lower(candidate) == value) + let version-ok = get(matcher, "versions", ()).len() == 0 or get(matcher, "versions", ()).contains(value-text(get(item, get(matcher, "version_field", "DriverVersion"), ""))) + let state-ok = not get(matcher, "enabled_only", false) or get(item, "State", none) in (2, "Enabled", "enabled") + identity and version-ok and state-ok + }).map(item => ( + section: name, + identity: value-text(get(item, matcher.field, "Unknown")), + version: value-text(get(item, "DriverVersion", get(item, "DisplayVersion", none))), + state: value-text(get(item, "State", none)), + )) + } +} + +#let watchlist-findings(report, events, catalog: watchlist-catalog) = { + let matches = () + for entry in catalog.entries { + let evidence = entry.match.map(matcher => watch-matches(report, matcher)).flatten().dedup() + let prerequisites = get(entry, "requires", ()).all(matcher => watch-matches(report, matcher).len() > 0) + let event-gate = get(entry, "events", none) + let signals = if event-gate == none { () } else { events.filter(e => e.provider == event-gate.provider and e.id in event-gate.ids) } + if evidence.len() > 0 and prerequisites and (event-gate == none or signals.len() >= event-gate.minimum) { + matches.push(( + severity: "warning", title: entry.title, watch_id: entry.id, + detail: entry.detail + " Evidence: " + evidence.map(e => e.section + " / " + e.identity + " (version " + e.version + "; state " + e.state + ")").join("; ") + if signals.len() > 0 { ". Matching events: " + str(signals.len()) + "." } else { "." }, + confidence: 85, weight_factor: get(entry, "weight_factor", 0), + resolution_steps: (entry.action,), reference_url: entry.reference_url, + reference_label: "Known-issue advisory", matched_records: evidence, + )) + } + } + matches +} + +// Reliability history can retain actionable records omitted from a bounded log. +// Keep only reviewed actionable provider/ID pairs and avoid counting the same +// source event twice. Same-second comparison allows collector timestamp rounding; +// normalized messages must also match so distinct events are not discarded. +#let reliability-events(report, raw, rules) = { + let extra = () + for item in section-data(report, "reliability_records") { + let event = (provider: get(item, "SourceName", "Unknown"), id: value-text(get(item, "EventIdentifier", "?")), time: value-text(get(item, "TimeGenerated", "Unknown")), message: value-text(get(item, "Message", "No message")), log: "Reliability", source_section: "reliability_records", level: none, level_display: "Not supplied") + let rule = event-rule(rules, event) + let when = datetime-second(event.time) + let duplicate = (raw + extra).any(e => e.provider == event.provider and e.id == event.id and get(e, "message", "").replace(regex("\\s+"), " ").trim() == event.message.replace(regex("\\s+"), " ").trim() and (e.time == event.time or (when != none and datetime-second(e.time) == when))) + if rule != none and get(rule, "severity", "info") in ("warning", "critical") and not duplicate { extra.push(event) } + } + extra +} + +#let normalize(report, rules: (:), source-name: "WinDiagnostics JSON") = { + let schema = get(report, "schema_version", 0) + if schema not in (1, 2) { panic("Unsupported WinDiagnostics schema_version: " + str(schema) + "; supported versions: 1 and 2") } + + if type(report) != dictionary { panic("Malformed WinDiagnostics report: expected a JSON object") } + if type(get(report, "sections", (:))) != dictionary { panic("Malformed WinDiagnostics sections: expected an object") } + for (name, value) in get(report, "sections", (:)).pairs() { + if type(value) != dictionary or type(get(value, "data", ())) != array { + panic("Malformed WinDiagnostics section " + name + ": expected an envelope with optional data array") + } + } + 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", (:)) + // Use available check metadata regardless of the producer's version label. + // Older Compact captures contain summary values without check envelopes. + let compact-checks = compact and get(report, "sections", (:)).len() > 0 + + 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 reliability = reliability-events(report, raw, rules) + let events = group-events(raw + reliability, 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", "missing") not in ("ok", "missing") { + findings.push((severity: "warning", title: "Collector coverage: " + name, detail: get(value, "status", "") + ": " + str(get(value, "error", "No result collected")), confidence: 100, weight_factor: 0)) + } + } + + findings += watchlist-findings(report, raw) + + let catalog-cluster = catalog-correlation(raw + reliability) + 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.rationale, + evidence: event.messages.first(), + event_key: event.provider + "/" + event.id, + 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").map(device => { + for (key, alias) in (("FriendlyName", "Name"), ("Class", "PNPClass"), ("InstanceId", "DeviceID")) { + if get(device, key, none) == none { device.insert(key, get(device, alias, "Unknown")) } + } + device + }) } + for device in problem-devices { + if (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", "Device"))) + " is disabled (Code 22)", detail: "The device is disabled. This does not establish 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 the device works under its normal workload."))) + } + } + if problem-devices.len() > 0 or (compact and (not compact-checks or section-status(report, "problem_devices") == "ok") 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 + ) + + // Only explicit health/signing evidence creates a finding, never absent fields. + for (source, records) in (("storage.storage_health (Get-PhysicalDisk)", get(storage-root, "storage_health", ())), ("storage_disks (Get-Disk)", section-data(report, "storage_disks"))) { + let unhealthy = records.filter(item => lower(value-text(get(item, "HealthStatus", ""))) in ("warning", "unhealthy", "1", "2")) + if unhealthy.len() > 0 { + findings.push((severity: "warning", title: "Storage health requires review: " + source, + detail: unhealthy.map(item => value-text(get(item, "FriendlyName", "Unidentified disk")) + ": " + value-text(get(item, "HealthStatus", "Unknown"))).join("; ") + ". Source device sets are not joined by position.", + confidence: 90, resolution_steps: ("Preserve important data and identify each disk using its serial or device identifier. Review vendor diagnostics before attributing physical failure.",))) + } + } + let unsigned = section-data(report, "signed_drivers").filter(item => get(item, "IsSigned", none) == false) + if unsigned.len() > 0 { + findings.push((severity: "warning", title: "Drivers explicitly report unsigned status", + detail: str(unsigned.len()) + " records in signed_drivers report IsSigned=false. This is not proof of malware or crash causation. " + unsigned.slice(0, calc.min(3, unsigned.len())).map(item => value-text(get(item, "DeviceName", get(item, "InfName", "Unnamed device")))).join("; ") + if unsigned.len() > 3 { "; remaining identities are in source JSON." } else { "." }, + confidence: 90, resolution_steps: ("Verify each driver package and signer with the OEM. Obtain a trusted signed replacement where appropriate; keep signing enforcement enabled.",))) + } + + 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")), + ) + } + + if compact-checks { + for (index, name) in ("installed_programs", "appx_packages", "startup_programs", "automatic_services").enumerate() { + if section-status(report, name) != "ok" { inventory.at(index).count = "Unavailable" } + } + } + // Absent sections belong only in the final coverage recap. + let inventory-names = if compact { ("installed_programs", "appx_packages", "startup_programs", "automatic_services") } else { ("installed_programs", "appx_packages", "automatic_services", "signed_drivers", "hotfixes", "non_microsoft_scheduled_tasks", "startup_programs", "active_tcp_listeners") } + if not compact or compact-checks { + inventory = inventory.enumerate().filter(pair => section-status(report, inventory-names.at(pair.at(0))) != "missing").map(pair => pair.at(1)) + } + 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 evidence-sections = ( + "signed_drivers", "system_drivers", "services", "storage_disks", "storage_pnp_devices", + "driver_store", "filter_drivers", "filter_instances", "upper_filters", "lower_filters", + "boot_configuration", "enabled_windows_features", "reliability_records", "minidumps", + ) + let count-only-sections = ("system_drivers", "services", "storage_pnp_devices", "driver_store", "filter_instances", "upper_filters", "lower_filters", "boot_configuration") + let excerpt-fields = ( + signed_drivers: (("Device", "DeviceName"), ("Driver", "DriverVersion"), ("INF", "InfName"), ("IsSigned", "IsSigned")), + storage_disks: (("Disk", "Number"), ("Name", "FriendlyName"), ("Bus", "BusType"), ("Health", "HealthStatus"), ("IsBoot", "IsBoot")), + minidumps: (("File", "Name"), ("Bytes", "Length"), ("Modified", "LastWriteTime")), + enabled_windows_features: (("Feature", "FeatureName"),), + reliability_records: (("Source", "SourceName"), ("Event", "EventIdentifier"), ("Product", "ProductName")), + ) + for name in evidence-sections { + let records = section-data(report, name) + if name != "signed_drivers" and section-status(report, name) != "missing" { inventory.push((label: name.replace("_", " "), count: section-count(report, name))) } + let failed = section-status(report, name) != "ok" + if records.len() > 0 and (name not in count-only-sections or failed) { + // Reliability successes are inventory noise; actionable records feed events. + let candidates = if name == "reliability_records" { + records.filter(item => { + let rule = event-rule(rules, (provider: get(item, "SourceName", ""), id: value-text(get(item, "EventIdentifier", "")))) + rule != none and get(rule, "severity", "info") in ("warning", "critical") + }) + } else if name == "signed_drivers" { + let relevant(item) = get(item, "IsSigned", none) == false or problem-devices.any(device => get(item, "DeviceID", none) != none and get(item, "DeviceID", none) == get(device, "InstanceId", none)) + records.filter(relevant) + records.filter(item => not relevant(item)) + } else { records } + let selected = candidates.slice(0, calc.min(3, candidates.len())) + if selected.len() > 0 { + let fields = get(excerpt-fields, name, ()) + let text = selected.map(item => if fields.len() > 0 { object-lines(item, fields).replace("\n", " · ") } else { value-text(item) }).join("\n") + excerpts.push((title: upper(name.replace("_", " ")), severity: if failed { "warning" } else { "info" }, text: "Source: sections." + name + "; showing " + str(selected.len()) + " of " + str(records.len()) + " returned records. Full records remain in source JSON.\n" + text.slice(0, calc.min(1200, text.len())) + if text.len() > 1200 { "\n[Display shortened at 1200 characters; see source JSON.]" } else { "" })) + } + } + } + for name in ("component_store", "system_file_check") { + if section-status(report, name) != "ok" and section-data(report, name).len() > 0 { + excerpts.push((title: upper(name), severity: "warning", text: repr(section-data(report, name)))) + } + } + if not compact and storage-root != (:) { + excerpts.push((title: "STORAGE SOURCES", severity: "info", text: get(storage-root, "physical_disks", ()).map(item => object-lines(item, (("Disk", "Model"), ("Interface", "InterfaceType"), ("Status", "Status"), ("Firmware", "FirmwareRevision"))).replace("\n", " · ")).join("\n"))) + } + + let storage-health = get(storage-root, "storage_health", ()) + let unhealthy-storage = storage-health.filter(item => lower(str(get(item, "HealthStatus", "Unknown"))) != "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 summary; check individual collection states", records: 1, severity: "info")) } + for (name, value) in get(report, "sections", (:)).pairs() { + let status = get(value, "status", "missing") + let event-source = event-sections(report).any(pair => pair.at(0) == name) + let use = if status != "ok" { status + ": " + str(get(value, "error", "No verified result")) } + else if legacy-incomplete(report, name) { "Legacy conversion incomplete; recollect JSON" } + else if event-source { "Grouped by log, provider, ID and Windows level" } + else if name in count-only-sections { "Count and watchlist review; full records in source" } + else if name == "reliability_records" { "Reviewed failure events; successful updates omitted" } + else if name in evidence-sections { "Count and selected fields (up to 3 records)" } + else if compact { "Compact summary check completed" } + else if name in inventory-sections { "Inventory count" } + else if name in detailed-sections { "Structured health evidence" } + else { "Retained in source; no specific analysis" } + if event-source { + use += "; truncation: " + if get(value, "truncated", none) == true { "yes; records omitted" } else if get(value, "truncated", none) == false { "no" } else { "unknown" } + use += "; limit: " + str(get(value, "limit", "unknown")) + } + coverage.push((section: name, use: use, records: section-count(report, name), severity: if status not in ("ok", "missing") or legacy-incomplete(report, name) { "warning" } else { "info" })) + } + // Outer success does not imply that nested APIs were available. + for (name, records) in (("storage.storage_health", get(storage-root, "storage_health", ())), ("storage.reliability_counters", get(storage-root, "reliability_counters", ())), ("defender", (defender,))) { + for item in records { + if get(item, "status", "ok") != "ok" or get(item, "available", true) == false { + coverage.push((section: name, use: str(get(item, "status", "unavailable")) + ": " + str(get(item, "error", "Nested check unavailable")), records: "Unavailable", severity: "warning")) + } + } + } + let recap-sections = if compact { ("operating_system", "computer_system", "problem_devices") } else { ("operating_system", "computer_system", "storage", "problem_devices", "defender", "component_store", "system_file_check") + inventory-sections + evidence-sections + ("bios", "cpu", "memory_modules", "motherboard", "gpus", "code_integrity") + event-sections(report).slice(0, 2).map(pair => pair.at(0)) } + for name in recap-sections.dedup() { + if section-status(report, name) == "missing" and not coverage.any(item => item.section == name) and not (compact and not compact-checks) { + coverage.push((section: name, use: "Not supplied in this capture", records: "Unavailable", severity: "info")) + } + } + let incomplete = compact or get(report, "legacy", none) != none or coverage.any(item => item.severity == "warning") or event-sections(report).any(pair => get(section(report, pair.at(0)), "truncated", false) == true) + + 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 if incomplete { "Insufficient evidence for a complete assessment" } else { "No actionable issue detected in collected evidence" }, + health_score: health-score, + collection_incomplete: incomplete, + parameters: get(report, "parameters", (:)), + diagnostic_collection: get(report, "diagnostic_collection", (:)), + source_report: report, + raw_events: raw, + reliability_events: reliability, + watchlist: watchlist-catalog, + event_counts: (critical: raw.filter(e => e.level == 1).len(), error: raw.filter(e => e.level == 2).len(), warning: raw.filter(e => e.level == 3).len(), information: raw.filter(e => e.level in (4, 5)).len(), unknown: raw.filter(e => e.level == none).len()), + analysis_confidence: if incomplete { calc.min(50, analysis-confidence) } else { 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, + ) +} diff --git a/tests/fixtures/legacy-diagnostic.json b/tests/fixtures/legacy-diagnostic.json new file mode 100644 index 0000000..c02cf78 --- /dev/null +++ b/tests/fixtures/legacy-diagnostic.json @@ -0,0 +1,384 @@ +{ + "schema_version": 2, + "report_type": "windows_system_maintenance", + "mode": "Full", + "generated_at": "2026-09-15T12:00:00Z", + "host": { + "computer_name": "SYNTHETIC-V2", + "administrator": true + }, + "parameters": { + "event_log_days": 30, + "max_event_errors": 3 + }, + "warnings": [], + "summary": null, + "sections": { + "operating_system": { + "status": "ok", + "count": 0, + "data": [], + "error": null + }, + "computer_system": { + "status": "ok", + "count": 0, + "data": [], + "error": null + }, + "problem_devices": { + "status": "ok", + "count": 0, + "data": [], + "error": null + }, + "component_store": { + "status": "ok", + "count": 0, + "data": [], + "error": null + }, + "system_file_check": { + "status": "ok", + "count": 0, + "data": [], + "error": null + }, + "recent_system_events": { + "status": "ok", + "count": 3, + "data": [ + { + "TimeCreated": "2026-09-14T12:00:00Z", + "ProviderName": "Synthetic provider", + "Id": 123, + "Level": 2, + "LevelDisplayName": "Localized level", + "Message": "Synthetic Unicode \u00e9 # [test] C:\\Windows" + }, + { + "TimeCreated": "2026-09-14T12:00:00Z", + "ProviderName": "Synthetic provider", + "Id": 123, + "Level": 3, + "LevelDisplayName": "Localized level", + "Message": "Synthetic Unicode \u00e9 # [test] C:\\Windows" + }, + { + "TimeCreated": "2026-09-14T12:00:00Z", + "ProviderName": "Synthetic provider", + "Id": 123, + "Level": 3, + "LevelDisplayName": "Localized level", + "Message": "Synthetic Unicode \u00e9 # [test] C:\\Windows" + } + ], + "error": null, + "limit": 3, + "truncated": false + }, + "recent_system_errors": { + "status": "ok", + "count": 1, + "data": [ + { + "TimeCreated": "2026-09-14T12:00:00Z", + "ProviderName": "Synthetic provider", + "Id": 123, + "Level": 1, + "LevelDisplayName": "Localized level", + "Message": "Synthetic Unicode \u00e9 # [test] C:\\Windows" + } + ], + "error": null + }, + "recent_application_events": { + "status": "ok", + "count": 0, + "data": [], + "error": null, + "limit": 3, + "truncated": true + }, + "code_integrity": { + "status": "ok", + "count": 1, + "data": [ + { + "TimeCreated": "2026-09-14T12:00:00Z", + "ProviderName": "Synthetic provider", + "Id": 123, + "Level": 4, + "LevelDisplayName": "Localized level", + "Message": "Synthetic Unicode \u00e9 # [test] C:\\Windows" + } + ], + "error": null + }, + "storage": { + "status": "ok", + "count": 1, + "data": [ + { + "storage_health": [ + { + "status": "unavailable", + "error": "Synthetic API failure" + } + ], + "reliability_counters": [ + { + "status": "skipped", + "error": "Synthetic elevation gap" + } + ] + } + ], + "error": null + }, + "defender": { + "status": "ok", + "count": 1, + "data": [ + { + "available": false, + "error": "Synthetic unavailable Defender" + } + ], + "error": null + }, + "signed_drivers": { + "status": "ok", + "count": 1, + "data": [ + { + "Name": null, + "DeviceID": "synthetic", + "State": "Stopped", + "Message": "Synthetic evidence" + } + ], + "error": null + }, + "system_drivers": { + "status": "ok", + "count": 1, + "data": [ + { + "Name": null, + "DeviceID": "synthetic", + "State": "Stopped", + "Message": "Synthetic evidence" + } + ], + "error": null + }, + "services": { + "status": "ok", + "count": 1, + "data": [ + { + "Name": null, + "DeviceID": "synthetic", + "State": "Stopped", + "Message": "Synthetic evidence" + } + ], + "error": null + }, + "storage_disks": { + "status": "ok", + "count": 1, + "data": [ + { + "Name": null, + "DeviceID": "synthetic", + "State": "Stopped", + "Message": "Synthetic evidence" + } + ], + "error": null + }, + "storage_pnp_devices": { + "status": "ok", + "count": 1, + "data": [ + { + "Name": null, + "DeviceID": "synthetic", + "State": "Stopped", + "Message": "Synthetic evidence" + } + ], + "error": null + }, + "enabled_windows_features": { + "status": "ok", + "count": 1, + "data": [ + { + "Name": null, + "DeviceID": "synthetic", + "State": "Stopped", + "Message": "Synthetic evidence" + } + ], + "error": null + }, + "reliability_records": { + "status": "ok", + "count": 1, + "data": [ + { + "Name": null, + "DeviceID": "synthetic", + "State": "Stopped", + "Message": "Synthetic evidence" + } + ], + "error": null + }, + "minidumps": { + "status": "ok", + "count": 1, + "data": [ + { + "Name": null, + "DeviceID": "synthetic", + "State": "Stopped", + "Message": "Synthetic evidence" + } + ], + "error": null + }, + "driver_store": { + "status": "unavailable", + "count": 1, + "data": [ + { + "executable": "synthetic.exe", + "arguments": [ + "/test" + ], + "exit_code": 5, + "output": [ + "\u00c9chec # [test] C:\\Windows" + ] + } + ], + "error": null + }, + "filter_drivers": { + "status": "unavailable", + "count": 1, + "data": [ + { + "executable": "synthetic.exe", + "arguments": [ + "/test" + ], + "exit_code": 5, + "output": [ + "\u00c9chec # [test] C:\\Windows" + ] + } + ], + "error": null + }, + "filter_instances": { + "status": "unavailable", + "count": 1, + "data": [ + { + "executable": "synthetic.exe", + "arguments": [ + "/test" + ], + "exit_code": 5, + "output": [ + "\u00c9chec # [test] C:\\Windows" + ] + } + ], + "error": null + }, + "upper_filters": { + "status": "unavailable", + "count": 1, + "data": [ + { + "executable": "synthetic.exe", + "arguments": [ + "/test" + ], + "exit_code": 5, + "output": [ + "\u00c9chec # [test] C:\\Windows" + ] + } + ], + "error": null + }, + "lower_filters": { + "status": "unavailable", + "count": 1, + "data": [ + { + "executable": "synthetic.exe", + "arguments": [ + "/test" + ], + "exit_code": 5, + "output": [ + "\u00c9chec # [test] C:\\Windows" + ] + } + ], + "error": null + }, + "boot_configuration": { + "status": "unavailable", + "count": 1, + "data": [ + { + "executable": "synthetic.exe", + "arguments": [ + "/test" + ], + "exit_code": 5, + "output": [ + "\u00c9chec # [test] C:\\Windows" + ] + } + ], + "error": null + } + }, + "diagnostic_collection": { + "operating_system": true, + "computer_system": true, + "problem_devices": true, + "component_store": true, + "system_file_check": true, + "recent_system_events": true, + "recent_system_errors": true, + "recent_application_events": true, + "code_integrity": true, + "storage": true, + "defender": true, + "signed_drivers": true, + "system_drivers": true, + "services": true, + "storage_disks": true, + "storage_pnp_devices": true, + "enabled_windows_features": true, + "reliability_records": true, + "minidumps": true, + "driver_store": false, + "filter_drivers": false, + "filter_instances": false, + "upper_filters": false, + "lower_filters": false, + "boot_configuration": false + } +} \ No newline at end of file diff --git a/tests/fixtures/logo.png b/tests/fixtures/logo.png new file mode 100644 index 0000000..51c9e58 Binary files /dev/null and b/tests/fixtures/logo.png differ diff --git a/tests/test_render.py b/tests/test_render.py index 9fb563a..466b1e7 100644 --- a/tests/test_render.py +++ b/tests/test_render.py @@ -99,6 +99,26 @@ class RenderTests(unittest.TestCase): self.assertEqual(result.returncode, 0, result.stderr) self.assert_pdf(output) + def test_legacy_diagnostic_renderer_processes_full_capture(self): + logo = ROOT / "tests" / "fixtures" / "logo.png" + output = self.work / "diagnostic.pdf" + result = subprocess.run([ + "bash", str(ROOT / "render-diagnostic.sh"), + str(ROOT / "tests" / "fixtures" / "legacy-diagnostic.json"), + "--output", str(output), "--author", "Synthetic Reviewer", + "--logo", str(logo), + ], cwd=self.work, text=True, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assert_pdf(output) + + if PDFTOTEXT: + extracted = subprocess.run( + [PDFTOTEXT, str(output), "-"], text=True, + capture_output=True, check=True, + ).stdout + self.assertIn("Windows diagnostic assessment", extracted) + self.assertIn("Synthetic Reviewer", extracted) + @unittest.skipUnless(PDFINFO and PDFTOTEXT, "Poppler PDF inspection tools are not installed") def test_long_content_paginates_without_losing_tail_content(self): paragraphs = [