Skip to content
Merged
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
671 changes: 127 additions & 544 deletions README.md

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/mem/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""mem — your shell history, understood."""

__version__ = "0.5.1"
__version__ = "0.5.2"
16 changes: 16 additions & 0 deletions src/mem/_text.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 8 additions & 6 deletions src/mem/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
51 changes: 34 additions & 17 deletions src/mem/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,20 @@
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
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]:
Expand Down Expand Up @@ -188,7 +196,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)}[/]"
Expand Down Expand Up @@ -318,17 +326,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()
Expand Down Expand Up @@ -364,15 +376,13 @@ 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 = []
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)
)
Comment on lines +383 to +385

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 Filter legacy mem invocations from session listings

For users upgrading from 0.5.1, persisted work sessions can already contain mem ... commands, but read_all_sessions() does not apply ranking.canonical() and this loop still renders every stored command and subsequently offers it for replay. Thus mem session continues to list legacy self-invocations even though command-history readers now hide them; session commands and summaries need equivalent normalization.

Useful? React with 👍 / 👎.

console.print(Panel(panel_content, title=header, border_style="dim"))
console.print()

Expand All @@ -386,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:
Expand Down Expand Up @@ -439,7 +451,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:
Expand Down Expand Up @@ -726,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():
Expand Down Expand Up @@ -760,7 +777,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)}[/]"
Expand Down
28 changes: 13 additions & 15 deletions src/mem/groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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:
Expand Down
6 changes: 5 additions & 1 deletion src/mem/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
15 changes: 10 additions & 5 deletions src/mem/patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
37 changes: 37 additions & 0 deletions src/mem/ranking.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from __future__ import annotations

import math
import os
from collections.abc import Sequence

from mem import picks
Expand Down Expand Up @@ -145,6 +146,42 @@ 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 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():
name, equals, _ = word.partition("=")
if equals and name.isidentifier():
continue
return os.path.basename(word) == "mem"
Comment on lines +177 to +181

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 Detect wrapped and compound mem invocations

When mem is invoked through a shell wrapper or later in a compound command—such as command mem forget SECRET, env FOO=bar mem stats, sudo mem ..., or echo ok; mem forget SECRET—the first non-assignment word is not mem, so this function returns false and the hook records the entire line. Quoted assignments such as FOO='a b' mem ... are also split incorrectly. These cases preserve the original secret-recapture bug that this filter is intended to prevent.

Useful? React with 👍 / 👎.

return False


def score(
command: str,
ts: int | float,
Expand Down
Loading