From 5f083b4b8b3f2379497c02bd024e3ccad5406f8d Mon Sep 17 00:00:00 2001 From: Matias Date: Tue, 4 Aug 2026 02:03:49 -0300 Subject: [PATCH] =?UTF-8?q?feat(fix):=20the=20one=20question=20only=20mem?= =?UTF-8?q?=20can=20answer=20=E2=80=94=20what=20fixed=20this=20last=20time?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit thefuck has 97k stars correcting shell mistakes with hand-written rules and no access to your history. atuin and mcfly have your history and correct nothing. mem has captured exit_code, timestamps, dir, repo and session since its first commit, and search has never read a single one of them. `mem fix` spends them: it finds commands that exited non-zero and were followed, within seconds, by a near-variant of themselves that exited zero, and reports what worked, how often, and when. It prints; it never executes. The mining is entirely deterministic — two exit codes, two timestamps and the textual relationship between two lines. No AI, no network. Every threshold is set to reject a doubtful pair rather than catch one more real one, because the failure mode of a suggestion engine is not silence, it is a confident wrong answer. The load-bearing decision is refusing fuzzy string similarity. Measured on real tokens, `test_a.py`/`test_b.py` scores 0.89 while the genuine typo `psuh`/`push` scores 0.75 — the two things that must be separated are ordered the wrong way round, so no threshold on that number can work, and one tuned to catch the typo would confidently report "the fix for `pytest test_a.py` is `pytest test_b.py`". Corrections are recognised by the *shape* of the edit instead: an added argument, a removed flag, or one token transposed or missing a letter. Every substitution is rejected, which costs real pairs (`git push` → `git pull` is not mined) and is worth it. On a 40-pair calibration set of realistic sequences that rule recovers 19/20 true corrections with 0/20 false positives; the ratio-based rule it replaced scored 19/20 and 9/20. mcp.recent_failures now calls the shared history scan instead of keeping its own copy. Two duplications have already cost this repo real bugs — a stale shell hook served to every pip user, and a ranking formula split across two call sites — and a second definition of "a failure and what came after it" would drift the same way. It gains one behaviour change from the shared definition: a command with no exit code (imported history) is no longer reported as a failure, which it never was. Output goes through render.py as Text, so a captured `sed 's/[a-z]//'` or a bare `[/]` renders as itself. Credentials are stripped by variables. redact_secrets at a single payload choke point shared by --json and the terminal rendering. --- README.md | 94 +++++ src/mem/cli.py | 112 ++++++ src/mem/fix.py | 798 +++++++++++++++++++++++++++++++++++++ src/mem/mcp.py | 40 +- tests/test_fix.py | 973 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 1998 insertions(+), 19 deletions(-) create mode 100644 src/mem/fix.py create mode 100644 tests/test_fix.py diff --git a/README.md b/README.md index 8164ffd..8423c45 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ mem silently captures every command you type, then lets you search, save, and re ```bash Ctrl+R # interactive finder, ranked mem deploy # or search from the command line +mem fix # what fixed the last thing that broke mem save "cmd" -t ops # save a command to a group mem run ops # run the group interactively mem vars set API_KEY # store a secret for saved commands @@ -150,6 +151,97 @@ Patterns for "kubectl": --- +## Fix + +`mem fix` answers one question: **last time this failed, what did you do next that worked?** + +mem has been recording the exit code of every command since day one. `mem fix` reads them back, looking for a command that failed and a near-variant of it that succeeded seconds later — the shape of you reading an error message and retyping the line. + +```bash +mem fix # the last thing that failed here +mem fix npm build # a specific one +mem fix --json # machine-readable +mem fix -n 5 # show more candidate fixes +``` + +``` + failed npm run buld + exit 1 · 3m ago · /Users/dev/work/api + + fixed by npm run build + seen 4 times · last worked 3m ago + + also npm run build --if-present + seen once · last worked 2d ago · one observation only + + mem does not run it for you. Read it, then decide. +``` + +**It never runs anything.** `mem fix` prints the command and stops. Same reason `mem run` asks before each step: a tool that executes on your behalf is how people delete the wrong branch. + +**Confidence is repetition.** A pair seen four times and a pair seen once are different claims, and the output says which. Candidates are ranked by how often the pairing was observed, then by whether the fix has itself broken since, then by recency. + +``` + fixed by npm ci + seen 3 times · last worked 1h ago + careful: this command has itself failed 2 times since. +``` + +**When there is no evidence, it says so.** No suggestion is invented: + +``` + failed terraform apply + exit 1 · just now · /Users/dev/infra + + mem has no record of anything fixing this. +``` + +### What it will and won't pair + +The matching is deterministic — no AI, no network, just exit codes and text. It is deliberately strict, because a wrong "fix" suggested confidently is worse than no suggestion at all. A pair is only recorded when all of these hold: + +| Condition | Why | +|---|---| +| The first command exited non-zero, the second exited exactly `0` | A missing exit code is not a success | +| At most 3 commands apart | You often `ls` and `cat` before fixing | +| Typed within 60 seconds | Longer, and the connection is a guess | +| Same terminal session | Two tabs in one repo interleave in one history file | +| Same program (after ignoring `sudo`) | `git status` failing then `git push` working is two events | +| The second is the first *retyped* | See below | + +"Retyped" means the edit has the shape of a correction: a flag or argument **added**, a flag **removed**, or **one token mistyped** — a transposition (`psuh` → `push`), a dropped letter (`buld` → `build`), a doubled one (`hostt` → `host`). + +It specifically does **not** use fuzzy string similarity, because that measures the wrong thing. `test_a.py`/`test_b.py` scores *higher* than `psuh`/`push`, so any threshold that catches the real typo also reports "the fix for `pytest tests/test_a.py` is `pytest tests/test_b.py`". Substituting one token for a different one is never treated as a correction. + +Things mem finds: + +``` +apt install htop → sudo apt install htop +npm i → npm i --legacy-peer-deps +gti status → git status (only when the shell said "command not found") +kubectl get pods -n prd → kubectl get pods -n prod +npm ci --frozen-lockfile → npm ci +``` + +Things mem deliberately refuses, even though they sit next to each other in your history: + +``` +pytest tests/test_a.py → pytest tests/test_b.py a different file +terraform plan → terraform apply the next step, not a repair +brew install jq → brew install yq a different package +ssh prod-1 → ssh prod-2 a different host +ls /nope → ls worked by doing less +``` + +Two consequences worth knowing: + +- **Imported history is invisible to `mem fix`.** `mem import` reads your old `.zsh_history`, which records no exit codes, so there is nothing to mine. Only commands captured by the shell hook are paired. +- **Some real fixes are missed.** `git push` → `git pull --rebase` is not found, because the rule that would find it would also produce the false positives above. Missing a fix is invisible; inventing one is not. + +Credentials are removed from the output using the same redaction that guards the MCP server, so a `curl` with an auth header still shows you the fix without reprinting the token. + +--- + ## Groups Groups are named collections of commands — like runbooks you can execute. @@ -371,6 +463,8 @@ Every request is appended to `~/.mem/agent-audit.jsonl`, redacted, and shown by ## Other commands ```bash +mem fix # what fixed the last failure (see Fix) +mem fix kubectl --json # ...for a specific one, machine-readable mem stats # top commands, repos, totals mem stats --json # machine-readable stats mem forget "API_KEY=sk-..." # permanently delete matching commands diff --git a/src/mem/cli.py b/src/mem/cli.py index 6dca595..19a21dc 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -357,6 +357,118 @@ def stats(as_json: bool) -> None: console.print(f" {i:>2} {safe(fit(repo, 20))} {count}") +def _fix_line(label: str, style: str, value: str) -> Text: + """Build one ``label command`` row of ``mem fix`` output. + + Returned as a :class:`Text` rather than a markup string because the value + is a command line the user once typed: ``sed 's/[a-z]//'`` interpolated + into a styled string loses its character class, and a bare ``[/]`` raises + ``MarkupError``. Only the label carries a style; the data carries none. + """ + line = Text(" ") + line.append(f"{label:<9}", style=style) + line.append(value) + return line + + +def _fix_detail(text: str) -> Text: + """Build a dim continuation line, aligned under the command above it.""" + return Text(f" {text}", style="dim") + + +def _fix_evidence(entry: dict) -> str: + """Summarize how strong the evidence for one fix is, in words. + + The count is the claim. "Seen once" and "seen 6 times" are different + statements about the same kind of observation, and a tool that renders + them identically is overstating the first one. + """ + times = entry["occurrences"] + seen = "seen once" if times == 1 else f"seen {times} times" + parts = [seen, f"last worked {_relative_time(entry['last_seen'])}"] + if entry["confidence"] == "weak": + parts.append("one observation only") + return " · ".join(parts) + + +@cli.command(name="fix") +@click.argument("query", nargs=-1) +@click.option("--json", "as_json", is_flag=True, help="Output as JSON") +@click.option("--limit", "-n", default=3, help="Maximum fixes to show") +def fix_cmd(query: tuple[str, ...], as_json: bool, limit: int) -> None: + """Show what fixed a failed command the last time it broke. + + With no argument, answers for the most recent failure in this repository + (falling back to the whole store). With a QUERY, answers for the most + recent failure matching every word given. + + The answer is mined from exit codes already in your history: a command + that failed, and the near-variant of it that succeeded seconds later. It + is printed, never executed — mem hands you the line and you decide. + """ + from mem import fix as fix_mining + + text = " ".join(query) if query else None + report = fix_mining.build_report( + query=text, current_repo=_current_repo(), limit=max(1, limit) + ) + payload = fix_mining.report_payload(report) + + if as_json: + click.echo(json.dumps(payload, indent=2)) + return + + failure = payload["failure"] + if failure is None: + # No invention: if nothing failed, there is nothing to say about it. + if text: + console.print( + f'No failed command matching "{safe(text)}" in mem\'s memory.' + ) + else: + console.print("No failed commands captured yet — nothing to fix.") + return + + console.print() + console.print(_fix_line("failed", "bold red", failure["command"])) + where = failure["repo"] or failure["dir"] + console.print( + _fix_detail( + f"exit {failure['exit_code']} · {_relative_time(failure['ts'])} · {where}" + ) + ) + console.print() + + if not payload["fixes"]: + console.print(_fix_detail("mem has no record of anything fixing this.")) + console.print() + return + + best, *others = payload["fixes"] + console.print(_fix_line("fixed by", "bold green", best["command"])) + console.print(_fix_detail(_fix_evidence(best))) + if best["failed_since"]: + times = best["failed_since"] + console.print( + _fix_detail( + f"careful: this command has itself failed " + f"{times} time{'s' if times > 1 else ''} since." + ) + ) + + if others: + console.print() + # Ranked, so "also tried" is genuinely the weaker evidence, not a + # second opinion of equal standing. + for entry in others: + console.print(_fix_line("also", "dim", entry["command"])) + console.print(_fix_detail(_fix_evidence(entry))) + + console.print() + console.print(_fix_detail("mem does not run it for you. Read it, then decide.")) + console.print() + + @cli.command() @click.argument("query") @click.option("--yes", "-y", is_flag=True, help="Skip confirmation") diff --git a/src/mem/fix.py b/src/mem/fix.py new file mode 100644 index 0000000..97f7ee7 --- /dev/null +++ b/src/mem/fix.py @@ -0,0 +1,798 @@ +"""Correction mining — "last time this failed, you fixed it with Y". + +Every other tool in this space has half the picture. Rule-based correctors +(``thefuck``) know that ``git psuh`` should be ``git push``, but have never +seen your history, so they cannot know that *your* fix for a rejected push in +this repo was ``git pull --rebase``. History tools (atuin, mcfly) have your +history but throw away the one field that makes it a debugging record: the +exit code. + +mem has captured ``exit_code``, ``ts``, ``dir``, ``repo`` and ``session`` +since its first commit, and until now search ignored all of them. This module +spends them. It looks for pairs where a command exited non-zero and was +followed, within seconds, by a near-variant of itself that exited zero — the +shape of a human reading an error message and typing the corrected line. + +Deterministic by construction +----------------------------- + +There is no inference here. A pair is admitted only on evidence that is +already in the store: two exit codes, two timestamps, and the textual +relationship between two command lines. That matters because the failure mode +of this feature is not "no suggestion" — it is a *confident wrong* +suggestion. Proposing an unrelated command as "the fix" costs the user more +than silence does, so every threshold below is set to reject a doubtful pair +rather than to catch one more real one. + +The rules, and why each number is what it is +-------------------------------------------- + +A candidate ``Y`` is accepted as the correction of a failure ``X`` when all of +the following hold: + +``X`` failed and ``Y`` succeeded, both explicitly + ``X.exit_code`` is a non-zero integer and ``Y.exit_code`` is exactly 0. + ``None`` is not "probably fine": commands from ``mem import`` carry no + exit code at all, and treating a missing code as success would mine a + correction out of a file that never recorded whether anything worked. + The practical consequence — imported history is invisible to ``mem fix`` + — is stated in the README rather than papered over. + +``Y`` came at most :data:`MAX_LOOKAHEAD` commands later + Three, not one. A human very often looks before they leap: the real + sequence is ``pytest`` (fails), ``cat pytest.ini``, ``ls tests/``, + ``pytest -c setup.cfg`` (works). Allowing two diagnostic commands in + between keeps that case; allowing twenty would let an unrelated command + five minutes of shell activity later be crowned "the fix". + +``Y`` was typed within :data:`WINDOW_SECONDS` of ``X`` finishing + Sixty seconds. A correction written while the error message is still on + screen is typed in seconds; past a minute the user has read docs, opened + a browser or switched task, and any causal link is a guess. The gap is + measured as *think time* — see :func:`_think_seconds` — because mem + timestamps a command when it *completes*, so a fix that itself takes two + minutes to run would otherwise fall out of a window it never left. + +``X`` and ``Y`` came from the same terminal + Same ``session`` when both have one; the same ``dir`` when they do not + (imported and pre-session captures). Two shell tabs working in one repo + interleave their lines in a single history file, and a command from the + other tab is not a correction — it is a coincidence. + +``Y`` invokes the same program as ``X`` + Compared after stripping a leading ``sudo``/``doas``, which is what makes + the single most valuable pair in this whole file minable: ``apt install + foo`` (fails, exit 100) → ``sudo apt install foo`` (works). The one + licensed exception is exit code 127, "command not found" — the only exit + code that is hard evidence that ``argv[0]`` itself was the mistake. Only + then may the program names differ, and only if one is a mistyping of the + other (:func:`looks_like_typo`) — which is how ``gti status`` → ``git + status`` is mined without opening the door to ``cat x`` → ``cd x``. + +``Y`` is a near variant of ``X`` + See :func:`is_near_variant` and :func:`looks_like_typo`. Same-program + alone is far too weak: ``git status`` failing and ``git push`` succeeding + one second later is two events, not a correction. Notably this is *not* + done with fuzzy string similarity, which measures the wrong thing — + ``test_a.py``/``test_b.py`` scores higher than ``psuh``/``push`` — but by + classifying the *shape* of the edit. + +``Y`` is not textually identical to ``X`` + A command that fails and then succeeds unchanged is a flake — a network + blip, a lock that cleared — not a fix. Printing "the fix is: run it + again" would be noise, and an identical success also *ends* the lookahead: + whatever comes after it is a new activity, not a repair. + +What this deliberately does not find +------------------------------------ + +Stated rather than hidden, because a mining rule's misses are as much a part +of its contract as its hits: + +- **Imported history.** ``mem import`` cannot recover exit codes from a shell + history file, so nothing imported is ever paired. +- **Substituted words.** ``git push`` → ``git pull`` is a real fix and is not + mined, because the same rule that admitted it would admit ``pytest + test_a.py`` → ``pytest test_b.py``. +- **Fixes typed more than a minute later**, in another terminal, or after + three intervening commands. +- **Multi-step repairs.** ``npm ci`` then ``npm run build`` is recorded as a + fix for whichever single command failed, not as a two-command procedure — + that is what ``mem save``/``mem group`` are for. + +Confidence is repetition +------------------------ + +A pair seen five times is a different claim from a pair seen once, and the +output says which (:func:`confidence`). This is the one place where the +feature can be honest cheaply, and it is why ``occurrences`` is the primary +sort key rather than recency. + +Nothing here executes anything, and there is no code path that could: the +module imports no subprocess machinery. ``mem fix`` prints a command for a +human to read and decide on, for the same reason ``mem``'s finder does — a +tool that runs commands on your behalf is how people delete the wrong branch. +""" + +from __future__ import annotations + +import difflib +import shlex +from dataclasses import dataclass +from datetime import datetime, timezone +from functools import lru_cache +from typing import Any, Callable, Iterable, Iterator, Sequence + +from mem import storage +from mem.models import CapturedCommand +from mem.variables import redact_secrets + +# --- thresholds ------------------------------------------------------------ +# +# Every number here is a false-positive control. Raising one loses real pairs; +# lowering one invents fake ones, which is the strictly worse failure. The +# reasoning for each is in the module docstring. + +#: Maximum think time between a failure completing and its correction being +#: typed, in seconds. +WINDOW_SECONDS = 60 + +#: How many commands after a failure may be considered its correction. +MAX_LOOKAHEAD = 3 + +#: Longest length difference two tokens may have and still be called a +#: mistyping of one another. Two, so ``prd``/``prod`` and ``instal``/``install`` +#: qualify while ``k``/``kubectl`` (an unset alias, not a typo) does not. +MAX_TYPO_LENGTH_DELTA = 2 + +#: How many tokens may be rewritten between a failure and its fix. One. A +#: person correcting an error message changes the thing the message named; +#: someone who changed two unrelated tokens has moved on to a different +#: command, and pairing those is how a suggestion engine starts lying. +MAX_SUBSTITUTIONS = 1 + +#: "command not found". The only exit code that identifies ``argv[0]`` itself +#: as the mistake, and therefore the only one under which ``mem fix`` will +#: pair two different programs. +COMMAND_NOT_FOUND = 127 + +#: Occurrence counts at which the wording of the claim changes. +STRONG_EVIDENCE = 3 +MODERATE_EVIDENCE = 2 + +#: Program names that are a modifier rather than the command being run. +_PRIVILEGE_PREFIXES = frozenset({"sudo", "doas"}) + + +# --- shared history scanning ---------------------------------------------- +# +# `mem.mcp`'s recent_failures tool mines the same two facts this module does +# (a non-zero exit code, and what capture order put after it). It calls the +# helpers below rather than keeping a second copy: this codebase has already +# paid twice for duplicated logic — a stale shell hook shipped to every pip +# user, and a ranking formula that could drift between call sites — and a +# second failure scanner would drift the same way. + + +def iter_histories( + include: Callable[[str], bool] | None = None, +) -> Iterator[tuple[str, list[CapturedCommand]]]: + """Yield ``(storage key, commands in capture order)`` per history file. + + Order is file order, not timestamp order, and deliberately so: append + order *is* the order the user typed things, which is the signal both + callers are reading. Sorting by ``ts`` would look tidier and would + reorder the one thing that must not be reordered. + + ``include`` filters on the file stem (the storage key). It is a predicate + rather than a repo path because the two callers resolve a repo to a key + differently, and unifying that resolution is a separate change from + unifying this scan. + """ + repos_dir = storage.MEM_DIR / "repos" + if not repos_dir.exists(): + return + for path in sorted(repos_dir.glob("*.jsonl")): + if include is not None and not include(path.stem): + continue + yield path.stem, list(storage.read_commands(path.stem)) + + +@dataclass(frozen=True) +class Failure: + """One non-zero exit, with the commands capture order put after it.""" + + index: int + command: CapturedCommand + following: tuple[CapturedCommand, ...] + + +def iter_failures( + commands: Sequence[CapturedCommand], lookahead: int = MAX_LOOKAHEAD +) -> Iterator[Failure]: + """Yield each explicitly-failed command with the next *lookahead* commands. + + "Explicitly" excludes ``exit_code is None``: an imported history line + records no exit code, and reporting it as a failure would invent one. + """ + for index, cmd in enumerate(commands): + if cmd.exit_code is None or cmd.exit_code == 0: + continue + yield Failure( + index=index, + command=cmd, + following=tuple(commands[index + 1 : index + 1 + lookahead]), + ) + + +# --- textual comparison ---------------------------------------------------- + + +@lru_cache(maxsize=4096) +def normalized_tokens(command: str) -> tuple[str, ...]: + """Split a command line into comparison tokens. + + Two normalizations, both narrow on purpose: + + - ``shlex`` splitting, so ``git commit -m "wip"`` compares as four tokens + rather than by raw characters. Unbalanced quotes raise, and a shell + history is full of half-typed lines, so that falls back to a plain + whitespace split instead of discarding the command. + - A leading ``sudo``/``doas`` is dropped, which is what lets + ``apt install x`` and ``sudo apt install x`` be recognised as the same + command modulo privilege — the pair this feature most wants to find. + + Explicitly *not* normalized: ``argv[0]`` keeps its path. Reducing + ``./scripts/a/run.sh`` to ``run.sh`` would make it indistinguishable from + ``./scripts/b/run.sh``, and "the fix is the other project's deploy + script" is the precise kind of confident-wrong answer this module refuses + to produce. + + Cached because mining compares each command against several neighbours + and ``shlex`` is the most expensive thing in the loop. + """ + try: + tokens = shlex.split(command) + except ValueError: + tokens = command.split() + start = 0 + while start < len(tokens) and tokens[start] in _PRIVILEGE_PREFIXES: + start += 1 + return tuple(tokens[start:]) + + +def _is_flag(token: str) -> bool: + """True if a token is an option rather than a thing being operated on. + + A bare ``-`` is not a flag: it means stdin, and dropping it changes what + the command reads. + """ + return len(token) > 1 and token.startswith("-") + + +def _is_subsequence(short: str, long: str) -> bool: + """True if every character of *short* appears in *long*, in order.""" + remaining = iter(long) + return all(char in remaining for char in short) + + +def looks_like_typo(wrong: str, right: str) -> bool: + """True if *right* is *wrong* mistyped, rather than a different thing. + + This function is the whole false-positive story of ``mem fix``, so the + reasoning is worth stating in full. + + The obvious implementation is fuzzy string similarity, and it does not + work. Measured with ``difflib`` on real command tokens: + + ============================== ===== ========================== + pair ratio what it actually is + ============================== ===== ========================== + ``test_a.py`` / ``test_b.py`` 0.89 two different test files + ``prod-1`` / ``prod-2`` 0.83 two different hosts + ``psuh`` / ``push`` 0.75 a typo + ``push`` / ``pull`` 0.50 two different subcommands + ============================== ===== ========================== + + The two things that must be separated are *ordered the wrong way round* + by similarity: the sibling filenames score higher than the genuine typo. + No threshold on that column can work, and one tuned to catch ``psuh`` + would confidently report "the fix for ``pytest test_a.py`` is ``pytest + test_b.py``" — a wrong answer delivered with a straight face, which is + the exact failure this feature cannot afford. + + What separates them is not *how much* changed but *what shape* the change + has. A mistyping is a finger error: a transposition, a doubled or dropped + character, an omitted letter. Choosing a different target is a + substitution: same shape, different content. So: + + - **Transposition** — the two tokens are anagrams (``psuh``/``push``, + ``docekr``/``docker``, ``mian``/``main``, ``sl``/``ls``). + - **Insertion or deletion** — the shorter is a subsequence of the longer, + within :data:`MAX_TYPO_LENGTH_DELTA` characters (``buld``/``build``, + ``prd``/``prod``, ``instal``/``install``, ``hostt``/``host``). + + Every substitution is rejected, which costs real pairs — ``git push`` → + ``git pull`` is not mined — and that price is paid deliberately. Missing + a fix is invisible; inventing one is not. + """ + if wrong == right: + return False + if sorted(wrong) == sorted(right): + return True + + longer, shorter = (wrong, right) if len(wrong) > len(right) else (right, wrong) + if not shorter or len(longer) - len(shorter) > MAX_TYPO_LENGTH_DELTA: + return False + return _is_subsequence(shorter, longer) + + +def is_near_variant(failed: Sequence[str], fix: Sequence[str]) -> bool: + """True if *fix* looks like *failed* re-typed rather than a new thought. + + The two token lists are aligned with ``difflib`` and every edit between + them is classified. An edit is admissible only if it is one of: + + **An insertion.** The user kept everything they had typed and added to + it: ``docker ps`` → ``docker ps -a``, ``npm i`` → ``npm i + --legacy-peer-deps``, ``kubectl logs api`` → ``kubectl logs api -n + prod``. Intent is preserved by construction, which is what makes this the + safest edit to accept unconditionally. + + **A deletion of flags only.** Dropping ``--frozen-lockfile`` is a fix. + Dropping an operand is not: ``ls /nope`` → ``ls`` succeeded because it + stopped doing the thing that was asked for, and reporting that as "the + fix" would be actively misleading. + + **One token mistyped**, in the strict structural sense of + :func:`looks_like_typo`, and at most :data:`MAX_SUBSTITUTIONS` of them. + + ``difflib`` merges adjacent edits into a single ``replace`` opcode, so + ``npm run buld`` → ``npm run build --if-present`` arrives as "one token + became two" rather than as a typo plus an insertion. Such a block is + therefore re-aligned left-to-right by :func:`_replacement_is_admissible` + before being judged, which is what keeps a genuinely common repair — + correct the spelling *and* add the flag you also forgot — from being + thrown away on a technicality of the diff algorithm. + """ + matcher = difflib.SequenceMatcher(None, list(failed), list(fix), autojunk=False) + substitutions = 0 + + for tag, i1, i2, j1, j2 in matcher.get_opcodes(): + if tag == "equal" or tag == "insert": + continue + if tag == "delete": + if not all(_is_flag(token) for token in failed[i1:i2]): + return False + continue + # tag == "replace" + rewrites = _replacement_is_admissible(failed[i1:i2], fix[j1:j2]) + if rewrites is None: + return False + substitutions += rewrites + if substitutions > MAX_SUBSTITUTIONS: + return False + + return True + + +def _replacement_is_admissible( + removed: Sequence[str], added: Sequence[str] +) -> int | None: + """Judge one ``replace`` block. Returns its substitution count, or None. + + The block is re-aligned left to right, which is the order a person edits + a command line in: the first removed token is judged against the first + added one, and so on. Whatever is left over on the removed side is a + deletion (flags only, per :func:`is_near_variant`) and whatever is left + over on the added side is an insertion (always allowed). + + ``None`` means "not a correction" and is deliberately distinct from + ``0``, which means "a block that changed nothing that counts as a + rewrite" — collapsing the two would let a rejected block pass as free. + """ + substitutions = 0 + for old, new in zip(removed, added): + if old == new: + continue + if not looks_like_typo(old, new): + return None + substitutions += 1 + + for leftover in removed[len(added) :]: + if not _is_flag(leftover): + return None + + return substitutions + + +def is_plausible_correction(failed: str, fix: str, exit_code: int | None) -> bool: + """True if *fix* is admissible as the correction of *failed*. + + The textual half of the rule set; the caller still has to satisfy the + temporal, session and exit-code conditions. Kept separate so it can be + tested exhaustively against command pairs without constructing history. + """ + if failed == fix: + return False + + failed_tokens = normalized_tokens(failed) + fix_tokens = normalized_tokens(fix) + if not failed_tokens or not fix_tokens: + return False + + if failed_tokens[0] != fix_tokens[0]: + # Different programs. Only exit 127 makes that a correction rather + # than a change of subject, and even then the two names must stand in + # the same mistyping relationship any other token would have to. + if exit_code != COMMAND_NOT_FOUND: + return False + if not looks_like_typo(failed_tokens[0], fix_tokens[0]): + return False + # Forgive the program name and judge the arguments on their own; the + # exit code has already accounted for the difference. + failed_tokens = (fix_tokens[0], *failed_tokens[1:]) + + return is_near_variant(failed_tokens, fix_tokens) + + +def _think_seconds(failed: CapturedCommand, candidate: CapturedCommand) -> int: + """Seconds between *failed* finishing and *candidate* being typed. + + mem timestamps a command when the shell hook fires, i.e. when it + *completes*. Naively subtracting timestamps therefore charges the + candidate's own runtime to the user's thinking time, and a correction that + happens to be a four-minute ``docker build`` would be discarded for being + slow rather than for being unrelated. Subtracting the known duration + measures what the window is actually about: how long the human paused. + + Integer seconds against millisecond durations, so the result can land one + second low; that slack is harmless against a 60-second window. + """ + gap = candidate.ts - failed.ts + if candidate.duration_ms: + gap -= candidate.duration_ms // 1000 + return gap + + +def _same_terminal(failed: CapturedCommand, candidate: CapturedCommand) -> bool: + """True if both commands plausibly came from the same shell. + + Session id when both have one — it is the only field that actually + identifies a terminal. Falling back to the working directory when either + is missing keeps pre-session captures usable while still rejecting the + common interleaving case, two tabs in one repo. + """ + if failed.session and candidate.session: + return failed.session == candidate.session + return failed.dir == candidate.dir + + +# --- mining ---------------------------------------------------------------- + + +@dataclass(frozen=True) +class Correction: + """One observed ``failure → fix`` pairing, aggregated over history. + + ``occurrences`` is the whole confidence story: the same pair mined five + times is five independent instances of a human making a mistake and + correcting it the same way. + + ``fix_failures`` counts times the *fix* command itself exited non-zero + after this pairing was last seen. A fix that has since stopped working is + still worth showing — it is the best evidence available — but presenting + it without that caveat would be dishonest. + """ + + failed: str + fix: str + occurrences: int + first_seen: int + last_seen: int + exit_code: int | None + repo: str | None + fix_failures: int = 0 + + @property + def confidence(self) -> str: + """``strong`` / ``moderate`` / ``weak``, from :data:`occurrences`.""" + return confidence(self.occurrences) + + +def confidence(occurrences: int) -> str: + """Label an occurrence count. + + Three is "strong" because two is where coincidence stops being a + reasonable explanation and three is where it stops being an interesting + one. The label exists so the output can make a proportionate claim + instead of asserting the same certainty for one observation and fifty. + """ + if occurrences >= STRONG_EVIDENCE: + return "strong" + if occurrences >= MODERATE_EVIDENCE: + return "moderate" + return "weak" + + +def _find_fix(failure: Failure) -> CapturedCommand | None: + """The first admissible correction among a failure's following commands. + + First, not best: the commands in between are the user diagnosing, and the + first thing they run that both resembles the failure and works is the + thing that worked. Scanning further for a "better" match would mean + preferring a later command over the one that actually resolved it. + """ + for candidate in failure.following: + if candidate.ts < failure.command.ts: + continue # out-of-order line; a fix cannot precede its failure + if _think_seconds(failure.command, candidate) > WINDOW_SECONDS: + break # the window only widens from here + if not _same_terminal(failure.command, candidate): + continue + if candidate.exit_code != 0: + continue + if candidate.command == failure.command.command: + # Succeeded unchanged: the failure was transient, not fixed. + # Anything after this is new work, so stop looking. + break + if is_plausible_correction( + failure.command.command, candidate.command, failure.command.exit_code + ): + return candidate + return None + + +def mine(commands: Sequence[CapturedCommand]) -> list[Correction]: + """Extract every ``failure → fix`` pairing from one history file. + + Aggregation is by exact command text on both sides. Normalizing before + counting (folding ``sudo apt update`` into ``apt update``) would inflate + occurrence counts by merging pairs the user experienced as distinct, and + ``occurrences`` is the number the output makes its claim from. + """ + pairs: dict[tuple[str, str], list[CapturedCommand]] = {} + for failure in iter_failures(commands): + fix = _find_fix(failure) + if fix is None: + continue + pairs.setdefault((failure.command.command, fix.command), []).append( + failure.command + ) + + if not pairs: + return [] + + # When did each command text fail? Used to answer "has this fix itself + # broken since?" without a second pass per pair. + failure_times: dict[str, list[int]] = {} + for cmd in commands: + if cmd.exit_code: + failure_times.setdefault(cmd.command, []).append(cmd.ts) + + corrections = [] + for (failed_text, fix_text), instances in pairs.items(): + timestamps = [c.ts for c in instances] + last_seen = max(timestamps) + newest = max(instances, key=lambda c: c.ts) + corrections.append( + Correction( + failed=failed_text, + fix=fix_text, + occurrences=len(instances), + first_seen=min(timestamps), + last_seen=last_seen, + exit_code=newest.exit_code, + repo=newest.repo, + fix_failures=sum( + 1 for ts in failure_times.get(fix_text, ()) if ts > last_seen + ), + ) + ) + return corrections + + +def merge(corrections: Iterable[Correction]) -> list[Correction]: + """Combine per-repo corrections describing the same pairing. + + A fix learned in one repository is still the fix in another — ``docker`` + and ``kubectl`` do not care which checkout the terminal was in — so the + same pair mined from two history files is one piece of evidence seen + twice, and its occurrence count has to say so. + """ + merged: dict[tuple[str, str], Correction] = {} + for correction in corrections: + key = (correction.failed, correction.fix) + existing = merged.get(key) + if existing is None: + merged[key] = correction + continue + newer = correction if correction.last_seen >= existing.last_seen else existing + merged[key] = Correction( + failed=correction.failed, + fix=correction.fix, + occurrences=existing.occurrences + correction.occurrences, + first_seen=min(existing.first_seen, correction.first_seen), + last_seen=max(existing.last_seen, correction.last_seen), + exit_code=newer.exit_code, + repo=newer.repo, + fix_failures=existing.fix_failures + correction.fix_failures, + ) + return list(merged.values()) + + +def rank(corrections: Iterable[Correction]) -> list[Correction]: + """Order candidate fixes best-first. + + The rule, in order: + + 1. **Most occurrences.** Repetition is the only evidence of correctness + this module has. A pair seen four times beat coincidence four times. + 2. **Fewest failures since.** Between equally-attested fixes, prefer the + one that has not broken since it last worked. + 3. **Most recent.** Environments drift; the newer observation describes + the machine as it is now. + 4. **Command text**, so that a tie produces the same answer twice. + """ + return sorted( + corrections, + key=lambda c: (-c.occurrences, c.fix_failures, -c.last_seen, c.fix), + ) + + +def mine_all( + include: Callable[[str], bool] | None = None, +) -> tuple[list[Correction], list[CapturedCommand]]: + """Mine every history file. Returns ``(corrections, failures)``. + + Both halves come from one pass because ``mem fix`` needs both and the scan + is the expensive part: the failures answer "what broke?" and the + corrections answer "what fixed it?", and reading the store twice to + produce them would double the cost of the only slow thing this command + does. + """ + corrections: list[Correction] = [] + failures: list[CapturedCommand] = [] + for _key, commands in iter_histories(include): + corrections.extend(mine(commands)) + failures.extend( + cmd for cmd in commands if cmd.exit_code is not None and cmd.exit_code != 0 + ) + return merge(corrections), failures + + +# --- selection ------------------------------------------------------------- + + +def matches(command: str, terms: Sequence[str]) -> bool: + """True if *command* contains every term, case-insensitively. + + Same all-terms-must-appear contract as ``mem`` search, so that + ``mem fix npm build`` narrows to what the user expects rather than + matching anything mentioning either word. + """ + lowered = command.lower() + return all(term in lowered for term in terms) + + +def select_failure( + failures: Sequence[CapturedCommand], + query: str | None = None, + current_repo: str | None = None, +) -> CapturedCommand | None: + """Pick which failure ``mem fix`` is about. + + Most recent wins, but the current repository is consulted first: someone + typing ``mem fix`` has just broken something *here*, and answering with a + failure from another checkout would be technically-most-recent and + practically useless. Falling back to the whole store rather than giving up + keeps the command useful outside a repo and right after a ``cd``. + """ + candidates = list(failures) + if query: + terms = [t for t in query.lower().split() if t] + candidates = [c for c in candidates if matches(c.command, terms)] + if not candidates: + return None + + local = [c for c in candidates if current_repo and c.repo == current_repo] + return max(local or candidates, key=lambda c: c.ts) + + +def fixes_for( + corrections: Sequence[Correction], failed_command: str +) -> list[Correction]: + """Every recorded fix for one exact failing command line, best first.""" + return rank(c for c in corrections if c.failed == failed_command) + + +# --- report ---------------------------------------------------------------- + + +@dataclass(frozen=True) +class FixReport: + """What ``mem fix`` found: the failure it is about, and the fixes seen.""" + + failure: CapturedCommand | None + fixes: list[Correction] + query: str | None = None + + +def build_report( + query: str | None = None, current_repo: str | None = None, limit: int = 3 +) -> FixReport: + """Mine the store and answer one ``mem fix`` invocation.""" + corrections, failures = mine_all() + failure = select_failure(failures, query=query, current_repo=current_repo) + if failure is None: + return FixReport(failure=None, fixes=[], query=query) + return FixReport( + failure=failure, + fixes=fixes_for(corrections, failure.command)[:limit], + query=query, + ) + + +def _iso(ts: int) -> str: + """Format an epoch timestamp as UTC ISO-8601, for machine consumers.""" + return ( + datetime.fromtimestamp(ts, tz=timezone.utc) + .isoformat(timespec="seconds") + .replace("+00:00", "Z") + ) + + +def _redact(value: Any) -> Any: + """Recursively redact every string in a JSON-shaped structure. + + Applied to the whole payload at one choke point rather than field by + field, for the same reason ``mem.mcp`` does it: a per-field call is a rule + a future field can forget, and the cost of forgetting is a printed + credential. ``mem fix`` in particular quotes commands the user has + forgotten they ran. + """ + if isinstance(value, str): + return redact_secrets(value) + if isinstance(value, dict): + return {k: _redact(v) for k, v in value.items()} + if isinstance(value, list): + return [_redact(v) for v in value] + return value + + +def report_payload(report: FixReport) -> dict[str, Any]: + """Render a report as redacted, JSON-ready data. + + The single exit from this module. Both ``--json`` and the terminal + rendering read this structure, so there is exactly one place where a + command string can escape unredacted, and it is this function. + """ + failure = report.failure + payload: dict[str, Any] = { + "query": report.query, + "failure": None + if failure is None + else { + "command": failure.command, + "exit_code": failure.exit_code, + "ts": failure.ts, + "when": _iso(failure.ts), + "repo": failure.repo, + "dir": failure.dir, + }, + "count": len(report.fixes), + "fixes": [ + { + "command": c.fix, + "occurrences": c.occurrences, + "confidence": c.confidence, + "first_seen": c.first_seen, + "last_seen": c.last_seen, + "last_seen_iso": _iso(c.last_seen), + "failed_since": c.fix_failures, + "repo": c.repo, + } + for c in report.fixes + ], + } + return _redact(payload) diff --git a/src/mem/mcp.py b/src/mem/mcp.py index 64dc75e..08ade75 100644 --- a/src/mem/mcp.py +++ b/src/mem/mcp.py @@ -380,42 +380,44 @@ def _tool_recent_failures(args: dict[str, Any]) -> dict[str, Any]: later successful run of the *same* command is proof the fix worked — which is the single most useful thing a shell history can tell an agent and needs no inference to extract. + + The scan itself lives in :mod:`mem.fix`, which mines the same two facts + for ``mem fix``. Sharing it is deliberate: two independent definitions of + "a failure and what came after it" would drift, and this codebase has + already been bitten twice by exactly that — a stale shell hook served to + every pip user, and a ranking formula duplicated across two call sites. + What stays here is what is genuinely this tool's own: the shape of the + JSON, the two-command lookahead, and ``retried_successfully``. """ + from mem.fix import iter_failures, iter_histories + limit = _optional_limit(args, 10) repo_filter = _optional_str(args, "repo") - repos_dir = storage.MEM_DIR / "repos" - if not repos_dir.exists(): - return {"count": 0, "failures": []} - sanitized = storage.sanitize_repo_name(repo_filter) if repo_filter else None + include = None if sanitized is None else (lambda stem: stem == sanitized) failures: list[dict[str, Any]] = [] - for path in sorted(repos_dir.glob("*.jsonl")): - if sanitized is not None and path.stem != sanitized: - continue - commands = list(storage.read_commands(path.stem)) + for _key, commands in iter_histories(include): succeeded_later: dict[str, int] = {} for index, cmd in enumerate(commands): if cmd.exit_code == 0: succeeded_later.setdefault(cmd.command, index) - for index, cmd in enumerate(commands): - if cmd.exit_code == 0: - continue - retry = succeeded_later.get(cmd.command) + for failure in iter_failures(commands, lookahead=2): + retry = succeeded_later.get(failure.command.command) failures.append( { - "command": cmd.command, - "repo": cmd.repo, - "ts": cmd.ts, - "when": _iso(cmd.ts), - "exit_code": cmd.exit_code, + "command": failure.command.command, + "repo": failure.command.repo, + "ts": failure.command.ts, + "when": _iso(failure.command.ts), + "exit_code": failure.command.exit_code, "followed_by": [ {"command": nxt.command, "exit_code": nxt.exit_code} - for nxt in commands[index + 1 : index + 3] + for nxt in failure.following ], - "retried_successfully": retry is not None and retry > index, + "retried_successfully": retry is not None and retry > failure.index, } ) diff --git a/tests/test_fix.py b/tests/test_fix.py new file mode 100644 index 0000000..ed061fb --- /dev/null +++ b/tests/test_fix.py @@ -0,0 +1,973 @@ +"""Contract tests for correction mining and ``mem fix``. + +The thing under test is a *suggestion engine*, and the failure that matters +is not "found nothing" — it is "confidently proposed an unrelated command as +the fix". So this suite is weighted accordingly: for every test that pins a +pair mem must find, there is at least one pinning a pair it must refuse. + +:class:`TestFalsePositives` in particular is the load-bearing class. Every +case in it is a real shell sequence where two neighbouring commands share a +program and a shape but not an intent — one test file after another, one pod +after another, plan then apply. If a future change to the matching rules +starts admitting those, this feature becomes a liar, and that is precisely +the regression a threshold tweak is most likely to introduce. + +Every test builds its own history; nothing here reads the developer's real +``~/.mem`` (see ``conftest.tmp_mem_dir``, which is autouse). +""" + +from __future__ import annotations + +import json +import time +from pathlib import Path + +import pytest +from click.testing import CliRunner + +from mem import fix, storage +from mem.cli import cli +from mem.models import CapturedCommand + +NOW = int(time.time()) +REPO = "/Users/dev/work/api" + + +# --- helpers --------------------------------------------------------------- + + +def cmd( + command: str, + ts: int, + exit_code: int | None = 0, + *, + session: str | None = "session-1", + directory: str = REPO, + repo: str | None = REPO, + duration_ms: int | None = 100, +) -> CapturedCommand: + """Build one captured command with sane defaults for pairing. + + Defaults are chosen so a test that says nothing about sessions, + directories or durations gets a pair mem *would* accept — leaving each + test free to break exactly one condition and assert that this alone is + what rejected the pair. + """ + return CapturedCommand( + command=command, + ts=ts, + dir=directory, + repo=repo, + exit_code=exit_code, + duration_ms=duration_ms, + session=session, + ) + + +def write_history(commands: list[CapturedCommand], key: str = "work-api") -> Path: + """Write commands to a repo history file in the given order. + + Raw file writing rather than ``storage.append_command`` because capture + order is the signal under test, and going through the capture layer would + stamp its own timestamps over the ones each test carefully chose. + """ + path = storage.MEM_DIR / "repos" / f"{key}.jsonl" + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + for command in commands: + handle.write(command.to_jsonl() + "\n") + return path + + +def mined(commands: list[CapturedCommand]) -> dict[str, str]: + """Mine a command sequence down to a ``{failed: fix}`` mapping.""" + return {c.failed: c.fix for c in fix.mine(commands)} + + +def run_fix(*args: str) -> str: + """Invoke ``mem fix`` and return its stdout.""" + result = CliRunner().invoke(cli, ["fix", *args]) + assert result.exception is None, result.exception + assert result.exit_code == 0 + return result.output + + +# --- the core pairing rule ------------------------------------------------- + + +class TestCleanPair: + """The happy path: a failure and the corrected re-typing that followed.""" + + def test_a_typo_and_its_correction_are_paired(self) -> None: + pairs = mined( + [ + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build", NOW - 95, 0), + ] + ) + assert pairs == {"npm run buld": "npm run build"} + + def test_the_pairing_records_when_and_how_often(self) -> None: + """Occurrences and timestamps are the output's entire evidence.""" + (correction,) = fix.mine( + [ + cmd("npm run buld", NOW - 500, 1), + cmd("npm run build", NOW - 495, 0), + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build", NOW - 95, 0), + ] + ) + assert correction.occurrences == 2 + assert correction.first_seen == NOW - 500 + assert correction.last_seen == NOW - 100 + assert correction.exit_code == 1 + + def test_a_forgotten_sudo_is_the_pair_worth_finding_most(self) -> None: + """``apt install x`` → ``sudo apt install x``: same command, more rights.""" + pairs = mined( + [ + cmd("apt install htop", NOW - 40, 100), + cmd("sudo apt install htop", NOW - 36, 0), + ] + ) + assert pairs == {"apt install htop": "sudo apt install htop"} + + def test_a_forgotten_flag_is_paired(self) -> None: + pairs = mined( + [ + cmd("npm i", NOW - 40, 1), + cmd("npm i --legacy-peer-deps", NOW - 30, 0), + ] + ) + assert pairs == {"npm i": "npm i --legacy-peer-deps"} + + def test_a_bad_flag_removed_is_paired(self) -> None: + """Dropping a flag is a fix; dropping an operand is not (see below).""" + pairs = mined( + [ + cmd("npm ci --frozen-lockfile", NOW - 40, 1), + cmd("npm ci", NOW - 30, 0), + ] + ) + assert pairs == {"npm ci --frozen-lockfile": "npm ci"} + + def test_diagnostic_commands_between_do_not_break_the_pair(self) -> None: + """The real sequence is: it broke, I looked, I fixed it.""" + pairs = mined( + [ + cmd("pytest -q", NOW - 50, 1), + cmd("ls tests/", NOW - 45, 0), + cmd("cat pytest.ini", NOW - 43, 0), + cmd("pytest -q tests/unit", NOW - 40, 0), + ] + ) + assert pairs == {"pytest -q": "pytest -q tests/unit"} + + def test_the_lookahead_does_not_reach_a_fourth_command(self) -> None: + """MAX_LOOKAHEAD is 3; the fourth command is no longer "right after".""" + pairs = mined( + [ + cmd("pytest -q", NOW - 50, 1), + cmd("ls", NOW - 48, 0), + cmd("cat setup.cfg", NOW - 46, 0), + cmd("git status", NOW - 44, 0), + cmd("pytest -q tests/unit", NOW - 42, 0), + ] + ) + assert pairs == {} + + +class TestCommandNotFound: + """Exit 127 is the only licence to pair two different programs.""" + + def test_a_mistyped_program_name_is_paired_when_the_shell_said_127(self) -> None: + pairs = mined( + [ + cmd("gti status", NOW - 30, 127), + cmd("git status", NOW - 28, 0), + ] + ) + assert pairs == {"gti status": "git status"} + + def test_the_same_pair_is_refused_under_any_other_exit_code(self) -> None: + """Without 127 there is no evidence that argv[0] was the mistake. + + The pair is textually identical to the one above; only the exit code + differs. That is the whole point: the licence comes from the exit + code, not from the strings looking alike. + """ + pairs = mined( + [ + cmd("gti status", NOW - 30, 1), + cmd("git status", NOW - 28, 0), + ] + ) + assert pairs == {} + + def test_127_still_requires_the_names_to_be_a_mistyping(self) -> None: + """``cd`` is not a mistyping of ``cat``, whatever the exit code.""" + pairs = mined( + [ + cmd("cat notes.txt", NOW - 30, 127), + cmd("cd notes", NOW - 28, 0), + ] + ) + assert pairs == {} + + +class TestFalsePositives: + """Pairs mem must refuse. The reason this feature can be trusted. + + Each case is two adjacent commands that pass every structural filter — + same program, seconds apart, same session, failure then success — and are + still not a correction. Only the textual rule can reject them. + """ + + @pytest.mark.parametrize( + "failed,succeeded,reason", + [ + ("git status", "git push", "a different subcommand is a different intent"), + ("git diff", "git add .", "one token became two"), + ("make clean", "make install", "different targets"), + ("terraform plan", "terraform apply", "the next step, not a repair"), + ("npm test", "npm run dev", "unrelated script"), + ( + "pytest tests/test_a.py", + "pytest tests/test_b.py", + "sibling files score higher than real typos on fuzzy similarity", + ), + ("kubectl delete pod a", "kubectl delete pod b", "a different pod"), + ("kubectl apply -f a.yaml", "kubectl apply -f b.yaml", "a different file"), + ("ssh prod-1", "ssh prod-2", "a different host"), + ("brew install jq", "brew install yq", "a different package"), + ("go test ./pkg/a", "go test ./pkg/b", "a different package path"), + ("mv a b", "mv c d", "two tokens changed"), + ("docker build .", "docker push img", "a different verb"), + ("ls /nope", "ls", "succeeded by doing less, not by being fixed"), + ], + ) + def test_a_neighbouring_success_is_not_automatically_the_fix( + self, failed: str, succeeded: str, reason: str + ) -> None: + assert mined([cmd(failed, NOW - 30, 1), cmd(succeeded, NOW - 28, 0)]) == {}, ( + reason + ) + + def test_fuzzy_similarity_would_have_got_these_backwards(self) -> None: + """The measurement that justifies rejecting all substitutions. + + Character similarity ranks two different test files *above* a genuine + typo, so no threshold on it can separate them. Pinned as a test + because it is the single fact the whole matching design rests on, and + a future contributor reaching for ``SequenceMatcher.ratio`` deserves + to trip over it. + """ + import difflib + + def ratio(a: str, b: str) -> float: + return difflib.SequenceMatcher(None, a, b, autojunk=False).ratio() + + assert ratio("test_a.py", "test_b.py") > ratio("psuh", "push") + assert fix.looks_like_typo("psuh", "push") + assert not fix.looks_like_typo("test_a.py", "test_b.py") + + def test_two_tokens_rewritten_at_once_is_not_a_correction(self) -> None: + """Even when both rewrites are individually typo-shaped.""" + assert not fix.is_near_variant( + ["git", "comit", "-m", "wipp"], ["git", "commit", "-m", "wip"] + ) + + +class TestTypoShape: + """The unit rule that decides everything above.""" + + @pytest.mark.parametrize( + "wrong,right", + [ + ("psuh", "push"), # transposition + ("docekr", "docker"), + ("mian", "main"), + ("buld", "build"), # dropped character + ("prd", "prod"), + ("instal", "install"), + ("hostt", "host"), # doubled character + ("sl", "ls"), + ], + ) + def test_finger_errors_are_typos(self, wrong: str, right: str) -> None: + assert fix.looks_like_typo(wrong, right) + assert fix.looks_like_typo(right, wrong), "the relation is symmetric" + + @pytest.mark.parametrize( + "left,right", + [ + ("push", "pull"), # substitution: a different subcommand + ("plan", "apply"), + ("jq", "yq"), + ("a", "b"), + ("prod-1", "prod-2"), + ("test_a.py", "test_b.py"), + ("k", "kubectl"), # an unset alias, not a mistyping + ("", "ls"), # nothing is not a mistyping of something + ], + ) + def test_substitutions_and_wholesale_differences_are_not( + self, left: str, right: str + ) -> None: + assert not fix.looks_like_typo(left, right) + + def test_a_token_is_not_a_mistyping_of_itself(self) -> None: + """Guards the caller's substitution budget from being spent on nothing.""" + assert not fix.looks_like_typo("git", "git") + + def test_a_command_is_not_a_correction_of_itself(self) -> None: + assert not fix.is_plausible_correction("ls -la", "ls -la", 1) + + +class TestReplacementBlocks: + """``_replacement_is_admissible`` distinguishes "free" from "refused". + + Returning ``0`` (a block that changed nothing chargeable) and returning + ``None`` (a block that disqualifies the pair) are different answers, and + collapsing them into a falsy value would let a rejected block pass. + """ + + def test_a_typo_plus_an_added_flag_costs_one_substitution(self) -> None: + assert fix._replacement_is_admissible(["buld"], ["build", "--if-present"]) == 1 + + def test_a_typo_plus_a_dropped_flag_is_allowed(self) -> None: + assert fix._replacement_is_admissible(["psh", "-f"], ["push"]) == 1 + + def test_a_dropped_operand_disqualifies_the_block(self) -> None: + assert fix._replacement_is_admissible(["psh", "origin"], ["push"]) is None + + def test_an_unchanged_aligned_token_costs_nothing(self) -> None: + assert fix._replacement_is_admissible(["build", "-v"], ["build"]) == 0 + + def test_an_unrelated_token_disqualifies_the_block(self) -> None: + assert fix._replacement_is_admissible(["status"], ["push"]) is None + + +class TestTimeWindow: + """A correction is typed while the error is still on screen.""" + + def test_a_pair_too_far_apart_in_time_is_not_mined(self) -> None: + pairs = mined( + [ + cmd("npm run buld", NOW - 5000, 1), + cmd("npm run build", NOW - 5000 + fix.WINDOW_SECONDS + 5, 0), + ] + ) + assert pairs == {} + + def test_a_pair_at_the_edge_of_the_window_is_still_mined(self) -> None: + pairs = mined( + [ + cmd("npm run buld", NOW - 5000, 1), + cmd( + "npm run build", + NOW - 5000 + fix.WINDOW_SECONDS, + 0, + duration_ms=0, + ), + ] + ) + assert pairs == {"npm run buld": "npm run build"} + + def test_a_slow_fix_is_not_penalised_for_its_own_runtime(self) -> None: + """mem timestamps completion, so the window must discount duration. + + Without that, a four-minute ``docker build`` typed two seconds after + the failure would be discarded for being slow rather than unrelated — + and slow builds are exactly where corrections happen. + """ + pairs = mined( + [ + cmd("docker build -t app .", NOW - 400, 1), + cmd( + "docker build -t app . --no-cache", + NOW - 400 + 242, + 0, + duration_ms=240_000, + ), + ] + ) + assert pairs == {"docker build -t app .": "docker build -t app . --no-cache"} + + def test_a_candidate_recorded_before_the_failure_is_ignored(self) -> None: + """Out-of-order lines exist; a fix cannot precede what it fixed.""" + pairs = mined( + [ + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build", NOW - 400, 0), + ] + ) + assert pairs == {} + + +class TestSameTerminal: + """Two tabs in one repo interleave into one history file.""" + + def test_a_command_from_another_session_is_not_a_correction(self) -> None: + pairs = mined( + [ + cmd("npm run buld", NOW - 30, 1, session="tab-1"), + cmd("npm run build", NOW - 28, 0, session="tab-2"), + ] + ) + assert pairs == {} + + def test_without_sessions_the_directory_is_the_fallback(self) -> None: + """Pre-session and imported captures still get a sanity check.""" + assert ( + mined( + [ + cmd("npm run buld", NOW - 30, 1, session=None, directory="/a"), + cmd("npm run build", NOW - 28, 0, session=None, directory="/b"), + ] + ) + == {} + ) + assert mined( + [ + cmd("npm run buld", NOW - 30, 1, session=None, directory="/a"), + cmd("npm run build", NOW - 28, 0, session=None, directory="/a"), + ] + ) == {"npm run buld": "npm run build"} + + +class TestExitCodes: + """Only explicit exit codes count.""" + + def test_a_failure_never_fixed_yields_nothing(self) -> None: + pairs = mined( + [ + cmd("npm run buld", NOW - 30, 1), + cmd("npm run buld", NOW - 20, 1), + cmd("npm run buld", NOW - 10, 1), + ] + ) + assert pairs == {} + + def test_a_candidate_that_also_failed_is_not_a_fix(self) -> None: + pairs = mined( + [ + cmd("npm run buld", NOW - 30, 1), + cmd("npm run build", NOW - 28, 1), + ] + ) + assert pairs == {} + + def test_imported_commands_carry_no_exit_code_and_are_never_paired(self) -> None: + """``mem import`` cannot recover exit codes, so it contributes nothing. + + Asserted in both directions: a ``None`` must not be read as a failure + *or* as a success, because either reading would fabricate evidence out + of a file that recorded none. + """ + assert ( + mined( + [cmd("npm run buld", NOW - 30, None), cmd("npm run build", NOW - 28, 0)] + ) + == {} + ) + assert ( + mined( + [cmd("npm run buld", NOW - 30, 1), cmd("npm run build", NOW - 28, None)] + ) + == {} + ) + + def test_a_command_that_succeeds_unchanged_is_a_flake_not_a_fix(self) -> None: + """ "Run it again" is not advice, and it ends the search.""" + pairs = mined( + [ + cmd("terraform apply", NOW - 40, 1), + cmd("terraform apply", NOW - 35, 0), + cmd("terraform apply -refresh=false", NOW - 30, 0), + ] + ) + assert pairs == {} + + +class TestRanking: + """Several fixes for one failure: pick the best, and say why.""" + + def test_the_most_repeated_fix_wins(self) -> None: + """Repetition is the only evidence of correctness available.""" + commands = [] + for offset in (900, 800, 700): + commands += [ + cmd("npm run buld", NOW - offset, 1), + cmd("npm run build", NOW - offset + 4, 0), + ] + commands += [ + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build --if-present", NOW - 96, 0), + ] + + ranked = fix.fixes_for(fix.mine(commands), "npm run buld") + + assert [c.fix for c in ranked] == [ + "npm run build", + "npm run build --if-present", + ] + assert ranked[0].occurrences == 3 + # The winner is the older observation: repetition beats recency, and + # this is the case that proves the sort keys are in that order. + assert ranked[0].last_seen < ranked[1].last_seen + + def test_a_tie_on_repetition_is_broken_by_recency(self) -> None: + commands = [ + cmd("npm run buld", NOW - 900, 1), + cmd("npm run build", NOW - 896, 0), + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build --if-present", NOW - 96, 0), + ] + + ranked = fix.fixes_for(fix.mine(commands), "npm run buld") + + assert [c.fix for c in ranked] == [ + "npm run build --if-present", + "npm run build", + ] + + def test_a_fix_that_itself_later_failed_is_flagged_and_demoted(self) -> None: + """Still the best evidence available — but not silently so. + + The fix is reported, because a command that worked twice and has since + broken is genuinely what fixed this last time. Suppressing it would + answer "no idea" when mem does in fact know something. Reporting it + without the caveat would be the dishonest option. + """ + commands = [ + cmd("npm run buld", NOW - 900, 1), + cmd("npm run build", NOW - 896, 0), + cmd("npm run buld", NOW - 800, 1), + cmd("npm run build --if-present", NOW - 796, 0), + # The winner has since started failing on its own. + cmd("npm run build", NOW - 200, 1), + cmd("npm run build", NOW - 100, 1), + ] + + ranked = fix.fixes_for(fix.mine(commands), "npm run buld") + by_command = {c.fix: c for c in ranked} + + assert by_command["npm run build"].fix_failures == 2 + assert by_command["npm run build --if-present"].fix_failures == 0 + # Equal occurrences, so the tie-break on "has it broken since?" runs + # before recency and puts the still-working fix first. + assert ranked[0].fix == "npm run build --if-present" + + def test_confidence_wording_tracks_the_count(self) -> None: + assert fix.confidence(1) == "weak" + assert fix.confidence(2) == "moderate" + assert fix.confidence(5) == "strong" + + +class TestCrossRepoMerge: + """A fix learned in one checkout is still the fix in another.""" + + def test_the_same_pair_from_two_repos_counts_twice(self) -> None: + left = fix.mine( + [ + cmd("docker ps", NOW - 900, 1, repo="/a", directory="/a"), + cmd("sudo docker ps", NOW - 896, 0, repo="/a", directory="/a"), + ] + ) + right = fix.mine( + [ + cmd("docker ps", NOW - 100, 1, repo="/b", directory="/b"), + cmd("sudo docker ps", NOW - 96, 0, repo="/b", directory="/b"), + ] + ) + + (merged,) = fix.merge(left + right) + + assert merged.occurrences == 2 + assert merged.first_seen == NOW - 900 + assert merged.last_seen == NOW - 100 + assert merged.repo == "/b" # attributed to the most recent sighting + + +class TestEmptyHistory: + """A machine with nothing captured must answer, not crash.""" + + def test_mining_an_empty_store_is_empty(self) -> None: + assert fix.mine_all() == ([], []) + assert list(fix.iter_histories()) == [] + + def test_build_report_on_an_empty_store(self) -> None: + report = fix.build_report() + assert report.failure is None + assert report.fixes == [] + + def test_the_command_says_so_plainly(self) -> None: + assert "No failed commands captured yet" in run_fix() + + def test_a_query_matching_nothing_says_so_plainly(self) -> None: + write_history([cmd("git status", NOW - 10, 0)]) + assert "No failed command matching" in run_fix("kubectl") + + def test_an_empty_command_line_is_not_paired(self) -> None: + """Blank and whitespace-only lines reach the store; they match nothing.""" + assert not fix.is_plausible_correction("", "git status", 1) + assert not fix.is_plausible_correction("git status", " ", 1) + + def test_unbalanced_quotes_do_not_crash_the_tokenizer(self) -> None: + """Half-typed lines are ordinary in a shell history.""" + assert fix.normalized_tokens("echo 'unterminated") == ("echo", "'unterminated") + + +# --- selection ------------------------------------------------------------- + + +class TestFailureSelection: + """Which failure ``mem fix`` is about.""" + + def test_the_most_recent_failure_is_chosen(self) -> None: + failures = [ + cmd("old-thing", NOW - 5000, 2), + cmd("new-thing", NOW - 10, 1), + ] + assert fix.select_failure(failures).command == "new-thing" + + def test_the_current_repo_is_preferred_over_a_newer_failure_elsewhere(self) -> None: + """Someone typing ``mem fix`` has just broken something *here*.""" + failures = [ + cmd("local-thing", NOW - 5000, 1, repo="/here"), + cmd("other-thing", NOW - 10, 1, repo="/elsewhere"), + ] + chosen = fix.select_failure(failures, current_repo="/here") + assert chosen.command == "local-thing" + + def test_it_falls_back_to_the_whole_store_outside_a_known_repo(self) -> None: + failures = [cmd("other-thing", NOW - 10, 1, repo="/elsewhere")] + assert fix.select_failure(failures, current_repo="/here").command == ( + "other-thing" + ) + + def test_every_query_word_must_match(self) -> None: + failures = [ + cmd("npm run build", NOW - 20, 1), + cmd("npm run test", NOW - 10, 1), + ] + assert fix.select_failure(failures, query="npm build").command == ( + "npm run build" + ) + assert fix.select_failure(failures, query="npm missing") is None + + +# --- the command ----------------------------------------------------------- + + +class TestFixCommand: + """End-to-end through Click, against a real history file.""" + + def test_it_reports_the_failure_the_fix_and_the_evidence(self) -> None: + commands = [] + for offset in (900, 800, 700): + commands += [ + cmd("npm run buld", NOW - offset, 1), + cmd("npm run build", NOW - offset + 4, 0), + ] + write_history(commands) + + output = run_fix() + + assert "npm run buld" in output + assert "npm run build" in output + assert "seen 3 times" in output + assert "exit 1" in output + + def test_one_observation_is_reported_as_one_observation(self) -> None: + """A pair seen once is a different claim from a pair seen five times.""" + write_history( + [ + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build", NOW - 96, 0), + ] + ) + + output = run_fix() + + assert "seen once" in output + assert "one observation only" in output + + def test_a_failure_with_no_known_fix_says_so_without_inventing_one(self) -> None: + write_history( + [ + cmd("terraform apply", NOW - 100, 1), + cmd("git status", NOW - 96, 0), + ] + ) + + output = run_fix() + + assert "terraform apply" in output + assert "no record of anything fixing this" in output + assert "git status" not in output + + def test_a_fix_that_has_since_broken_carries_a_warning(self) -> None: + write_history( + [ + cmd("npm run buld", NOW - 900, 1), + cmd("npm run build", NOW - 896, 0), + cmd("npm run build", NOW - 100, 1), + ] + ) + + output = run_fix("buld") + + assert "npm run build" in output + assert "failed 1 time since" in output + + def test_runner_up_fixes_are_listed_below_the_winner(self) -> None: + commands = [] + for offset in (900, 800): + commands += [ + cmd("npm run buld", NOW - offset, 1), + cmd("npm run build", NOW - offset + 4, 0), + ] + commands += [ + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build --if-present", NOW - 96, 0), + ] + write_history(commands) + + output = run_fix("buld") + + assert output.index("fixed by") < output.index("also") + assert "npm run build --if-present" in output + + def test_it_never_offers_to_run_anything(self) -> None: + """The output is text to read. That is the whole safety model.""" + write_history( + [ + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build", NOW - 96, 0), + ] + ) + + output = run_fix() + + assert "does not run it for you" in output + + def test_the_module_cannot_execute_anything(self) -> None: + """Pinned structurally: the capability is simply not imported. + + The dangerous future change is someone adding ``subprocess.run(fix)`` + for convenience. This fails the moment the import appears, which is + earlier and louder than any behavioural assertion. + """ + import ast + + tree = ast.parse(Path(fix.__file__).read_text(encoding="utf-8")) + imported: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + imported.add(node.module.split(".")[0]) + + assert not imported & {"subprocess", "os", "pty", "ctypes"} + + +class TestJsonOutput: + """``--json`` is the contract other tools read.""" + + def test_the_payload_carries_the_evidence(self) -> None: + write_history( + [ + cmd("npm run buld", NOW - 900, 1), + cmd("npm run build", NOW - 896, 0), + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build", NOW - 96, 0), + ] + ) + + payload = json.loads(run_fix("--json")) + + assert payload["failure"]["command"] == "npm run buld" + assert payload["failure"]["exit_code"] == 1 + assert payload["count"] == 1 + assert payload["fixes"][0] == { + "command": "npm run build", + "occurrences": 2, + "confidence": "moderate", + "first_seen": NOW - 900, + "last_seen": NOW - 100, + "last_seen_iso": payload["fixes"][0]["last_seen_iso"], + "failed_since": 0, + "repo": REPO, + } + + def test_an_empty_store_is_a_well_formed_answer_not_an_error(self) -> None: + payload = json.loads(run_fix("--json")) + assert payload == {"query": None, "failure": None, "count": 0, "fixes": []} + + def test_the_limit_caps_the_number_of_fixes(self) -> None: + commands = [ + cmd("npm run buld", NOW - 900, 1), + cmd("npm run build", NOW - 896, 0), + cmd("npm run buld", NOW - 500, 1), + cmd("npm run build --if-present", NOW - 496, 0), + cmd("npm run buld", NOW - 100, 1), + cmd("npm run build --silent", NOW - 96, 0), + ] + write_history(commands) + + assert len(json.loads(run_fix("--json", "-n", "1"))["fixes"]) == 1 + assert len(json.loads(run_fix("--json"))["fixes"]) == 3 + + +class TestRedaction: + """History is where credentials end up. mem fix quotes history back.""" + + SECRET = "sk-ant-abcdefghijklmnopqrstuvwx" + + def _plant_secret(self) -> None: + failed = f"curl -H 'Authorization: Bearer {self.SECRET}' https://api.example" + write_history( + [ + cmd(failed, NOW - 100, 7), + cmd(f"{failed} --retry 3", NOW - 96, 0), + ] + ) + + def test_a_credential_in_the_failure_is_redacted(self) -> None: + self._plant_secret() + output = run_fix() + assert self.SECRET not in output + assert "[REDACTED]" in output + + def test_a_credential_in_the_fix_is_redacted(self) -> None: + self._plant_secret() + output = run_fix() + assert "--retry 3" in output # the useful part survives + assert output.count(self.SECRET) == 0 + + def test_json_output_is_redacted_too(self) -> None: + """Both renderings read the same payload, so neither can be forgotten.""" + self._plant_secret() + assert self.SECRET not in run_fix("--json") + + def test_redaction_happens_in_the_payload_not_the_renderer(self) -> None: + """One choke point, so a future output format inherits it. + + Asserted against ``report_payload`` directly: if redaction moved into + the CLI's printing code, a second consumer of this function would + silently start leaking. + """ + self._plant_secret() + payload = fix.report_payload(fix.build_report()) + assert self.SECRET not in json.dumps(payload) + + +class TestRichMarkupSafety: + """A command containing Rich markup must render as itself. + + mem has already crashed once on a captured ``[/]``. ``mem fix`` prints + commands more prominently than anything else in the CLI, so it gets its + own regression test rather than trusting that render.py is used correctly. + """ + + def test_bracket_syntax_in_a_command_survives_verbatim(self) -> None: + write_history( + [ + cmd("sed 's/[a-z]//' fil", NOW - 100, 1), + cmd("sed 's/[a-z]//' file", NOW - 96, 0), + ] + ) + + output = run_fix() + + assert "sed 's/[a-z]//' file" in output + + def test_a_bare_closing_tag_does_not_raise(self) -> None: + write_history( + [ + cmd("awk '{print [/]}' fil", NOW - 100, 1), + cmd("awk '{print [/]}' file", NOW - 96, 0), + ] + ) + + output = run_fix() + + assert "[/]" in output + + +# --- the extraction shared with mem.mcp ------------------------------------ + + +class TestSharedScan: + """``mem.mcp.recent_failures`` mines the same facts through these helpers. + + Tested here rather than only through MCP because the point of the + extraction is that there is *one* definition of "a failure and what came + after it". A second copy would drift, which this codebase has paid for + twice already. + """ + + def test_iter_histories_yields_files_in_capture_order(self) -> None: + write_history([cmd("first", NOW - 30, 0), cmd("second", NOW - 20, 0)]) + + ((key, commands),) = list(fix.iter_histories()) + + assert key == "work-api" + assert [c.command for c in commands] == ["first", "second"] + + def test_iter_histories_honours_the_include_predicate(self) -> None: + write_history([cmd("a", NOW, 0)], key="repo-a") + write_history([cmd("b", NOW, 0)], key="repo-b") + + keys = [key for key, _ in fix.iter_histories(lambda stem: stem == "repo-b")] + + assert keys == ["repo-b"] + + def test_iter_failures_attaches_the_following_commands(self) -> None: + commands = [ + cmd("boom", NOW - 30, 2), + cmd("look", NOW - 28, 0), + cmd("fix", NOW - 26, 0), + cmd("later", NOW - 24, 0), + ] + + (failure,) = list(fix.iter_failures(commands, lookahead=2)) + + assert failure.index == 0 + assert failure.command.command == "boom" + assert [c.command for c in failure.following] == ["look", "fix"] + + def test_iter_failures_ignores_commands_with_no_exit_code(self) -> None: + """The shared definition of "failure" excludes imported lines. + + ``exit_code is None`` is not a failure and not a success. Reporting it + as either — which a naive ``!= 0`` test does — invents a fact. + """ + commands = [cmd("imported", NOW - 30, None), cmd("real", NOW - 20, 1)] + + assert [f.command.command for f in fix.iter_failures(commands)] == ["real"] + + def test_mcp_recent_failures_still_works_through_the_shared_scan(self) -> None: + """The extraction must not have changed the MCP tool's answer.""" + from mem import mcp + + write_history( + [ + cmd("pytest -q", NOW - 300, 1), + cmd("pip install -e '.[dev]'", NOW - 290, 0), + cmd("pytest -q", NOW - 280, 0), + ] + ) + + payload = mcp._tool_recent_failures({}) + + assert payload["count"] == 1 + failure = payload["failures"][0] + assert failure["command"] == "pytest -q" + assert [f["command"] for f in failure["followed_by"]] == [ + "pip install -e '.[dev]'", + "pytest -q", + ] + assert failure["retried_successfully"] is True