limitless-cli 1.0.0

A beginner-friendly environment diagnostic tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
//! Translates raw technical errors into beginner-friendly advice.
//!
//! [`translate_error`] takes a [`DiagnosticResult`] (or a raw error surfaced
//! as one) and turns it into a [`MentorMessage`]: the raw error is kept as
//! `technical_detail`, while `plain_english` explains it in everyday terms —
//! often with an analogy — and `suggested_action` gives a concrete next step.
//!
//! The translation database lives in [`TRANSLATIONS`] and covers 50+ common
//! Node.js, Python, Rust and port/system errors. Patterns are matched with a
//! simple case-insensitive substring check (`OR` across each entry's
//! needles), so the same error from different tools can share one entry.
//!
//! # Example
//!
//! ```
//! use limitless_cli::models::{CheckStatus, DiagnosticResult, Severity};
//! use limitless_cli::modules::translator::translate_error;
//!
//! let port_error = DiagnosticResult::new(
//!     "Server",
//!     CheckStatus::Fail,
//!     "Error: EADDRINUSE: address already in use :::3000",
//! );
//! let mentor = translate_error(&port_error);
//!
//! assert_eq!(mentor.severity, Severity::Warning);
//! assert!(mentor.plain_english.contains("3000"));
//! assert!(mentor.technical_detail.contains("EADDRINUSE"));
//! assert!(mentor.suggested_action.contains("3000"));
//! ```

use colored::Colorize;

use crate::models::{CheckStatus, DiagnosticResult, MentorMessage, Severity};

// ---------------------------------------------------------------------------
// Translation database
// ---------------------------------------------------------------------------

/// Which ecosystem an error belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Category {
    /// Node.js / npm / JavaScript runtime errors.
    Node,
    /// Python / pip interpreter errors.
    Python,
    /// Rust / cargo compiler and linker errors.
    Rust,
    /// Operating-system, networking and port errors.
    PortSystem,
}

impl Category {
    /// Short human-readable label for the category.
    pub fn label(&self) -> &'static str {
        match self {
            Category::Node => "Node.js",
            Category::Python => "Python",
            Category::Rust => "Rust",
            Category::PortSystem => "Port/System",
        }
    }
}

/// A single translation entry.
///
/// `plain_english` and `action` may contain `{port}`, `{pid}`, `{module}`,
/// `{pkg}`, `{lib}` and `{tool}` placeholders that are filled from the error
/// text at translation time.
pub struct TranslationEntry {
    /// Ecosystem this error belongs to.
    pub category: Category,
    /// Lower-case substrings that identify the error. Any one of them is
    /// enough to match.
    pub needles: &'static [&'static str],
    /// How urgent the situation is for a beginner.
    pub severity: Severity,
    /// Jargon-free explanation, ideally with an analogy.
    pub plain_english: &'static str,
    /// A concrete command or next step.
    pub action: &'static str,
}

impl TranslationEntry {
    /// Whether any needle appears in the (lower-cased) haystack.
    pub fn matches(&self, haystack: &str) -> bool {
        self.needles.iter().any(|needle| haystack.contains(needle))
    }
}

/// The full translation database (> 50 entries). Order matters: earlier
/// entries win when several could match.
pub const TRANSLATIONS: &[TranslationEntry] = &[
    // ------------------------------------------------------------------
    // Node.js errors
    // ------------------------------------------------------------------
    TranslationEntry {
        category: Category::Node,
        needles: &["err_require_esm"],
        severity: Severity::Critical,
        plain_english: "Your project uses modern JavaScript modules (ESM), but the startup file is written in old-style CommonJS. It's like trying to read a book written in French using an English grammar guide — the import rules just don't line up.",
        action: "Rename .js files to .mjs, or add \"type\": \"module\" to package.json",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["cannot find module", "err_module_not_found"],
        severity: Severity::Critical,
        plain_english: "Node can't locate {module}. Either the file was renamed or moved, or the package was never installed. Think of it like a friend pointing at an empty desk and saying \"the book is right here\".",
        action: "Check the import path, then run: npm install",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["cannot find package"],
        severity: Severity::Critical,
        plain_english: "The package {module} that package.json asks for isn't in node_modules. The recipe lists the ingredient but the pantry is bare.",
        action: "Run: npm install, then verify the name/version in package.json",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["erresolve", "peer dep missing", "peer dependency"],
        severity: Severity::Warning,
        plain_english: "Two packages disagree about which versions of each other they need — like two flatmates who each demand the kitchen be cleaned \"their\" way.",
        action: "Run: npm install --legacy-peer-deps, or align the versions manually",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["elflcic", "lifecycle"],
        severity: Severity::Critical,
        plain_english: "npm ran the script your package defines (like 'start' or 'build'), but the command inside it crashed. The wrapper is fine; the command it launched is not.",
        action: "Read the last lines of the log above this message and fix that script",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["missing script"],
        severity: Severity::Critical,
        plain_english: "package.json doesn't define the npm script you asked for. You asked the kitchen for a menu item that isn't on the menu.",
        action: "Check the scripts section of package.json, or run it directly (e.g. node src/index.js)",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["enoent"],
        severity: Severity::Critical,
        plain_english: "A file npm expected to find doesn't exist — often node_modules is out of date or a lock file is missing. Like a file labelled 'here' that isn't in its drawer.",
        action: "Delete node_modules and run: npm install (or npm ci)",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["eexist", "file exists"],
        severity: Severity::Warning,
        plain_english: "npm tried to create a file or folder that's already there. The tool is only complaining that the desk drawer is already occupied.",
        action: "Remove the conflicting file or folder, then retry",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["eacces", "eperm"],
        severity: Severity::Critical,
        plain_english: "node/npm doesn't have permission to do this. It's like a librarian who is locked out of the room where the books are kept.",
        action: "Fix folder permissions (chown/chmod), or reinstall without a sandbox; avoid running as admin where possible",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["err_dlopen_failed"],
        severity: Severity::Critical,
        plain_english: "A native (compiled) add-on couldn't be loaded, usually because it was compiled for a different platform or Node version. Like bringing a bookshelf made for a different shelf height home.",
        action: "Rebuild native modules: npm rebuild, or reinstall the package",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["headers already sent"],
        severity: Severity::Warning,
        plain_english: "Your server already sent the response and then tried to change it again — like closing a letter and then trying to add another paragraph after posting it.",
        action: "Return from the request handler after sending a response (avoid double res.send/res.json)",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["cannot read properties of undefined", "cannot read property"],
        severity: Severity::Critical,
        plain_english: "Your code reached into an object that doesn't exist yet. It's like unlocking a car door by reaching for a handle that isn't there — the object is nothing, so any handle on it is also nothing.",
        action: "Add a null check or a fallback default before reading the property",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["is not a function", "is not callable"],
        severity: Severity::Critical,
        plain_english: "Your code tried to call something that isn't a function — like dialing a phone number where the line has been disconnected. Often a name collision or a missing import.",
        action: "Print/inspect the value before calling it; check for a missing or renamed import",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["is not defined"],
        severity: Severity::Critical,
        plain_english: "You used a name that was never declared in this scope. It's like asking for a colleague who doesn't work in this office. Usually a typo or a missing import.",
        action: "Define the variable or import it at the top of the file",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["unexpected identifier", "unexpected token", "unexpected string"],
        severity: Severity::Critical,
        plain_english: "The JavaScript engine hit a word it didn't expect — a missing bracket, comma or quote earlier on made the sentence grammatically wrong.",
        action: "Look at the line and column in the error and check brackets, commas and quotes nearby",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["maximum call stack size exceeded"],
        severity: Severity::Warning,
        plain_english: "Your functions are calling each other without ever stopping — a loop of infinite phone calls. Usually recursion without a base case.",
        action: "Find the recursive call and give it a stopping condition",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["heap out of memory", "javascript heap"],
        severity: Severity::Critical,
        plain_english: "The program ran out of memory storing data — like stuffing an infinite pile of papers into a briefcase. Often a loop that keeps growing an array or object.",
        action: "Check for unbounded loops/accumulation, or raise the limit: node --max-old-space-size=4096",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["unhandledpromiserejection", "unhandled promise rejection"],
        severity: Severity::Critical,
        plain_english: "An async operation failed and nobody was there to catch it, like dropping a plate nobody was standing next to.",
        action: "Wrap the promise in try/catch (or .catch()) or add a process.on('unhandledRejection') handler",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["cannot be resolved", "not resolve", "failed to resolve", "no matching files", "matching entry for"],
        severity: Severity::Critical,
        plain_english: "The bundler/build tool can't find the file an import points to. The map to the treasure is right, but the treasure chest was moved.",
        action: "Fix the import path or file extension (check ./index paths), then restart the dev server",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["err_invalid_arg_type", "invalid argument"],
        severity: Severity::Critical,
        plain_english: "A Node function received a value of the wrong kind — like fitting a key of the right colour but wrong shape into a lock.",
        action: "Check the function call: every argument must be the documented type (string, number, buffer...)",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["err_stream_write_after_end", "write after end"],
        severity: Severity::Warning,
        plain_english: "Your code wrote to a stream that was already closed — like trying to push water through a shut-off pipe.",
        action: "Stop writing to the stream after calling .end(); check the lifecycle of the response/socket",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["'emitted', 'error' event", "unhandled 'error' event"],
        severity: Severity::Critical,
        plain_english: "Something (a server, socket or stream) failed, and no error handler was listening, so Node gave up. The radio is on a dead station and nobody turned the dial.",
        action: "Attach an .on('error', ...) handler right where the emitter is created",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["err_socket_timeout", "socket hang up"],
        severity: Severity::Warning,
        plain_english: "A network connection stopped mid-conversation. The other side just hung up — maybe a timeout, a crash, or a firewall.",
        action: "Retry with a longer timeout, check the service is running, and look for proxy/firewall interference",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["econnrefused"],
        severity: Severity::Critical,
        plain_english: "Your code tried to connect to a server, but nothing is listening on that address — it knocked on a door that no one is behind.",
        action: "Start the service first, then check the host/port in your connection settings",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["etimedout", "operation timed out"],
        severity: Severity::Warning,
        plain_english: "A request waited too long and gave up. It's like calling someone who never picks up. Often a slow registry, proxy, or too-short timeout.",
        action: "Increase the timeout or retry; check network and registry (npm config get registry)",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["getaddrinfo enotfound", "connect enotfound", "enotfound -2"],
        severity: Severity::Critical,
        plain_english: "The domain name couldn't be turned into an address — the phone book has no entry for it. A typo, DNS issue, or the site is down.",
        action: "Check the URL spelling, then `nslookup <host>`; if it fails, fix DNS/VPN connectivity",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["connection reset by peer", "connection reset"],
        severity: Severity::Warning,
        plain_english: "The remote server dropped a connection that was already in progress, like a call cut off mid-sentence.",
        action: "Retry the request; check the server logs and any load balancer/firewall timeouts",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["epipe", "broken pipe"],
        severity: Severity::Warning,
        plain_english: "The program your tool was talking to stopped reading partway through — the pipe between them was snapped. Commonly seen when piping into `head`.",
        action: "That's usually harmless; suppress it or handle EPIPE in your script (process.stdout.on('error'))",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["cannot read properties of null"],
        severity: Severity::Critical,
        plain_english: "Your code reached into a value that is literally nothing (null), like pressing floor buttons in an elevator that isn't there.",
        action: "Guard the value (if (x && x.y)) or use optional chaining x?.y before reading deeper",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["'await' is only allowed", "top-level await"],
        severity: Severity::Warning,
        plain_english: "You used `await` where the file isn't treated as a modern module, so top-level await isn't allowed. Rules are language-dependent here, not something you did wrong.",
        action: "Add \"type\": \"module\" to package.json, or wrap the code in an async function",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["npm err", "npm error"],
        severity: Severity::Warning,
        plain_english: "npm reported a problem with the installation or script step. The message directly above is the real clue.",
        action: "Read the last npm error line; run npm install --verbose to see more",
    },
    TranslationEntry {
        category: Category::Node,
        needles: &["invalid regexp flag"],
        severity: Severity::Critical,
        plain_english: "A regular expression was given a flag JavaScript doesn't know — like a bookmark with a page number that doesn't exist.",
        action: "Remove or correct the flag after the closing slash of the regex",
    },

    // ------------------------------------------------------------------
    // Python errors
    // ------------------------------------------------------------------
    TranslationEntry {
        category: Category::Python,
        needles: &["modulenotfounderror", "no module named"],
        severity: Severity::Critical,
        plain_english: "Your project depends on a library called {module}, but it hasn't been installed in this Python environment. It's like a recipe that asks for an ingredient you never bought.",
        action: "Run: pip install {module}",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["importerror", "cannot import name"],
        severity: Severity::Critical,
        plain_english: "The module is there, but the specific name you imported isn't — a typo, or the author renamed it. You asked for a chapter that isn't in this edition of the book.",
        action: "Check the spelling and the module docs; run `python -c \"import {module}\"` to see what exists",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["syntaxerror: invalid syntax", "invalid syntax"],
        severity: Severity::Critical,
        plain_english: "Python hit a line it couldn't parse — a missing colon, bracket, or mismatched quote earlier. Grammar error, not a logic error.",
        action: "Look at the line/column in the traceback and fix missing colons, brackets, or parentheses",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["indentationerror", "unexpected indent", "unindent"],
        severity: Severity::Critical,
        plain_english: "Python is very strict about indentation — a block that stepped the wrong amount confuses it. It's like a paragraph where the margins suddenly shift for no reason.",
        action: "Make all lines in a block line up exactly (4 spaces is conventional); check for mixed tabs and spaces",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["nameerror", "is not defined"],
        severity: Severity::Critical,
        plain_english: "You used a name Python has never seen — usually a typo, a missing assignment, or a misnamed variable. You called a meeting with a colleague who doesn't work here.",
        action: "Check the spelling and ensure the variable/function is defined before that line runs",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["typeerror", "object is not callable", "not iterable", "not subscriptable"],
        severity: Severity::Critical,
        plain_english: "You used a value as the wrong kind of thing — like trying to run a parking ticket as a car. Usually a value didn't turn out to be the type you expected.",
        action: "Check the value's type (print(type(x))) and adjust the operation or the data",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["attributeerror", "has no attribute"],
        severity: Severity::Critical,
        plain_english: "You asked an object for something it doesn't have — reaching for a pocket on a shirt with none. Usually a typo or the wrong object entirely.",
        action: "Check the spelling; list available attributes with dir(obj)",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["valueerror", "invalid literal for int"],
        severity: Severity::Critical,
        plain_english: "A value has the right type but the wrong content — like handing an envelope full of letters where a number was expected.",
        action: "Inspect the value (print(it)) and validate/normalise it before converting",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["keyerror"],
        severity: Severity::Critical,
        plain_english: "You asked a dict for a key that isn't there — like opening a filing cabinet drawer someone never labelled. Often the key name or the data content changed.",
        action: "Use dict.get(key, default) or check the key with `in` before accessing",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["indexerror", "list index out of range"],
        severity: Severity::Critical,
        plain_english: "You reached for an item past the end of a list — like grabbing the 11th room key in a building with 10 rooms.",
        action: "Check the list length before indexing, or use .get()/slicing that can't overrun",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["filenotfounderror", "filenotfound"],
        severity: Severity::Critical,
        plain_english: "The program tried to open a file that isn't at that path. Maybe it was moved, renamed, or the working directory is different from a relative path.",
        action: "Print/normalise the path (os.path.abspath), confirm the file exists where the script expects",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["permissionerror", "errno 13"],
        severity: Severity::Critical,
        plain_english: "Python doesn't have permission to read/write that file — the security guard said no. Often a read-only folder or file owned by another user.",
        action: "Fix file/folder permissions or move the file somewhere writable",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["externally-managed-environment", "externally managed environment"],
        severity: Severity::Warning,
        plain_english: "pip won't install into this system Python because the OS manages its packages. Installing system-wide would be like repainting a rental apartment's walls without asking the landlord.",
        action: "Create and activate a virtual environment, then pip install inside it: python -m venv .venv && .venv\\Scripts\\activate",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["no matching distribution found", "could not find a version that satisfies"],
        severity: Severity::Critical,
        plain_english: "pip searched every index for the package/version and found nothing — the dish isn't on any menu it can access. Often a typo, or the package only exists on another index.",
        action: "Check the name/version spelling, then pip install --upgrade pip and retry",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["recursionerror", "maximum recursion depth exceeded"],
        severity: Severity::Warning,
        plain_english: "A function kept calling itself until Python put its foot down — like a stack of plates being built until it topples. Usually recursion without a base case.",
        action: "Fix the recursion base case, or convert to an iterative loop",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["unboundlocalerror"],
        severity: Severity::Critical,
        plain_english: "Python knows the name (it's assigned somewhere in the function), but it's being used before that assignment runs. The shelf exists, but the book hasn't been placed on it yet.",
        action: "Move the assignment above its use, or make it global explicitly",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["assertionerror"],
        severity: Severity::Warning,
        plain_english: "An `assert` check failed — code assumed something about the data that turned out false. It's a tripwire your own program set off on purpose.",
        action: "Look at the assertion's message and fix the condition or input that made it fail",
    },
    TranslationEntry {
        category: Category::Python,
        needles: &["cannot open shared object", "libssl.so"],
        severity: Severity::Warning,
        plain_english: "A compiled Python extension is missing a native library the operating system must provide, not just Python.",
        action: "Install the binary package (e.g. apt install libssl-dev / python3-numpy) for your distribution",
    },

    // ------------------------------------------------------------------
    // Rust errors
    // ------------------------------------------------------------------
    TranslationEntry {
        category: Category::Rust,
        needles: &["cannot find value", "cannot find function", "cannot find constant"],
        severity: Severity::Critical,
        plain_english: "Rust looked up a name in this scope and didn't find it — a typo, a missing import, or using it before it exists. You asked a library for a book it doesn't shelve.",
        action: "Check the spelling and add the right `use` import at the top of the file",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["could not find 'main' in crate", "main function not found", "no 'main' function"],
        severity: Severity::Critical,
        plain_english: "cargo expects an entry point named `main` in the binary crate, but it's missing, private, or has the wrong signature. A building needs a front door.",
        action: "Add `fn main() {}` (or `async fn main()` with #[tokio::main]) to a src file",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["cannot find -l"],
        severity: Severity::Critical,
        plain_english: "Your Rust code needs an external C/C++ library named {lib}, and the linker can't find it on this system. It's like a furniture kit that assumes you already own a specific screwdriver.",
        action: "Install the system dev package for {lib} (Ubuntu: sudo apt-get install lib{lib}-dev; macOS: brew install {lib})",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["mismatched types", "error[e0308]"],
        severity: Severity::Critical,
        plain_english: "You gave Rust a value of a different type than it expected — like plugging a USB-C cable into a USB-A port. The types have to match exactly.",
        action: "Look at the 'expected/found' part of the error and convert the value (e.g. .to_string(), as i32, or deref)",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["does not live long enough", "error[e0597]", "error[e0592]"],
        severity: Severity::Critical,
        plain_english: "You're holding a reference to data that gets destroyed while you still use it — like keeping a promise from someone who already left. Rust's borrow checker protects you from using freed memory.",
        action: "Give the data a longer lifetime (clone it, or restructure so the owner outlives the reference)",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["cannot move out of", "use of moved value", "moved value"],
        severity: Severity::Critical,
        plain_english: "You used a value after handing it somewhere else (it was 'moved'). In Rust, each value has exactly one owner — like giving away your only coffee cup and still reaching for it.",
        action: "Borrow it with & (or &mut) instead of moving, or clone when you need it in two places",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["trait bound", "trait `std::", "is not satisfied"],
        severity: Severity::Critical,
        plain_english: "A generic type needs to support certain operations (a 'trait'), but the concrete type doesn't. It's like a machine that accepts only square pegs, and you're offering a round one.",
        action: "Check which trait is missing and add a derive (e.g. #[derive(Debug)]) or import the right trait",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["no method named"],
        severity: Severity::Critical,
        plain_english: "Rust can't find a method with that name on this type — a typo, wrong type, or a needed trait import. You reached for a tool that isn't in this toolbox.",
        action: "Verify the method name, or import the trait that provides it (e.g. `use std::io::prelude::*`)",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["cannot borrow as immutable"],
        severity: Severity::Critical,
        plain_english: "You're trying to read and change something at the same time. Rust only allows one writer or many readers at once — like one pipe flowing, you can't also drain it from the same end.",
        action: "Re-order the code so reads finish before the write, or clone the data you need to read",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["cannot borrow"],
        severity: Severity::Critical,
        plain_english: "Two borrows of the same value are conflicting. Rust's borrow checker is strict so you never hit memory bugs — it's a gatekeeper, not a nag.",
        action: "Separate the borrows in time or scope; use cloning when the conflict isn't really about the same data",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["expected struct", "found struct", "expected enum", "found enum"],
        severity: Severity::Critical,
        plain_english: "You constructed the wrong shape of value — different type than the function wanted. Like delivering a microphone to someone who asked for a microphone stand.",
        action: "Match the error's expected type by reading the struct/enum docs, or derive From for a conversion",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["the size for values of type", "cannot be known at compilation", "infinite size", "recursive type"],
        severity: Severity::Critical,
        plain_english: "A type contains itself without any end point, so its size is infinite. Think of a box that contains a box that contains a box... forever. Rust needs a measurer, so one item must live behind a pointer.",
        action: "Put one level behind Box<T>, Rc<T> or Arc<T> to end the recursion (this is normal for linked lists/trees)",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["linker `link.exe` not found", "linker not found", "link.exe"],
        severity: Severity::Critical,
        plain_english: "Rust found the compiler fine, but the tool that glues compiled pieces into a program (the linker) is missing. The builder arrived but brought no hammer.",
        action: "Install a C linker (Windows: MSVC Build Tools or mingw-w64; Ubuntu: sudo apt-get install build-essential)",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["could not compile", "due to previous error"],
        severity: Severity::Warning,
        plain_english: "cargo stopped because an earlier error in this build made further steps pointless. Fix the first real error and the rest usually follow.",
        action: "Scroll to the FIRST error in the output; fix that one, then rebuild",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["failed to run custom build command"],
        severity: Severity::Critical,
        plain_english: "A build script (build.rs) that prepares a dependency crashed. The dependency's own build step failed, usually because of missing system tools.",
        action: "Read the child process output; install the missing system library/tool the crate documents (e.g. protoc, openssl-dev)",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["could not parse manifest", "toml parse error", "invalid toml", "expected a table key"],
        severity: Severity::Critical,
        plain_english: "Cargo.toml isn't valid TOML, so cargo can't even read the project spec. It's like handing in a form that's missing its checkboxes.",
        action: "Fix the TOML syntax on the reported line (quotes around strings, no stray commas)",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["the trait `display` is not implemented", "trait `fmt::debug`"],
        severity: Severity::Warning,
        plain_english: "You tried to print a value with {} but that type doesn't say how it should be printed. The object has no speaking part in the display script.",
        action: "Add #[derive(Debug)] or #[derive(Display)] to the type, or use {:?} with Debug",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["cannot infer type", "type annotations needed"],
        severity: Severity::Warning,
        plain_english: "Rust can't guess what type a value should be because there's nothing to infer from. It's a blank line where the expected format is obvious to a person but not to the compiler.",
        action: "Add an explicit type annotation (let x: Vec<String> = ...) or annotate the variable",
    },
    TranslationEntry {
        category: Category::Rust,
        needles: &["error[e0382]", "error[e0505]"],
        severity: Severity::Critical,
        plain_english: "A value was used after being given away or dropped. Rust is meticulous about ownership — each item has one owner at a time.",
        action: "Borrow (&x) instead of moving, or clone the value when you need it again later",
    },

    // ------------------------------------------------------------------
    // Port / system errors
    // ------------------------------------------------------------------
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["eaddrinuse", "address already in use"],
        severity: Severity::Warning,
        plain_english: "Port {port} is jammed by an old background process. Think of it like a parking spot that hasn't been cleared yet — the app that parked there earlier never left.",
        action: "Find and stop the process holding it, then retry: kill -9 {pid} (or `lsof -i :{port}` to discover it)",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["occupied by pid"],
        severity: Severity::Warning,
        plain_english: "Port {port} is already taken by a running process (PID {pid}). It's like arriving at the only free seat and finding someone already sitting in it.",
        action: "Stop that process (kill -9 {pid}), or configure your app to use a different port",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["cannot connect to the docker daemon", "docker daemon is not running", "is the docker daemon running"],
        severity: Severity::Critical,
        plain_english: "Docker is installed but the background service that does the work isn't running — the engine is off even though the car looks ready.",
        action: "Start the Docker Desktop / docker service (systemctl start docker on Linux), then retry",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &[
            "command not found",
            "not recognized as the name",
            "was not found on path",
        ],
        severity: Severity::Critical,
        plain_english: "The shell couldn't find a program named {tool} on your PATH. It's like having the address but the street not existing. Usually it's not installed, or the install folder isn't on PATH.",
        action: "Install {tool} and add its folder to PATH, then open a fresh terminal",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["not a git repository", "not a git repo"],
        severity: Severity::Warning,
        plain_english: "You ran a git command outside a Git repository, so git has no history to work with — like asking a library for a book's borrowing record when the book was never checked in.",
        action: "Run `git init` here, or cd into the right project folder",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["permission denied", "operation not permitted"],
        severity: Severity::Critical,
        plain_english: "The system refused an action because it requires more privileges than you have — the bouncer said you're not on the list.",
        action: "Run the command with elevated privileges if appropriate (sudo / admin), or fix file permissions",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["no such file or directory", "cannot stat", "can't open file"],
        severity: Severity::Critical,
        plain_english: "The command pointed at a file or folder that isn't there — a typo in the path, or the file was moved. The shortcut still exists, but the target is gone.",
        action: "Double-check the path (case matters!). Use ls / Get-ChildItem to confirm it exists",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["connection refused", "ecould not connect", "bind: address already in use"],
        severity: Severity::Critical,
        plain_english: "Nothing is answering at that address/port — the doorbell rings into an empty apartment. The service isn't running, or it listens somewhere else.",
        action: "Start the service and confirm it listens on the expected host/port (lsof -i / netstat -ano)",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["dns", "hostname not found", "unknown host"],
        severity: Severity::Critical,
        plain_english: "The network can't translate a hostname into an address — the phone book doesn't list it, or the lookup service is down.",
        action: "Check spelling, DNS settings and VPN; try `nslookup <host>` to test resolution",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["point to folders that do not exist", "broken path entries", "not exist on path"],
        severity: Severity::Warning,
        plain_english: "Some folders in your PATH point to places that no longer exist. The system checks the whole route list each time it looks for a program, and dead streets slow it down.",
        action: "Edit your PATH to remove (or fix) the entries listed in the check report",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["listed more than once", "duplicate path", "listed twice"],
        severity: Severity::Warning,
        plain_english: "Some folders appear on your PATH more than once. It's not harmful, just clutter — like delivering the same flyer to the same house several times.",
        action: "Remove the duplicated PATH entries in your shell profile",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["editor/visual is not set", "no default editor"],
        severity: Severity::Warning,
        plain_english: "No default editor is configured, so command-line tools may pick a random one or fail. It's like having mail delivered but no default address on file.",
        action: "Set EDITOR in your profile, e.g. export EDITOR=\"code --wait\" (or vim / notepad).",
    },
    TranslationEntry {
        category: Category::PortSystem,
        needles: &["externally-managed"],
        severity: Severity::Warning,
        plain_english: "The system won't let pip write to its own Python because the OS manages those packages. Reinstalling managed software directly is like editing a system file an admin checks out.",
        action: "Use a virtual environment: python -m venv .venv and activate it before installing packages",
    },
];

/// Looks up translator database entries by category (used for coverage tests).
pub fn translations_for(category: Category) -> impl Iterator<Item = &'static TranslationEntry> {
    TRANSLATIONS.iter().filter(move |e| e.category == category)
}

// ---------------------------------------------------------------------------
// Matching and extraction
// ---------------------------------------------------------------------------

/// Everything needed to fill placeholders from a diagnostic.
struct MatchContext<'d> {
    check_name: &'d str,
    message: &'d str,
}

impl<'d> MatchContext<'d> {
    /// The port number, taken from the check name (e.g. `Port 5432`) or the
    /// first number in the message.
    fn port(&self) -> Option<String> {
        if let Some(rest) = self.check_name.strip_prefix("Port ") {
            let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
            if !digits.is_empty() {
                return Some(digits);
            }
        }
        Self::first_number(self.message)
    }

    /// The process ID: the first number in the message that is not the port.
    fn pid(&self) -> Option<String> {
        let port = self.port();
        Self::numbers(self.message)
            .into_iter()
            .find(|n| Some(n.as_str()) != port.as_deref())
    }

    /// The first quoted name in the message (`'requests'`, `"lodash"`).
    fn quoted(&self) -> Option<String> {
        let bytes = self.message.as_bytes();
        for (i, &b) in bytes.iter().enumerate() {
            if b == b'\'' || b == b'"' {
                let mut out = String::new();
                for &next in &bytes[i + 1..] {
                    if next == b {
                        return if out.is_empty() { None } else { Some(out) };
                    }
                    out.push(next as char);
                }
            }
        }
        None
    }

    /// The tool name, from the check name (`Tool node`) or the message's
    /// first word.
    fn tool(&self) -> Option<String> {
        if let Some(rest) = self.check_name.strip_prefix("Tool ") {
            let name = rest.split_whitespace().next().unwrap_or("");
            if !name.is_empty() {
                return Some(name.to_string());
            }
        }
        self.message
            .split_whitespace()
            .next()
            .map(|w| w.to_string())
    }

    /// The library name from a `cannot find -lfoo` linker error.
    fn lib(&self) -> Option<String> {
        let lower = self.message.to_ascii_lowercase();
        let idx = lower.find("-l")?;
        let rest = &self.message[idx + 2..];
        let name: String = rest
            .chars()
            .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
            .collect();
        if name.is_empty() {
            None
        } else {
            Some(name)
        }
    }

    fn first_number(text: &str) -> Option<String> {
        Self::numbers(text).into_iter().next()
    }

    fn numbers(text: &str) -> Vec<String> {
        let mut out = Vec::new();
        let mut current = String::new();
        for ch in text.chars() {
            if ch.is_ascii_digit() {
                current.push(ch);
            } else if !current.is_empty() {
                out.push(std::mem::take(&mut current));
            }
        }
        if !current.is_empty() {
            out.push(current);
        }
        out
    }
}

/// Fills `{port}`, `{pid}`, `{module}`, `{pkg}`, `{lib}` and `{tool}`
/// placeholders, degrading gracefully to hints when a value is unknown.
fn fill(template: &str, ctx: &MatchContext<'_>) -> String {
    let port = ctx.port().unwrap_or_else(|| "(unknown port)".to_string());
    let pid = ctx
        .pid()
        .unwrap_or_else(|| format!("(unknown — run `lsof -i :{port}` to find it)"));
    let module = ctx.quoted().unwrap_or_else(|| "(the module)".to_string());
    let pkg = ctx.quoted().unwrap_or_else(|| "(the package)".to_string());
    let tool = ctx.tool().unwrap_or_else(|| "(the tool)".to_string());
    let lib = ctx.lib().unwrap_or_else(|| "(the library)".to_string());

    let replacements: &[(&str, String)] = &[
        ("{port}", port),
        ("{pid}", pid),
        ("{module}", module),
        ("{pkg}", pkg),
        ("{tool}", tool),
        ("{lib}", lib),
    ];

    let mut out = template.to_string();
    for (key, value) in replacements {
        out = out.replace(key, value);
    }
    out
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Translates a [`DiagnosticResult`] into a beginner-friendly
/// [`MentorMessage`].
///
/// The `technical_detail` always carries the original error text so nothing
/// is hidden from power users; `plain_english` and `suggested_action` do the
/// "translation". When a diagnostic already carries a remediation hint (for
/// example one produced by the port watcher), that concrete step is used
/// verbatim as the suggested action.
///
/// A passing diagnostic becomes an informational message; an unrecognised
/// error falls back to a generic (but still actionable) message.
pub fn translate_error(diagnostic: &DiagnosticResult) -> MentorMessage {
    if diagnostic.status == CheckStatus::Pass {
        return MentorMessage {
            severity: Severity::Info,
            plain_english: "This check passed — nothing to fix.".to_string(),
            technical_detail: diagnostic.message.clone(),
            suggested_action: "No action needed.".to_string(),
        };
    }

    let haystack = format!("{} {}", diagnostic.check_name, diagnostic.message).to_lowercase();

    let entry = TRANSLATIONS.iter().find(|e| e.matches(&haystack));

    match entry {
        Some(entry) => {
            let ctx = MatchContext {
                check_name: &diagnostic.check_name,
                message: &diagnostic.message,
            };
            MentorMessage {
                severity: entry.severity,
                plain_english: fill(entry.plain_english, &ctx),
                technical_detail: diagnostic.message.clone(),
                suggested_action: diagnostic
                    .remediation
                    .clone()
                    .unwrap_or_else(|| fill(entry.action, &ctx)),
            }
        }
        None => MentorMessage {
            severity: Severity::Warning,
            plain_english: "Something in your setup needs attention, but this tool doesn't have a ready-made explanation for it yet. The technical detail below is the exact clue to search for.".to_string(),
            technical_detail: diagnostic.message.clone(),
            suggested_action: diagnostic.remediation.clone().unwrap_or_else(|| {
                "Search the web for the exact error text above, then retry.".to_string()
            }),
        },
    }
}

// ---------------------------------------------------------------------------
// Legacy error-code helpers
// ---------------------------------------------------------------------------

// Kept for backwards compatibility with earlier versions of the module.

pub fn translate_issue(code: &str) -> String {
    match code {
        "E001" => format!(
            "{}: Node.js is not installed. Visit https://nodejs.org",
            "E001".red().bold()
        ),
        "E002" => format!(
            "{}: Rust toolchain not found. Install via https://rustup.rs",
            "E002".red().bold()
        ),
        "E003" => format!(
            "{}: Python is not installed or not in PATH",
            "E003".red().bold()
        ),
        "E004" => format!(
            "{}: Git is not installed. Visit https://git-scm.com",
            "E004".red().bold()
        ),
        "E005" => format!(
            "{}: Go is not installed. Visit https://go.dev",
            "E005".red().bold()
        ),
        _ => format!("{}: Unknown error code", code.red().bold()),
    }
}

pub fn explain_error(code: &str) -> &str {
    match code {
        "E001" => "Node.js is required for JavaScript/TypeScript development.",
        "E002" => "Rust toolchain is required for building Rust projects.",
        "E003" => "Python is required for Python development and many build tools.",
        "E004" => "Git is required for version control and package management.",
        "E005" => "Go is required for Go development.",
        _ => "No further information available.",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::CheckStatus;

    fn err(check_name: &str, message: &str) -> DiagnosticResult {
        DiagnosticResult::new(check_name, CheckStatus::Fail, message)
    }

    // --- Database coverage ---------------------------------------------------

    #[test]
    fn database_meets_coverage_targets() {
        let count = |c: Category| translations_for(c).count();
        assert!(
            count(Category::Node) >= 30,
            "Node entries: {}",
            count(Category::Node)
        );
        assert!(
            count(Category::Python) >= 15,
            "Python entries: {}",
            count(Category::Python)
        );
        assert!(
            count(Category::Rust) >= 15,
            "Rust entries: {}",
            count(Category::Rust)
        );
        assert!(
            count(Category::PortSystem) >= 10,
            "System entries: {}",
            count(Category::PortSystem)
        );
        assert!(
            TRANSLATIONS.len() >= 50,
            "total entries: {}",
            TRANSLATIONS.len()
        );
    }

    #[test]
    fn every_entry_is_complete() {
        for entry in TRANSLATIONS {
            assert!(
                !entry.needles.is_empty(),
                "empty needles: {}",
                entry.plain_english
            );
            assert!(!entry.plain_english.is_empty());
            assert!(!entry.action.is_empty());
            for needle in entry.needles {
                assert!(!needle.is_empty());
            }
        }
    }

    // --- Headline translations ----------------------------------------------

    #[test]
    fn translates_require_esm() {
        let mentor = translate_error(&err("Startup", "ERR_REQUIRE_ESM: jwt package"));
        assert_eq!(mentor.severity, Severity::Critical);
        assert!(mentor.plain_english.contains("CommonJS"));
        assert!(
            mentor.suggested_action.contains("module") || mentor.suggested_action.contains(".mjs")
        );
    }

    #[test]
    fn translates_module_not_found_with_package_name() {
        let mentor = translate_error(&err(
            "Import",
            "ModuleNotFoundError: No module named 'requests'",
        ));
        assert!(mentor.plain_english.contains("requests"));
        assert!(mentor.suggested_action.contains("pip install requests"));
    }

    #[test]
    fn translates_eaddrinuse_with_port_and_pid_hint() {
        let mentor = translate_error(&err(
            "Server",
            "Error: listen EADDRINUSE: address already in use :::3000",
        ));
        assert_eq!(mentor.severity, Severity::Warning);
        assert!(mentor.plain_english.contains("3000"));
        assert!(mentor.technical_detail.contains("EADDRINUSE"));
        assert!(mentor.suggested_action.contains("lsof -i :3000"));
    }

    #[test]
    fn translates_port_occupied_from_our_diagnostics() {
        let mentor = translate_error(&err(
            "Port 5432",
            "Port 5432 is occupied by PID 6880 (postgres)",
        ));
        assert!(mentor.plain_english.contains("5432"));
        assert!(mentor.plain_english.contains("6880"));
        assert!(mentor.suggested_action.contains("6880"));
    }

    #[test]
    fn translates_rust_linker_error_with_library() {
        let mentor = translate_error(&err(
            "Build",
            "cannot find -lfoo: No such file or directory",
        ));
        assert!(mentor.plain_english.contains("foo"));
        assert!(mentor.suggested_action.contains("libfoo-dev"));
    }

    #[test]
    fn reuses_diagnostic_remediation_when_present() {
        let mut diagnostic = err("Tool node", "node was not found on PATH");
        diagnostic.set_remediation("Install node via nvm");
        let mentor = translate_error(&diagnostic);
        assert_eq!(mentor.suggested_action, "Install node via nvm");
        assert!(mentor.plain_english.contains("node"));
    }

    #[test]
    fn technical_detail_keeps_raw_error() {
        let mentor = translate_error(&err("Bundler", "SyntaxError: Unexpected token '}'"));
        assert_eq!(mentor.technical_detail, "SyntaxError: Unexpected token '}'");
    }

    // --- Fallbacks and guards ------------------------------------------------

    #[test]
    fn unknown_error_falls_back_gracefully() {
        let mentor = translate_error(&err(
            "Mystery",
            "Quadretic binary transform failed on sector 7",
        ));
        assert_eq!(mentor.severity, Severity::Warning);
        assert!(mentor.plain_english.contains("ready-made explanation"));
        assert_eq!(
            mentor.technical_detail,
            "Quadretic binary transform failed on sector 7"
        );
    }

    #[test]
    fn passing_diagnostic_is_informational() {
        let mentor = translate_error(&DiagnosticResult::new(
            "Runtime Check",
            CheckStatus::Pass,
            "Node v22.9.0 meets the minimum requirement",
        ));
        assert_eq!(mentor.severity, Severity::Info);
        assert!(mentor.suggested_action.contains("No action"));
    }

    #[test]
    fn placeholder_extraction_is_precise() {
        let ctx = MatchContext {
            check_name: "Port 8080",
            message: "Port 8080 is occupied by PID 12345 (node)",
        };
        assert_eq!(ctx.port().as_deref(), Some("8080"));
        assert_eq!(ctx.pid().as_deref(), Some("12345"));

        let raw = MatchContext {
            check_name: "",
            message: "EADDRINUSE: address already in use :::3000",
        };
        assert_eq!(raw.port().as_deref(), Some("3000"));
        assert_eq!(raw.pid(), None);

        let quoted = MatchContext {
            check_name: "",
            message: "No module named 'requests'",
        };
        assert_eq!(quoted.quoted().as_deref(), Some("requests"));

        let lib = MatchContext {
            check_name: "",
            message: "cannot find -lssl",
        };
        assert_eq!(lib.lib().as_deref(), Some("ssl"));
    }

    // --- Named coverage tests ----------------------------------------------

    #[test]
    fn test_error_translation_node_errors() {
        let mentor = translate_error(&err(
            "Runtime Check",
            "Error: Cannot find module 'express'",
        ));
        assert_eq!(mentor.severity, Severity::Critical);
        assert!(mentor.plain_english.contains("express"));
        assert!(mentor.suggested_action.contains("npm install"));
        assert!(mentor.technical_detail.contains("Cannot find module"));
    }

    #[test]
    fn test_error_translation_python_errors() {
        let mentor = translate_error(&err(
            "Tools Check",
            "ModuleNotFoundError: No module named 'requests'",
        ));
        assert_eq!(mentor.severity, Severity::Critical);
        assert!(mentor.plain_english.contains("requests"));
        assert!(mentor.suggested_action.contains("pip install requests"));
    }

    #[test]
    fn test_error_translation_port_errors() {
        let mentor = translate_error(&err(
            "Server",
            "listen EADDRINUSE: address already in use :::3000",
        ));
        assert_eq!(mentor.severity, Severity::Warning);
        assert!(mentor.plain_english.contains("3000"));
        assert!(mentor.technical_detail.contains("EADDRINUSE"));
        assert!(mentor.suggested_action.contains("lsof -i :3000"));
    }
}