Skip to content

feat(fix): the one question only mem can answer — what fixed this last time - #24

Merged
matinsaurralde merged 1 commit into
masterfrom
feat/17-mem-fix
Aug 4, 2026
Merged

matinsaurralde merged 1 commit into
masterfrom
feat/17-mem-fix

Conversation

@matinsaurralde

Copy link
Copy Markdown
Owner

thefuck has 97,500 stars — the largest repo in this entire category — correcting shell mistakes with hand-written rules and no access to your history. atuin and mcfly have your history and correct nothing.

mem is the only tool holding both pieces: exit_code, temporal sequence and session grouping, captured since day one and until now never read by anything.

$ mem fix

  failed   apt install jq
           exit 1 · 10m ago · /w

  fixed by sudo apt install jq
           seen once · last worked 10m ago · one observation only

           mem does not run it for you. Read it, then decide.

The finding that decided the design

The obvious approach is "if Y is similar enough to X, it is the fix." That approach is not merely imprecise — it is inverted. Measured with difflib.SequenceMatcher:

pair ratio is it a fix?
pytest test_a.py → pytest test_b.py 0.94 no
kubectl delete pod x → kubectl delete pod y 0.95 no
git psuh → git push 0.88 yes
apt install htop → sudo apt install htop 0.86 yes
mkdir a/b → mkdir -p a/b 0.86 yes

The non-corrections score higher than the corrections, so no threshold exists that separates them. A first implementation using a ratio scored 9 false positives out of 20 and was thrown out.

Corrections are instead matched by edit shape: additions are free, deletions are flags-only, and at most one token may differ — and only as a transposition or a ≤2-character insertion/deletion. On 40 hand-built realistic pairs: 19/20 recall, 0/20 false positives. The 14 adversarial rejections are pinned as parametrised tests, and so is the similarity inversion itself, so anyone reaching for SequenceMatcher.ratio trips over the measurement first.

Verified end to end: given pytest test_a.py (failed) followed by pytest test_b.py (succeeded) five seconds later — a 0.94 similarity match — mem fix pytest answers "mem has no record of anything fixing this."

The other thresholds, and why

  • 60-second window, measured as think time (y.ts - y.duration_ms - x.ts). mem timestamps completion, so a naive window drops a four-minute docker build that never left it.
  • Lookahead 3. People ls or cat before fixing; 1 loses that, 20 crowns a stranger.
  • Both exit codes explicit. None is not success — so imported shell history, which has no exit codes, is invisible to this. Documented rather than hidden.
  • Same session when both have one, otherwise same directory: two terminal tabs interleave in one file.
  • Same program after stripping sudo/doas — this is what mines apt install x → sudo apt install x. The single exception is exit 127, the only code that proves argv[0] itself was the mistake.

Confidence is reported, not implied

A pair seen five times is a different claim from one seen once, and the output says which. When there is no evidence it says so plainly rather than inventing a suggestion.

It never executes anything. The finder made the same call for the same reason: a tool that runs commands on your behalf is how people delete the wrong branch.

Shared mining, not a second copy

iter_histories() and iter_failures() live in fix.py; mcp._tool_recent_failures now calls them. All 166 MCP tests pass unchanged. One behaviour change falls out of the shared definition: a None exit code is no longer reported as a failure, because it never was one.

This mattered — duplicated logic has already caused two separate defects in this codebase (a stale shell hook served to every pip user, and a ranking formula that could have diverged between two call sites).

Tests

1198 passed (master: 1103), 89% branch coverage (was 87%), fix.py at 100%.

Not done

The optional Apple FM second stage. The rule is binary, so there is no borderline band to hand a model, and there is no way to validate its judgement here — shipping an unmeasured non-deterministic judge would undercut the "heuristic first" ordering this was built under.

Single documented miss: git push → git pull --rebase.

…t time

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.
@matinsaurralde
matinsaurralde merged commit 17b5361 into master Aug 4, 2026
5 checks passed
@matinsaurralde
matinsaurralde deleted the feat/17-mem-fix branch August 4, 2026 05:11

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5f083b4b8b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/mem/fix.py
Comment on lines +466 to +468
if failed.session and candidate.session:
return failed.session == candidate.session
return failed.dir == candidate.dir

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Populate session IDs before relying on them

Every hook-captured command currently gets constructed without a session value in src/mem/capture.py:56-63, so in production both values are always absent and this function falls back to comparing directories. Commands from two terminal tabs in the same working directory therefore pass the terminal check; for example, a failure of npm run buld in one tab can be paired with npm run build run independently in another, despite the README promising same-terminal matching.

Useful? React with 👍 / 👎.

Comment thread src/mem/fix.py
Comment on lines +361 to +363
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "equal" or tag == "insert":
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject shell operators that manufacture a zero exit code

Treating every insertion as admissible accepts commands such as pytest || true or npm test ; true as fixes for their failing prefixes. shlex exposes the operator and trailing command as inserted tokens, while the recorded exit code is zero only because true masks the original failure, so mem fix can confidently recommend suppressing an error rather than fixing it.

Useful? React with 👍 / 👎.

Comment thread src/mem/fix.py
Comment on lines +559 to +560
pairs.setdefault((failure.command.command, fix.command), []).append(
failure.command

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Count each successful correction only once

When the same bad command fails repeatedly before one corrected command succeeds, each preceding failure whose lookahead reaches that single success appends the same pair. For example, npm run buld failing three times followed by one npm run build success produces three occurrences and therefore “strong” confidence, even though only one correction was observed; this overstates the primary evidence used for ranking and display.

Useful? React with 👍 / 👎.

Comment thread src/mem/fix.py
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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recompute failures after the globally latest success

Summing per-repository fix_failures retains failures that occurred before a newer successful pairing in another repository. If repo A observes the pair, then the fix fails there, and repo B later observes the same pair succeeding, the merged correction still reports that it “failed since” the latest observation and may be incorrectly demoted, even though the failure predates the globally latest success.

Useful? React with 👍 / 👎.

Comment thread src/mem/fix.py
Comment on lines +529 to +530
if _think_seconds(failure.command, candidate) > WINDOW_SECONDS:
break # the window only widens from here

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep scanning for long-running candidates

The assumption that think time only widens is invalid because _think_seconds subtracts each candidate's independently varying duration. With interleaved history, a short command from another terminal can finish 70 seconds after the failure and trigger this break, while the next entry is a four-minute correction that started five seconds after the failure and therefore remains inside the intended window; the advertised support for long-running fixes is lost in this case.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant