1use colored::Colorize;
33
34use crate::models::{CheckStatus, DiagnosticResult, MentorMessage, Severity};
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Category {
43 Node,
45 Python,
47 Rust,
49 PortSystem,
51}
52
53impl Category {
54 pub fn label(&self) -> &'static str {
56 match self {
57 Category::Node => "Node.js",
58 Category::Python => "Python",
59 Category::Rust => "Rust",
60 Category::PortSystem => "Port/System",
61 }
62 }
63}
64
65pub struct TranslationEntry {
71 pub category: Category,
73 pub needles: &'static [&'static str],
76 pub severity: Severity,
78 pub plain_english: &'static str,
80 pub action: &'static str,
82}
83
84impl TranslationEntry {
85 pub fn matches(&self, haystack: &str) -> bool {
87 self.needles.iter().any(|needle| haystack.contains(needle))
88 }
89}
90
91pub const TRANSLATIONS: &[TranslationEntry] = &[
94 TranslationEntry {
98 category: Category::Node,
99 needles: &["err_require_esm"],
100 severity: Severity::Critical,
101 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.",
102 action: "Rename .js files to .mjs, or add \"type\": \"module\" to package.json",
103 },
104 TranslationEntry {
105 category: Category::Node,
106 needles: &["cannot find module", "err_module_not_found"],
107 severity: Severity::Critical,
108 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\".",
109 action: "Check the import path, then run: npm install",
110 },
111 TranslationEntry {
112 category: Category::Node,
113 needles: &["cannot find package"],
114 severity: Severity::Critical,
115 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.",
116 action: "Run: npm install, then verify the name/version in package.json",
117 },
118 TranslationEntry {
119 category: Category::Node,
120 needles: &["erresolve", "peer dep missing", "peer dependency"],
121 severity: Severity::Warning,
122 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.",
123 action: "Run: npm install --legacy-peer-deps, or align the versions manually",
124 },
125 TranslationEntry {
126 category: Category::Node,
127 needles: &["elflcic", "lifecycle"],
128 severity: Severity::Critical,
129 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.",
130 action: "Read the last lines of the log above this message and fix that script",
131 },
132 TranslationEntry {
133 category: Category::Node,
134 needles: &["missing script"],
135 severity: Severity::Critical,
136 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.",
137 action: "Check the scripts section of package.json, or run it directly (e.g. node src/index.js)",
138 },
139 TranslationEntry {
140 category: Category::Node,
141 needles: &["enoent"],
142 severity: Severity::Critical,
143 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.",
144 action: "Delete node_modules and run: npm install (or npm ci)",
145 },
146 TranslationEntry {
147 category: Category::Node,
148 needles: &["eexist", "file exists"],
149 severity: Severity::Warning,
150 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.",
151 action: "Remove the conflicting file or folder, then retry",
152 },
153 TranslationEntry {
154 category: Category::Node,
155 needles: &["eacces", "eperm"],
156 severity: Severity::Critical,
157 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.",
158 action: "Fix folder permissions (chown/chmod), or reinstall without a sandbox; avoid running as admin where possible",
159 },
160 TranslationEntry {
161 category: Category::Node,
162 needles: &["err_dlopen_failed"],
163 severity: Severity::Critical,
164 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.",
165 action: "Rebuild native modules: npm rebuild, or reinstall the package",
166 },
167 TranslationEntry {
168 category: Category::Node,
169 needles: &["headers already sent"],
170 severity: Severity::Warning,
171 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.",
172 action: "Return from the request handler after sending a response (avoid double res.send/res.json)",
173 },
174 TranslationEntry {
175 category: Category::Node,
176 needles: &["cannot read properties of undefined", "cannot read property"],
177 severity: Severity::Critical,
178 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.",
179 action: "Add a null check or a fallback default before reading the property",
180 },
181 TranslationEntry {
182 category: Category::Node,
183 needles: &["is not a function", "is not callable"],
184 severity: Severity::Critical,
185 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.",
186 action: "Print/inspect the value before calling it; check for a missing or renamed import",
187 },
188 TranslationEntry {
189 category: Category::Node,
190 needles: &["is not defined"],
191 severity: Severity::Critical,
192 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.",
193 action: "Define the variable or import it at the top of the file",
194 },
195 TranslationEntry {
196 category: Category::Node,
197 needles: &["unexpected identifier", "unexpected token", "unexpected string"],
198 severity: Severity::Critical,
199 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.",
200 action: "Look at the line and column in the error and check brackets, commas and quotes nearby",
201 },
202 TranslationEntry {
203 category: Category::Node,
204 needles: &["maximum call stack size exceeded"],
205 severity: Severity::Warning,
206 plain_english: "Your functions are calling each other without ever stopping — a loop of infinite phone calls. Usually recursion without a base case.",
207 action: "Find the recursive call and give it a stopping condition",
208 },
209 TranslationEntry {
210 category: Category::Node,
211 needles: &["heap out of memory", "javascript heap"],
212 severity: Severity::Critical,
213 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.",
214 action: "Check for unbounded loops/accumulation, or raise the limit: node --max-old-space-size=4096",
215 },
216 TranslationEntry {
217 category: Category::Node,
218 needles: &["unhandledpromiserejection", "unhandled promise rejection"],
219 severity: Severity::Critical,
220 plain_english: "An async operation failed and nobody was there to catch it, like dropping a plate nobody was standing next to.",
221 action: "Wrap the promise in try/catch (or .catch()) or add a process.on('unhandledRejection') handler",
222 },
223 TranslationEntry {
224 category: Category::Node,
225 needles: &["cannot be resolved", "not resolve", "failed to resolve", "no matching files", "matching entry for"],
226 severity: Severity::Critical,
227 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.",
228 action: "Fix the import path or file extension (check ./index paths), then restart the dev server",
229 },
230 TranslationEntry {
231 category: Category::Node,
232 needles: &["err_invalid_arg_type", "invalid argument"],
233 severity: Severity::Critical,
234 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.",
235 action: "Check the function call: every argument must be the documented type (string, number, buffer...)",
236 },
237 TranslationEntry {
238 category: Category::Node,
239 needles: &["err_stream_write_after_end", "write after end"],
240 severity: Severity::Warning,
241 plain_english: "Your code wrote to a stream that was already closed — like trying to push water through a shut-off pipe.",
242 action: "Stop writing to the stream after calling .end(); check the lifecycle of the response/socket",
243 },
244 TranslationEntry {
245 category: Category::Node,
246 needles: &["'emitted', 'error' event", "unhandled 'error' event"],
247 severity: Severity::Critical,
248 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.",
249 action: "Attach an .on('error', ...) handler right where the emitter is created",
250 },
251 TranslationEntry {
252 category: Category::Node,
253 needles: &["err_socket_timeout", "socket hang up"],
254 severity: Severity::Warning,
255 plain_english: "A network connection stopped mid-conversation. The other side just hung up — maybe a timeout, a crash, or a firewall.",
256 action: "Retry with a longer timeout, check the service is running, and look for proxy/firewall interference",
257 },
258 TranslationEntry {
259 category: Category::Node,
260 needles: &["econnrefused"],
261 severity: Severity::Critical,
262 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.",
263 action: "Start the service first, then check the host/port in your connection settings",
264 },
265 TranslationEntry {
266 category: Category::Node,
267 needles: &["etimedout", "operation timed out"],
268 severity: Severity::Warning,
269 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.",
270 action: "Increase the timeout or retry; check network and registry (npm config get registry)",
271 },
272 TranslationEntry {
273 category: Category::Node,
274 needles: &["getaddrinfo enotfound", "connect enotfound", "enotfound -2"],
275 severity: Severity::Critical,
276 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.",
277 action: "Check the URL spelling, then `nslookup <host>`; if it fails, fix DNS/VPN connectivity",
278 },
279 TranslationEntry {
280 category: Category::Node,
281 needles: &["connection reset by peer", "connection reset"],
282 severity: Severity::Warning,
283 plain_english: "The remote server dropped a connection that was already in progress, like a call cut off mid-sentence.",
284 action: "Retry the request; check the server logs and any load balancer/firewall timeouts",
285 },
286 TranslationEntry {
287 category: Category::Node,
288 needles: &["epipe", "broken pipe"],
289 severity: Severity::Warning,
290 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`.",
291 action: "That's usually harmless; suppress it or handle EPIPE in your script (process.stdout.on('error'))",
292 },
293 TranslationEntry {
294 category: Category::Node,
295 needles: &["cannot read properties of null"],
296 severity: Severity::Critical,
297 plain_english: "Your code reached into a value that is literally nothing (null), like pressing floor buttons in an elevator that isn't there.",
298 action: "Guard the value (if (x && x.y)) or use optional chaining x?.y before reading deeper",
299 },
300 TranslationEntry {
301 category: Category::Node,
302 needles: &["'await' is only allowed", "top-level await"],
303 severity: Severity::Warning,
304 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.",
305 action: "Add \"type\": \"module\" to package.json, or wrap the code in an async function",
306 },
307 TranslationEntry {
308 category: Category::Node,
309 needles: &["npm err", "npm error"],
310 severity: Severity::Warning,
311 plain_english: "npm reported a problem with the installation or script step. The message directly above is the real clue.",
312 action: "Read the last npm error line; run npm install --verbose to see more",
313 },
314 TranslationEntry {
315 category: Category::Node,
316 needles: &["invalid regexp flag"],
317 severity: Severity::Critical,
318 plain_english: "A regular expression was given a flag JavaScript doesn't know — like a bookmark with a page number that doesn't exist.",
319 action: "Remove or correct the flag after the closing slash of the regex",
320 },
321
322 TranslationEntry {
326 category: Category::Python,
327 needles: &["modulenotfounderror", "no module named"],
328 severity: Severity::Critical,
329 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.",
330 action: "Run: pip install {module}",
331 },
332 TranslationEntry {
333 category: Category::Python,
334 needles: &["importerror", "cannot import name"],
335 severity: Severity::Critical,
336 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.",
337 action: "Check the spelling and the module docs; run `python -c \"import {module}\"` to see what exists",
338 },
339 TranslationEntry {
340 category: Category::Python,
341 needles: &["syntaxerror: invalid syntax", "invalid syntax"],
342 severity: Severity::Critical,
343 plain_english: "Python hit a line it couldn't parse — a missing colon, bracket, or mismatched quote earlier. Grammar error, not a logic error.",
344 action: "Look at the line/column in the traceback and fix missing colons, brackets, or parentheses",
345 },
346 TranslationEntry {
347 category: Category::Python,
348 needles: &["indentationerror", "unexpected indent", "unindent"],
349 severity: Severity::Critical,
350 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.",
351 action: "Make all lines in a block line up exactly (4 spaces is conventional); check for mixed tabs and spaces",
352 },
353 TranslationEntry {
354 category: Category::Python,
355 needles: &["nameerror", "is not defined"],
356 severity: Severity::Critical,
357 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.",
358 action: "Check the spelling and ensure the variable/function is defined before that line runs",
359 },
360 TranslationEntry {
361 category: Category::Python,
362 needles: &["typeerror", "object is not callable", "not iterable", "not subscriptable"],
363 severity: Severity::Critical,
364 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.",
365 action: "Check the value's type (print(type(x))) and adjust the operation or the data",
366 },
367 TranslationEntry {
368 category: Category::Python,
369 needles: &["attributeerror", "has no attribute"],
370 severity: Severity::Critical,
371 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.",
372 action: "Check the spelling; list available attributes with dir(obj)",
373 },
374 TranslationEntry {
375 category: Category::Python,
376 needles: &["valueerror", "invalid literal for int"],
377 severity: Severity::Critical,
378 plain_english: "A value has the right type but the wrong content — like handing an envelope full of letters where a number was expected.",
379 action: "Inspect the value (print(it)) and validate/normalise it before converting",
380 },
381 TranslationEntry {
382 category: Category::Python,
383 needles: &["keyerror"],
384 severity: Severity::Critical,
385 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.",
386 action: "Use dict.get(key, default) or check the key with `in` before accessing",
387 },
388 TranslationEntry {
389 category: Category::Python,
390 needles: &["indexerror", "list index out of range"],
391 severity: Severity::Critical,
392 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.",
393 action: "Check the list length before indexing, or use .get()/slicing that can't overrun",
394 },
395 TranslationEntry {
396 category: Category::Python,
397 needles: &["filenotfounderror", "filenotfound"],
398 severity: Severity::Critical,
399 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.",
400 action: "Print/normalise the path (os.path.abspath), confirm the file exists where the script expects",
401 },
402 TranslationEntry {
403 category: Category::Python,
404 needles: &["permissionerror", "errno 13"],
405 severity: Severity::Critical,
406 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.",
407 action: "Fix file/folder permissions or move the file somewhere writable",
408 },
409 TranslationEntry {
410 category: Category::Python,
411 needles: &["externally-managed-environment", "externally managed environment"],
412 severity: Severity::Warning,
413 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.",
414 action: "Create and activate a virtual environment, then pip install inside it: python -m venv .venv && .venv\\Scripts\\activate",
415 },
416 TranslationEntry {
417 category: Category::Python,
418 needles: &["no matching distribution found", "could not find a version that satisfies"],
419 severity: Severity::Critical,
420 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.",
421 action: "Check the name/version spelling, then pip install --upgrade pip and retry",
422 },
423 TranslationEntry {
424 category: Category::Python,
425 needles: &["recursionerror", "maximum recursion depth exceeded"],
426 severity: Severity::Warning,
427 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.",
428 action: "Fix the recursion base case, or convert to an iterative loop",
429 },
430 TranslationEntry {
431 category: Category::Python,
432 needles: &["unboundlocalerror"],
433 severity: Severity::Critical,
434 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.",
435 action: "Move the assignment above its use, or make it global explicitly",
436 },
437 TranslationEntry {
438 category: Category::Python,
439 needles: &["assertionerror"],
440 severity: Severity::Warning,
441 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.",
442 action: "Look at the assertion's message and fix the condition or input that made it fail",
443 },
444 TranslationEntry {
445 category: Category::Python,
446 needles: &["cannot open shared object", "libssl.so"],
447 severity: Severity::Warning,
448 plain_english: "A compiled Python extension is missing a native library the operating system must provide, not just Python.",
449 action: "Install the binary package (e.g. apt install libssl-dev / python3-numpy) for your distribution",
450 },
451
452 TranslationEntry {
456 category: Category::Rust,
457 needles: &["cannot find value", "cannot find function", "cannot find constant"],
458 severity: Severity::Critical,
459 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.",
460 action: "Check the spelling and add the right `use` import at the top of the file",
461 },
462 TranslationEntry {
463 category: Category::Rust,
464 needles: &["could not find 'main' in crate", "main function not found", "no 'main' function"],
465 severity: Severity::Critical,
466 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.",
467 action: "Add `fn main() {}` (or `async fn main()` with #[tokio::main]) to a src file",
468 },
469 TranslationEntry {
470 category: Category::Rust,
471 needles: &["cannot find -l"],
472 severity: Severity::Critical,
473 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.",
474 action: "Install the system dev package for {lib} (Ubuntu: sudo apt-get install lib{lib}-dev; macOS: brew install {lib})",
475 },
476 TranslationEntry {
477 category: Category::Rust,
478 needles: &["mismatched types", "error[e0308]"],
479 severity: Severity::Critical,
480 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.",
481 action: "Look at the 'expected/found' part of the error and convert the value (e.g. .to_string(), as i32, or deref)",
482 },
483 TranslationEntry {
484 category: Category::Rust,
485 needles: &["does not live long enough", "error[e0597]", "error[e0592]"],
486 severity: Severity::Critical,
487 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.",
488 action: "Give the data a longer lifetime (clone it, or restructure so the owner outlives the reference)",
489 },
490 TranslationEntry {
491 category: Category::Rust,
492 needles: &["cannot move out of", "use of moved value", "moved value"],
493 severity: Severity::Critical,
494 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.",
495 action: "Borrow it with & (or &mut) instead of moving, or clone when you need it in two places",
496 },
497 TranslationEntry {
498 category: Category::Rust,
499 needles: &["trait bound", "trait `std::", "is not satisfied"],
500 severity: Severity::Critical,
501 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.",
502 action: "Check which trait is missing and add a derive (e.g. #[derive(Debug)]) or import the right trait",
503 },
504 TranslationEntry {
505 category: Category::Rust,
506 needles: &["no method named"],
507 severity: Severity::Critical,
508 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.",
509 action: "Verify the method name, or import the trait that provides it (e.g. `use std::io::prelude::*`)",
510 },
511 TranslationEntry {
512 category: Category::Rust,
513 needles: &["cannot borrow as immutable"],
514 severity: Severity::Critical,
515 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.",
516 action: "Re-order the code so reads finish before the write, or clone the data you need to read",
517 },
518 TranslationEntry {
519 category: Category::Rust,
520 needles: &["cannot borrow"],
521 severity: Severity::Critical,
522 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.",
523 action: "Separate the borrows in time or scope; use cloning when the conflict isn't really about the same data",
524 },
525 TranslationEntry {
526 category: Category::Rust,
527 needles: &["expected struct", "found struct", "expected enum", "found enum"],
528 severity: Severity::Critical,
529 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.",
530 action: "Match the error's expected type by reading the struct/enum docs, or derive From for a conversion",
531 },
532 TranslationEntry {
533 category: Category::Rust,
534 needles: &["the size for values of type", "cannot be known at compilation", "infinite size", "recursive type"],
535 severity: Severity::Critical,
536 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.",
537 action: "Put one level behind Box<T>, Rc<T> or Arc<T> to end the recursion (this is normal for linked lists/trees)",
538 },
539 TranslationEntry {
540 category: Category::Rust,
541 needles: &["linker `link.exe` not found", "linker not found", "link.exe"],
542 severity: Severity::Critical,
543 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.",
544 action: "Install a C linker (Windows: MSVC Build Tools or mingw-w64; Ubuntu: sudo apt-get install build-essential)",
545 },
546 TranslationEntry {
547 category: Category::Rust,
548 needles: &["could not compile", "due to previous error"],
549 severity: Severity::Warning,
550 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.",
551 action: "Scroll to the FIRST error in the output; fix that one, then rebuild",
552 },
553 TranslationEntry {
554 category: Category::Rust,
555 needles: &["failed to run custom build command"],
556 severity: Severity::Critical,
557 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.",
558 action: "Read the child process output; install the missing system library/tool the crate documents (e.g. protoc, openssl-dev)",
559 },
560 TranslationEntry {
561 category: Category::Rust,
562 needles: &["could not parse manifest", "toml parse error", "invalid toml", "expected a table key"],
563 severity: Severity::Critical,
564 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.",
565 action: "Fix the TOML syntax on the reported line (quotes around strings, no stray commas)",
566 },
567 TranslationEntry {
568 category: Category::Rust,
569 needles: &["the trait `display` is not implemented", "trait `fmt::debug`"],
570 severity: Severity::Warning,
571 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.",
572 action: "Add #[derive(Debug)] or #[derive(Display)] to the type, or use {:?} with Debug",
573 },
574 TranslationEntry {
575 category: Category::Rust,
576 needles: &["cannot infer type", "type annotations needed"],
577 severity: Severity::Warning,
578 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.",
579 action: "Add an explicit type annotation (let x: Vec<String> = ...) or annotate the variable",
580 },
581 TranslationEntry {
582 category: Category::Rust,
583 needles: &["error[e0382]", "error[e0505]"],
584 severity: Severity::Critical,
585 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.",
586 action: "Borrow (&x) instead of moving, or clone the value when you need it again later",
587 },
588
589 TranslationEntry {
593 category: Category::PortSystem,
594 needles: &["eaddrinuse", "address already in use"],
595 severity: Severity::Warning,
596 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.",
597 action: "Find and stop the process holding it, then retry: kill -9 {pid} (or `lsof -i :{port}` to discover it)",
598 },
599 TranslationEntry {
600 category: Category::PortSystem,
601 needles: &["occupied by pid"],
602 severity: Severity::Warning,
603 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.",
604 action: "Stop that process (kill -9 {pid}), or configure your app to use a different port",
605 },
606 TranslationEntry {
607 category: Category::PortSystem,
608 needles: &["cannot connect to the docker daemon", "docker daemon is not running", "is the docker daemon running"],
609 severity: Severity::Critical,
610 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.",
611 action: "Start the Docker Desktop / docker service (systemctl start docker on Linux), then retry",
612 },
613 TranslationEntry {
614 category: Category::PortSystem,
615 needles: &[
616 "command not found",
617 "not recognized as the name",
618 "was not found on path",
619 ],
620 severity: Severity::Critical,
621 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.",
622 action: "Install {tool} and add its folder to PATH, then open a fresh terminal",
623 },
624 TranslationEntry {
625 category: Category::PortSystem,
626 needles: &["not a git repository", "not a git repo"],
627 severity: Severity::Warning,
628 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.",
629 action: "Run `git init` here, or cd into the right project folder",
630 },
631 TranslationEntry {
632 category: Category::PortSystem,
633 needles: &["permission denied", "operation not permitted"],
634 severity: Severity::Critical,
635 plain_english: "The system refused an action because it requires more privileges than you have — the bouncer said you're not on the list.",
636 action: "Run the command with elevated privileges if appropriate (sudo / admin), or fix file permissions",
637 },
638 TranslationEntry {
639 category: Category::PortSystem,
640 needles: &["no such file or directory", "cannot stat", "can't open file"],
641 severity: Severity::Critical,
642 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.",
643 action: "Double-check the path (case matters!). Use ls / Get-ChildItem to confirm it exists",
644 },
645 TranslationEntry {
646 category: Category::PortSystem,
647 needles: &["connection refused", "ecould not connect", "bind: address already in use"],
648 severity: Severity::Critical,
649 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.",
650 action: "Start the service and confirm it listens on the expected host/port (lsof -i / netstat -ano)",
651 },
652 TranslationEntry {
653 category: Category::PortSystem,
654 needles: &["dns", "hostname not found", "unknown host"],
655 severity: Severity::Critical,
656 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.",
657 action: "Check spelling, DNS settings and VPN; try `nslookup <host>` to test resolution",
658 },
659 TranslationEntry {
660 category: Category::PortSystem,
661 needles: &["point to folders that do not exist", "broken path entries", "not exist on path"],
662 severity: Severity::Warning,
663 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.",
664 action: "Edit your PATH to remove (or fix) the entries listed in the check report",
665 },
666 TranslationEntry {
667 category: Category::PortSystem,
668 needles: &["listed more than once", "duplicate path", "listed twice"],
669 severity: Severity::Warning,
670 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.",
671 action: "Remove the duplicated PATH entries in your shell profile",
672 },
673 TranslationEntry {
674 category: Category::PortSystem,
675 needles: &["editor/visual is not set", "no default editor"],
676 severity: Severity::Warning,
677 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.",
678 action: "Set EDITOR in your profile, e.g. export EDITOR=\"code --wait\" (or vim / notepad).",
679 },
680 TranslationEntry {
681 category: Category::PortSystem,
682 needles: &["externally-managed"],
683 severity: Severity::Warning,
684 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.",
685 action: "Use a virtual environment: python -m venv .venv and activate it before installing packages",
686 },
687];
688
689pub fn translations_for(category: Category) -> impl Iterator<Item = &'static TranslationEntry> {
691 TRANSLATIONS.iter().filter(move |e| e.category == category)
692}
693
694struct MatchContext<'d> {
700 check_name: &'d str,
701 message: &'d str,
702}
703
704impl<'d> MatchContext<'d> {
705 fn port(&self) -> Option<String> {
708 if let Some(rest) = self.check_name.strip_prefix("Port ") {
709 let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
710 if !digits.is_empty() {
711 return Some(digits);
712 }
713 }
714 Self::first_number(self.message)
715 }
716
717 fn pid(&self) -> Option<String> {
719 let port = self.port();
720 Self::numbers(self.message)
721 .into_iter()
722 .find(|n| Some(n.as_str()) != port.as_deref())
723 }
724
725 fn quoted(&self) -> Option<String> {
727 let bytes = self.message.as_bytes();
728 for (i, &b) in bytes.iter().enumerate() {
729 if b == b'\'' || b == b'"' {
730 let mut out = String::new();
731 for &next in &bytes[i + 1..] {
732 if next == b {
733 return if out.is_empty() { None } else { Some(out) };
734 }
735 out.push(next as char);
736 }
737 }
738 }
739 None
740 }
741
742 fn tool(&self) -> Option<String> {
745 if let Some(rest) = self.check_name.strip_prefix("Tool ") {
746 let name = rest.split_whitespace().next().unwrap_or("");
747 if !name.is_empty() {
748 return Some(name.to_string());
749 }
750 }
751 self.message
752 .split_whitespace()
753 .next()
754 .map(|w| w.to_string())
755 }
756
757 fn lib(&self) -> Option<String> {
759 let lower = self.message.to_ascii_lowercase();
760 let idx = lower.find("-l")?;
761 let rest = &self.message[idx + 2..];
762 let name: String = rest
763 .chars()
764 .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
765 .collect();
766 if name.is_empty() {
767 None
768 } else {
769 Some(name)
770 }
771 }
772
773 fn first_number(text: &str) -> Option<String> {
774 Self::numbers(text).into_iter().next()
775 }
776
777 fn numbers(text: &str) -> Vec<String> {
778 let mut out = Vec::new();
779 let mut current = String::new();
780 for ch in text.chars() {
781 if ch.is_ascii_digit() {
782 current.push(ch);
783 } else if !current.is_empty() {
784 out.push(std::mem::take(&mut current));
785 }
786 }
787 if !current.is_empty() {
788 out.push(current);
789 }
790 out
791 }
792}
793
794fn fill(template: &str, ctx: &MatchContext<'_>) -> String {
797 let port = ctx.port().unwrap_or_else(|| "(unknown port)".to_string());
798 let pid = ctx
799 .pid()
800 .unwrap_or_else(|| format!("(unknown — run `lsof -i :{port}` to find it)"));
801 let module = ctx.quoted().unwrap_or_else(|| "(the module)".to_string());
802 let pkg = ctx.quoted().unwrap_or_else(|| "(the package)".to_string());
803 let tool = ctx.tool().unwrap_or_else(|| "(the tool)".to_string());
804 let lib = ctx.lib().unwrap_or_else(|| "(the library)".to_string());
805
806 let replacements: &[(&str, String)] = &[
807 ("{port}", port),
808 ("{pid}", pid),
809 ("{module}", module),
810 ("{pkg}", pkg),
811 ("{tool}", tool),
812 ("{lib}", lib),
813 ];
814
815 let mut out = template.to_string();
816 for (key, value) in replacements {
817 out = out.replace(key, value);
818 }
819 out
820}
821
822pub fn translate_error(diagnostic: &DiagnosticResult) -> MentorMessage {
838 if diagnostic.status == CheckStatus::Pass {
839 return MentorMessage {
840 severity: Severity::Info,
841 plain_english: "This check passed — nothing to fix.".to_string(),
842 technical_detail: diagnostic.message.clone(),
843 suggested_action: "No action needed.".to_string(),
844 };
845 }
846
847 let haystack = format!("{} {}", diagnostic.check_name, diagnostic.message).to_lowercase();
848
849 let entry = TRANSLATIONS.iter().find(|e| e.matches(&haystack));
850
851 match entry {
852 Some(entry) => {
853 let ctx = MatchContext {
854 check_name: &diagnostic.check_name,
855 message: &diagnostic.message,
856 };
857 MentorMessage {
858 severity: entry.severity,
859 plain_english: fill(entry.plain_english, &ctx),
860 technical_detail: diagnostic.message.clone(),
861 suggested_action: diagnostic
862 .remediation
863 .clone()
864 .unwrap_or_else(|| fill(entry.action, &ctx)),
865 }
866 }
867 None => MentorMessage {
868 severity: Severity::Warning,
869 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(),
870 technical_detail: diagnostic.message.clone(),
871 suggested_action: diagnostic.remediation.clone().unwrap_or_else(|| {
872 "Search the web for the exact error text above, then retry.".to_string()
873 }),
874 },
875 }
876}
877
878pub fn translate_issue(code: &str) -> String {
885 match code {
886 "E001" => format!(
887 "{}: Node.js is not installed. Visit https://nodejs.org",
888 "E001".red().bold()
889 ),
890 "E002" => format!(
891 "{}: Rust toolchain not found. Install via https://rustup.rs",
892 "E002".red().bold()
893 ),
894 "E003" => format!(
895 "{}: Python is not installed or not in PATH",
896 "E003".red().bold()
897 ),
898 "E004" => format!(
899 "{}: Git is not installed. Visit https://git-scm.com",
900 "E004".red().bold()
901 ),
902 "E005" => format!(
903 "{}: Go is not installed. Visit https://go.dev",
904 "E005".red().bold()
905 ),
906 _ => format!("{}: Unknown error code", code.red().bold()),
907 }
908}
909
910pub fn explain_error(code: &str) -> &str {
911 match code {
912 "E001" => "Node.js is required for JavaScript/TypeScript development.",
913 "E002" => "Rust toolchain is required for building Rust projects.",
914 "E003" => "Python is required for Python development and many build tools.",
915 "E004" => "Git is required for version control and package management.",
916 "E005" => "Go is required for Go development.",
917 _ => "No further information available.",
918 }
919}
920
921#[cfg(test)]
922mod tests {
923 use super::*;
924 use crate::models::CheckStatus;
925
926 fn err(check_name: &str, message: &str) -> DiagnosticResult {
927 DiagnosticResult::new(check_name, CheckStatus::Fail, message)
928 }
929
930 #[test]
933 fn database_meets_coverage_targets() {
934 let count = |c: Category| translations_for(c).count();
935 assert!(
936 count(Category::Node) >= 30,
937 "Node entries: {}",
938 count(Category::Node)
939 );
940 assert!(
941 count(Category::Python) >= 15,
942 "Python entries: {}",
943 count(Category::Python)
944 );
945 assert!(
946 count(Category::Rust) >= 15,
947 "Rust entries: {}",
948 count(Category::Rust)
949 );
950 assert!(
951 count(Category::PortSystem) >= 10,
952 "System entries: {}",
953 count(Category::PortSystem)
954 );
955 assert!(
956 TRANSLATIONS.len() >= 50,
957 "total entries: {}",
958 TRANSLATIONS.len()
959 );
960 }
961
962 #[test]
963 fn every_entry_is_complete() {
964 for entry in TRANSLATIONS {
965 assert!(
966 !entry.needles.is_empty(),
967 "empty needles: {}",
968 entry.plain_english
969 );
970 assert!(!entry.plain_english.is_empty());
971 assert!(!entry.action.is_empty());
972 for needle in entry.needles {
973 assert!(!needle.is_empty());
974 }
975 }
976 }
977
978 #[test]
981 fn translates_require_esm() {
982 let mentor = translate_error(&err("Startup", "ERR_REQUIRE_ESM: jwt package"));
983 assert_eq!(mentor.severity, Severity::Critical);
984 assert!(mentor.plain_english.contains("CommonJS"));
985 assert!(
986 mentor.suggested_action.contains("module") || mentor.suggested_action.contains(".mjs")
987 );
988 }
989
990 #[test]
991 fn translates_module_not_found_with_package_name() {
992 let mentor = translate_error(&err(
993 "Import",
994 "ModuleNotFoundError: No module named 'requests'",
995 ));
996 assert!(mentor.plain_english.contains("requests"));
997 assert!(mentor.suggested_action.contains("pip install requests"));
998 }
999
1000 #[test]
1001 fn translates_eaddrinuse_with_port_and_pid_hint() {
1002 let mentor = translate_error(&err(
1003 "Server",
1004 "Error: listen EADDRINUSE: address already in use :::3000",
1005 ));
1006 assert_eq!(mentor.severity, Severity::Warning);
1007 assert!(mentor.plain_english.contains("3000"));
1008 assert!(mentor.technical_detail.contains("EADDRINUSE"));
1009 assert!(mentor.suggested_action.contains("lsof -i :3000"));
1010 }
1011
1012 #[test]
1013 fn translates_port_occupied_from_our_diagnostics() {
1014 let mentor = translate_error(&err(
1015 "Port 5432",
1016 "Port 5432 is occupied by PID 6880 (postgres)",
1017 ));
1018 assert!(mentor.plain_english.contains("5432"));
1019 assert!(mentor.plain_english.contains("6880"));
1020 assert!(mentor.suggested_action.contains("6880"));
1021 }
1022
1023 #[test]
1024 fn translates_rust_linker_error_with_library() {
1025 let mentor = translate_error(&err(
1026 "Build",
1027 "cannot find -lfoo: No such file or directory",
1028 ));
1029 assert!(mentor.plain_english.contains("foo"));
1030 assert!(mentor.suggested_action.contains("libfoo-dev"));
1031 }
1032
1033 #[test]
1034 fn reuses_diagnostic_remediation_when_present() {
1035 let mut diagnostic = err("Tool node", "node was not found on PATH");
1036 diagnostic.set_remediation("Install node via nvm");
1037 let mentor = translate_error(&diagnostic);
1038 assert_eq!(mentor.suggested_action, "Install node via nvm");
1039 assert!(mentor.plain_english.contains("node"));
1040 }
1041
1042 #[test]
1043 fn technical_detail_keeps_raw_error() {
1044 let mentor = translate_error(&err("Bundler", "SyntaxError: Unexpected token '}'"));
1045 assert_eq!(mentor.technical_detail, "SyntaxError: Unexpected token '}'");
1046 }
1047
1048 #[test]
1051 fn unknown_error_falls_back_gracefully() {
1052 let mentor = translate_error(&err(
1053 "Mystery",
1054 "Quadretic binary transform failed on sector 7",
1055 ));
1056 assert_eq!(mentor.severity, Severity::Warning);
1057 assert!(mentor.plain_english.contains("ready-made explanation"));
1058 assert_eq!(
1059 mentor.technical_detail,
1060 "Quadretic binary transform failed on sector 7"
1061 );
1062 }
1063
1064 #[test]
1065 fn passing_diagnostic_is_informational() {
1066 let mentor = translate_error(&DiagnosticResult::new(
1067 "Runtime Check",
1068 CheckStatus::Pass,
1069 "Node v22.9.0 meets the minimum requirement",
1070 ));
1071 assert_eq!(mentor.severity, Severity::Info);
1072 assert!(mentor.suggested_action.contains("No action"));
1073 }
1074
1075 #[test]
1076 fn placeholder_extraction_is_precise() {
1077 let ctx = MatchContext {
1078 check_name: "Port 8080",
1079 message: "Port 8080 is occupied by PID 12345 (node)",
1080 };
1081 assert_eq!(ctx.port().as_deref(), Some("8080"));
1082 assert_eq!(ctx.pid().as_deref(), Some("12345"));
1083
1084 let raw = MatchContext {
1085 check_name: "",
1086 message: "EADDRINUSE: address already in use :::3000",
1087 };
1088 assert_eq!(raw.port().as_deref(), Some("3000"));
1089 assert_eq!(raw.pid(), None);
1090
1091 let quoted = MatchContext {
1092 check_name: "",
1093 message: "No module named 'requests'",
1094 };
1095 assert_eq!(quoted.quoted().as_deref(), Some("requests"));
1096
1097 let lib = MatchContext {
1098 check_name: "",
1099 message: "cannot find -lssl",
1100 };
1101 assert_eq!(lib.lib().as_deref(), Some("ssl"));
1102 }
1103
1104 #[test]
1107 fn test_error_translation_node_errors() {
1108 let mentor = translate_error(&err(
1109 "Runtime Check",
1110 "Error: Cannot find module 'express'",
1111 ));
1112 assert_eq!(mentor.severity, Severity::Critical);
1113 assert!(mentor.plain_english.contains("express"));
1114 assert!(mentor.suggested_action.contains("npm install"));
1115 assert!(mentor.technical_detail.contains("Cannot find module"));
1116 }
1117
1118 #[test]
1119 fn test_error_translation_python_errors() {
1120 let mentor = translate_error(&err(
1121 "Tools Check",
1122 "ModuleNotFoundError: No module named 'requests'",
1123 ));
1124 assert_eq!(mentor.severity, Severity::Critical);
1125 assert!(mentor.plain_english.contains("requests"));
1126 assert!(mentor.suggested_action.contains("pip install requests"));
1127 }
1128
1129 #[test]
1130 fn test_error_translation_port_errors() {
1131 let mentor = translate_error(&err(
1132 "Server",
1133 "listen EADDRINUSE: address already in use :::3000",
1134 ));
1135 assert_eq!(mentor.severity, Severity::Warning);
1136 assert!(mentor.plain_english.contains("3000"));
1137 assert!(mentor.technical_detail.contains("EADDRINUSE"));
1138 assert!(mentor.suggested_action.contains("lsof -i :3000"));
1139 }
1140}