From 9aa08a823d7f2722779987dcccc975b396e5a6be Mon Sep 17 00:00:00 2001
From: Matias
Date: Thu, 24 Sep 2026 03:49:28 -0300
Subject: [PATCH 1/8] fix(capture): mem recorded its own invocations, so a
repeated search answered itself
The shell hooks hand every typed line to `mem _capture`, mem's own included,
and nothing filtered them. Three silent failures followed, all exit code 0:
- Asking a question twice matched the first asking on every word. The literal
pass answered with it and the concept map never ran, so the README's own
example, `mem "how do I see what's listening on a port"` -> `lsof -i :8080`,
worked at most once per question.
- `mem forget "API_KEY=sk-..."` deleted the key, then the hook captured the
line that deleted it and wrote the secret back. `mem run api TOKEN=...` and
`mem vars set NAME value` stored their secrets the same way.
- After one session following the README, 118 of 218 records were mem itself.
`ranking.canonical()` now decides what a command is: surrounding whitespace
removed, so `ls` and `ls ` stop being two results with half the frequency
each, and mem's own invocations rejected. It is applied at capture, on every
read (`storage.read_commands` and the finder's `parse_entry`, so stores written
by 0.5.1 are cleaned without rewriting them), in the shell-history import, and
in `mem save '!'`. It lives in ranking.py because the finder cannot import
Pydantic.
The new end-to-end test replays the reported transcript in real zsh and bash
sessions. It and every new unit test failed before this change.
---
src/mem/capture.py | 14 ++++---
src/mem/groups.py | 28 +++++++-------
src/mem/history.py | 6 ++-
src/mem/ranking.py | 30 +++++++++++++++
src/mem/storage.py | 15 +++++++-
src/mem/tui.py | 5 ++-
tests/test_capture.py | 42 +++++++++++++++++++++
tests/test_groups.py | 12 ++++++
tests/test_hooks_e2e.py | 41 +++++++++++++++++++++
tests/test_import.py | 11 ++++++
tests/test_search.py | 81 +++++++++++++++++++++++++++++++++++++++++
tests/test_tui.py | 23 ++++++++++++
12 files changed, 283 insertions(+), 25 deletions(-)
diff --git a/src/mem/capture.py b/src/mem/capture.py
index 11af8d7..c77e847 100644
--- a/src/mem/capture.py
+++ b/src/mem/capture.py
@@ -14,7 +14,7 @@
import uuid
from mem.models import CapturedCommand, SessionState, WorkSession
-from mem import storage
+from mem import ranking, storage
# Idle seconds that end a work session. The one definition: `mem promote`
# re-derives sessions from the command files (ADR-012) and imports this rather
@@ -83,15 +83,17 @@ def capture_command(raw: str, directory: str, exit_code: int, duration_ms: int)
Builds a CapturedCommand with the current timestamp and git repo,
then appends it to the appropriate JSONL file.
- Terminal noise is dropped before anything runs — no repo lookup, no
- session update, no sync counter — and silently, like every other skip in
- the capture path (`mem _capture` never prints and always exits 0).
+ Terminal noise and whatever :func:`mem.ranking.canonical` rejects are
+ dropped before anything runs — no repo lookup, no session update, no sync
+ counter — and silently, like every other skip in the capture path
+ (`mem _capture` never prints and always exits 0).
"""
- if looks_like_terminal_noise(raw):
+ command = ranking.canonical(raw)
+ if command is None or looks_like_terminal_noise(command):
return
repo = get_git_repo(directory)
cmd = CapturedCommand(
- command=raw,
+ command=command,
ts=int(time.time()),
dir=directory,
repo=repo,
diff --git a/src/mem/groups.py b/src/mem/groups.py
index c68e0f1..8216697 100644
--- a/src/mem/groups.py
+++ b/src/mem/groups.py
@@ -21,7 +21,7 @@
import click
-from mem import storage
+from mem import ranking, storage
from mem.capture import get_git_repo
from mem.models import Group, GroupCommand, GroupFile, SavedCommand, VarDeclaration
from mem.variables import (
@@ -139,25 +139,23 @@ def get_last_captured_command(repo: str | None) -> str:
"""
path = storage.repo_file(storage.resolve_repo_key(repo))
- if not path.exists():
+ found, last = False, None
+ if path.exists():
+ with path.open("r", encoding="utf-8") as f:
+ for _line, data in storage.iter_jsonl_objects(f):
+ raw = data.get("command") if isinstance(data, dict) else None
+ command = ranking.canonical(raw) if isinstance(raw, str) else None
+ if isinstance(raw, str) and command is None:
+ continue # mem's own invocation, recorded by an older version
+ found, last = True, command
+
+ if not found:
raise click.ClickException(
"No captured history found. Run some commands first."
)
-
- last: tuple[str, dict | None] | None = None
- with path.open("r", encoding="utf-8") as f:
- for last in storage.iter_jsonl_objects(f):
- pass
-
if last is None:
- raise click.ClickException(
- "No captured history found. Run some commands first."
- )
-
- _line, data = last
- if data is None or "command" not in data:
raise click.ClickException("Could not read last command from history.")
- return data["command"]
+ return last
def list_all(repo_path: Path | None, global_path: Path) -> dict:
diff --git a/src/mem/history.py b/src/mem/history.py
index 73c491f..32468a0 100644
--- a/src/mem/history.py
+++ b/src/mem/history.py
@@ -35,7 +35,7 @@
from dataclasses import dataclass, field
from pathlib import Path
-from mem import storage
+from mem import ranking, storage
from mem.models import CapturedCommand
from mem.variables import looks_like_credential
@@ -543,6 +543,10 @@ def build_plan(sources: list[tuple[str, Path]]) -> ImportPlan:
resolve_timestamps(parsed.entries, path)
for entry in parsed.entries:
+ command = ranking.canonical(entry.command)
+ if command is None:
+ continue
+ entry.command = command
if looks_like_credential(entry.command):
file_plan.credentials += 1
continue
diff --git a/src/mem/ranking.py b/src/mem/ranking.py
index f4a6235..c37e2a4 100644
--- a/src/mem/ranking.py
+++ b/src/mem/ranking.py
@@ -17,6 +17,7 @@
from __future__ import annotations
import math
+import os
from collections.abc import Sequence
from mem import picks
@@ -145,6 +146,35 @@ def matches(command: str, query_terms: Sequence[str]) -> bool:
return all(term in lowered for term in query_terms)
+# --- what counts as history --------------------------------------------------
+#
+# Capture, storage, the finder and import all decide what a command is, and the
+# finder cannot import Pydantic, so the rule lives here beside `matches`.
+
+
+def canonical(command: str) -> str | None:
+ """The command as history stores and compares it, or None if it is not history.
+
+ Surrounding whitespace is dropped, so ``ls`` and ``ls `` are one command.
+ mem's own invocations are not history: recording them made a repeated search
+ answer itself, and wrote ``mem forget SECRET`` back to disk as it deleted it.
+ """
+ command = command.strip()
+ if not command or _runs_mem(command):
+ return None
+ return command
+
+
+def _runs_mem(command: str) -> bool:
+ """True when the first word, after any NAME=value prefixes, is mem."""
+ for word in command.split():
+ name, equals, _ = word.partition("=")
+ if equals and name.isidentifier():
+ continue
+ return os.path.basename(word) == "mem"
+ return False
+
+
def score(
command: str,
ts: int | float,
diff --git a/src/mem/storage.py b/src/mem/storage.py
index d25b952..e58bb64 100644
--- a/src/mem/storage.py
+++ b/src/mem/storage.py
@@ -27,7 +27,7 @@
from pathlib import Path
from typing import Callable, Iterable, Iterator, NamedTuple, Sequence
-from mem import _fsutil, keychain
+from mem import _fsutil, keychain, ranking
from mem._fsutil import FILE_MODE, atomic_write
from mem._fsutil import fsync_dir as _fsync_dir
from mem._fsutil import harden_dir as _harden_dir
@@ -537,6 +537,10 @@ def read_commands(
:func:`prefilter_needles`; a line missing any of them is skipped without
being parsed. Callers that want every command leave it unset.
+ Every reader goes through here, so :func:`mem.ranking.canonical` is
+ applied on read as well as on capture: stores written before it existed
+ hold mem's own invocations and untrimmed commands.
+
``line_filter`` is the same optimisation for a caller whose test is not
"every needle present" — query expansion needs "*any* of these forty",
which no list of needles can express here, because ``needles`` are ANDed.
@@ -560,7 +564,7 @@ def read_commands(
if not all(needle in lowered for needle in needles):
continue
try:
- yield CapturedCommand.from_jsonl(line)
+ cmd = CapturedCommand.from_jsonl(line)
# Pydantic's ValidationError subclasses ValueError, so this covers
# both a line that is not JSON and one that is JSON of the wrong
# shape — and nothing else, which is the point.
@@ -569,6 +573,13 @@ def read_commands(
f"warning: skipping corrupted line {line_num} in {path.name}",
file=sys.stderr,
)
+ continue
+ command = ranking.canonical(cmd.command)
+ if command is None:
+ continue
+ if command != cmd.command:
+ cmd = cmd.model_copy(update={"command": command})
+ yield cmd
def read_all_commands() -> Iterator[CapturedCommand]:
diff --git a/src/mem/tui.py b/src/mem/tui.py
index 26fc700..616eba6 100644
--- a/src/mem/tui.py
+++ b/src/mem/tui.py
@@ -164,7 +164,10 @@ def parse_entry(line: str) -> Entry | None:
# reachable in a hand-edited file, which is exactly why it is checked.
return None
command = record.get("command")
- if not isinstance(command, str) or not command:
+ if not isinstance(command, str):
+ return None
+ command = ranking.canonical(command)
+ if command is None:
return None
ts = record.get("ts")
if not isinstance(ts, (int, float)):
diff --git a/tests/test_capture.py b/tests/test_capture.py
index dc9839d..9074a71 100644
--- a/tests/test_capture.py
+++ b/tests/test_capture.py
@@ -656,3 +656,45 @@ def test_spawn_background_sync_is_detached_and_silent(self):
assert kwargs["stdout"] is subprocess.DEVNULL
assert kwargs["stderr"] is subprocess.DEVNULL
assert kwargs["start_new_session"] is True
+
+
+class TestMemDoesNotRecordItself:
+ """The hook hands every line to ``mem _capture``, including mem's own.
+
+ Recording them made every repeated search answer itself, and it re-wrote
+ secrets straight back into history: ``mem forget "API_KEY=sk-…"`` deleted
+ the key, and the hook then captured the line that deleted it.
+ """
+
+ @pytest.mark.parametrize(
+ ("raw", "secret"),
+ [
+ ('mem forget "API_KEY=sk-test123"', "sk-test123"),
+ ("mem vars set TOKEN hunter2-value", "hunter2-value"),
+ ("mem run api API_TOKEN=abc123-value", "abc123-value"),
+ ('mem "check disk space"', "check disk space"),
+ ],
+ )
+ def test_an_invocation_of_mem_is_written_nowhere(self, tmp_mem_dir, raw, secret):
+ with (
+ patch("mem.capture.get_git_repo", return_value=None),
+ patch("mem.capture._spawn_background_sync"),
+ ):
+ capture_command(raw, "/tmp", 0, 5)
+
+ leaked = [
+ path
+ for path in storage.MEM_DIR.rglob("*")
+ if path.is_file() and secret in path.read_text(errors="replace")
+ ]
+ assert leaked == []
+ assert storage.read_sync_counter() == 0
+
+ def test_surrounding_whitespace_is_not_part_of_the_command(self, tmp_mem_dir):
+ with (
+ patch("mem.capture.get_git_repo", return_value=None),
+ patch("mem.capture._spawn_background_sync"),
+ ):
+ capture_command("ls ", "/tmp", 0, 5)
+
+ assert [c.command for c in storage.read_all_commands()] == ["ls"]
diff --git a/tests/test_groups.py b/tests/test_groups.py
index e1e4054..dce60d5 100644
--- a/tests/test_groups.py
+++ b/tests/test_groups.py
@@ -2452,3 +2452,15 @@ def test_init_unsupported_shell(self):
for shell in ("zsh", "bash", "fish"):
assert shell in result.output
assert "_mem_preexec" not in result.output
+
+
+class TestSaveLastCommandSkipsMem:
+ """``mem save '!'`` means the last command you ran, not a mem invocation."""
+
+ def test_an_earlier_invocation_of_mem_is_skipped(self, tmp_mem_dir):
+ from conftest import make_command
+
+ for command in ["docker ps", "mem ls"]:
+ storage.append_command(make_command(command=command, repo=None))
+
+ assert groups.get_last_captured_command(None) == "docker ps"
diff --git a/tests/test_hooks_e2e.py b/tests/test_hooks_e2e.py
index 80aeb79..688b5c2 100644
--- a/tests/test_hooks_e2e.py
+++ b/tests/test_hooks_e2e.py
@@ -1141,6 +1141,47 @@ def test_hook_does_not_delay_the_prompt(
# --- Isolation guard ---------------------------------------------------------
+class TestMemDoesNotRecordItself:
+ """The user's own transcript, replayed in a real hooked shell.
+
+ Ask a question, run the command that answers it, ask again. Under 0.5.1 the
+ second answer was the first question: the hook had recorded it, it matched
+ every word literally, and the concept map never got a turn.
+ """
+
+ @pytest.mark.parametrize(
+ "shell",
+ [
+ pytest.param("zsh", marks=requires_zsh),
+ pytest.param("bash", marks=requires_bash),
+ ],
+ )
+ def test_asking_twice_still_answers_the_question(
+ self,
+ shell: str,
+ hook_files: dict[str, Path],
+ shell_home: Path,
+ shell_cwd: Path,
+ ) -> None:
+ _run_shell(
+ shell,
+ ['mem "check disk space"', "du -sh ."],
+ shell_home,
+ shell_cwd,
+ hook_files,
+ )
+ _wait_for_command(shell_home, "du -sh .")
+ _wait_for_quiescence(shell_home)
+
+ second = _run_shell(
+ shell, ['mem "check disk space"'], shell_home, shell_cwd, hook_files
+ )
+
+ assert "du -sh ." in second.stdout
+ records = _wait_for_quiescence(shell_home)
+ assert [c for c in _commands(records) if c.startswith("mem")] == []
+
+
@requires_zsh
def test_harness_writes_only_inside_the_temporary_home(
hook_files: dict[str, Path], shell_home: Path, shell_cwd: Path
diff --git a/tests/test_import.py b/tests/test_import.py
index aa24f30..433fe71 100644
--- a/tests/test_import.py
+++ b/tests/test_import.py
@@ -1158,3 +1158,14 @@ def test_appending_preserves_what_was_already_there(self) -> None:
storage.append_commands([make_command(command="later", repo=None)])
assert stored_commands() == ["earlier", "later"]
+
+
+class TestMemIsNotItsOwnHistory:
+ """A shell's history file holds every ``mem …`` the user ever typed."""
+
+ def test_invocations_of_mem_are_not_imported(self, home: Path) -> None:
+ path = zsh_history(home, "mem docker\nls -la\nmem forget sk-test123\n")
+
+ plan = history.build_plan([("zsh", path)])
+
+ assert [cmd.command for cmd in plan.files[0].commands] == ["ls -la"]
diff --git a/tests/test_search.py b/tests/test_search.py
index 2606977..5786374 100644
--- a/tests/test_search.py
+++ b/tests/test_search.py
@@ -553,3 +553,84 @@ def test_empty_query_returns_empty(self, tmp_mem_dir):
def test_no_match_returns_empty(self, tmp_mem_dir):
storage.append_session(self._session("s1", 1700000000, "work", ["ls"]))
assert search.search_sessions("kubernetes") == []
+
+
+class TestMemIsNotItsOwnHistory:
+ """mem's own invocations are not history, and whitespace is not a difference.
+
+ Found by following the README in a real hooked shell. The hook recorded
+ every ``mem …`` line, so asking a question a second time matched the
+ recorded question on every word: the literal pass answered with it, the
+ concept map never ran, and "what's listening on a port" was answered with
+ the question itself. A store written by 0.5.1 already holds those rows, so
+ they are skipped when read as well as no longer written.
+ """
+
+ QUESTION = "how do I see what's listening on a port"
+
+ @pytest.mark.parametrize(
+ ("command", "expected"),
+ [
+ ("mem", None),
+ ("mem docker", None),
+ ('mem "how do I see it"', None),
+ ("/opt/homebrew/bin/mem ls", None),
+ ("MEM_DEBUG=1 mem stats", None),
+ (" mem ls", None),
+ (" ", None),
+ ("ls ", "ls"),
+ ("memo list", "memo list"),
+ ("echo mem", "echo mem"),
+ ("git commit -m 'mem fix'", "git commit -m 'mem fix'"),
+ ("vim ~/.mem/concepts.json", "vim ~/.mem/concepts.json"),
+ ("FOO=1", "FOO=1"),
+ ],
+ )
+ def test_what_counts_as_history(self, command, expected):
+ assert search.ranking.canonical(command) == expected
+
+ def test_asking_twice_still_reaches_the_concept_map(self, tmp_mem_dir):
+ """The user's transcript, as the 0.5.1 hook stored it."""
+ now = int(time.time())
+ for offset, command, exit_code in [
+ (30, f'mem "{self.QUESTION}"', 0),
+ (20, "lsof -i :8080", 1),
+ (10, f'mem "{self.QUESTION}"', 0),
+ ]:
+ storage.append_command(
+ make_command(
+ command=command,
+ ts=now - offset,
+ repo=None,
+ dir="/Users/test",
+ exit_code=exit_code,
+ )
+ )
+
+ results = search.search(self.QUESTION)
+
+ assert [cmd.command for cmd, _ in results] == ["lsof -i :8080"]
+
+ def test_a_search_never_returns_an_earlier_search(self, tmp_mem_dir):
+ for command in ["mem docker compose", "docker compose up -d"]:
+ storage.append_command(make_command(command=command, repo=None))
+
+ results = search.search("docker compose")
+
+ assert [cmd.command for cmd, _ in results] == ["docker compose up -d"]
+
+ def test_whitespace_variants_are_one_result_with_their_runs_summed(
+ self, tmp_mem_dir, frozen_clock
+ ):
+ """`ls` and `ls ` were two rows, each with half the frequency."""
+ for command in ["ls", "ls ", "ls"]:
+ storage.append_command(
+ make_command(command=command, ts=frozen_clock, repo=None)
+ )
+
+ results = search.search("ls")
+
+ assert [cmd.command for cmd, _ in results] == ["ls"]
+ assert results[0][1] == pytest.approx(
+ expected_score(frequency=3, recency=1.0, prefix=1.0, context=0.0)
+ )
diff --git a/tests/test_tui.py b/tests/test_tui.py
index 99f3c84..a51b0b9 100644
--- a/tests/test_tui.py
+++ b/tests/test_tui.py
@@ -1086,3 +1086,26 @@ def test_anything_else_goes_to_the_full_cli(self, monkeypatch, capsys):
assert exit_info.value.code == 0
assert capsys.readouterr().out.startswith("mem, version ")
+
+
+class TestMemIsNotItsOwnHistory:
+ """The finder applies the same two rules as ``mem ``."""
+
+ def test_an_invocation_of_mem_is_not_a_candidate(self):
+ assert tui.parse_entry(line_of("mem kubectl")) is None
+
+ def test_whitespace_variants_are_one_row(self):
+ now = time.time()
+ lines = [line_of("ls", ts=int(now)), line_of("ls ", ts=int(now))]
+
+ results = tui.rank(lines, "ls", None, now)
+
+ assert [(r.entry.command, r.frequency) for r in results] == [("ls", 2)]
+
+ def test_the_empty_query_lists_no_invocation_of_mem(self):
+ now = int(time.time())
+ lines = [line_of("git status", ts=now - 1), line_of("mem git", ts=now)]
+
+ results = tui.rank(lines, "", None, float(now))
+
+ assert [r.entry.command for r in results] == ["git status"]
From f35d3545c2e0fe7d65f42f5ec00f59f3488d005e Mon Sep 17 00:00:00 2001
From: Matias
Date: Thu, 24 Sep 2026 03:50:41 -0300
Subject: [PATCH 2/8] fix(cli): the repo column printed a cut path, so every
repo looked the same
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Search, forget, session and stats listings printed the first characters of
the repo's absolute path. Every repo under a home directory rendered as
`/Users/mati…`, so the column that is meant to show which repo a command
came from could not tell any two apart, and never looked like the README's
`infra` / `backend` example.
`ranking.repo_name()` returns the repo's directory name, and every listing
uses it, including the finder, which already did this with its own copy. The
full path is unchanged in `--json`.
The test stores commands from two repos under one parent and checks both
names appear and no path does; it failed before this change.
---
src/mem/cli.py | 10 +++++-----
src/mem/ranking.py | 7 +++++++
src/mem/tui.py | 2 +-
tests/test_cli.py | 26 ++++++++++++++++++++++++++
4 files changed, 39 insertions(+), 6 deletions(-)
diff --git a/src/mem/cli.py b/src/mem/cli.py
index 4a124e7..37d5895 100644
--- a/src/mem/cli.py
+++ b/src/mem/cli.py
@@ -19,7 +19,7 @@
from rich.panel import Panel
from rich.text import Text
-from mem import __version__
+from mem import __version__, ranking
from mem import concepts as mem_concepts
from mem.capture import get_git_repo
from mem.history import SUPPORTED_SHELLS as IMPORTABLE_SHELLS
@@ -188,7 +188,7 @@ def cli(ctx: click.Context, pattern: bool, as_json: bool, limit: int) -> None:
# 16 the other tables use — were chosen by eye for an 80-column
# terminal, not measured.
command_text = fit(cmd.command, 40)
- repo_text = fit(cmd.repo or "global", 12)
+ repo_text = fit(ranking.repo_name(cmd.repo), 12)
time_text = _relative_time(cmd.ts)
console.print(
f"{rank} {safe(command_text)} [dim cyan]{safe(repo_text)}[/]"
@@ -364,7 +364,7 @@ def session(query: str, as_json: bool) -> None:
for i, s in enumerate(results, 1):
dt = datetime.fromtimestamp(s.started_at, tz=timezone.utc)
header = safe(
- f"[{i}] Session: {dt.strftime('%Y-%m-%d %H:%M')} {s.repo or 'global'}"
+ f"[{i}] Session: {dt.strftime('%Y-%m-%d %H:%M')} {ranking.repo_name(s.repo)}"
)
lines = []
@@ -439,7 +439,7 @@ def stats(as_json: bool) -> None:
if repo_freq:
console.print("Top repos:")
for i, (repo, count) in enumerate(repo_freq, 1):
- console.print(f" {i:>2} {safe(fit(repo, 20))} {count}")
+ console.print(f" {i:>2} {safe(fit(ranking.repo_name(repo), 20))} {count}")
def _fix_line(label: str, style: str, value: str) -> Text:
@@ -760,7 +760,7 @@ def forget(query: str, yes: bool) -> None:
# 20 rows of preview before the confirmation: chosen by eye, not
# measured. Column widths: see the search listing.
for i, cmd in enumerate(matches[:20], 1):
- repo_text = cmd.repo or "global"
+ repo_text = ranking.repo_name(cmd.repo)
time_text = _relative_time(cmd.ts)
console.print(
f" {i:>2} {safe(fit(cmd.command, 40))} [dim cyan]{safe(repo_text)}[/]"
diff --git a/src/mem/ranking.py b/src/mem/ranking.py
index c37e2a4..b4823bf 100644
--- a/src/mem/ranking.py
+++ b/src/mem/ranking.py
@@ -165,6 +165,13 @@ def canonical(command: str) -> str | None:
return command
+def repo_name(repo: str | None) -> str:
+ """How listings show a repo: its directory name, or ``global``."""
+ if not repo:
+ return "global"
+ return os.path.basename(repo.rstrip("/")) or repo
+
+
def _runs_mem(command: str) -> bool:
"""True when the first word, after any NAME=value prefixes, is mem."""
for word in command.split():
diff --git a/src/mem/tui.py b/src/mem/tui.py
index 616eba6..2ec865e 100644
--- a/src/mem/tui.py
+++ b/src/mem/tui.py
@@ -466,7 +466,7 @@ def _render_row(result: Result, is_selected: bool, columns: int, now: float) ->
"""
entry = result.entry
age = relative_time(entry.ts, now)
- repo = os.path.basename(entry.repo) if entry.repo else ""
+ repo = ranking.repo_name(entry.repo) if entry.repo else ""
# 22 columns for the metadata, or a third of the row when that is less:
# chosen by eye, not measured.
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 124cf13..02f692f 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -1038,3 +1038,29 @@ def test_copy_reports_a_failed_pbcopy(self) -> None:
),
):
assert _copy_to_clipboard("x") is False
+
+
+class TestSearchShowsTheRepo:
+ """The location column names the repo, as the README's example shows.
+
+ It printed the first eleven characters of the absolute path, so every repo
+ under a home directory rendered as ``/Users/mati…`` and the column could
+ not tell two repos apart.
+ """
+
+ def test_the_repo_is_shown_by_name(
+ self, tmp_mem_dir, runner: CliRunner, outside_repo: None
+ ) -> None:
+ for i, repo in enumerate(
+ ["/Users/someone/code/infra", "/Users/someone/code/backend"]
+ ):
+ storage.append_command(
+ make_command(command=f"kubectl get pods -n ns{i}", repo=repo, dir=repo)
+ )
+
+ result = runner.invoke(cli, ["kubectl"])
+
+ assert result.exit_code == 0
+ assert "infra" in result.stdout
+ assert "backend" in result.stdout
+ assert "/Users" not in result.stdout
From 4fa6a9f9dbcba04befef986ea5a08a165e0d8980 Mon Sep 17 00:00:00 2001
From: Matias
Date: Thu, 24 Sep 2026 03:51:45 -0300
Subject: [PATCH 3/8] fix(patterns): a tool run by path wrote its patterns
outside ~/.mem
A pattern file was named after a command's raw first word. For
`/abs/dir/tool.sh` run five times, `MEM_DIR/"patterns"/"/abs/dir/tool.sh.json"`
resolved to `/abs/dir/tool.sh.json`: the file landed beside the script,
outside ~/.mem where `forget` never looks, and the directory was tightened to
0700. Where that directory was not writable, the OSError ended the whole
background sync, so every other tool stopped getting patterns and, because
rotation shared the same `try`, 90-day retention stopped with it. No message,
no exit code.
- `storage.tool_name()` files a program under its name (`/usr/bin/git` is
`git`), for extraction and for `mem -p` alike.
- `storage.pattern_file()` refuses anything but a plain name.
- One tool's failure is logged and skipped instead of ending the sync.
- Rotation runs in its own `try` after extraction.
Each of the four tests failed before this change.
---
src/mem/cli.py | 14 +++++++----
src/mem/patterns.py | 15 ++++++++----
src/mem/search.py | 5 +++-
src/mem/storage.py | 14 ++++++++++-
tests/test_cli.py | 16 ++++++++++++
tests/test_patterns.py | 55 ++++++++++++++++++++++++++++++++++++++++++
6 files changed, 107 insertions(+), 12 deletions(-)
diff --git a/src/mem/cli.py b/src/mem/cli.py
index 37d5895..f75cd31 100644
--- a/src/mem/cli.py
+++ b/src/mem/cli.py
@@ -318,17 +318,21 @@ def sync_cmd() -> None:
if not storage.try_sync_lock():
return
+ log = logging.getLogger("mem.sync")
try:
from mem.patterns import sync_all_patterns
sync_all_patterns(silent=True)
- # Rotation lives here rather than in the capture path because it
- # rewrites every history file, which is far too much work to do on a
- # prompt. It also means retention only ever runs if this command does —
- # which for four months it did not.
+ except Exception:
+ log.debug("background pattern extraction failed", exc_info=True)
+
+ # Rotation lives here rather than in the capture path because it rewrites
+ # every history file, which is far too much work to do on a prompt. It has
+ # its own `try` because retention must not depend on extraction succeeding.
+ try:
storage.rotate()
except Exception:
- logging.getLogger("mem.sync").debug("background sync failed", exc_info=True)
+ log.debug("background rotation failed", exc_info=True)
@cli.command()
diff --git a/src/mem/patterns.py b/src/mem/patterns.py
index 1f4bb09..ee79ca1 100644
--- a/src/mem/patterns.py
+++ b/src/mem/patterns.py
@@ -485,7 +485,7 @@ def sync_all_patterns(silent: bool = False) -> tuple[int, int]:
for cmd in storage.read_all_commands():
parts = cmd.command.split()
if parts:
- tool_commands[parts[0]].append(cmd.command)
+ tool_commands[storage.tool_name(parts[0])].append(cmd.command)
new_count = 0
updated_count = 0
@@ -501,10 +501,15 @@ def sync_all_patterns(silent: bool = False) -> tuple[int, int]:
if remaining <= 0:
break # Out of budget; the next sync picks up where this stopped
- existing = storage.read_patterns(tool)
- spent = run_pattern_extraction(
- tool, commands=commands, budget=remaining, existing=existing
- )
+ # One tool's unwritable file must not cost every other tool its patterns.
+ try:
+ existing = storage.read_patterns(tool)
+ spent = run_pattern_extraction(
+ tool, commands=commands, budget=remaining, existing=existing
+ )
+ except (OSError, ValueError):
+ logger.debug("pattern extraction failed for %r", tool, exc_info=True)
+ continue
remaining -= max(spent, 0)
if existing is None:
diff --git a/src/mem/search.py b/src/mem/search.py
index a47cfb0..6f9ff47 100644
--- a/src/mem/search.py
+++ b/src/mem/search.py
@@ -326,7 +326,10 @@ def search_patterns(tool: str) -> list[CommandPattern]:
Returns patterns sorted by frequency (most common first).
Returns empty list if no patterns exist for this tool.
"""
- pf = storage.read_patterns(tool)
+ try:
+ pf = storage.read_patterns(storage.tool_name(tool))
+ except ValueError:
+ return [] # not a program name, so there is no pattern file for it
if pf is None:
return []
return sorted(pf.patterns, key=lambda p: p.frequency, reverse=True)
diff --git a/src/mem/storage.py b/src/mem/storage.py
index e58bb64..62b0436 100644
--- a/src/mem/storage.py
+++ b/src/mem/storage.py
@@ -172,8 +172,20 @@ def session_file(date: str) -> Path:
return MEM_DIR / "sessions" / f"{date}.jsonl"
+def tool_name(program: str) -> str:
+ """The name a program's patterns are filed under: ``/usr/bin/git`` is ``git``."""
+ return os.path.basename(program)
+
+
def pattern_file(tool: str) -> Path:
- """Path to a tool's pattern file."""
+ """Path to a tool's pattern file.
+
+ Raises ValueError for anything but a plain name. The tool used to be a
+ command's raw first word, so ``/abs/dir/tool.sh`` wrote its patterns into
+ /abs/dir, outside ~/.mem, and tightened that directory to 0700.
+ """
+ if tool in ("", ".", "..") or "/" in tool:
+ raise ValueError(f"not a tool name: {tool!r}")
return MEM_DIR / "patterns" / f"{tool}.json"
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 02f692f..2febc9b 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -1064,3 +1064,19 @@ def test_the_repo_is_shown_by_name(
assert "infra" in result.stdout
assert "backend" in result.stdout
assert "/Users" not in result.stdout
+
+
+class TestBackgroundSync:
+ def test_rotation_runs_even_when_pattern_extraction_fails(
+ self, tmp_mem_dir, runner: CliRunner
+ ) -> None:
+ """Retention shared a ``try`` with extraction, so any extraction error
+ silently stopped the 90-day rotation for good."""
+ with (
+ patch("mem.patterns.sync_all_patterns", side_effect=OSError("read-only")),
+ patch.object(storage, "rotate") as rotate,
+ ):
+ result = runner.invoke(cli, ["_sync"])
+
+ assert result.exit_code == 0
+ assert rotate.call_count == 1
diff --git a/tests/test_patterns.py b/tests/test_patterns.py
index f41923a..34e06e8 100644
--- a/tests/test_patterns.py
+++ b/tests/test_patterns.py
@@ -1123,3 +1123,58 @@ def test_real_model_summarizes_a_session(self):
assert isinstance(summary, str)
assert summary.strip()
+
+
+class TestPatternFilesStayInsideMem:
+ """A pattern file is named after its tool, and a tool is a name, not a path.
+
+ The key was the raw first token, so ``/abs/dir/deploy.sh`` run five times
+ wrote ``/abs/dir/deploy.sh.json`` — outside ~/.mem — and tightened that
+ directory to 0700. Where the directory was not writable, the error ended
+ the whole sync, and with it every other tool's extraction.
+ """
+
+ def test_a_tool_run_by_path_is_filed_under_its_name(self, tmp_mem_dir, tmp_path):
+ import stat
+
+ scripts = tmp_path / "scripts"
+ scripts.mkdir()
+ scripts.chmod(0o755)
+ now = int(time.time())
+ for i in range(6):
+ storage.append_command(
+ make_command(command=f"{scripts}/deploy.sh --target t{i}", ts=now)
+ )
+
+ with patch.object(patterns, "_apple_fm_available", return_value=False):
+ patterns.sync_all_patterns(silent=True)
+
+ assert list(scripts.iterdir()) == []
+ assert stat.S_IMODE(scripts.stat().st_mode) == 0o755
+ assert storage.read_patterns("deploy.sh") is not None
+
+ @pytest.mark.parametrize("tool", ["../x", "/etc/x", "a/b", "", ".", ".."])
+ def test_a_path_is_never_a_pattern_file_name(self, tool):
+ with pytest.raises(ValueError):
+ storage.pattern_file(tool)
+
+ def test_one_tool_failing_does_not_stop_the_others(self, tmp_mem_dir):
+ now = int(time.time())
+ for i in range(7):
+ storage.append_command(make_command(command=f"tool-a x{i}", ts=now))
+ for i in range(6):
+ storage.append_command(make_command(command=f"tool-b x{i}", ts=now))
+ real = patterns.run_pattern_extraction
+
+ def flaky(tool, **kwargs):
+ if tool == "tool-a":
+ raise OSError("read-only directory")
+ return real(tool, **kwargs)
+
+ with (
+ patch.object(patterns, "run_pattern_extraction", side_effect=flaky),
+ patch.object(patterns, "_apple_fm_available", return_value=False),
+ ):
+ patterns.sync_all_patterns(silent=True)
+
+ assert storage.read_patterns("tool-b") is not None
From f12ef2a4e93dd1aa6541e13130f434cb6747eb55 Mon Sep 17 00:00:00 2001
From: Matias
Date: Thu, 24 Sep 2026 04:00:25 -0300
Subject: [PATCH 4/8] fix(render): stored commands reached the terminal with
their control characters
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
`safe()` and `plain()` neutralised Rich markup but passed escape sequences
through, and the session replay prompt printed stored text raw. History is
whatever somebody pasted into a shell, so listing a command containing
`ESC ]0;…BEL` or `ESC [2J` retitled the window or cleared the screen: the
command acted on the terminal instead of being shown. The finder already
replaced these characters; the CLI never did.
The finder's rule moves to `_text.printable()`, standard library only so the
finder can still use it, and every CLI surface now shares it: `safe()`,
`plain()`, the session panel (built line by line, so its own newlines are
not data) and the replay confirmation.
The new tests seed an OSC title change and a clear-screen into every listing
surface and the replay prompt; all seven failed before this change.
---
src/mem/_text.py | 16 ++++++++++++++++
src/mem/cli.py | 22 +++++++++++++++-------
src/mem/render.py | 9 ++++++---
src/mem/tui.py | 12 +++---------
tests/test_cli.py | 37 +++++++++++++++++++++++++++++++++++++
5 files changed, 77 insertions(+), 19 deletions(-)
create mode 100644 src/mem/_text.py
diff --git a/src/mem/_text.py b/src/mem/_text.py
new file mode 100644
index 0000000..a7a1571
--- /dev/null
+++ b/src/mem/_text.py
@@ -0,0 +1,16 @@
+"""Text rules shared by both output surfaces, the CLI and the Ctrl+R finder.
+
+Standard library only: the finder imports it before Rich is loaded.
+"""
+
+from __future__ import annotations
+
+
+def printable(text: str) -> str:
+ """Replace every character a terminal would act on, rather than show, with ``?``.
+
+ History is untrusted input — whatever somebody pasted into a shell — and a
+ stray escape sequence repaints the screen, sets a colour that bleeds into
+ every later row, or rewrites the window title, purely by being listed.
+ """
+ return "".join(ch if ch.isprintable() or ch == " " else "?" for ch in text)
diff --git a/src/mem/cli.py b/src/mem/cli.py
index f75cd31..da7e2e4 100644
--- a/src/mem/cli.py
+++ b/src/mem/cli.py
@@ -24,7 +24,15 @@
from mem.capture import get_git_repo
from mem.history import SUPPORTED_SHELLS as IMPORTABLE_SHELLS
from mem.history import ImportPlan
-from mem.render import console, err_console, fit, no_matches, plain, safe
+from mem.render import (
+ console,
+ err_console,
+ fit,
+ no_matches,
+ plain,
+ printable,
+ safe,
+)
def _protected_args(ctx: click.Context) -> list[str]:
@@ -371,12 +379,10 @@ def session(query: str, as_json: bool) -> None:
f"[{i}] Session: {dt.strftime('%Y-%m-%d %H:%M')} {ranking.repo_name(s.repo)}"
)
- lines = []
- for j, cmd in enumerate(s.commands, 1):
- lines.append(f" {j:>2} {cmd}")
-
# Text, not a markup string: Panel parses its renderable for tags.
- panel_content = plain("\n".join(lines))
+ panel_content = Text("\n").join(
+ plain(f" {j:>2} {cmd}") for j, cmd in enumerate(s.commands, 1)
+ )
console.print(Panel(panel_content, title=header, border_style="dim"))
console.print()
@@ -390,7 +396,9 @@ def session(query: str, as_json: bool) -> None:
if 0 <= idx < len(results):
console.print()
for cmd in results[idx].commands:
- if not click.confirm(f" Run: {cmd}?", default=True, err=True):
+ if not click.confirm(
+ f" Run: {printable(cmd)}?", default=True, err=True
+ ):
continue
console.print(f" [dim]$ {safe(cmd)}[/]")
try:
diff --git a/src/mem/render.py b/src/mem/render.py
index 103545b..6b0e793 100644
--- a/src/mem/render.py
+++ b/src/mem/render.py
@@ -25,6 +25,8 @@
from rich.markup import escape
from rich.text import Text
+from mem._text import printable
+
# highlight=False so Rich does not colourize things that look like numbers,
# paths or URLs inside a command. A command is text, not a value to prettify.
console = Console(highlight=False)
@@ -36,9 +38,10 @@ def safe(value: object) -> str:
Use for anything interpolated into a string that Rich will parse for
markup. ``escape`` backslash-escapes bracket sequences that would
- otherwise be read as tags, so the text survives byte-for-byte.
+ otherwise be read as tags; :func:`printable` neutralises the characters a
+ terminal would obey instead of display.
"""
- return escape(str(value))
+ return escape(printable(str(value)))
def plain(value: object) -> Text:
@@ -47,7 +50,7 @@ def plain(value: object) -> Text:
Preferred over :func:`safe` when the value is printed on its own, since
it removes the escaping step entirely rather than relying on it.
"""
- return Text(str(value))
+ return Text(printable(str(value)))
def no_matches(query: str) -> None:
diff --git a/src/mem/tui.py b/src/mem/tui.py
index 2ec865e..6187587 100644
--- a/src/mem/tui.py
+++ b/src/mem/tui.py
@@ -38,6 +38,7 @@
from typing import IO, Iterator, NamedTuple, Sequence
from mem import picks, ranking
+from mem._text import printable
# --- Terminal control --------------------------------------------------------
@@ -380,15 +381,8 @@ def display_width(text: str) -> int:
def _visible(text: str, width: int) -> str:
- """Fit text into *width* columns, stripping anything the terminal obeys.
-
- Control characters are replaced rather than escaped: a command containing
- a stray escape sequence would otherwise repaint the screen, set a colour
- that bleeds into every row after it, or rewrite the window title, purely
- by being *listed*. History is untrusted input — it is whatever somebody
- pasted into a shell.
- """
- cleaned = "".join(ch if ch.isprintable() or ch == " " else "?" for ch in text)
+ """Fit text into *width* columns, after :func:`mem._text.printable`."""
+ cleaned = printable(text)
if display_width(cleaned) <= width:
return cleaned
if width <= 1:
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 2febc9b..809c966 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -42,6 +42,11 @@
CLOSE_TAG_CMD = "echo payload [/] done"
"""A stray ``[/]`` has nothing to close — Rich raises ``MarkupError``."""
+CONTROL_CMD = "echo payload\x1b]0;pwned\x07\x1b[2J"
+"""An OSC window-title change and a clear-screen, obeyed by any terminal."""
+
+CONTROL_CMD_SHOWN = "echo payload?]0;pwned??[2J"
+
CONCEAL_CMD = "echo [conceal]payload[/conceal]"
"""``conceal`` renders the text invisible in a real terminal."""
@@ -180,6 +185,38 @@ def test_stray_closing_tag_does_not_crash(
assert result.exit_code == 0
assert CLOSE_TAG_CMD in result.stdout
+ @pytest.mark.parametrize(
+ ("args", "stdin"),
+ [(args, stdin) for _id, args, stdin in RENDERING_SURFACES],
+ ids=SURFACE_IDS,
+ )
+ def test_control_characters_are_shown_not_obeyed(
+ self,
+ tmp_mem_dir,
+ runner: CliRunner,
+ outside_repo: None,
+ args: list[str],
+ stdin: str,
+ ) -> None:
+ """Listing a command must not let it retitle the window or clear the screen."""
+ _seed_every_surface(CONTROL_CMD)
+
+ result = runner.invoke(cli, args, input=stdin)
+
+ assert result.exit_code == 0
+ assert CONTROL_CMD_SHOWN in result.stdout
+ assert "\x1b" not in result.output
+
+ def test_session_replay_prompt_shows_the_command_neutralised(
+ self, tmp_mem_dir, runner: CliRunner, outside_repo: None
+ ) -> None:
+ _seed_every_surface(CONTROL_CMD)
+
+ result = runner.invoke(cli, ["session", "demo"], input="1\nn\n")
+
+ assert f"Run: {CONTROL_CMD_SHOWN}?" in result.stderr
+ assert "\x1b" not in result.stderr
+
def test_conceal_tag_cannot_hide_the_payload(
self, tmp_mem_dir, runner: CliRunner, outside_repo: None
) -> None:
From 5f918c05281f689c20180133295a007cbad7f839 Mon Sep 17 00:00:00 2001
From: Matias
Date: Thu, 24 Sep 2026 04:00:26 -0300
Subject: [PATCH 5/8] fix(forget): an empty query deleted the whole store
An empty string is a substring of every command, so `mem forget ""`, or
`mem forget "$UNSET" --yes` in a script, matched everything. The confirmation
counted only history lines ("Delete all 15?") and never said that every saved
command, runbook, variable and pattern would go too.
A blank query is now a usage error, raised before anything is previewed or
touched. Both tests (empty and whitespace-only) failed before this change.
---
src/mem/cli.py | 5 +++++
tests/test_cli.py | 21 +++++++++++++++++++++
2 files changed, 26 insertions(+)
diff --git a/src/mem/cli.py b/src/mem/cli.py
index da7e2e4..c81c3b8 100644
--- a/src/mem/cli.py
+++ b/src/mem/cli.py
@@ -738,6 +738,11 @@ def forget(query: str, yes: bool) -> None:
"""Permanently delete commands matching a query."""
from mem import storage
+ if not query.strip():
+ raise click.BadParameter(
+ "an empty query matches every command.", param_hint="QUERY"
+ )
+
# Preview matches
matches = []
for cmd in storage.read_all_commands():
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 809c966..99ad728 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -1117,3 +1117,24 @@ def test_rotation_runs_even_when_pattern_extraction_fails(
assert result.exit_code == 0
assert rotate.call_count == 1
+
+
+class TestForgetRefusesAnEmptyQuery:
+ """An empty query is a substring of everything, so it deleted the store.
+
+ The confirmation counted only history lines, never saying that every saved
+ command, runbook, variable and pattern would go too.
+ """
+
+ @pytest.mark.parametrize("query", ["", " "])
+ def test_nothing_is_deleted(
+ self, tmp_mem_dir, runner: CliRunner, outside_repo: None, query: str
+ ) -> None:
+ _seed_every_surface("git status")
+
+ result = runner.invoke(cli, ["forget", query, "--yes"])
+
+ assert result.exit_code == 2
+ assert "empty query" in result.stderr
+ assert [c.command for c in storage.read_all_commands()] == ["git status"]
+ assert storage.read_group_file(storage.GROUPS_GLOBAL_FILE).saved
From c2ddba9d9f13c7c150940f1274d97a6f26b72e0d Mon Sep 17 00:00:00 2001
From: Matias
Date: Thu, 24 Sep 2026 04:03:20 -0300
Subject: [PATCH 6/8] docs(readme): the basics, and only what a fresh install
actually does
The README had grown to 751 lines and made promises the code does not keep
for a new user: the bash hook went into ~/.bashrc, which macOS terminals never
read, so bash users captured nothing; `mem save "!"` is eaten by the shell's
history expansion; the variables example quoted `$API_TOKEN` in single quotes,
which sends the literal text; and "<5 ms" per prompt measured only the fork.
It now follows the structure of the July README: install, search, the Ctrl+R
finder, patterns, scoping, groups, variables, then how it works, storage and
privacy, with every example checked against the installed binary. The search
listing shows repo names, as it now does, and the variables block is the
real output of `mem list `.
---
README.md | 671 +++++++++++-------------------------------------------
1 file changed, 127 insertions(+), 544 deletions(-)
diff --git a/README.md b/README.md
index b5210af..f98f86c 100644
--- a/README.md
+++ b/README.md
@@ -1,37 +1,36 @@
-
-
mem
-
- Your shell, remembered.
-
-
- A privacy-first CLI that captures, searches, and organizes your terminal history
- with on-device AI. Nothing ever leaves your machine.
-
-
-
-
-
-
-
-
+
+
+# mem
+
+**Your shell, remembered.**
+
+A privacy-first CLI that captures, ranks, and organizes your terminal history.
+Nothing ever leaves your machine.
+
+[](https://github.com/matinsaurralde/mem/actions/workflows/ci.yml)
+[](https://pypi.org/project/cli-mem/)
+[](pyproject.toml)
+[](#requirements)
+[](LICENSE)
+
+
---
## What mem does
-mem silently captures every command you type, then lets you search, save, and replay them — scoped to the git repo you're in.
+mem silently captures every command you type — with its directory, git repo, exit code and duration — and gives it back ranked, scoped to the repo you're in.
```bash
-Ctrl+R # interactive finder, ranked
-mem deploy # or search from the command line
-mem fix # what fixed the last thing that broke
-mem promote # sequences you repeat, ready to become runbooks
-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
+mem deploy # search your history
+mem kubectl -p # the patterns you actually use
+mem save "cmd" -t ops # save a command to a group
+mem run ops # run the group, step by step
```
-mem replaces `Ctrl+R` rather than competing with it. Your shell's version does a literal reverse scan; mem ranks by how often you run a command, how recently, whether it's how the line *starts*, and which repo you're standing in. Unlike cloud-based tools, everything stays on your machine as plain text files in `~/.mem/` — readable with `cat`, greppable, and yours to delete.
+Press `Ctrl+R` to search interactively, right at your prompt.
+
+Your shell's own `Ctrl+R` does a literal reverse scan. mem ranks by how often you run a command, how recently, whether it *starts* with what you typed, and which repo you're standing in. Everything stays on your machine as plain text in `~/.mem/`.
---
@@ -44,126 +43,84 @@ brew install matinsaurralde/tap/mem
# pip
pip install cli-mem
-# With AI features (pattern extraction + credential detection)
+# pip, with on-device pattern extraction
pip install "cli-mem[ai]"
```
-Then activate the shell hook for your shell:
+Then add the hook for your shell:
```bash
# zsh
echo 'eval "$(mem init zsh)"' >> ~/.zshrc
source ~/.zshrc
-# bash
-echo 'eval "$(mem init bash)"' >> ~/.bashrc
-source ~/.bashrc
+# bash (macOS terminals read ~/.bash_profile; Ctrl+R needs bash 4+)
+echo 'eval "$(mem init bash)"' >> ~/.bash_profile
+source ~/.bash_profile
# fish
echo 'mem init fish | source' >> ~/.config/fish/config.fish
source ~/.config/fish/config.fish
```
-That's it. Every command you type is now silently captured with full context (directory, git repo, exit code, duration), and **Ctrl+R** now searches it.
-
----
-
-## Ctrl+R
-
-The shell hook rebinds Ctrl+R to mem's finder. Type to filter, `↑`/`↓` to move, `⏎` to put the command on your command line — where you can read it and edit it before running it. `esc` cancels and leaves your line untouched.
-
-```
-mem kube▏ 3/12417
-────────────────────────────────────────────────────────────
- ▸ kubectl logs -f deploy/api -n prod infra 2h
- kubectl get pods -w infra 1d
- ✗ kubectl rollout undo deploy/api infra 3d
-↑↓ select · ⏎ accept · ^U clear · esc cancel
-```
-
-Results are ranked by the same formula `mem ` uses, so the two never disagree. Commands that failed are marked, because "the one that worked" is usually what you are looking for.
+That's it. From the next command on, everything you type is captured, and `Ctrl+R` searches it.
-**It learns from what you pick.** Choosing a result is the one moment you say, unambiguously, which command you meant — so mem counts it, and weighs it above everything it can only infer. One selection is enough to move a command past one you happen to have run twenty times:
-
-```bash
-mem "git commit" # 1. git commit --amend (run 20 times)
- # 3. git commit -v (run once)
-# ...pick `git commit -v` in the finder, once...
-mem "git commit" # 1. git commit -v
-```
-
-Picks fade with a three-week half-life, so a command you chose constantly last quarter stops steering results once you stop choosing it. They live in `~/.mem/picks.json` — the one file here that cannot be rebuilt from your history, and the only one worth backing up. If you never open the finder, your ranking is exactly what it was.
-
-It never runs anything for you. A history search that executes behind your back is how people delete the wrong branch.
-
-Prefer your shell's own Ctrl+R? Set `MEM_NO_KEYBINDING=1` before loading the hook; capture still works.
-
-### Import what you already typed
-
-The hook only sees commands typed after it was installed. To start from the years of history your shell has already been keeping:
+To start from the history your shell has already been keeping:
```bash
mem import --from-shell-history --dry-run # see what would be imported
mem import --from-shell-history # import it
-
-mem import --from-shell-history --shell zsh # one shell only
-mem import --from-shell-history --file ~/backup.hist # a specific file
```
-`~/.zsh_history`, `~/.bash_history` and `~/.local/share/fish/fish_history` are detected automatically. Imported commands keep their recorded timestamps where the file has them, and are back-dated (never stamped as "now") where it does not. Because a history file records no directory, exit code or duration, mem stores those as unknown rather than guessing, and imported commands go to the global scope.
-
-Running the import twice is safe: it never double-counts a command. Commands that look like they contain credentials are skipped, and the count is reported.
-
---
## Search
-Just type `mem` followed by any keyword. Results are ranked by your current repo.
+Type `mem` followed by any words. A command matches when it contains every word, and the best matches come first.
```bash
-mem kubectl # search by keyword
-mem "docker compose" # search by phrase
-mem deploy -n 20 # more results
+mem kubectl # one word
+mem docker compose # every word must appear
+mem deploy -n 20 # more results (default: 10)
mem deploy --json # machine-readable output
```
```
1 kubectl apply -f deployment.yaml infra 2h ago
- 2 docker compose up -d backend 1d ago
- 3 fly deploy api 3d ago
+ 2 kubectl get pods -n production infra 1d ago
+ 3 kubectl rollout status deploy/api api 3d ago
```
-### Ask in English
-
-You do not always remember the command. You remember what it was *for*. When a query matches nothing literally, mem re-reads it through a concept map — a dictionary from what people say to what they type — and answers with commands that share the meaning instead of the letters.
+When nothing matches literally, mem reads the words through a concept map, so a question finds the command that answers it:
```bash
-mem "how do I see what's listening on a port" # -> lsof -i :8080
-mem "the command I used to fix the certificate" # -> openssl x509 -in cert.pem -noout -dates
-mem "check disk space" # -> du -sh * | sort -h
+mem "check disk space" # -> du -sh .
```
-This is a fallback, never a filter. A query that matches literally is answered literally, with the same results in the same order as before — type `openssl` and you get `openssl`, not everything tagged "certificate". Only when substring search finds nothing does the map get a turn, and a synonym that appears everywhere in your history is weighted down to nothing, so a broad entry cannot drag unrelated commands up.
+When nothing matches at all, stdout stays empty, one line on stderr says so, and the exit code is still `0`.
-The map is a plain JSON file you can read, grep and correct. Copy it and make it yours:
+### Ctrl+R
-```bash
-mem concepts > ~/.mem/concepts.json # then edit it
-```
+The shell hook binds `Ctrl+R` to mem's finder. Type to filter, `↑`/`↓` to move, `⏎` to put the command on your prompt — where you can read and edit it before running it. `esc` cancels and leaves your line untouched.
-```json
-{
- "certificate": ["openssl", "x509", "cert", "pem", "tls", "certbot"],
- "port": ["lsof", "netstat", "listen", "port", "8080"],
- "deploy": ["deploy", "kubectl apply", "fly deploy", "ansible-playbook"]
-}
```
+mem kube▏ 3/12417
+────────────────────────────────────────────────────────────
+ ▸ kubectl logs -f deploy/api -n prod infra 2h
+ kubectl get pods -w infra 1d
+ ✗ kubectl rollout undo deploy/api infra 3d
+↑↓ select · ⏎ accept · ^U clear · esc cancel
+```
+
+Commands that failed are marked with `✗`, and the finder never runs anything for you.
-A concept you define replaces the shipped one of the same name; new concepts are added; everything else is untouched by upgrades. Keys starting with `_` are metadata — `_comment` for the comments JSON does not have, `_stopwords` for the filler words your language uses to ask a question (yours are added to the built-in English ones, so the map translates). A broken file prints a warning and mem falls back to the shipped map; it never stops searching.
+It also learns from what you pick. Choosing a result is the one moment you say exactly which command you meant, so a pick outweighs anything mem can only infer. If you never open the finder, your ranking is unaffected.
+
+Prefer your shell's own `Ctrl+R`? Set `MEM_NO_KEYBINDING=1` before loading the hook. Capture keeps working.
### Patterns
-mem automatically learns structural patterns from your history using on-device AI. No manual step needed — extraction runs in the background every 20 commands.
+mem learns the structure of the commands you run and shows it with `-p`:
```bash
mem kubectl -p
@@ -178,432 +135,91 @@ Patterns for "kubectl":
kubectl apply -f
```
----
-
-## 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.
+No manual step: extraction runs in the background every 20 commands, with Apple Foundation Models on your Mac.
---
-## Promote
-
-Groups are the most useful thing mem does and the least used, because building one means remembering to run `mem save` at the exact moment you're busy doing the thing. `mem promote` closes that gap: it reads the history you already have, finds sequences you repeat across separate work sessions, and works out which argument changed between runs.
-
-```bash
-mem promote # what looks promotable
-mem promote 1 # save candidate 1 as a group (asks first)
-mem promote 1 --name ship
-mem promote --json
-```
-
-```
-$ mem promote
-
- 1. kubectl-rollout
- 6 times · last 2d ago · strong
- kubectl config use-context $CONFIG_ARG
- kubectl apply -f deploy.yaml -n $CONFIG_ARG
- kubectl rollout status deploy/api -n $CONFIG_ARG
- $CONFIG_ARG was staging, prod, dev
-
- 2. terraform-apply
- 4 times · last 6d ago · moderate
- terraform fmt -recursive
- terraform plan -out plan.tfplan
- terraform apply plan.tfplan
-
- mem promote saves one as a group. It runs nothing.
-```
-
-```
-$ mem promote 1 --name deploy-staging
-
- group deploy-staging
- kubectl config use-context $CONFIG_ARG
- kubectl apply -f deploy.yaml -n $CONFIG_ARG
- kubectl rollout status deploy/api -n $CONFIG_ARG
- $CONFIG_ARG was staging, prod, dev
-
-Save these 3 commands as 'deploy-staging'? [y/N]: y
-Saved group deploy-staging with 3 commands.
- mem run deploy-staging
-```
-
-The variable is the point. A sequence that recurs with a changing namespace or branch is worth *more* than an identical one, because that difference is precisely the parameter the runbook should take. `$CONFIG_ARG` above is a name mem derived, not a name it understood — rename it with `mem group edit`.
-
-### What it will and won't propose
-
-A sequence has to recur in **three separate sessions**. Repetitions inside one session don't count: a build loop run eight times in one afternoon is one episode of work, not eight.
-
-Commands that only *look* at things — `ls`, `cd`, `cat`, `git status` — are dropped before mining, so an inspection command between two steps doesn't break the sequence. Failed commands are dropped too: a command that exited non-zero isn't part of a working procedure.
-
-A token becomes a `$VAR` only in an argument position — never the program, never the subcommand after it, never a flag name. That's the rule that separates `git checkout main` / `git checkout staging` (a branch, so a variable) from `git push` / `git pull` (a different intent, so not the same sequence at all). Commands containing a pipe or a redirection are never generalised, because mem doesn't parse shell and won't guess inside one.
-
-**It will sometimes suggest `git add -A; git commit -m $MSG; git push`.** That really is a sequence you repeat, and it really is a poor runbook — the whole point is the message you type fresh each time. mem can't tell the difference from the outside. On the calibration corpus this was about one in eight suggestions. Skip it; it isn't a sign anything is broken.
+## Scoping
-**Nothing is written without confirmation and nothing is ever executed.** A sequence containing something credential-shaped is shown with a warning and refused for promotion outright — there's no `--force`, because a secret in a saved runbook is a second copy of it on disk. Use `mem save --var` to save those steps with the secret as a variable instead.
+mem knows which git repo every command was run in.
-By default the five best candidates are shown. That number is calibrated, not cosmetic: ranking is what keeps the list trustworthy, and going deeper costs accuracy. See [ADR-012](docs/decisions/012-promote-mines-sequences-not-commands.md) for the corpus and the measurements.
+- **History** is stored per repo. Searching from inside a repo favors that repo's commands, and those of sibling checkouts, without hiding the rest.
+- **Groups and saved commands** live in either **repo scope** or **global scope**:
+ - inside a git repo they default to repo scope; outside one, to global scope
+ - `--global` / `-g` forces global scope
+ - a repo group **shadows** a global group with the same name
---
## Groups
-Groups are named collections of commands — like runbooks you can execute.
-
-### Save commands to a group
+Groups are named collections of commands — runbooks you can execute.
```bash
mem save "kubectl get pods -n production" --group k8s --comment "list pods"
-mem save "docker compose up -d" -t deploy -c "start services"
-```
-
-Save the last command you ran:
+mem save '!' -t troubleshooting # the last command you ran
-```bash
-mem save "!" -t troubleshooting
-```
-
-### List groups
-
-```bash
-mem list # show all groups and saved commands
-mem list k8s # show commands in a specific group
-mem list -g # global scope only
-mem list -r # current repo only
-mem list --json # JSON output
-```
+mem list # all groups and saved commands
+mem list k8s # the commands in one group
+mem list --json # JSON output
-### Run a group
+mem run k8s # pick one step, or run them all
+mem run k8s -y # run every step without prompting
-```bash
-mem run k8s # run interactively (pick one or all)
-mem run deploy -y # run all without prompts
-```
-
-### Manage groups
-
-```bash
-mem group rename old new # rename a group
-mem group remove k8s # delete a group
-mem group copy k8s --global # copy from repo to global scope
-mem group edit k8s # open in $EDITOR
-```
-
-### Export and import
-
-```bash
-mem export k8s # copy JSON to clipboard
-mem export k8s --format markdown # copy as markdown
-mem export k8s --stdout # print instead of clipboard
-
-mem import # import from clipboard (auto-detect format + group name)
-mem import -t renamed # import from clipboard with custom group name
-mem import runbook.json -t ops # import from file (auto-detects format)
-mem import runbook.md -t ops # markdown works too
+mem group rename k8s kube # rename, remove, copy --global, or edit in $EDITOR
+mem export k8s --stdout # print as JSON (without --stdout: copy to the clipboard)
+mem import runbook.json -t ops # import from a file, or from the clipboard with no file
```
---
## Variables
-Saved commands can contain `$VAR_NAME` placeholders that get resolved at runtime. Values never get stored in group files.
-
-### Save commands with variables
+Saved commands can contain `$VAR_NAME` placeholders, resolved when the command runs. Values are never stored in group files.
```bash
-# Variables are detected automatically from $VAR_NAME tokens
mem save "ssh -i ~/.ssh/\$KEY_NAME ubuntu@\$BASTION_HOST" -t ssh
-
-# Set a default value with --var
mem save "kubectl get pods -n \$NAMESPACE" -t k8s --var NAMESPACE=production
-
-# AI detects hardcoded credentials and suggests variables
-mem save "curl -H 'Authorization: Bearer eyJhbGci...' https://api.example.com/users" -t api
-# Detected possible credential: Bearer token
-# Suggested: curl -H 'Authorization: Bearer $API_TOKEN' ...
-# Variable name [API_TOKEN]: █
```
-### Resolution priority
+When `mem run` meets a variable, it takes the first value it finds, in this order:
-When `mem run` encounters variables, it resolves them in this order:
-
-1. **Inline arguments** — `mem run api API_TOKEN=abc123`
-2. **Shell environment** — `export API_TOKEN=abc123`
-3. **Persistent store** — `mem vars set API_TOKEN` (macOS Keychain)
-4. **Default value** — from `--var NAME=default` at save time
-5. **Interactive prompt** — asks you, only as a last resort
-
-All prompts are collected upfront before any command runs. With `--yes`, unresolved variables cause an immediate error listing what's missing.
-
-### Variable store
-
-For values that persist across sessions but shouldn't be in `.zshrc`:
+1. **Inline** — `mem run api API_TOKEN=abc123`
+2. **Environment** — `export API_TOKEN=abc123`
+3. **Variable store** — `mem vars set API_TOKEN`
+4. **Default** — from `--var NAME=default` at save time
+5. **Prompt** — asked once, before any command runs
```bash
-mem vars set API_TOKEN # hidden input (like sudo)
-mem vars set DB_HOST staging.db # inline for non-sensitive values
-mem vars list # shows names and backend, never values
+mem vars set API_TOKEN # hidden input, like sudo
+mem vars list # names, never values
mem vars remove API_TOKEN
-mem vars clear
```
-**Values live in the macOS Keychain**, not in a file ([ADR-010](docs/decisions/010-keychain-for-variable-values.md)). They are encrypted at rest under your login password, and mem hands them to `/usr/bin/security` over a pipe — never on a command line, where `ps` would show them to every process on the machine.
+Stored values live in the **macOS Keychain**, under the service `mem-cli-vars`, never in a file. mem hands them to `/usr/bin/security` over a pipe, so they never appear on a command line where `ps` could see them.
-```bash
-# Everything mem stores is filed under one service, and it is yours:
-security find-generic-password -s mem-cli-vars -a API_TOKEN -w
-```
-
-They are also visible in **Keychain Access** under the service `mem-cli-vars`, listed as `mem-cli-vars:API_TOKEN`.
-
-If you used `mem vars` before this landed, your values are moved out of `~/.mem/vars.json` and into the Keychain the first time you run any `mem vars` command — one at a time, and each plaintext copy is deleted only after the Keychain has been read back and agrees. `vars.json` stays as the index of *which* variables exist:
-
-```json
-{"vars": {"API_TOKEN": {"value": null, "last_used": 0, "backend": "keychain"}}}
-```
-
-**When the Keychain is not available** — a locked keychain, a declined authorization prompt, a non-macOS machine — `mem vars set` fails and stores nothing. It does not fall back to writing your token in cleartext under a promise of encryption. Values that could not be migrated keep working and are listed as `plaintext`, with a warning, every time:
+`mem list ` shows whether each variable is ready:
```
-Stored variables (values hidden) — macOS Keychain, service 'mem-cli-vars'
- API_TOKEN keychain last used 2h ago
- LEGACY_TOKEN plaintext never used
-
- ! 1 value(s) are still in plaintext in ~/.mem/vars.json.
+● global / api
+ ──────────────────────────────────────────────────
+ 1. curl -H "Authorization: Bearer $API_TOKEN" .../users/$USER_ID
+ ✓ $API_TOKEN from environment
+ ⚠ $USER_ID unset — pass inline: mem run api USER_ID=
```
-Two limits worth knowing: a value is capped at roughly 2 KB (`security` truncates longer command lines instead of failing, so mem refuses them), and `mem forget` has to ask the Keychain for each stored value in order to match it — the only place mem reads them all.
-
-### Variable status in listings
-
-`mem list` shows whether each variable is ready:
-
-```
-● backend / api
- ──────────────────────────────────────────────────────
- 1. curl -H 'Authorization: Bearer $API_TOKEN' .../users/$USER_ID
- ✓ $API_TOKEN resolved from environment
- ⚠ $USER_ID unset — pass inline: mem run api USER_ID=42
-```
-
----
-
-## Scoping
-
-Every group and saved command lives in either **repo scope** (tied to the current git repo) or **global scope** (available everywhere).
-
-- Inside a git repo: defaults to repo scope
-- Outside a git repo: defaults to global scope
-- Use `--global` / `-g` to force global scope
-- A repo group **shadows** a global group with the same name
-
----
-
-## Sessions
-
-mem groups your commands into work sessions (based on 5-minute idle gaps and repo changes) so you can recall exactly what you did.
-
-```bash
-mem session "api outage" # search sessions by keyword
-mem session debug --json # machine-readable output
-```
-
-```
-┌ [1] Session: 2026-03-07 14:30 myapp ──────────────────┐
-│ 1 kubectl logs api-7f9b --tail=100 │
-│ 2 kubectl get pods -n production │
-│ 3 kubectl rollout restart deploy api │
-│ 4 curl -s localhost:8080/health │
-└─────────────────────────────────────────────────────────┘
-
-Replay a session? [number/n]: _
-```
-
-Replaying a session executes each command with per-command confirmation.
-
----
-
-## AI agents (MCP)
-
-mem can lend your shell memory to an AI agent — Claude Code, Claude Desktop, or
-anything else that speaks MCP — so it stops guessing at commands you have
-already run a hundred times.
-
-**It is off until you turn it on.**
-
-```bash
-mem agent status # disabled by default
-mem agent enable # opt in
-mem agent log # what an agent asked for, and when
-mem agent disable # revoke — takes effect on the next request
-```
-
-### Register the server
-
-Claude Code:
-
-```bash
-claude mcp add mem -- mem mcp
-```
-
-Claude Desktop (`claude_desktop_config.json`) or a project-level `.mcp.json`:
-
-```json
-{
- "mcpServers": {
- "mem": {
- "command": "mem",
- "args": ["mcp"]
- }
- }
-}
-```
-
-That is the whole configuration. `mem mcp` speaks JSON-RPC 2.0 over stdin and
-stdout — there is no port, no URL and no token, because there is no server
-listening for anything. Run it by hand and it will simply wait on stdin.
-
-### What an agent can see
-
-| Tool | What it answers |
-|---|---|
-| `search_history` | How *you* actually run a tool in this repo — real flags, real hosts |
-| `list_runbooks` | Which named groups you have curated |
-| `get_runbook` | The ordered commands of one runbook, with your comments |
-| `recent_failures` | What broke recently, and what you ran next to fix it |
-
-Read-only, all four. **No tool executes anything.** An agent gets the *text* of
-a command to propose to you; you still press Enter.
-
-### What it cannot see
-
-- Anything, until `mem agent enable`.
-- Credentials: every string leaving mem passes through redaction first — AWS
- keys, bearer tokens and JWTs, `PGPASSWORD=`, `curl -u user:pass`,
- `--token=`, private key blobs, `.env`-style assignments and vendor tokens
- (`ghp_`, `xox…`, `sk-…`, `AKIA…`) come out as `[REDACTED]`.
-- Your stored variable values (`~/.mem/vars.json`) — they are never exposed;
- a runbook shows `$API_TOKEN`, never the token.
-
-Every request is appended to `~/.mem/agent-audit.jsonl`, redacted, and shown by
-`mem agent log`. `mem forget` scrubs that file too.
-
---
## Other commands
```bash
-mem fix # what fixed the last failure (see Fix)
-mem fix kubectl --json # ...for a specific one, machine-readable
-mem promote # repeated sequences worth saving (see Promote)
-mem promote 1 --name deploy # ...turn one into a group, after confirming
+mem fix # what fixed the last command that failed
mem stats # top commands, repos, totals
-mem stats --json # machine-readable stats
mem forget "API_KEY=sk-..." # permanently delete matching commands
-mem forget "password" --yes # skip confirmation
-mem init zsh # print shell hook code (also: bash, fish)
-mem tui # the Ctrl+R finder, on demand
-mem tui -- kubectl # ...opened on a query
-
-mem import --from-shell-history --dry-run # see what your old history holds
-mem import --from-shell-history # bring it in
-
-mem agent status # is AI-agent access on?
-mem agent enable / disable # turn it on or revoke it
-mem agent log # what an agent asked for, and when
-mem mcp # run the MCP server (agents call this, not you)
+mem tui -- kubectl # open the Ctrl+R finder on a query
+mem init zsh # print the shell hook (also: bash, fish)
```
-`mem forget` reaches everywhere mem stores text — history, saved commands and runbooks, variables, extracted patterns, sessions and the agent log — not just the command history.
-
---
## How it works
@@ -612,103 +228,69 @@ mem mcp # run the MCP server (agents call this, not you
You type a command
│
▼
- Shell hook (preexec/precmd)
+ Shell hook (preexec / precmd)
│
▼
- mem _capture ← runs in background, <5ms
+ mem _capture ← in the background; never blocks your prompt
│
- ├─→ Append to ~/.mem/repos/-.jsonl
- └─→ Every 20 captures: background pattern extraction
+ ├─→ append to ~/.mem/repos/-.jsonl
+ └─→ every 20 captures: pattern extraction and retention, in the background
```
-**Search scoring:**
+### Ranking
```
-score = (picks × 0.40) + (frequency × 0.21) + (recency × 0.21)
- + (prefix × 0.09) + (context × 0.09)
+score = 0.40 × picks + 0.21 × frequency + 0.21 × recency + 0.09 × prefix + 0.09 × context
```
-- **Picks** — how often you chose this command in the finder, halving every
- 21 days. Weighted highest because it is the only signal that is not an
- inference: it is you having already answered the question. Zero until you
- use `Ctrl+R`, and with none recorded the ordering is exactly what the other
- four produce on their own.
-- **Frequency** — how often you ran it: `log1p(n)/log1p(50)`, capped, so the
- jump from 1 to 5 counts and one repeated command cannot own every result
-- **Recency** — exponential decay, 7-day half-life
-- **Prefix** — the command *starts with* your query, not merely contains it
-- **Context** — 1.0 same repo, 0.5 sibling directory, 0.0 otherwise
-
-Every feature is normalised to [0, 1] and the weights sum to 1, so a score
-reads as a fraction. If nothing matches literally, the
-[concept map](#search) expands the query — and only then.
+| Signal | Meaning |
+|---|---|
+| **Picks** | How often you chose the command in `Ctrl+R`, halving every 21 days |
+| **Frequency** | How often you ran it: `log1p(n) / log1p(50)`, capped at 1 |
+| **Recency** | Exponential decay with a 7-day half-life |
+| **Prefix** | 1 when the command *starts with* your query |
+| **Context** | 1 in the current repo, 0.5 in a sibling checkout, 0 otherwise |
-**AI features** use [Apple Foundation Models](https://developer.apple.com/machine-learning/api/) running entirely on your Mac's neural engine. No API keys, no cloud, no data leaves the machine. If Apple Intelligence isn't available, everything still works — you just don't get pattern extraction or credential detection.
+Every signal is normalized to [0, 1] and the weights sum to 1, so a score reads as a fraction. The weights, and the measurement behind them, are in [ADR-009](docs/decisions/009-ranking-learns-from-selections.md).
---
## Storage
-All your data lives in `~/.mem/` as human-readable plain text, and these
-files are the only source of truth. Any index mem keeps for speed sits
-beside them, is rebuilt from them, and is safe to delete:
+Everything lives in `~/.mem/` as plain text:
```
~/.mem/
repos/
- myapp-3f9a1c07.jsonl # commands captured in this git repo
- _global.jsonl # commands outside any repo
- sessions/
- 2026-03-07.jsonl # work sessions by date
+ Users-you-code-myapp-3f9a1c07.jsonl # commands captured in one git repo
+ _global.jsonl # commands run outside any repo
patterns/
- kubectl.json # AI-extracted command patterns
- docker.json
+ kubectl.json # extracted command patterns
groups/
repos/
- myapp.json # repo-scoped groups and saved commands
- _global.json # global groups and saved commands
- concepts.json # your concept map, layered over the shipped one
- vars.json # which variables exist (values are in the Keychain)
- agent.json # AI agent access flag (off unless you enabled it)
- agent-audit.jsonl # append-only record of every agent request
+ Users-you-code-myapp.json # repo-scoped groups and saved commands
+ _global.json # global groups and saved commands
+ picks.json # what you chose in Ctrl+R
+ vars.json # which variables exist (values are in the Keychain)
```
-The suffix on a repo file is the first 8 hex characters of the sha256 of the
-repo's absolute path. It exists because the readable slug alone is ambiguous —
-`/work/a-b/c` and `/work/a/b/c` both slugify to `work-a-b-c` — and two unrelated
-repos sharing one history file merged their commands and leaked them into each
-other. History written by an older version is migrated to the new name
-automatically the first time mem touches that repo.
-
-Inspect anything:
+The suffix on a history file is the first 8 hex characters of the SHA-256 of the repo's path, so two repos whose paths slugify the same never share a history.
```bash
-cat ~/.mem/repos/myapp-*.jsonl
-tail -f ~/.mem/repos/myapp-*.jsonl # watch commands arrive in real-time
-grep "docker" ~/.mem/repos/*.jsonl # search across repos
+tail -f ~/.mem/repos/_global.jsonl # watch commands arrive in real time
+grep docker ~/.mem/repos/*.jsonl # search across every repo
```
-Data rotation happens automatically in the background:
-
-| Data | Retention |
-|------|-----------|
-| Commands | 90 days |
-| Sessions | 30 days |
-| Patterns | Forever |
+Captured commands are kept for 90 days; patterns are kept forever.
---
## Privacy
-- Zero network requests — not even update checks
-- Zero telemetry — no analytics, no crash reports
-- Zero cloud dependencies — fully offline, always
-- On-device AI only — runs on your Mac's neural engine
-- Plain text storage — no proprietary formats, you own your data. The one
- deliberate exception is variable *values*, which live in the macOS
- Keychain: "readable with `cat`" is the wrong property for a password
- ([ADR-010](docs/decisions/010-keychain-for-variable-values.md))
-- Agent access off by default — opt-in, redacted and audited ([MCP](#ai-agents-mcp))
+- **Zero network requests** — not even update checks. The test suite runs mem with sockets disabled to keep it that way.
+- **Zero telemetry** — no analytics, no crash reports.
+- **On-device AI only** — Apple Foundation Models, on your Mac.
+- **Plain-text storage** — your data is yours to read, grep and delete. The one exception is variable *values*, which belong in the Keychain rather than in a file.
Read more in [PHILOSOPHY.md](PHILOSOPHY.md).
@@ -720,22 +302,23 @@ Read more in [PHILOSOPHY.md](PHILOSOPHY.md).
|-------------|---------|
| macOS | 26.0+ |
| Python | 3.10+ |
-| Apple Intelligence | Optional (for patterns + credential detection) |
+| Apple Intelligence | Optional, for pattern extraction |
---
## Uninstall
```bash
+mem vars clear # remove stored variables from the Keychain
brew uninstall mem # or: pip uninstall cli-mem
rm -rf ~/.mem # remove all captured data
```
-Remove the shell hook line from your shell config (`~/.zshrc`, `~/.bashrc`, or `~/.config/fish/config.fish`).
+Then remove the hook line from your shell config.
---
-## Contributing
+## Development
```bash
git clone https://github.com/matinsaurralde/mem.git
@@ -744,7 +327,7 @@ pip install -e ".[dev]"
pytest
```
-Read [PHILOSOPHY.md](PHILOSOPHY.md) first.
+CI runs the suite on macOS against Python 3.10–3.13; the end-to-end tests drive the real binary inside real interactive shells. Design decisions and the measurements behind them are recorded as [ADRs](docs/decisions/). [ARCHITECTURE.md](ARCHITECTURE.md) maps the code, and [PHILOSOPHY.md](PHILOSOPHY.md) explains the principles it follows.
## License
From c19e2cde0be849428bd666357ff3d9d111c1870e Mon Sep 17 00:00:00 2001
From: Matias
Date: Thu, 24 Sep 2026 04:05:45 -0300
Subject: [PATCH 7/8] build: declare Python 3.13, which CI already tests
pyproject listed 3.10 to 3.12 while the CI matrix runs 3.10 to 3.13, so PyPI
advertised less than the project verifies.
---
pyproject.toml | 1 +
1 file changed, 1 insertion(+)
diff --git a/pyproject.toml b/pyproject.toml
index 527cf37..5bafa99 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -19,6 +19,7 @@ classifiers = [
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
"Topic :: System :: Shells",
]
# Upper bounds are deliberate. Unpinned ranges already bit us once: Click 9
From 96451dc594ac1f84c793cef11e3c14b95d87d3d7 Mon Sep 17 00:00:00 2001
From: Matias
Date: Thu, 24 Sep 2026 04:06:44 -0300
Subject: [PATCH 8/8] chore: release 0.5.2
---
CHANGELOG.md | 26 ++++++++++++++++++++++++++
pyproject.toml | 2 +-
src/mem/__init__.py | 2 +-
3 files changed, 28 insertions(+), 2 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff402e5..c9b2878 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,32 @@ All notable changes to this project are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.5.2] — 2026-09-24
+
+### Fixed
+
+- **mem recorded its own invocations.** Asking the same question twice
+ returned the first asking instead of the command that answers it, and
+ `mem forget X` wrote `X` back to history as it deleted it. Invocations of
+ mem are no longer captured, imported or listed, including the ones earlier
+ versions already stored.
+- **`ls` and `ls ` were two commands.** Surrounding whitespace is no longer
+ part of a command, so its runs are counted together.
+- **The repo column showed a cut path.** Every repo under a home directory
+ read `/Users/…`; listings now show the repo's name.
+- **A tool run by path wrote its patterns outside `~/.mem`.** Patterns are
+ filed under the program's name, one tool's failure no longer stops the
+ others, and data rotation no longer depends on pattern extraction.
+- **Listing a command could control the terminal.** Escape sequences in
+ stored commands are shown as `?` instead of being obeyed.
+- **`mem forget ""` deleted everything.** An empty query is a usage error.
+
+### Changed
+
+- The README covers the basics — install, search, Ctrl+R, patterns, scoping,
+ groups and variables — and the bash hook now goes in `~/.bash_profile`,
+ the file macOS terminals read.
+
## [0.5.1] — 2026-09-21
The first release of the 0.5 line to reach a user. The 0.5.0 entry below was
diff --git a/pyproject.toml b/pyproject.toml
index 5bafa99..3a4243c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "cli-mem"
-version = "0.5.1"
+version = "0.5.2"
description = "Privacy-first CLI that turns shell history into searchable memory"
license = "MIT"
readme = "README.md"
diff --git a/src/mem/__init__.py b/src/mem/__init__.py
index d342810..a0437da 100644
--- a/src/mem/__init__.py
+++ b/src/mem/__init__.py
@@ -1,3 +1,3 @@
"""mem — your shell history, understood."""
-__version__ = "0.5.1"
+__version__ = "0.5.2"