Skip to main content

hematite/agent/
diagnose_why.rs

1/// Symptom-driven cross-topic root-cause diagnosis — no model required.
2///
3/// Maps a user's plain-English symptom to a curated topic group, runs all
4/// topics, collects findings via the fix-recipe engine, and returns a ranked
5/// diagnosis with evidence excerpts from the live output.
6pub struct SymptomGroup {
7    pub category: &'static str,
8    pub keywords: &'static [&'static str],
9    pub topics: &'static [&'static str],
10}
11
12static SYMPTOM_GROUPS: &[SymptomGroup] = &[
13    SymptomGroup {
14        category: "Performance / Sluggishness",
15        keywords: &[
16            "slow",
17            "sluggish",
18            "lag",
19            "laggy",
20            "freeze",
21            "freezing",
22            "hang",
23            "hanging",
24            "unresponsive",
25            "high cpu",
26            "cpu usage",
27            "cpu spike",
28            "pc slow",
29            "computer slow",
30            "running slow",
31        ],
32        topics: &["resource_load", "processes", "thermal", "pagefile", "disk"],
33    },
34    SymptomGroup {
35        category: "Crash / Blue Screen",
36        keywords: &[
37            "bsod",
38            "blue screen",
39            "unexpected restart",
40            "restart unexpectedly",
41            "kernel panic",
42            "stop error",
43            "bugcheck",
44            "system crash",
45            "pc crashed",
46            "computer crashed",
47            "pc restart unexpectedly",
48        ],
49        topics: &[
50            "recent_crashes",
51            "disk_health",
52            "drivers",
53            "device_health",
54            "memory",
55        ],
56    },
57    SymptomGroup {
58        category: "No Internet / Offline",
59        keywords: &[
60            "no internet",
61            "no network",
62            "can't connect",
63            "cannot connect",
64            "offline",
65            "no connection",
66            "internet not working",
67            "internet down",
68            "can't browse",
69            "cannot browse",
70            "websites not loading",
71        ],
72        topics: &["connectivity", "wifi", "dns_cache", "vpn", "proxy"],
73    },
74    SymptomGroup {
75        category: "Slow Internet / Network",
76        keywords: &[
77            "slow internet",
78            "slow network",
79            "slow wifi",
80            "slow connection",
81            "high latency",
82            "packet loss",
83            "bad ping",
84            "buffering",
85            "low bandwidth",
86            "speed",
87            "network slow",
88        ],
89        topics: &["latency", "wifi", "connections", "network_stats"],
90    },
91    SymptomGroup {
92        category: "Slow Boot / Startup",
93        keywords: &[
94            "slow startup",
95            "slow boot",
96            "boot slow",
97            "startup slow",
98            "takes forever to start",
99            "takes long to start",
100            "long boot",
101            "long startup",
102            "slow to start",
103            "startup takes",
104        ],
105        topics: &["startup_items", "services", "disk", "pending_reboot"],
106    },
107    SymptomGroup {
108        category: "Overheating / Thermal",
109        keywords: &[
110            "hot",
111            "overheating",
112            "overheat",
113            "thermal",
114            "fan noise",
115            "fan loud",
116            "temperature",
117            "cpu temp",
118            "gpu temp",
119            "throttling",
120            "running hot",
121        ],
122        topics: &["thermal", "overclocker", "resource_load"],
123    },
124    SymptomGroup {
125        category: "No Sound / Audio",
126        keywords: &[
127            "no sound",
128            "no audio",
129            "audio not working",
130            "sound not working",
131            "microphone not working",
132            "mic not working",
133            "speakers not working",
134            "headphones not working",
135            "audio broken",
136            "can't hear",
137        ],
138        topics: &["audio", "services", "device_health"],
139    },
140    SymptomGroup {
141        category: "Printer / Printing",
142        keywords: &[
143            "can't print",
144            "cannot print",
145            "printer not working",
146            "print queue",
147            "printer offline",
148            "stuck print",
149            "printing problem",
150            "print error",
151        ],
152        topics: &["printers", "print_spooler", "services"],
153    },
154    SymptomGroup {
155        category: "High Disk Usage",
156        keywords: &[
157            "disk at 100",
158            "disk 100%",
159            "disk usage high",
160            "high disk usage",
161            "disk thrashing",
162            "disk maxed",
163            "storage full",
164            "drive full",
165            "low disk space",
166            "out of disk space",
167        ],
168        topics: &[
169            "processes",
170            "resource_load",
171            "storage",
172            "storage_deep",
173            "pagefile",
174            "disk_health",
175        ],
176    },
177    SymptomGroup {
178        category: "Windows Updates Failing",
179        keywords: &[
180            "updates failing",
181            "update error",
182            "update not working",
183            "windows update broken",
184            "update stuck",
185            "update failed",
186            "can't update",
187            "cannot update",
188            "updates won't install",
189        ],
190        topics: &["updates", "installer_health", "services", "pending_reboot"],
191    },
192    SymptomGroup {
193        category: "Sign-In / Authentication",
194        keywords: &[
195            "can't sign in",
196            "cannot sign in",
197            "login not working",
198            "password wrong",
199            "pin not working",
200            "fingerprint not working",
201            "hello not working",
202            "can't log in",
203            "account locked",
204            "authentication failed",
205            "sign-in failed",
206        ],
207        topics: &["sign_in", "identity_auth", "credentials"],
208    },
209    SymptomGroup {
210        category: "Malware / Suspicious Activity",
211        keywords: &[
212            "virus",
213            "malware",
214            "infected",
215            "suspicious",
216            "ransomware",
217            "trojan",
218            "spyware",
219            "adware",
220            "defender found",
221            "threat",
222            "unusual activity",
223            "something suspicious",
224        ],
225        topics: &[
226            "defender_quarantine",
227            "startup_items",
228            "connections",
229            "services",
230        ],
231    },
232    SymptomGroup {
233        category: "Low Memory / RAM",
234        keywords: &[
235            "out of memory",
236            "low memory",
237            "memory leak",
238            "ram usage high",
239            "not enough memory",
240            "memory full",
241            "ram maxed",
242            "memory pressure",
243            "high ram",
244            "high memory",
245        ],
246        topics: &["resource_load", "processes", "pagefile", "storage"],
247    },
248    SymptomGroup {
249        category: "Battery / Power",
250        keywords: &[
251            "battery",
252            "battery dying",
253            "battery not charging",
254            "short battery",
255            "power plan",
256            "cpu slow",
257            "plugged in not charging",
258        ],
259        topics: &["battery", "cpu_power", "thermal"],
260    },
261    SymptomGroup {
262        category: "Display / Screen",
263        keywords: &[
264            "screen flickering",
265            "display problem",
266            "resolution wrong",
267            "wrong resolution",
268            "black screen",
269            "monitor not detected",
270            "display not working",
271            "screen issues",
272            "flickering",
273        ],
274        topics: &["display_config", "drivers", "device_health"],
275    },
276    SymptomGroup {
277        category: "Hardware / Device Error",
278        keywords: &[
279            "device not working",
280            "hardware error",
281            "hardware not recognized",
282            "yellow bang",
283            "device manager error",
284            "unknown device",
285            "peripheral not working",
286            "usb not working",
287        ],
288        topics: &["device_health", "drivers", "peripherals"],
289    },
290    SymptomGroup {
291        category: "Network Share / Drive Access",
292        keywords: &[
293            "can't access share",
294            "network drive not working",
295            "mapped drive",
296            "shared folder not accessible",
297            "smb",
298            "unc path",
299            "network path",
300            "can't see network",
301            "network share",
302        ],
303        topics: &["shares", "services", "connectivity", "firewall_rules"],
304    },
305    SymptomGroup {
306        category: "Microsoft Teams Problems",
307        keywords: &[
308            "teams not working",
309            "teams crashing",
310            "teams won't open",
311            "teams won't start",
312            "teams black screen",
313            "teams slow",
314            "teams freezing",
315            "teams keeps crashing",
316            "teams microphone",
317            "teams camera",
318            "teams audio",
319            "teams video",
320            "teams sign-in",
321            "teams login",
322            "teams can't join",
323            "teams meeting issue",
324            "teams echo",
325            "teams no sound",
326            "teams not loading",
327            "microsoft teams",
328            "teams",
329            "meeting",
330        ],
331        topics: &[
332            "teams",
333            "identity_auth",
334            "audio",
335            "camera",
336            "browser_health",
337        ],
338    },
339    SymptomGroup {
340        category: "Outlook / Email Problems",
341        keywords: &[
342            "outlook not working",
343            "outlook crashing",
344            "outlook won't open",
345            "outlook slow",
346            "outlook not syncing",
347            "email not working",
348            "email not syncing",
349            "outlook freezing",
350            "outlook keeps crashing",
351            "outlook error",
352            "can't send email",
353            "can't receive email",
354            "outlook profile",
355            "outlook add-in",
356            "new outlook",
357            "outlook calendar",
358            "ost file",
359            "outlook",
360            "email not",
361        ],
362        topics: &["outlook", "identity_auth", "installer_health"],
363    },
364    SymptomGroup {
365        category: "Bluetooth Problems",
366        keywords: &[
367            "bluetooth not working",
368            "bluetooth won't pair",
369            "can't pair",
370            "bluetooth device not found",
371            "bluetooth keeps disconnecting",
372            "bluetooth headphones not working",
373            "bluetooth speaker not working",
374            "bluetooth mouse not working",
375            "bluetooth keyboard not working",
376            "bluetooth adapter",
377            "bluetooth radio",
378            "pairing failed",
379            "bluetooth audio",
380            "airpods not connecting",
381        ],
382        topics: &["bluetooth", "audio", "device_health", "services"],
383    },
384    SymptomGroup {
385        category: "Camera / Webcam Problems",
386        keywords: &[
387            "camera not working",
388            "webcam not working",
389            "camera not detected",
390            "camera blocked",
391            "camera privacy",
392            "webcam black screen",
393            "camera in use",
394            "camera busy",
395            "no camera",
396            "webcam not showing",
397            "camera not found",
398            "video not working",
399            "can't use camera",
400        ],
401        topics: &["camera", "device_health", "drivers", "services"],
402    },
403    SymptomGroup {
404        category: "USB / Device Not Recognized",
405        keywords: &[
406            "usb not recognized",
407            "usb not working",
408            "device not recognized",
409            "usb device not found",
410            "usb keeps disconnecting",
411            "usb drops",
412            "flash drive not showing",
413            "external drive not showing",
414            "usb port not working",
415            "keyboard not working",
416            "mouse not working",
417            "external hard drive not detected",
418            "usb connection",
419        ],
420        topics: &["peripherals", "device_health", "drivers", "usb_history"],
421    },
422    SymptomGroup {
423        category: "Sleep / Wake Problems",
424        keywords: &[
425            "won't sleep",
426            "won't wake",
427            "can't wake",
428            "sleep not working",
429            "sleep mode broken",
430            "pc won't go to sleep",
431            "wakes up randomly",
432            "wakes itself",
433            "wake on lan",
434            "hibernate not working",
435            "screen won't turn off",
436            "sleep then restart",
437            "stuck after sleep",
438            "black screen after sleep",
439            "won't resume",
440        ],
441        topics: &[
442            "services",
443            "device_health",
444            "drivers",
445            "scheduled_tasks",
446            "pending_reboot",
447        ],
448    },
449    SymptomGroup {
450        category: "App / Program Crashing",
451        keywords: &[
452            "app keeps crashing",
453            "program crashing",
454            "application crash",
455            "keeps closing",
456            "randomly closes",
457            "crashes after opening",
458            "word crashing",
459            "excel crashing",
460            "chrome crashing",
461            "edge crashing",
462            "firefox crashing",
463            "discord crashing",
464            "photoshop crashing",
465            "app crash",
466            "software crash",
467            "program won't open",
468            "keeps crashing",
469        ],
470        topics: &[
471            "app_crashes",
472            "installer_health",
473            "device_health",
474            "log_check",
475        ],
476    },
477];
478
479/// Find the best matching symptom group for the given user query.
480/// Returns `None` if no keywords match.
481pub fn match_symptom(query: &str) -> Option<&'static SymptomGroup> {
482    let lower = query.to_ascii_lowercase();
483    // Pick the group with the most keyword hits for best specificity.
484    SYMPTOM_GROUPS
485        .iter()
486        .map(|g| {
487            let hits = g.keywords.iter().filter(|k| lower.contains(*k)).count();
488            (hits, g)
489        })
490        .filter(|(hits, _)| *hits > 0)
491        .max_by_key(|(hits, _)| *hits)
492        .map(|(_, g)| g)
493}
494
495pub struct DiagnosisResult {
496    pub category: &'static str,
497    pub topics_run: Vec<&'static str>,
498    pub findings: Vec<Finding>,
499    pub root_causes: Vec<crate::agent::correlation::CorrelatedFinding>,
500    pub raw_output: String,
501}
502
503pub struct Finding {
504    pub severity: &'static str,
505    pub title: &'static str,
506    pub steps: Vec<&'static str>,
507    pub evidence: Vec<String>,
508    pub dig_deeper: Option<&'static str>,
509}
510
511/// Extract up to `max` lines from `haystack` that contain any of `keywords`.
512/// Returns them as evidence excerpts.
513fn extract_evidence(haystack: &str, keywords: &[&str], max: usize) -> Vec<String> {
514    let lower_hay = haystack.to_ascii_lowercase();
515    let mut out: Vec<String> = Vec::new();
516    for (line, lower_line) in haystack.lines().zip(lower_hay.lines()) {
517        if out.len() >= max {
518            break;
519        }
520        let trimmed = line.trim();
521        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("──") {
522            continue;
523        }
524        if keywords.iter().any(|k| lower_line.contains(k)) {
525            out.push(trimmed.to_string());
526        }
527    }
528    out
529}
530
531/// Build a diagnosis from raw multi-topic output using the fix-recipe engine.
532pub fn build_diagnosis(group: &'static SymptomGroup, raw_output: &str) -> DiagnosisResult {
533    use crate::agent::fix_recipes::match_recipes;
534
535    let recipes = match_recipes(raw_output);
536
537    // Sort: ACTION first, INVESTIGATE second, MONITOR last.
538    let severity_rank = |s: &str| match s {
539        "ACTION" => 0u8,
540        "INVESTIGATE" => 1,
541        _ => 2,
542    };
543
544    let mut sorted_recipes: Vec<_> = recipes.into_iter().collect();
545    sorted_recipes.sort_by_key(|r| severity_rank(r.severity));
546
547    let findings = sorted_recipes
548        .into_iter()
549        .map(|r| {
550            // Build evidence: look for lines related to this finding's trigger words
551            // by searching with the recipe title keywords in the raw output.
552            let title_words: Vec<&str> =
553                r.title.split_whitespace().filter(|w| w.len() > 3).collect();
554            let evidence = extract_evidence(raw_output, &title_words, 2);
555            Finding {
556                severity: r.severity,
557                title: r.title,
558                steps: r.steps.to_vec(),
559                evidence,
560                dig_deeper: r.dig_deeper,
561            }
562        })
563        .collect();
564
565    let root_causes = crate::agent::correlation::correlate_findings(raw_output);
566
567    DiagnosisResult {
568        category: group.category,
569        topics_run: group.topics.to_vec(),
570        findings,
571        root_causes,
572        raw_output: raw_output.to_string(),
573    }
574}