use colored::Colorize;
use crate::models::{CheckStatus, DiagnosticResult, MentorMessage, Severity};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Category {
Node,
Python,
Rust,
PortSystem,
}
impl Category {
pub fn label(&self) -> &'static str {
match self {
Category::Node => "Node.js",
Category::Python => "Python",
Category::Rust => "Rust",
Category::PortSystem => "Port/System",
}
}
}
pub struct TranslationEntry {
pub category: Category,
pub needles: &'static [&'static str],
pub severity: Severity,
pub plain_english: &'static str,
pub action: &'static str,
}
impl TranslationEntry {
pub fn matches(&self, haystack: &str) -> bool {
self.needles.iter().any(|needle| haystack.contains(needle))
}
}
pub const TRANSLATIONS: &[TranslationEntry] = &[
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",
},
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",
},
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",
},
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",
},
];
pub fn translations_for(category: Category) -> impl Iterator<Item = &'static TranslationEntry> {
TRANSLATIONS.iter().filter(move |e| e.category == category)
}
struct MatchContext<'d> {
check_name: &'d str,
message: &'d str,
}
impl<'d> MatchContext<'d> {
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)
}
fn pid(&self) -> Option<String> {
let port = self.port();
Self::numbers(self.message)
.into_iter()
.find(|n| Some(n.as_str()) != port.as_deref())
}
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
}
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())
}
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
}
}
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
}
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()
}),
},
}
}
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)
}
#[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());
}
}
}
#[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 '}'");
}
#[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"));
}
#[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"));
}
}