Skip to main content

hematite/agent/
fix_recipes.rs

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