Skip to main content

hematite/agent/
fix_recipes.rs

1pub struct Recipe {
2    pub severity: &'static str,
3    pub title: &'static str,
4    pub steps: &'static [&'static str],
5    pub dig_deeper: Option<&'static str>,
6}
7
8struct RecipeAc {
9    ac: aho_corasick::AhoCorasick,
10    recipe_indices: Vec<usize>,
11}
12
13static RECIPE_AC: std::sync::OnceLock<RecipeAc> = std::sync::OnceLock::new();
14
15fn recipe_ac() -> &'static RecipeAc {
16    RECIPE_AC.get_or_init(|| {
17        let mut patterns: Vec<&str> = Vec::new();
18        let mut recipe_indices: Vec<usize> = Vec::new();
19        for (i, entry) in ALL_RECIPES.iter().enumerate() {
20            for &trigger in entry.triggers {
21                patterns.push(trigger);
22                recipe_indices.push(i);
23            }
24        }
25        RecipeAc {
26            ac: aho_corasick::AhoCorasick::new(&patterns).expect("valid patterns"),
27            recipe_indices,
28        }
29    })
30}
31
32pub fn match_recipes(output: &str) -> Vec<&'static Recipe> {
33    let lower = output.to_ascii_lowercase();
34    let state = recipe_ac();
35    let mut seen = std::collections::HashSet::new();
36    let mut matches: Vec<&'static Recipe> = Vec::new();
37    for mat in state.ac.find_iter(&lower) {
38        let idx = state.recipe_indices[mat.pattern().as_usize()];
39        if seen.insert(idx) {
40            matches.push(&ALL_RECIPES[idx].recipe);
41        }
42    }
43    matches
44}
45
46struct RecipeEntry {
47    triggers: &'static [&'static str],
48    recipe: Recipe,
49}
50
51static ALL_RECIPES: &[RecipeEntry] = &[
52    // ── Disk / Storage ────────────────────────────────────────────────────────
53    RecipeEntry {
54        triggers: &["very low", "disk:", "free space"],
55        recipe: Recipe {
56            severity: "ACTION",
57            title: "Low disk space",
58            steps: &[
59                "Open Disk Cleanup: press Win+R → type 'cleanmgr' → select C: → check all boxes including 'Windows Update Cleanup'",
60                "Empty the Recycle Bin: right-click desktop icon → Empty Recycle Bin",
61                "Clear Temp folder: press Win+R → type '%temp%' → Ctrl+A → Delete (skip files in use)",
62                "Check largest folders: open PowerShell → Get-ChildItem C:\\ -Recurse -ErrorAction SilentlyContinue | Sort-Object Length -Descending | Select-Object -First 20 FullName, Length",
63                "If space is still tight, run: winget install -e --id Microsoft.PowerToys then use PowerToys Disk Space Analyzer",
64            ],
65            dig_deeper: Some("storage"),
66        },
67    },
68    RecipeEntry {
69        triggers: &["disk_health", "smart", "predictive failure", "wear"],
70        recipe: Recipe {
71            severity: "ACTION",
72            title: "Drive health warning — possible failure",
73            steps: &[
74                "Back up your important files immediately before doing anything else",
75                "Verify the SMART status: open PowerShell (admin) → Get-PhysicalDisk | Select FriendlyName, HealthStatus, OperationalStatus",
76                "If HealthStatus is 'Unhealthy' or 'Warning', replace the drive — do not wait",
77                "For SSDs: check manufacturer's NVMe/SSD tool (Samsung Magician, Crucial Storage Executive, etc.) for wear level",
78            ],
79            dig_deeper: Some("disk_health"),
80        },
81    },
82
83    // ── Reboot ────────────────────────────────────────────────────────────────
84    RecipeEntry {
85        triggers: &["pending reboot", "restart when convenient", "reboot required"],
86        recipe: Recipe {
87            severity: "INVESTIGATE",
88            title: "Restart required",
89            steps: &[
90                "Save your work and restart the computer — pending file operations and updates cannot apply until you do",
91                "After restarting, run this report again to confirm the reboot flag cleared",
92                "If the flag persists after a restart, check Windows Update: Settings → Windows Update → View update history → look for stuck installs",
93            ],
94            dig_deeper: Some("pending_reboot"),
95        },
96    },
97
98    // ── Event log errors ──────────────────────────────────────────────────────
99    RecipeEntry {
100        triggers: &["critical/error event", "error events in windows event log", "critical error"],
101        recipe: Recipe {
102            severity: "INVESTIGATE",
103            title: "Windows event log errors detected",
104            steps: &[
105                "Find the top error sources: PowerShell → Get-WinEvent -FilterHashtable @{LogName='System','Application';Level=1,2} -MaxEvents 100 | Group-Object ProviderName | Sort-Object Count -Descending | Select -First 10",
106                "One crashing service or driver usually causes most of the noise — focus on the source with the highest count",
107                "For 'Service Control Manager' errors: check which service is crashing → Get-WinEvent -FilterHashtable @{LogName='System';ProviderName='Service Control Manager';Level=2} -MaxEvents 10 | Select Message",
108                "For application crashes: check AppEvent for the faulting app name → Get-WinEvent -FilterHashtable @{LogName='Application';Level=2} -MaxEvents 10 | Select TimeCreated,Message",
109            ],
110            dig_deeper: Some("log_check"),
111        },
112    },
113
114    // ── Services ──────────────────────────────────────────────────────────────
115    RecipeEntry {
116        triggers: &["critical service", "not running: windefend", "not running: eventlog", "not running: dnscache"],
117        recipe: Recipe {
118            severity: "ACTION",
119            title: "Critical Windows service not running",
120            steps: &[
121                "Open Services: press Win+R → type 'services.msc' → Enter",
122                "Find the stopped service, right-click → Start",
123                "If it fails to start, right-click → Properties → Recovery tab → set 'First failure' to 'Restart the Service'",
124                "For Windows Defender (WinDefend) stopped: open Windows Security → Virus & threat protection → turn on Real-time protection",
125                "If EventLog is stopped, restart is required — this service cannot be started manually once stopped",
126            ],
127            dig_deeper: Some("services"),
128        },
129    },
130
131    // ── Network ───────────────────────────────────────────────────────────────
132    RecipeEntry {
133        triggers: &["internet connectivity: unreachable", "could not ping 1.1.1.1"],
134        recipe: Recipe {
135            severity: "ACTION",
136            title: "No internet connectivity",
137            steps: &[
138                "Check physical connection: is the Ethernet cable plugged in, or is Wi-Fi connected?",
139                "Test gateway reachability: PowerShell → Test-Connection (Get-NetRoute -DestinationPrefix '0.0.0.0/0').NextHop -Count 1",
140                "Flush DNS cache: PowerShell (admin) → Clear-DnsClientCache",
141                "Reset TCP/IP stack: PowerShell (admin) → netsh int ip reset; netsh winsock reset → then restart",
142                "If on Wi-Fi: forget the network and reconnect, or try 'netsh wlan disconnect' then 'netsh wlan connect name=\"SSID\"'",
143            ],
144            dig_deeper: Some("connectivity"),
145        },
146    },
147    RecipeEntry {
148        triggers: &["high latency", "ms rtt — high latency"],
149        recipe: Recipe {
150            severity: "MONITOR",
151            title: "High network latency detected",
152            steps: &[
153                "Run a traceroute to find where the delay is: PowerShell → tracert 1.1.1.1",
154                "Check for background bandwidth consumers: Task Manager → Performance → Open Resource Monitor → Network tab",
155                "If on Wi-Fi, check signal strength and try moving closer to the router or switching to 5GHz",
156                "Check your ISP's status page for outages in your area",
157            ],
158            dig_deeper: Some("latency"),
159        },
160    },
161
162    // ── RAM ───────────────────────────────────────────────────────────────────
163    RecipeEntry {
164        triggers: &["ram:", "very low", "running a bit low", "free of"],
165        recipe: Recipe {
166            severity: "MONITOR",
167            title: "High memory usage",
168            steps: &[
169                "Find the top RAM consumers: Task Manager → Memory column (sort descending)",
170                "Close unused browser tabs — each tab can consume 100–500 MB",
171                "Check for memory leaks: if one process is growing over time without release, restart it",
172                "Disable startup programs that aren't needed: Task Manager → Startup tab → disable high-impact items",
173                "If consistently above 85% with normal usage, consider adding RAM",
174            ],
175            dig_deeper: Some("resource_load"),
176        },
177    },
178
179    // ── Thermal ───────────────────────────────────────────────────────────────
180    RecipeEntry {
181        triggers: &["very high", "check cooling", "elevated under load", "°c — very high"],
182        recipe: Recipe {
183            severity: "ACTION",
184            title: "CPU running hot",
185            steps: &[
186                "Shut down and clean dust from fans and heatsink with compressed air — this is the fix 90% of the time",
187                "Check that all fan headers are connected and fans are spinning on boot",
188                "Verify thermal paste on CPU heatsink — if it's more than 4 years old and temperatures are high, repaste",
189                "In BIOS: confirm fan curve is not set to 'Silent' mode — switch to 'Standard' or 'Performance'",
190                "Check for CPU throttling: PowerShell → Get-WmiObject -Class Win32_Processor | Select Name,CurrentClockSpeed,MaxClockSpeed — if Current is much lower than Max under load, it's throttling",
191            ],
192            dig_deeper: Some("thermal"),
193        },
194    },
195
196    // ── Security ──────────────────────────────────────────────────────────────
197    RecipeEntry {
198        triggers: &["real-time protection: disabled", "defender.*disabled", "firewall.*off"],
199        recipe: Recipe {
200            severity: "ACTION",
201            title: "Windows security protection disabled",
202            steps: &[
203                "Re-enable Defender real-time protection: Windows Security → Virus & threat protection → turn on Real-time protection",
204                "If Defender shows as disabled by a third-party antivirus, ensure that AV is up to date and its own real-time protection is on",
205                "Re-enable Windows Firewall: Control Panel → Windows Defender Firewall → Turn Windows Defender Firewall on or off → turn on for all profiles",
206                "Run a quick scan: Windows Security → Virus & threat protection → Quick scan",
207            ],
208            dig_deeper: Some("security"),
209        },
210    },
211    RecipeEntry {
212        triggers: &["threat detected", "quarantine", "malware", "virus found"],
213        recipe: Recipe {
214            severity: "ACTION",
215            title: "Threat detected by Windows Defender",
216            steps: &[
217                "Open Windows Security → Virus & threat protection → Protection history → review detected threats",
218                "If action is 'Quarantined', Defender has contained it — review and remove from quarantine",
219                "Run a full offline scan: Windows Security → Virus & threat protection → Scan options → Microsoft Defender Offline scan",
220                "Change passwords for any accounts accessed on this machine after the infection date",
221                "Check browser extensions for anything you didn't install",
222            ],
223            dig_deeper: Some("defender_quarantine"),
224        },
225    },
226
227    // ── Windows Update ────────────────────────────────────────────────────────
228    RecipeEntry {
229        triggers: &["windows update", "pending update", "update.*required"],
230        recipe: Recipe {
231            severity: "INVESTIGATE",
232            title: "Windows updates pending",
233            steps: &[
234                "Open Settings → Windows Update → Check for updates",
235                "Install all available updates, then restart when prompted",
236                "If updates are stuck: PowerShell (admin) → net stop wuauserv; net stop bits; net start wuauserv; net start bits",
237                "If stuck for more than 24 hours: run the Windows Update Troubleshooter from Settings → System → Troubleshoot → Other troubleshooters",
238            ],
239            dig_deeper: Some("updates"),
240        },
241    },
242
243    // ── Device / driver errors ────────────────────────────────────────────────
244    RecipeEntry {
245        triggers: &["yellow bang", "pnp error", "configmanager error", "error code 43", "error code 10", "error code 28", "device problem", "driver error"],
246        recipe: Recipe {
247            severity: "ACTION",
248            title: "Hardware device error detected",
249            steps: &[
250                "Open Device Manager: press Win+R → type 'devmgmt.msc' → Enter",
251                "Look for yellow exclamation marks (!) — right-click → Properties → note the error code and device name",
252                "Error Code 43 (USB/GPU): unplug and replug the device, or roll back the driver: right-click → Properties → Driver → Roll Back Driver",
253                "Error Code 10 (failed to start): update the driver — right-click → Update driver → Search automatically",
254                "Error Code 28 (no driver): download the driver from the manufacturer's website (look up the device name + Windows version)",
255                "For recurring errors: run SFC scan → PowerShell (admin) → sfc /scannow",
256            ],
257            dig_deeper: Some("device_health"),
258        },
259    },
260
261    // ── No backup configured ──────────────────────────────────────────────────
262    RecipeEntry {
263        triggers: &["file history: disabled", "no backup configured", "no restore points", "last backup: never", "backup: not configured", "file history.*disabled", "no system restore"],
264        recipe: Recipe {
265            severity: "INVESTIGATE",
266            title: "No backup configured",
267            steps: &[
268                "Enable File History: Settings → System → Storage → Advanced storage settings → Backup options → Add a drive",
269                "Enable System Restore: search 'Create a restore point' → select C: → Configure → turn on protection → OK → Create",
270                "For a full image backup: search 'Backup and Restore (Windows 7)' → Create a system image → choose an external drive",
271                "OneDrive Known Folder Backup covers Desktop/Documents/Pictures: Settings → OneDrive → Backup → Manage backup",
272                "Run your first backup immediately — a backup that has never run has zero value",
273            ],
274            dig_deeper: Some("windows_backup"),
275        },
276    },
277
278    // ── SMB1 enabled ─────────────────────────────────────────────────────────
279    RecipeEntry {
280        triggers: &["smb1 is enabled", "smb1: enabled", "smb1 protocol: enabled", "smb version 1", "smbv1 enabled"],
281        recipe: Recipe {
282            severity: "ACTION",
283            title: "SMB1 protocol enabled — security risk",
284            steps: &[
285                "SMB1 is a deprecated protocol exploited by WannaCry and NotPetya ransomware — disable it immediately",
286                "Disable SMB1: PowerShell (admin) → Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force",
287                "Verify it's off: PowerShell → Get-SmbServerConfiguration | Select EnableSMB1Protocol (should show False)",
288                "If a legacy device (old NAS, printer) stops working after disabling, upgrade its firmware or replace it — do not re-enable SMB1",
289                "Restart required to fully remove the SMB1 listener",
290            ],
291            dig_deeper: Some("shares"),
292        },
293    },
294
295    // ── BitLocker not protecting ──────────────────────────────────────────────
296    RecipeEntry {
297        triggers: &["protection state: off", "bitlocker: off", "bitlocker.*not protecting", "encryption status: fully decrypted", "bitlocker.*disabled"],
298        recipe: Recipe {
299            severity: "MONITOR",
300            title: "Drive encryption not enabled",
301            steps: &[
302                "BitLocker encrypts your drive so data is unreadable if the laptop is lost or stolen — strongly recommended on portable machines",
303                "Enable BitLocker: search 'Manage BitLocker' → Turn on BitLocker for C: → follow the wizard",
304                "Save the recovery key to your Microsoft account or print it — you will need it if Windows can't auto-unlock at boot",
305                "Encryption runs in the background and takes 1–3 hours for a typical drive — the PC remains usable during this time",
306                "Requires TPM 1.2+ or USB key; check: PowerShell → Get-Tpm | Select TpmPresent,TpmReady",
307            ],
308            dig_deeper: Some("bitlocker"),
309        },
310    },
311
312    // ── DNS resolution failing ────────────────────────────────────────────────
313    RecipeEntry {
314        triggers: &["dns resolution: failed", "dns: failed", "dns fail", "dns resolution failed", "could not resolve"],
315        recipe: Recipe {
316            severity: "ACTION",
317            title: "DNS resolution failing",
318            steps: &[
319                "Flush DNS cache: PowerShell (admin) → Clear-DnsClientCache",
320                "Test DNS directly: PowerShell → Resolve-DnsName google.com -Server 8.8.8.8 — if this works, your DNS server is the problem",
321                "Switch to a reliable DNS server: PowerShell (admin) → Set-DnsClientServerAddress -InterfaceAlias 'Wi-Fi' -ServerAddresses ('8.8.8.8','1.1.1.1')",
322                "Check if the DNS client service is running: Get-Service Dnscache | Select Status",
323                "If on a corporate network or VPN, contact IT — split DNS may require the VPN to be connected for internal names to resolve",
324            ],
325            dig_deeper: Some("dns_servers"),
326        },
327    },
328
329    // ── Repeated app crashes ──────────────────────────────────────────────────
330    RecipeEntry {
331        triggers: &["faulting application", "crash count", "crash frequency", "application hang", "faulting module"],
332        recipe: Recipe {
333            severity: "INVESTIGATE",
334            title: "Application crashing repeatedly",
335            steps: &[
336                "Note the faulting application name and module from the report — these are the most important clues",
337                "If the faulting module is ntdll.dll or a system DLL: run SFC to repair Windows files → PowerShell (admin) → sfc /scannow",
338                "If the faulting module is a third-party DLL (e.g. a codec or plugin): uninstall the associated program",
339                "Update or reinstall the crashing application — corrupted installs are a common cause",
340                "Check for conflicting software: antivirus, screen recorders, and overlays (Discord, GeForce Experience) frequently inject into other processes",
341                "If it is a Microsoft Office app: run the Office repair → Control Panel → Programs → right-click Office → Change → Quick Repair",
342            ],
343            dig_deeper: Some("app_crashes"),
344        },
345    },
346
347    // ── Visual C++ / runtime missing ─────────────────────────────────────────
348    RecipeEntry {
349        triggers: &["vcruntime", "msvcr", "0xc000007b", "side-by-side configuration", "missing runtime", "vc++ redistributable"],
350        recipe: Recipe {
351            severity: "ACTION",
352            title: "Visual C++ runtime missing or corrupt",
353            steps: &[
354                "Download and install the latest Visual C++ Redistributable packages (both x64 and x86) from Microsoft: search 'Visual C++ Redistributable downloads'",
355                "Install all available years: 2015–2022 package covers most apps; older apps may need 2013, 2012, or 2010 separately",
356                "If a specific app shows error 0xc000007b: right-click the app → Properties → Compatibility → Run as administrator",
357                "Repair existing runtimes: Control Panel → Programs → find 'Microsoft Visual C++ 20XX' → Repair",
358                "After installing, restart before testing the application again — runtimes must be registered at boot",
359            ],
360            dig_deeper: None,
361        },
362    },
363
364    // ── Certificate expiring ──────────────────────────────────────────────────
365    RecipeEntry {
366        triggers: &["expiring within 30 days", "expires in", "certificate expir", "cert.*expir"],
367        recipe: Recipe {
368            severity: "INVESTIGATE",
369            title: "Certificate expiring soon",
370            steps: &[
371                "Open Certificate Manager: press Win+R → type 'certmgr.msc' → check Personal → Certificates for the expiring cert",
372                "Note the certificate subject and issuer — determines who you need to contact for renewal",
373                "For personal/S-MIME certificates: renew through your CA or email provider portal",
374                "For web/TLS certificates on a server: generate a new CSR and submit to your CA before expiry",
375                "For code-signing certificates: do not let these lapse — signed binaries will show 'unknown publisher' warnings after expiry",
376            ],
377            dig_deeper: Some("certificates"),
378        },
379    },
380
381    // ── Wi-Fi weak signal ─────────────────────────────────────────────────────
382    RecipeEntry {
383        triggers: &["signal: poor", "weak signal", "rssi: -8", "rssi: -9", "signal strength: poor", "quality: poor", "poor signal"],
384        recipe: Recipe {
385            severity: "MONITOR",
386            title: "Wi-Fi signal weak",
387            steps: &[
388                "Move closer to the router or access point — Wi-Fi degrades quickly through walls and floors",
389                "Switch to 5 GHz band if available — faster and less congested in most home environments (but shorter range than 2.4 GHz)",
390                "Check for interference: microwave ovens, baby monitors, and neighboring networks on the same channel all degrade signal",
391                "Change the router's Wi-Fi channel: log into router admin → Wireless settings → try channels 1, 6, or 11 (2.4 GHz) or auto (5 GHz)",
392                "Update the Wi-Fi adapter driver: Device Manager → Network Adapters → right-click adapter → Update driver",
393                "If signal is consistently poor from a fixed desk, consider a powerline adapter or mesh Wi-Fi node nearby",
394            ],
395            dig_deeper: Some("wifi"),
396        },
397    },
398
399    // ── NTP / time sync failure ───────────────────────────────────────────────
400    RecipeEntry {
401        triggers: &["time sync failed", "sync failed", "clock drift", "ntp.*error", "w32tm.*fail", "ntp source.*unreachable", "time.*not synchronized"],
402        recipe: Recipe {
403            severity: "INVESTIGATE",
404            title: "System clock not synchronizing",
405            steps: &[
406                "Force a sync now: PowerShell (admin) → w32tm /resync /force",
407                "Check the current NTP source: PowerShell → w32tm /query /source",
408                "If source shows 'Local CMOS Clock' or 'Free-running', the time service has lost its server",
409                "Reset to Microsoft's NTP server: PowerShell (admin) → w32tm /config /manualpeerlist:time.windows.com /syncfromflags:manual /reliable:YES /update",
410                "Restart the time service: PowerShell (admin) → Restart-Service w32tm",
411                "If clock drift is large (>5 minutes), some authentication systems (Kerberos, MFA) will fail until synced",
412            ],
413            dig_deeper: Some("ntp"),
414        },
415    },
416
417    // ── Page file missing ─────────────────────────────────────────────────────
418    RecipeEntry {
419        triggers: &["no page file", "pagefile: none", "page file: none", "virtual memory: none", "pagefile not configured", "no pagefile"],
420        recipe: Recipe {
421            severity: "INVESTIGATE",
422            title: "Page file not configured",
423            steps: &[
424                "Windows needs a page file even with plenty of RAM — some apps and crash dumps require it",
425                "Re-enable automatic page file management: search 'Adjust the appearance and performance of Windows' → Advanced → Virtual memory → Change → check 'Automatically manage'",
426                "If manually set: assign at least 1.5× your RAM as maximum size on the system drive",
427                "After changing page file settings, restart is required — changes do not take effect until reboot",
428                "Note: if this machine intentionally has no page file (e.g. a RAM disk setup), verify that was deliberate before changing it",
429            ],
430            dig_deeper: Some("pagefile"),
431        },
432    },
433
434    // ── System file corruption ────────────────────────────────────────────────
435    RecipeEntry {
436        triggers: &["corrupt files found", "autorepairrequired: true", "integrity.*failed", "component store corruption", "sfc.*corrupt", "windows resource protection found corrupt"],
437        recipe: Recipe {
438            severity: "ACTION",
439            title: "Windows system file corruption detected",
440            steps: &[
441                "Run SFC to repair corrupt files: PowerShell (admin) → sfc /scannow (takes 5–15 minutes)",
442                "If SFC reports 'Windows Resource Protection found corrupt files but was unable to fix some of them', run DISM next:",
443                "DISM repair: PowerShell (admin) → DISM /Online /Cleanup-Image /RestoreHealth (requires internet access, 10–30 minutes)",
444                "Run SFC again after DISM completes — DISM provides the source files SFC needs",
445                "Restart after both complete, then check Event Viewer for CBS log: Applications and Services Logs → Microsoft → Windows → Servicing",
446                "If corruption persists after both tools: in-place upgrade repair (Windows Setup without wiping data) is the next step",
447            ],
448            dig_deeper: Some("integrity"),
449        },
450    },
451
452    // ── Service start failure ─────────────────────────────────────────────────
453    RecipeEntry {
454        triggers: &["stopped unexpectedly", "failed to start", "error 1067", "error 1053", "service terminated", "exited with code", "failed to respond"],
455        recipe: Recipe {
456            severity: "INVESTIGATE",
457            title: "Service failed to start or stopped unexpectedly",
458            steps: &[
459                "Find the failing service name in the report, then check its status: PowerShell → Get-Service <ServiceName>",
460                "Read the specific error from the Application/System event log: Event Viewer → Windows Logs → System → filter for Service Control Manager (Event ID 7034 or 7031)",
461                "Try to start it manually: PowerShell (admin) → Start-Service <ServiceName> — note any error message",
462                "Check if the service account has the right permissions: Services console (services.msc) → right-click → Properties → Log On tab",
463                "Look for a dependent service that failed first — a service won't start if something it requires is stopped",
464                "If the service EXE is missing or corrupt, reinstall the application that owns it",
465            ],
466            dig_deeper: Some("services"),
467        },
468    },
469
470    // ── RDP unreachable ───────────────────────────────────────────────────────
471    RecipeEntry {
472        triggers: &["fdenytsconnections: 1", "no enabled rdp firewall", "rdp status: disabled"],
473        recipe: Recipe {
474            severity: "ACTION",
475            title: "Remote Desktop (RDP) is disabled or blocked",
476            steps: &[
477                "Enable RDP: Settings → System → Remote Desktop → Enable Remote Desktop (or PowerShell admin: Set-ItemProperty 'HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server' fDenyTSConnections 0)",
478                "Ensure the RDP firewall rule is enabled: PowerShell (admin) → Enable-NetFirewallRule -DisplayGroup 'Remote Desktop'",
479                "Verify port 3389 is listening after enabling: PowerShell → netstat -an | findstr 3389",
480                "If NLA is required, make sure the connecting user account has the right to log in remotely (must be in Remote Desktop Users group or Administrators)",
481                "Check that Windows Firewall is not blocking the connection — on the host, temporarily allow pings to confirm network path is open",
482                "For cloud VMs: check the security group / NSG allows inbound TCP 3389 from your IP",
483            ],
484            dig_deeper: Some("rdp"),
485        },
486    },
487
488    // ── Windows Update service broken ─────────────────────────────────────────
489    RecipeEntry {
490        triggers: &["wuauserv: stopped", "wuauserv stopped", "windows update: stopped", "update service stopped", "bits: stopped", "bits stopped"],
491        recipe: Recipe {
492            severity: "ACTION",
493            title: "Windows Update service is stopped or broken",
494            steps: &[
495                "Run the Windows Update Troubleshooter: Settings → Update & Security → Troubleshoot → Additional troubleshooters → Windows Update",
496                "Manually restart the update services: PowerShell (admin) → Stop-Service wuauserv, bits, cryptsvc, msiserver → Start-Service wuauserv, bits, cryptsvc",
497                "Clear the update cache if stuck: PowerShell (admin) → Stop-Service wuauserv → Remove-Item C:\\Windows\\SoftwareDistribution\\* -Recurse -Force → Start-Service wuauserv",
498                "Check for conflicting 3rd-party update tools (WSUS, SCCM, Intune policies) that may be disabling updates",
499                "Run the System Update Readiness Tool: DISM /Online /Cleanup-Image /RestoreHealth",
500                "If the service keeps stopping, check Event Viewer → Windows Logs → System for Windows Update Agent errors around the same time",
501            ],
502            dig_deeper: Some("updates"),
503        },
504    },
505
506    // ── Teams cache ───────────────────────────────────────────────────────────
507    RecipeEntry {
508        triggers: &["classic teams cache:", "new teams cache:", "msteams cache:", "teams cache size"],
509        recipe: Recipe {
510            severity: "INVESTIGATE",
511            title: "Teams cache — clear to resolve most Teams issues",
512            steps: &[
513                "Quit Teams completely: right-click the Teams icon in the system tray → Quit",
514                "Clear Classic Teams cache: open Run (Win+R) → type %AppData%\\Microsoft\\Teams → delete the contents of: Cache, blob_storage, databases, GPUCache, IndexedDB, Local Storage, tmp",
515                "Clear New Teams (MSTeams) cache: open Run → %LocalAppData%\\Packages\\MSTeams_8wekyb3d8bbwe\\LocalCache\\ → delete all contents",
516                "Restart Teams and sign in — cache rebuilds from the server automatically",
517                "If Teams still fails to sign in after clearing cache, also clear credentials: Credential Manager (Win+R → credmgr.msc) → Windows Credentials → remove all MicrosoftOffice16_Data:SSPI:* entries",
518            ],
519            dig_deeper: Some("teams"),
520        },
521    },
522
523    // ── M365 token broker not running ─────────────────────────────────────────
524    RecipeEntry {
525        triggers: &["token broker: not running", "aad broker plugin: not found", "web account manager: not running", "wam: not running", "aad broker: not found"],
526        recipe: Recipe {
527            severity: "ACTION",
528            title: "Microsoft 365 authentication broker not running",
529            steps: &[
530                "The Windows Account Manager (WAM) and AAD Broker are required for M365 sign-in — if they're not running, Teams, Outlook, and OneDrive will loop on sign-in",
531                "Re-register the token broker: PowerShell (admin) → sfc /scannow — this repairs the system files WAM depends on",
532                "Restart the TokenBroker service: PowerShell (admin) → Restart-Service TokenBroker -ErrorAction SilentlyContinue",
533                "If re-registering doesn't help, sign out of all work accounts: Settings → Accounts → Access work or school → disconnect and reconnect your org account",
534                "On Intune/AAD-joined machines: run 'dsregcmd /leave' then 'dsregcmd /join' (admin) to re-register the device — requires network connectivity to Azure AD",
535                "Check for conflicting credential entries: Credential Manager → Windows Credentials → remove stale MicrosoftOffice16_Data:SSPI:* and MicrosoftOffice15_Data:* entries",
536            ],
537            dig_deeper: Some("identity_auth"),
538        },
539    },
540
541    // ── WMI repository corrupt ────────────────────────────────────────────────
542    RecipeEntry {
543        triggers: &["wmi repository is inconsistent", "repository is inconsistent", "wmi: inconsistent", "verifyrepository: inconsistent", "wmi corruption"],
544        recipe: Recipe {
545            severity: "ACTION",
546            title: "WMI repository corrupt — cascading tool failures",
547            steps: &[
548                "WMI corruption breaks PowerShell Get-WmiObject, Defender, Windows Update, and many admin tools — fix it first before investigating other issues",
549                "Stop WMI: PowerShell (admin) → net stop winmgmt /y",
550                "Rebuild the repository: PowerShell (admin) → winmgmt /resetrepository",
551                "Start WMI: PowerShell (admin) → net start winmgmt",
552                "Verify the fix: PowerShell → winmgmt /verifyrepository — should say 'WMI repository is consistent'",
553                "If resetrepository fails, try salvage mode: winmgmt /salvagerepository — this preserves customizations",
554                "Restart the machine after repair — WMI caches are session-scoped and some tools won't see the fix until reboot",
555            ],
556            dig_deeper: Some("wmi_health"),
557        },
558    },
559
560    // ── Windows not activated ─────────────────────────────────────────────────
561    RecipeEntry {
562        triggers: &["license status: unlicensed", "license status: notification", "activation: not activated", "not genuine", "windows is not activated"],
563        recipe: Recipe {
564            severity: "INVESTIGATE",
565            title: "Windows not activated",
566            steps: &[
567                "Check activation status: Settings → System → Activation — note the exact status message",
568                "If you have a product key: Settings → System → Activation → Change product key → enter the 25-character key",
569                "If the key was tied to a Microsoft account: sign in with that Microsoft account and activation should happen automatically over the internet",
570                "Force activation attempt: PowerShell (admin) → slmgr /ato",
571                "If you get error 0xC004F074 (Key Management Service unreachable): you're on a domain with KMS — contact your IT department, the KMS server may be offline",
572                "If you recently changed hardware (motherboard): activation may need to be relinked — use the Activation Troubleshooter in Settings",
573            ],
574            dig_deeper: Some("activation"),
575        },
576    },
577
578    // ── Windows Search not indexing ───────────────────────────────────────────
579    RecipeEntry {
580        triggers: &["wsearch: stopped", "search service: stopped", "wsearch service: stopped", "indexer: stopped", "windows search: stopped"],
581        recipe: Recipe {
582            severity: "INVESTIGATE",
583            title: "Windows Search not running — search won't find files",
584            steps: &[
585                "Start the Windows Search service: PowerShell (admin) → Start-Service WSearch",
586                "Set it to start automatically: PowerShell (admin) → Set-Service WSearch -StartupType Automatic",
587                "If the service won't start: check Event Viewer → Windows Logs → Application → filter for 'Search' for the specific error",
588                "Rebuild the search index: Settings → Privacy & Security → Windows Search → Advanced indexing options → Advanced → Rebuild — takes 15–60 minutes",
589                "If rebuilding doesn't help, reset the index database: Stop-Service WSearch → delete C:\\ProgramData\\Microsoft\\Search\\Data\\Applications\\Windows\\Windows.edb → Start-Service WSearch",
590                "Restart File Explorer after: PowerShell → Stop-Process -Name explorer → Start-Process explorer",
591            ],
592            dig_deeper: Some("search_index"),
593        },
594    },
595
596    // ── OneDrive sync error ───────────────────────────────────────────────────
597    RecipeEntry {
598        triggers: &["sync status: error", "onedrive: not running", "sync errors detected", "onedrive sync error", "known folder backup: not configured"],
599        recipe: Recipe {
600            severity: "INVESTIGATE",
601            title: "OneDrive not syncing",
602            steps: &[
603                "Check the sync status icon in the system tray — hover over it for the specific error message",
604                "Common fix: right-click the OneDrive tray icon → Pause syncing → Resume syncing — resets stuck sync state",
605                "If that doesn't work: right-click the OneDrive tray icon → Settings → Account → Unlink this PC → relink with the same account",
606                "Check for conflicting files: File Explorer → OneDrive folder → look for files with a red X — rename or delete the local copy and let it sync from the cloud",
607                "If the issue is 'Not enough space in OneDrive': manage storage at onedrive.live.com/manage",
608                "Reset OneDrive if all else fails: Win+R → %localappdata%\\Microsoft\\OneDrive\\onedrive.exe /reset — wait 2 minutes, then reopen OneDrive from Start",
609            ],
610            dig_deeper: Some("onedrive"),
611        },
612    },
613
614    // ── Printer offline or stuck queue ────────────────────────────────────────
615    RecipeEntry {
616        triggers: &["status: offline", "pending jobs:", "print spooler: stopped", "spooler: stopped"],
617        recipe: Recipe {
618            severity: "INVESTIGATE",
619            title: "Printer offline or stuck print queue",
620            steps: &[
621                "Check the printer is powered on and connected (USB cable or same Wi-Fi network as the PC)",
622                "Clear the stuck print queue: PowerShell (admin) → Stop-Service Spooler → Remove-Item C:\\Windows\\System32\\spool\\PRINTERS\\* -Force → Start-Service Spooler",
623                "If printer shows Offline: right-click the printer in Settings → Printers & scanners → See what's printing → Printer menu → uncheck 'Use Printer Offline'",
624                "For network printers: verify the printer's IP hasn't changed — print a configuration page from the printer itself to check its current IP",
625                "Re-add the printer if the IP changed: Settings → Bluetooth & devices → Printers & scanners → Add device → Add manually → enter the new IP",
626                "If the Print Spooler service is stopped: PowerShell (admin) → Start-Service Spooler → Set-Service Spooler -StartupType Automatic",
627            ],
628            dig_deeper: Some("printers"),
629        },
630    },
631
632    // ── No Outlook mail profile ───────────────────────────────────────────────
633    RecipeEntry {
634        triggers: &["profile count: 0", "no mail profiles", "mail profile: none", "no profiles configured", "outlook profiles: 0"],
635        recipe: Recipe {
636            severity: "ACTION",
637            title: "No Outlook mail profile — Outlook will not open",
638            steps: &[
639                "Outlook requires at least one mail profile to start — create one from the Mail control panel applet, not from within Outlook",
640                "Open Mail applet: Win+R → type 'control mlcfg32.cpl' (or search 'Mail' in Control Panel) → Show Profiles → Add",
641                "Enter a profile name (e.g. 'Outlook') → Add Account → enter your email address and follow the auto-configuration wizard",
642                "For Exchange/Microsoft 365: the wizard needs network access to find the Autodiscover DNS record — ensure VPN is connected if this is a corporate account",
643                "For manual setup: choose 'Manual setup' → Microsoft Exchange or compatible service → enter server and username from your IT department",
644                "After creating the profile: launch Outlook, sign in if prompted — first launch will take 2–10 minutes to download the mailbox",
645            ],
646            dig_deeper: Some("outlook"),
647        },
648    },
649
650    // ── PrintNightmare not mitigated ──────────────────────────────────────────
651    RecipeEntry {
652        triggers: &["rpcauthnlevelprivacyenabled: 0", "printnightmare rpc mitigation not applied", "point and print allows silent", "finding: printnightmare"],
653        recipe: Recipe {
654            severity: "INVESTIGATE",
655            title: "PrintNightmare (CVE-2021-34527) mitigation not applied",
656            steps: &[
657                "Apply the RPC authentication hardening fix: PowerShell (admin) → Set-ItemProperty 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Print' -Name RpcAuthnLevelPrivacyEnabled -Value 1 -Type DWord",
658                "Restrict Point and Print driver installs to administrators: PowerShell (admin) → Set-ItemProperty 'HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows NT\\Printers\\PointAndPrint' -Name RestrictDriverInstallationToAdministrators -Value 1 -Type DWord",
659                "If the Print Spooler is not needed (e.g. server, workstation that never prints remotely): PowerShell (admin) → Stop-Service Spooler → Set-Service Spooler -StartupType Disabled",
660                "Verify patch KB5004945 or later is installed: check Windows Update history for July 2021 security updates",
661                "Restart the Spooler service after registry changes: PowerShell (admin) → Restart-Service Spooler",
662            ],
663            dig_deeper: Some("print_spooler"),
664        },
665    },
666];
667
668pub struct HealthScore {
669    pub grade: char,
670    pub label: &'static str,
671    pub action_count: usize,
672    pub investigate_count: usize,
673    pub monitor_count: usize,
674}
675
676impl HealthScore {
677    pub fn summary_line(&self) -> String {
678        match (
679            self.action_count,
680            self.investigate_count,
681            self.monitor_count,
682        ) {
683            (0, 0, 0) => "No issues found — machine is healthy.".to_string(),
684            (0, 0, m) => format!("{} item(s) to monitor.", m),
685            (0, i, 0) => format!("{} item(s) need investigation.", i),
686            (0, i, m) => format!("{} item(s) need investigation, {} to monitor.", i, m),
687            (a, 0, 0) => format!("{} item(s) require immediate action.", a),
688            (a, i, _) => format!(
689                "{} item(s) require immediate action, {} need investigation.",
690                a, i
691            ),
692        }
693    }
694
695    /// A plain-English sentence for non-technical users that explains what
696    /// the grade means and what to do next.
697    pub fn grade_intro(&self) -> &'static str {
698        match self.grade {
699            'A' => "Your PC is in great shape — no issues were found. The diagnostic data below is included for reference.",
700            'B' => "Your PC is doing well, but there's one thing worth a closer look. The action plan below has specific steps.",
701            'C' => "Your PC needs some attention. A couple of things should be investigated — follow the action plan below.",
702            'D' => "Your PC needs attention. There are issues that should be fixed — follow the action plan below.",
703            _ => "Your PC has critical issues that need immediate attention. Work through the action plan below as soon as possible.",
704        }
705    }
706}
707
708/// Compute a health grade (A–F) from diagnostic output sections.
709pub fn score_health(outputs: &[(&str, &str)]) -> HealthScore {
710    let mut all_recipes: Vec<&Recipe> = Vec::new();
711    let mut seen_titles = std::collections::HashSet::new();
712
713    for (_label, output) in outputs {
714        for recipe in match_recipes(output) {
715            if seen_titles.insert(recipe.title) {
716                all_recipes.push(recipe);
717            }
718        }
719    }
720
721    let action_count = all_recipes
722        .iter()
723        .filter(|r| r.severity == "ACTION")
724        .count();
725    let investigate_count = all_recipes
726        .iter()
727        .filter(|r| r.severity == "INVESTIGATE")
728        .count();
729    let monitor_count = all_recipes
730        .iter()
731        .filter(|r| r.severity == "MONITOR")
732        .count();
733
734    let (grade, label) = if action_count >= 3 {
735        ('F', "Critical")
736    } else if action_count >= 1 {
737        ('D', "Poor")
738    } else if investigate_count >= 2 {
739        ('C', "Fair")
740    } else if investigate_count >= 1 {
741        ('B', "Good")
742    } else {
743        ('A', "Excellent")
744    };
745
746    HealthScore {
747        grade,
748        label,
749        action_count,
750        investigate_count,
751        monitor_count,
752    }
753}
754
755/// Format all matching recipes for a given diagnostic output into a
756/// human-readable action plan section suitable for a Markdown report.
757pub fn format_action_plan(outputs: &[(&str, &str)]) -> String {
758    let mut all_recipes: Vec<&Recipe> = Vec::new();
759    let mut seen_titles = std::collections::HashSet::new();
760
761    for (_label, output) in outputs {
762        for recipe in match_recipes(output) {
763            if seen_titles.insert(recipe.title) {
764                all_recipes.push(recipe);
765            }
766        }
767    }
768
769    if all_recipes.is_empty() {
770        return "No actionable findings — machine appears healthy.\n".to_string();
771    }
772
773    // Sort: ACTION first, then INVESTIGATE, then MONITOR
774    all_recipes.sort_by_key(|r| match r.severity {
775        "ACTION" => 0,
776        "INVESTIGATE" => 1,
777        _ => 2,
778    });
779
780    let mut out = String::new();
781    for (i, recipe) in all_recipes.iter().enumerate() {
782        let badge = match recipe.severity {
783            "ACTION" => "⚠ ACTION REQUIRED",
784            "INVESTIGATE" => "🔍 INVESTIGATE",
785            _ => "📊 MONITOR",
786        };
787        out.push_str(&format!("### {}. {} — {}\n\n", i + 1, badge, recipe.title));
788        for step in recipe.steps {
789            out.push_str(&format!("- {}\n", step));
790        }
791        if let Some(_topic) = recipe.dig_deeper {
792            out.push_str("\n*Run `hematite --diagnose` for a deeper automated investigation.*\n");
793        }
794        out.push('\n');
795    }
796
797    out
798}
799
800/// Format all matching recipes as an HTML fragment for embedding in a report page.
801pub fn format_action_plan_html(outputs: &[(&str, &str)]) -> String {
802    let mut all_recipes: Vec<&Recipe> = Vec::new();
803    let mut seen_titles = std::collections::HashSet::new();
804
805    for (_label, output) in outputs {
806        for recipe in match_recipes(output) {
807            if seen_titles.insert(recipe.title) {
808                all_recipes.push(recipe);
809            }
810        }
811    }
812
813    if all_recipes.is_empty() {
814        return "<p class=\"healthy\">No actionable findings — machine appears healthy.</p>\n"
815            .to_string();
816    }
817
818    all_recipes.sort_by_key(|r| match r.severity {
819        "ACTION" => 0,
820        "INVESTIGATE" => 1,
821        _ => 2,
822    });
823
824    let mut out = String::new();
825    for (i, recipe) in all_recipes.iter().enumerate() {
826        let (sev_class, badge_class, badge_text) = match recipe.severity {
827            "ACTION" => ("sev-action", "b-action", "ACTION REQUIRED"),
828            "INVESTIGATE" => ("sev-investigate", "b-investigate", "INVESTIGATE"),
829            _ => ("sev-monitor", "b-monitor", "MONITOR"),
830        };
831        out.push_str(&format!("<div class=\"recipe {}\">\n", sev_class));
832        out.push_str(&format!(
833            "<h3><span class=\"badge {}\">{}</span> {}. {}</h3>\n",
834            badge_class,
835            badge_text,
836            i + 1,
837            he(recipe.title)
838        ));
839        out.push_str("<ol>\n");
840        for step in recipe.steps {
841            out.push_str(&format!("<li>{}</li>\n", he(step)));
842        }
843        out.push_str("</ol>\n");
844        if let Some(_topic) = recipe.dig_deeper {
845            out.push_str(
846                "<p class=\"dig-deeper\">Run <code>hematite --diagnose</code> for a deeper automated investigation of this issue.</p>\n"
847            );
848        }
849        out.push_str("</div>\n");
850    }
851    out
852}
853
854use crate::agent::html_template::he;