Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
112 changes: 112 additions & 0 deletions src/mem/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading