From 5c03f114f4b3fd7f47ac9ad3bed7245bd4e275b8 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:17:06 -0300 Subject: [PATCH 01/40] fix(capture): mouse-report garbage was being stored as failed commands A program that dies with mouse tracking enabled (here: `claude`, exit 139) leaves the terminal reporting every mouse move to the shell. The SGR payload `35;165;16M...` lands on the command line, Enter runs it, zsh answers 127 for each `;`-separated piece, and the hook captured it as an ordinary command. `mem fix` then offered it as "the last command that failed": no error, exit 0, two real lines in the owner's store. `capture_command` now drops a line that consists of nothing but SGR mouse reports before the git lookup, the session tracker and the sync counter. The match is deliberately whole-line: `echo 65;50;35M` is something a person chose to run and is kept. Bracketed-paste markers and X10 reports are left out on purpose; the shells handle the former and the latter is not printable. The finder is not the source: tui.py never enables mouse tracking, and its restore is a bare `finally`. Tests use the two strings verbatim and were watched go red with the predicate inverted. Co-Authored-By: Claude Fable 5.1 --- src/mem/capture.py | 29 +++++++++++++++ tests/test_capture.py | 84 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+) diff --git a/src/mem/capture.py b/src/mem/capture.py index f57cc6c..f2ecbf7 100644 --- a/src/mem/capture.py +++ b/src/mem/capture.py @@ -8,6 +8,7 @@ from __future__ import annotations import json +import re import subprocess import time import uuid @@ -45,13 +46,41 @@ def get_git_repo(directory: str) -> str | None: return None +# One or more SGR mouse reports (`CSI < button ; column ; row M`, `m` on release) +# with nothing else on the line, the CSI prefix optional because the line editor +# has usually already consumed it. This is what a shell prompt receives when a +# full-screen program dies without turning mouse tracking back off. +_TERMINAL_NOISE = re.compile(r"(?:(?:\x1b\[<|\[<)?\d+;\d+;\d+[Mm])+") + + +def looks_like_terminal_noise(command: str) -> bool: + """True when *command* is terminal mouse-report garbage, not something typed. + + Real case: `claude` segfaulted (exit 139) with mouse tracking enabled, so + every later mouse move at the prompt fed zsh `ESC [ < 35;165;16 M`. zle + dropped the unbound prefix and inserted the payload; Enter then ran + `35;165;16M...`, which failed with 127 and was captured as a command. It + surfaced as "the last command that failed" in `mem fix`. + + Deliberately narrow: the whole line must be mouse reports. `echo 65;50;35M` + or `sleep 1;ls` are commands someone chose to run and are kept. + """ + return _TERMINAL_NOISE.fullmatch(command.strip()) is not None + + def capture_command(raw: str, directory: str, exit_code: int, duration_ms: int) -> None: """Capture a shell command with full context and persist it. Called by the shell hook after every command execution. 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). """ + if looks_like_terminal_noise(raw): + return repo = get_git_repo(directory) cmd = CapturedCommand( command=raw, diff --git a/tests/test_capture.py b/tests/test_capture.py index 6cd08a2..8302403 100644 --- a/tests/test_capture.py +++ b/tests/test_capture.py @@ -16,6 +16,7 @@ _spawn_background_sync, capture_command, get_git_repo, + looks_like_terminal_noise, ) @@ -211,6 +212,89 @@ def test_session_tracking_failure_does_not_block_capture(self, tmp_mem_dir): assert len(cmds) == 1 +class TestTerminalNoise: + """Mouse-report garbage must never become a captured command. + + The two strings below were found verbatim in a real store. A `claude` + process had died with SIGSEGV (exit 139) while mouse tracking was on, so + every later mouse movement at the prompt reached zsh as an SGR mouse + report `ESC [ < Cb ; Cx ; Cy M`. zle swallowed the unbound `ESC [ <` + prefix and inserted the rest; Enter ran it, the shell said 127, and the + hook captured it — which made it "the last command that failed" in + `mem fix`. + """ + + # The 3-group real prefix of the 1689-character line, then the same shape + # repeated to the length that was actually stored. + REAL_PREFIX = "35;165;16M35;160;16M35;153;17M" + LONG_LINE = REAL_PREFIX + "".join( + f"{button};{column};{row}M" + for button, column, row in ( + (35, 144 - i % 140, 17 + i // 8) if i % 5 else (65, 71, 26) + for i in range(160) + ) + ) + + @pytest.mark.parametrize( + "command", + [ + pytest.param("65;50;35M", id="real-short-line"), + pytest.param(REAL_PREFIX, id="real-long-line-prefix"), + pytest.param(LONG_LINE, id="real-long-line-shape"), + pytest.param("35;165;16m", id="button-release"), + pytest.param("[<65;50;35M", id="csi-prefix-minus-esc"), + pytest.param("\x1b[<65;50;35M", id="raw-sequence-intact"), + pytest.param("[<35;165;16M[<35;160;16M", id="prefix-on-every-group"), + pytest.param("65;50;35M ", id="trailing-space"), + ], + ) + def test_matches_mouse_reports(self, command: str): + assert looks_like_terminal_noise(command) is True + + @pytest.mark.parametrize( + "command", + [ + "echo 65;50;35M", + "awk '{print $1;$2}'", + "sleep 1;ls", + "65;50;35M echo", + "65;50", # two fields is not a report + "65;50;35", # no final byte + "1;2;3M;", # a stray separator is something else + "ls", + "", + "[200~ls[201~", # bracketed paste, deliberately left out + ], + ) + def test_leaves_real_commands_alone(self, command: str): + assert looks_like_terminal_noise(command) is False + + def test_the_real_short_line_is_not_captured(self, tmp_mem_dir): + """The exact line from the store: nothing written, nothing tracked.""" + with patch("mem.capture.get_git_repo") as repo_lookup: + capture_command("65;50;35M", "/Users/test/myapp", 127, 22) + + assert list(storage.read_all_commands()) == [] + assert not (tmp_mem_dir / ".session_state.json").exists() + assert storage.read_sync_counter() == 0 + # Dropped before the git subprocess, not after it. + repo_lookup.assert_not_called() + + def test_the_real_long_line_is_not_captured(self, tmp_mem_dir): + assert len(self.LONG_LINE) > 1000 + with patch("mem.capture.get_git_repo", return_value=None): + capture_command(self.LONG_LINE, "/Users/test/myapp", 127, 703) + + assert list(storage.read_all_commands()) == [] + + def test_a_command_that_merely_contains_a_report_is_captured(self, tmp_mem_dir): + """The filter is about the whole line, so `echo 65;50;35M` survives.""" + with patch("mem.capture.get_git_repo", return_value=None): + capture_command("echo 65;50;35M", "/Users/test/myapp", 0, 3) + + assert [c.command for c in storage.read_all_commands()] == ["echo 65;50;35M"] + + class TestSessionTracker: """Tests for session boundary detection and lifecycle.""" From 53137b1b2ae7414bbcd4cf7a54c3f17a1f03e5e2 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:18:38 -0300 Subject: [PATCH 02/40] fix(cli): every CLI invocation emitted a Click deprecation warning Click 8.2 renamed `Context.protected_args` to `_protected_args` and made the old name a property that warns on every access. The implicit-search router read it twice per invocation, so the test suite ended with 268 warnings and a real one would have been invisible among them. The router now reads the private list where it exists and falls back to the public name on Click 8.1, which is still inside the pin. `pytest -q` reports zero warnings, and the suite also passes under `-W error`. Co-Authored-By: Claude Fable 5.1 --- pyproject.toml | 6 ++++-- src/mem/cli.py | 21 +++++++++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index bf1eff1..a0a9d4d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,8 +22,10 @@ classifiers = [ "Topic :: System :: Shells", ] # Upper bounds are deliberate. Unpinned ranges already bit us once: Click 9 -# removes `Context.protected_args`, which the implicit-search router depends on, -# so an unconstrained `click` would break the entire CLI on a routine upgrade. +# folds `Context.protected_args` (private `_protected_args` since 8.2) into +# `args`, and the implicit-search router reads that slot to tell a query from a +# subcommand, so an unconstrained `click` would break the entire CLI on a +# routine upgrade. dependencies = [ "click>=8.1,<9", "rich>=13.7,<15", diff --git a/src/mem/cli.py b/src/mem/cli.py index 50b40a6..08577fb 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -27,16 +27,33 @@ from mem.render import console, err_console, fit, plain, safe +def _protected_args(ctx: click.Context) -> list[str]: + """The subcommand slot Click parsed, on every Click inside our pin. + + Click 8.2 renamed the public ``protected_args`` list to ``_protected_args`` + and turned the old name into a property that emits a DeprecationWarning on + every access. That one attribute read was the entire 268-warning noise + floor of the test suite. Click 8.1 (still inside our pin) has only the + public name, so fall back to it there; on anything newer the private list + is the real storage and the one ``Group.invoke`` reads. + """ + protected = getattr(ctx, "_protected_args", None) + if protected is None: + protected = ctx.protected_args # Click 8.1 + return protected + + class MemGroup(click.Group): """Custom group that treats unknown commands as search queries.""" def invoke(self, ctx): # If the first arg isn't a known subcommand, treat it as a search query - args = list(ctx.protected_args) + list(ctx.args) + protected = _protected_args(ctx) + args = list(protected) + list(ctx.args) if args and args[0] not in self.commands: ctx.ensure_object(dict) ctx.obj["query_args"] = args - ctx.protected_args.clear() + protected.clear() ctx.args.clear() return super().invoke(ctx) From 4d0e7a03f3e4e9da1f63a6623658a93956f6645e Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:21:17 -0300 Subject: [PATCH 03/40] fix(cli): options after a query were searched for as text, and no match printed nothing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `mem deploy --json` and `mem deploy -n 20` are the forms the README documents. Neither worked: Click stops reading the group's options at the first positional, because what follows a subcommand belongs to the subcommand, and the implicit-search router then joined everything into the query. So `mem zzz --json` searched for the text "zzz --json", took the human path, found nothing, and printed nothing, exit 0. A script expecting JSON got an empty string. The router now re-parses the line once it knows the first positional is not a subcommand, with mem's own options allowed anywhere and unknown dash-words kept as query text, so `mem git commit -m` still searches for what it says and `--` still forces literal text. Visible consequence: `mem grep -n` with no value is now a Click usage error rather than a silent search for "grep -n"; quote it or use `--`. A query that matches nothing now says so in one dim line on stderr: `no matches for "…"`. stdout stays empty so pipes see nothing. Silence was never a recorded decision (the `return` dates from the first commit with no rationale), and it is indistinguishable from a broken hook, an empty store or a swallowed flag, all three of which have happened. Tests assert the exact stderr text with empty stdout, `[]` for a trailing `--json`, and the foreign-flag case, through CliRunner and the real binary. Each was watched go red under the matching mutation. Co-Authored-By: Claude Fable 5.1 --- src/mem/cli.py | 39 ++++++++++++++++++------ src/mem/render.py | 13 ++++++++ tests/test_cli.py | 75 +++++++++++++++++++++++++++++++++++++++++++++-- tests/test_e2e.py | 18 +++++++++++- 4 files changed, 133 insertions(+), 12 deletions(-) diff --git a/src/mem/cli.py b/src/mem/cli.py index 08577fb..bbf678f 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -24,7 +24,7 @@ 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, plain, safe +from mem.render import console, err_console, fit, no_matches, plain, safe def _protected_args(ctx: click.Context) -> list[str]: @@ -46,16 +46,30 @@ def _protected_args(ctx: click.Context) -> list[str]: class MemGroup(click.Group): """Custom group that treats unknown commands as search queries.""" - def invoke(self, ctx): - # If the first arg isn't a known subcommand, treat it as a search query + def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]: + rest = super().parse_args(ctx, list(args)) protected = _protected_args(ctx) - args = list(protected) + list(ctx.args) - if args and args[0] not in self.commands: + if protected and protected[0] not in self.commands: + # A query, not a subcommand. Click stopped reading the group's + # own options at the first positional because what follows a + # subcommand belongs to that subcommand — but here there is none, + # and ``mem foo --json`` searched for the literal text "foo --json" + # (nothing matched, nothing was printed, exit 0). Re-read the + # whole line with mem's options allowed anywhere; anything that + # is not one of them (``-m``, ``--force``) stays a query word, so + # ``mem git commit -m`` still searches for what it says. + ctx.allow_interspersed_args = True + ctx.ignore_unknown_options = True + # Click 8.2+ keeps the first value it stored for a parameter, so + # without this the second pass parses ``--json`` and drops it. + ctx.params.clear() + rest = super().parse_args(ctx, list(args)) + protected = _protected_args(ctx) ctx.ensure_object(dict) - ctx.obj["query_args"] = args + ctx.obj["query_args"] = [*protected, *ctx.args] protected.clear() ctx.args.clear() - return super().invoke(ctx) + return rest def _current_repo() -> str | None: @@ -99,7 +113,13 @@ def _relative_time(ts: int) -> str: @click.option("--limit", "-n", default=10, help="Maximum results") @click.pass_context def cli(ctx: click.Context, pattern: bool, as_json: bool, limit: int) -> None: - """mem — your shell history, understood.""" + """mem — your shell history, understood. + + Anything that is not a command is a search: ``mem docker compose`` lists + the captured commands containing every word given, one per line. When + nothing matches, stdout stays empty, one line on stderr says so, and the + exit code is still 0. + """ if ctx.invoked_subcommand is not None: return @@ -151,7 +171,8 @@ def cli(ctx: click.Context, pattern: bool, as_json: bool, limit: int) -> None: return if not results: - return # Empty results, no error (exit 0) + no_matches(query) # stderr only: stdout is the pipeable surface + return for i, (cmd, score) in enumerate(results, 1): rank = f" {i:>2}" diff --git a/src/mem/render.py b/src/mem/render.py index bb2accb..3c532be 100644 --- a/src/mem/render.py +++ b/src/mem/render.py @@ -50,6 +50,19 @@ def plain(value: object) -> Text: return Text(str(value)) +def no_matches(query: str) -> None: + """Say on stderr, in one dim line, that *query* matched nothing. + + stderr, because ``mem foo | head`` must stay empty on stdout when there + is nothing to pipe (Philosophy III: diagnostics go to stderr). One line, + because total silence is indistinguishable from a broken hook, an empty + store, or a flag that was swallowed into the query text — all three have + happened. The query is echoed unstyled and verbatim so the user sees + exactly what was searched for. + """ + err_console.print(Text.assemble(("no matches for ", "dim"), f'"{query}"')) + + def fit(value: str, width: int) -> str: """Pad or truncate to an exact display width, with an ellipsis if cut. diff --git a/tests/test_cli.py b/tests/test_cli.py index 9a6ed67..f7ad875 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -370,10 +370,15 @@ def test_no_arguments_prints_help(self, tmp_mem_dir, runner: CliRunner) -> None: assert "Usage:" in result.stdout assert "Commands:" in result.stdout - def test_query_with_no_matches_is_silent_and_succeeds( + def test_query_with_no_matches_says_so_on_stderr_only( self, tmp_mem_dir, runner: CliRunner, outside_repo: None ) -> None: - """No matches is a valid answer: exit 0, no output, no traceback.""" + """No matches is a valid answer: exit 0, empty stdout, one stderr line. + + stdout stays empty so ``mem foo | head`` pipes nothing; the line on + stderr is what tells a human the query ran and found nothing, which + pure silence could not distinguish from a broken hook. + """ _add_history("git status") result = runner.invoke(cli, ["zzzz-nothing-matches-this"]) @@ -381,6 +386,24 @@ def test_query_with_no_matches_is_silent_and_succeeds( assert result.exception is None assert result.exit_code == 0 assert result.stdout == "" + assert result.stderr == 'no matches for "zzzz-nothing-matches-this"\n' + + def test_concept_fallback_finding_nothing_gives_the_same_line( + self, tmp_mem_dir, runner: CliRunner, outside_repo: None + ) -> None: + """A question the concept map understands but history cannot answer. + + "certificate" expands to openssl, x509, certbot...; none of them was + ever run, so the expanded pass finds nothing too. The user gets the + one line, worded for the query they typed, not for the expansion. + """ + _add_history("git status") + + result = runner.invoke(cli, ["certificate"]) + + assert result.exit_code == 0 + assert result.stdout == "" + assert result.stderr == 'no matches for "certificate"\n' def test_query_against_empty_history_succeeds( self, tmp_mem_dir, runner: CliRunner, outside_repo: None @@ -403,6 +426,54 @@ def test_limit_option_caps_results( assert result.exit_code == 0 assert len(json.loads(result.stdout)) == 2 + def test_options_after_the_query_are_options( + self, tmp_mem_dir, runner: CliRunner, outside_repo: None + ) -> None: + """``mem git --json -n 1`` means the same as ``mem --json -n 1 git``. + + It used to search for the literal text "git --json -n 1": every + subcommand accepts its options after its arguments, and a script that + wrote ``mem "$q" --json`` got human output (or nothing) instead of + JSON, with exit code 0. + """ + _add_history("git status") + _add_history("git push") + + result = runner.invoke(cli, ["git", "--json", "-n", "1"]) + + assert result.exit_code == 0 + assert len(json.loads(result.stdout)) == 1 + + def test_json_after_a_query_with_no_matches_is_an_empty_list( + self, tmp_mem_dir, runner: CliRunner, outside_repo: None + ) -> None: + """The measured failure: ``mem zzz --json`` printed nothing at all.""" + _add_history("git status") + + result = runner.invoke(cli, ["zzzz-nothing-matches-this", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == [] + assert result.stderr == "" + + def test_a_flag_mem_does_not_own_stays_a_query_word( + self, tmp_mem_dir, runner: CliRunner, outside_repo: None + ) -> None: + """``mem git commit -m`` searches for exactly that. + + Shell fragments are full of flags; only mem's own options are lifted + out of the query, everything else is text to match. + """ + _add_history("git commit -m fix") + _add_history("git commit --amend") + + result = runner.invoke(cli, ["--json", "git", "commit", "-m"]) + + assert result.exit_code == 0 + assert [e["command"] for e in json.loads(result.stdout)] == [ + "git commit -m fix" + ] + # --------------------------------------------------------------------------- # Exit codes diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 2aed66e..3f9ab87 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -298,10 +298,26 @@ def test_plain_search_output_contains_the_command( assert "terraform apply" in search.stdout def test_search_without_matches_exits_zero(self, home: Path, workdir: Path) -> None: - """An empty result set is not an error — the shell must stay happy.""" + """An empty result set is not an error — the shell must stay happy. + + stdout is empty so a pipe sees nothing; the one-line note is on + stderr, where a redirect of the results does not pick it up. + """ result = run_mem(["nothing-was-ever-captured"], home, workdir) assert result.returncode == 0 + assert result.stdout == "" + assert result.stderr == 'no matches for "nothing-was-ever-captured"\n' + + def test_json_after_the_query_is_still_json( + self, home: Path, workdir: Path + ) -> None: + """``mem QUERY --json`` used to print nothing: the flag joined the query.""" + result = run_mem(["nothing-was-ever-captured", "--json"], home, workdir) + + assert result.returncode == 0 + assert json.loads(result.stdout) == [] + assert result.stderr == "" SHELLS = ["zsh", "bash", "fish"] From a609be69b48bffcbc647bd03960b6802438c126e Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:21:17 -0300 Subject: [PATCH 04/40] test(perf): the benchmarks ran under the coverage tracer and one always failed `addopts` keeps `--cov --cov-branch` on when `-m perf` replaces the mark expression, so the wall-clock tests were measuring instrumented code. The prefilter is a per-line Python loop, which the tracer slows; the `json.loads` it races is C, which the tracer does not touch. Instrumented, the prefilter came out at 1.1-1.3x instead of the 3.4-7.3x it measures uninstrumented, and `TestPrefilterIsFasterThanParsing` failed 5 runs out of 5 while passing 5 of 5 with `--no-cov`. Both perf classes now carry pytest-cov's `no_cover` mark, so `pytest -m perf` as written in CLAUDE.md gives a truthful answer. Co-Authored-By: Claude Fable 5.1 --- tests/test_hooks_e2e.py | 5 +++++ tests/test_storage.py | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/tests/test_hooks_e2e.py b/tests/test_hooks_e2e.py index 2edf8ae..80aeb79 100644 --- a/tests/test_hooks_e2e.py +++ b/tests/test_hooks_e2e.py @@ -1063,6 +1063,11 @@ def test_variables_are_stored_unexpanded( # --- 7. The hook must not block the prompt ----------------------------------- +# no_cover: the default addopts keep `--cov` on under `-m perf`, and the +# coverage tracer slows a per-line Python loop far more than the C-level +# `json.loads` it is raced against. Instrumented, the prefilter measured +# 1.1-1.3x instead of 3.4-7.3x and this class failed 5 runs out of 5. +@pytest.mark.no_cover @pytest.mark.perf class TestHookPerformance: """Capture is fire-and-forget: it must not add latency to the prompt. diff --git a/tests/test_storage.py b/tests/test_storage.py index 70f26ef..2167232 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -774,6 +774,11 @@ def test_every_needle_must_be_present(self, tmp_mem_dir): assert found == ["docker compose up"] +# no_cover: the default addopts keep `--cov` on under `-m perf`, and the +# coverage tracer slows a per-line Python loop far more than the C-level +# `json.loads` it is raced against. Instrumented, the prefilter measured +# 1.1-1.3x instead of 3.4-7.3x and this class failed 5 runs out of 5. +@pytest.mark.no_cover @pytest.mark.perf class TestPrefilterIsFasterThanParsing: """The prefilter exists for one reason: 82% of query time was wasted. From 3e9590623715855a3a658d1f2af568ba203e2cdb Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:30:34 -0300 Subject: [PATCH 05/40] refactor: four branches that could not change what the code did merge_var_declarations() had an if/else whose two arms ran the same assignment; _scrub_groups() wrote a dict entry back onto the key it was read from; import_from_markdown_str() checked for the header row and then `continue`d either way, and guarded `cells[1]` inside a block that had already required two cells; VarDeclaration.name carried a min_length=2 that its own pattern (a letter plus at least one more character) already enforces. None of these was a bug, but each reads as if there were a case being handled, and the next person to touch the code has to work out that there is not. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 14986717e89a394307ce02ba60b5bfa72f89d3f6) --- src/mem/groups.py | 7 +++---- src/mem/models.py | 4 +++- src/mem/storage.py | 1 - src/mem/variables.py | 11 ++++------- 4 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/mem/groups.py b/src/mem/groups.py index bfb4920..0c4df91 100644 --- a/src/mem/groups.py +++ b/src/mem/groups.py @@ -346,17 +346,16 @@ def import_from_markdown_str(content: str) -> tuple[str | None, list[GroupComman in_table = True continue - # Skip header row (| Command | Description |) + # Skip everything before the separator, including the header row + # (| Command | Description |): a row only counts once the table is open. if not in_table: - if "Command" in stripped and "Description" in stripped: - continue continue # Parse table row cells = [c.strip() for c in stripped.split("|")[1:-1]] if len(cells) >= 2: cmd_cell = cells[0] - comment_cell = cells[1] if len(cells) > 1 else "" + comment_cell = cells[1] match = re.search(r"`(.+?)`", cmd_cell) if match: diff --git a/src/mem/models.py b/src/mem/models.py index 5d262a1..c6d70e8 100644 --- a/src/mem/models.py +++ b/src/mem/models.py @@ -124,7 +124,9 @@ class SessionState(BaseModel): class VarDeclaration(BaseModel): """A variable placeholder in a saved command.""" - name: str = Field(min_length=2, pattern=r"^[A-Z][A-Z0-9_]+$") + # The pattern already demands a letter plus at least one more character, + # so the two-character minimum is enforced by it alone. + name: str = Field(pattern=r"^[A-Z][A-Z0-9_]+$") default: str | None = None diff --git a/src/mem/storage.py b/src/mem/storage.py index 02fd380..2dc98e5 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -848,7 +848,6 @@ def _scrub_groups(query: str) -> None: if query in (group.get("description") or ""): group["description"] = None changed = True - data["groups"][name] = group if changed: atomic_write(path, json.dumps(data, indent=2, ensure_ascii=False)) diff --git a/src/mem/variables.py b/src/mem/variables.py index 2853f2b..6fe194f 100644 --- a/src/mem/variables.py +++ b/src/mem/variables.py @@ -100,16 +100,13 @@ def merge_var_declarations( Returns: Merged list of VarDeclaration objects. """ - # Build a dict preserving detection order, then overlay explicit defaults + # Build a dict preserving detection order, then overlay explicit defaults. + # A declaration for a detected name enriches it with the default; one for + # a name absent from the command text appends it. Both are the same store. var_map: dict[str, str | None] = {name: None for name in detected} for name, default in explicit: - if name in var_map: - # Enrich existing detection with default value - var_map[name] = default - else: - # Add explicitly declared variable not found in command text - var_map[name] = default + var_map[name] = default return [ VarDeclaration(name=name, default=default) for name, default in var_map.items() From 823e6da7baea2a42616be74f2afb2f2b83d044fe Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:32:16 -0300 Subject: [PATCH 06/40] refactor(storage): two functions that only the test suite ever called MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit storage.get_var_value() and keychain.is_available() had no caller in src/: the CLI resolves variables through load_var_values() and checks the Keychain through unavailable_reason(). A function that exists only for its tests can drift from the production path without any test noticing — get_var_value() raised where load_var_values() reports, so the suite was pinning a contract nothing shipped. The tests now go through the production functions and assert the same values; the keychain_live tests were run against the real binary and pass. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit dcfbd197a268684611a0b2703860ce89ed341e66) --- src/mem/keychain.py | 5 ----- src/mem/storage.py | 15 --------------- tests/test_keychain.py | 33 +++++++++++++++++++++++---------- 3 files changed, 23 insertions(+), 30 deletions(-) diff --git a/src/mem/keychain.py b/src/mem/keychain.py index 0b69ea1..4ba695b 100644 --- a/src/mem/keychain.py +++ b/src/mem/keychain.py @@ -140,11 +140,6 @@ def unavailable_reason() -> str | None: return None -def is_available() -> bool: - """Whether the Keychain backend can be attempted at all.""" - return unavailable_reason() is None - - def label_for(name: str) -> str: """Keychain Access display name for a variable. diff --git a/src/mem/storage.py b/src/mem/storage.py index 2dc98e5..d97a7f0 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -1374,21 +1374,6 @@ def set_var(name: str, value: str, last_used: int = 0) -> None: write_vars_file(data) -def get_var_value(name: str) -> str | None: - """Value of one stored variable, from whichever backend holds it. - - None means "mem has no such variable". A Keychain that exists but cannot - be read raises instead — see :func:`mem.keychain.get_secret` for why that - distinction is worth keeping. - """ - entry = read_vars_file().vars.get(name) - if entry is None: - return None - if entry.value is not None: - return entry.value # not migrated yet - return keychain.get_secret(name) - - def load_var_values( names: Iterable[str], ) -> tuple[dict[str, StoredVariable], list[str]]: diff --git a/tests/test_keychain.py b/tests/test_keychain.py index d3dc091..5c08eae 100644 --- a/tests/test_keychain.py +++ b/tests/test_keychain.py @@ -81,6 +81,18 @@ def _raw_vars_json() -> str: return storage.VARS_FILE.read_text(encoding="utf-8") +def _stored_value(name: str) -> str | None: + """A variable's value as ``mem run`` would see it, from whichever backend. + + Goes through :func:`storage.load_var_values`, the production read path, + so the test asserts what a runbook actually resolves. None means the + store has no usable value for the name. + """ + entries, _unreadable = storage.load_var_values([name]) + entry = entries.get(name) + return None if entry is None else entry.value + + # --------------------------------------------------------------------------- # 1. The secret must never appear in argv # --------------------------------------------------------------------------- @@ -146,7 +158,7 @@ def test_value_round_trips_through_the_store( self, tmp_mem_dir: Path, label: str, value: str ) -> None: storage.set_var("API_TOKEN", value) - assert storage.get_var_value("API_TOKEN") == value + assert _stored_value("API_TOKEN") == value assert value not in _raw_vars_json() or value == "" def test_overwriting_replaces_the_value(self) -> None: @@ -329,21 +341,22 @@ class TestAvailability: def test_available_on_macos_with_the_binary(self) -> None: if sys.platform == "darwin" and os.access(keychain.SECURITY_BIN, os.X_OK): - assert keychain.is_available() assert keychain.unavailable_reason() is None def test_unavailable_off_macos(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(keychain.sys, "platform", "linux") - assert not keychain.is_available() - assert "linux" in (keychain.unavailable_reason() or "") + reason = keychain.unavailable_reason() + assert reason is not None + assert "linux" in reason def test_unavailable_without_the_binary( self, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr(keychain.sys, "platform", "darwin") monkeypatch.setattr(keychain.os, "access", lambda *a, **kw: False) - assert not keychain.is_available() - assert keychain.SECURITY_BIN in (keychain.unavailable_reason() or "") + reason = keychain.unavailable_reason() + assert reason is not None + assert keychain.SECURITY_BIN in reason def test_a_locked_keychain_raises_with_the_os_message( self, fake_keychain: FakeKeychain @@ -446,7 +459,7 @@ def test_migration_is_idempotent( assert len(fake_keychain.calls) == calls, ( "a clean store must cost no subprocess" ) - assert storage.get_var_value("API_TOKEN") == "sk-live-TESTONLY" + assert _stored_value("API_TOKEN") == "sk-live-TESTONLY" def test_a_failed_write_leaves_the_plaintext_value_alone( self, tmp_mem_dir: Path, fake_keychain: FakeKeychain @@ -463,7 +476,7 @@ def test_a_failed_write_leaves_the_plaintext_value_alone( assert result.failed == ["API_TOKEN"] assert "not correct" in (result.reason or "") assert storage.read_vars_file().vars["API_TOKEN"].value == "sk-live-TESTONLY" - assert storage.get_var_value("API_TOKEN") == "sk-live-TESTONLY" + assert _stored_value("API_TOKEN") == "sk-live-TESTONLY" def test_a_write_that_cannot_be_read_back_is_not_trusted( self, tmp_mem_dir: Path, fake_keychain: FakeKeychain, monkeypatch @@ -501,7 +514,7 @@ def test_a_keychainless_platform_reports_instead_of_migrating( assert result.migrated == 0 assert result.failed == ["API_TOKEN"] assert "linux" in (result.reason or "") - assert storage.get_var_value("API_TOKEN") == "sk-live-TESTONLY" + assert _stored_value("API_TOKEN") == "sk-live-TESTONLY" # --------------------------------------------------------------------------- @@ -786,7 +799,7 @@ def test_real_migration(self, throwaway_keychain: Path, tmp_mem_dir: Path) -> No assert storage.migrate_vars_to_keychain().migrated == 1 assert "sk-live-TESTONLY" not in _raw_vars_json() - assert storage.get_var_value("MEM_TEST_VAR") == "sk-live-TESTONLY" + assert _stored_value("MEM_TEST_VAR") == "sk-live-TESTONLY" storage.remove_var("MEM_TEST_VAR") From f059264a062fec7951ec45b3b2d260e47cb42af7 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:34:50 -0300 Subject: [PATCH 07/40] docs(storage): seven docstrings that described code other than the code below them Each stated something a reader would act on and be wrong: the Keychain move was cited as ADR-009 (that is the ranking ADR; it is ADR-010); storage.py called itself the only module touching the filesystem while capture.py, picks.py, tui.py and groups.py all do; _fsutil.py claimed storage re-exports it when nothing imports those names through storage; save_command() said it returns a bool and returns a tuple; forget_commands() said it scrubs two places and counts everything when it scrubs seven and counts only history lines; write_group_file() described atomic_write()'s job instead of its own (the lock); and read_vars_file() said "treating as empty" without saying that the next writer then replaces the corrupt file with a one-entry index. Text only, no behaviour changed. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 62fac76eb2390cef026769b425eb62afecc5f4cd) --- src/mem/_fsutil.py | 6 ++++-- src/mem/groups.py | 5 ++++- src/mem/models.py | 4 ++-- src/mem/storage.py | 39 ++++++++++++++++++++++++++++----------- 4 files changed, 38 insertions(+), 16 deletions(-) diff --git a/src/mem/_fsutil.py b/src/mem/_fsutil.py index aa3183e..5b0a553 100644 --- a/src/mem/_fsutil.py +++ b/src/mem/_fsutil.py @@ -11,8 +11,10 @@ copy of the ranking formula would have made the same history sort differently depending on how it was asked for. One implementation, two callers. -``mem.storage`` re-exports everything here under its historical names, so -nothing that already imports from ``storage`` needs to change. +``mem.storage`` imports what it uses from here — some of it under the +private names it had before the split — and wraps :func:`exclusive_lock` +with the lock path. Nothing else goes through ``storage`` for these: the +modules that cannot import it (``picks.py``) import from here directly. """ from __future__ import annotations diff --git a/src/mem/groups.py b/src/mem/groups.py index 0c4df91..543d28b 100644 --- a/src/mem/groups.py +++ b/src/mem/groups.py @@ -81,7 +81,10 @@ def save_command( ) -> tuple[bool, list[VarDeclaration]]: """Save a command to the saved list or a named group. - Returns True if saved, False if duplicate (same cmd string). + Returns ``(saved, vars)``: ``saved`` is False when the same cmd string is + already there, in which case ``vars`` is empty; otherwise ``vars`` is the + merged list of variable declarations recorded with the command, so the + caller can tell the user which placeholders it will prompt for. Creates the group if it doesn't exist, using description_callback to prompt the user for an optional group description. """ diff --git a/src/mem/models.py b/src/mem/models.py index c6d70e8..7617ad4 100644 --- a/src/mem/models.py +++ b/src/mem/models.py @@ -138,7 +138,7 @@ class StoredVariable(BaseModel): - ``value is None`` — the value lives in the macOS Keychain, under the service :data:`mem.keychain.SERVICE` and the variable's name as the - account. This is what every entry written since ADR-009 looks like. + account. This is what every entry written since ADR-010 looks like. - ``value`` is a string — a plaintext value from before the Keychain backend existed, or one whose migration has not succeeded yet. Still readable so nobody's setup breaks, never written by mem today. @@ -170,7 +170,7 @@ class VarsFile(BaseModel): """On-disk representation of the persistent variable store. An index, not a vault: it records which variables exist and when they were - last used. Since ADR-009 the values themselves are in the Keychain. + last used. Since ADR-010 the values themselves are in the Keychain. """ vars: dict[str, StoredVariable] = {} diff --git a/src/mem/storage.py b/src/mem/storage.py index d97a7f0..07b28d6 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -1,8 +1,12 @@ """ Storage layer for mem — pure file I/O with JSONL and JSON. -All mem data lives in ~/.mem/ as plain text files. This module is the -only place in the codebase that touches the filesystem for data storage. +All mem data lives in ~/.mem/ as plain text files. This module owns the +history, session, pattern, group, variable and agent files. It is not the +only module that touches ~/.mem: picks.py writes picks.json through the +same :mod:`mem._fsutil` primitives and lock, capture.py writes +.session_state.json with a plain unlocked write, and tui.py and groups.py +read the history JSONL directly. Why JSONL over SQLite: append-only writes are trivially safe (no write conflicts, no transactions). Files are human-readable and composable @@ -711,11 +715,16 @@ def rotate( def forget_commands(query: str) -> int: """Remove all commands matching query from ALL storage files. - Scrubs from both repo JSONL files AND session files (rewrites - sessions to remove matching command text). Privacy-first means - no traces left anywhere. + Scrubs seven places: repo JSONL files, session files (rewritten to drop + the matching commands and any summary quoting them), extracted patterns, + saved commands and runbooks, stored variables, the in-flight session + state and the agent audit log. Privacy-first means no traces left + anywhere. - Returns total number of removed entries. + Returns the number of repo history lines removed — only those. A forget + that hit nothing but a runbook or a variable returns 0 even though it + scrubbed something, which is why the CLI previews with + :func:`forget_targets` instead of trusting this count. """ removed = 0 @@ -1040,7 +1049,7 @@ def _file_holds(path: Path, query: str, jsonl: bool = False) -> bool: def forget_targets(query: str) -> list[str]: """Human-readable names of the places still holding *query*. - ``forget_commands`` scrubs six destinations, but the CLI only ever + ``forget_commands`` scrubs seven destinations, but the CLI only ever previewed the first one — so ``mem forget`` on text that lives *only* in a saved runbook, a stored variable, an extracted pattern or the agent audit log reported "no matching commands found" and returned without scrubbing @@ -1153,10 +1162,11 @@ def read_group_file(path: Path) -> GroupFile: def write_group_file(path: Path, data: GroupFile) -> None: - """Write group data atomically (tmp + rename pattern). + """Write a scope's group file under the storage lock. - Creates parent directories if needed. Uses the same atomic - write strategy as write_patterns to prevent corruption. + Serialization and atomicity are :func:`atomic_write`'s job; this adds the + lock so a save cannot interleave with ``forget``'s rewrite of the same + file. """ with exclusive_lock(): atomic_write(path, data.model_dump_json(indent=2)) @@ -1168,10 +1178,17 @@ def write_group_file(path: Path, data: GroupFile) -> None: def read_vars_file() -> VarsFile: """Read the persistent variable *index*. Returns empty if missing/corrupted. + "Treating as empty" has a consequence worth knowing: every writer here is + read-modify-write, so the next ``mem vars set`` (or ``touch_vars`` from a + ``mem run``) replaces a corrupt file with an index holding only the entry + it just wrote. Keychain-backed values survive that — the items are still + in the Keychain — but their names vanish from ``mem vars list`` until set + again, and a not-yet-migrated plaintext value goes with the file. + The vars file is global (not repo-scoped) because credentials and environment values typically apply across projects. - Since ADR-009 this file records which variables exist, not what they are: + Since ADR-010 this file records which variables exist, not what they are: values live in the macOS Keychain. Entries written by an older mem still carry their value here until :func:`migrate_vars_to_keychain` moves it. """ From 4b41795aedee41a5d5262d09684d97bc7e14db2d Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:36:59 -0300 Subject: [PATCH 08/40] refactor(storage): every reader caught Exception when it meant "this file is bad" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seven readers wrapped read_text() and a Pydantic parse in `except Exception`, which also swallowed a KeyboardInterrupt-adjacent MemoryError, a RecursionError, or a bug in the model class itself, and reported each as "corrupted file". Pydantic's ValidationError subclasses ValueError, so `ValueError` (plus OSError where the read is inside the try) covers exactly the two things that can be wrong with a file — not JSON, or JSON of the wrong shape — and nothing else. read_group_file() also printed the error to stderr before raising, and its one interactive caller then printed its own message: a corrupt runbook file was reported twice. The broad catch in detect_credentials() stays, because the SDK's failures have no common base class, but the comment now names them instead of hiding behind "detection fails". Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 67b38d1d40c18241b95846165622cf25e62e22a9) --- src/mem/_fsutil.py | 2 ++ src/mem/storage.py | 23 ++++++++++++++--------- src/mem/variables.py | 12 ++++++++++++ 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/mem/_fsutil.py b/src/mem/_fsutil.py index 5b0a553..8ee6833 100644 --- a/src/mem/_fsutil.py +++ b/src/mem/_fsutil.py @@ -98,6 +98,8 @@ def atomic_write(path: Path, data: str, mode: int = FILE_MODE) -> None: os.replace(tmp, path) fsync_dir(path.parent) except BaseException: + # Cleanup only: the temp file must not outlive a KeyboardInterrupt + # either, and the re-raise below lets every exception keep propagating. tmp.unlink(missing_ok=True) raise diff --git a/src/mem/storage.py b/src/mem/storage.py index 07b28d6..2dfb9d8 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -551,7 +551,10 @@ def read_commands( continue try: yield CapturedCommand.from_jsonl(line) - except Exception: + # 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. + except ValueError: print( f"warning: skipping corrupted line {line_num} in {path.name}", file=sys.stderr, @@ -590,7 +593,7 @@ def read_patterns(tool: str) -> PatternFile | None: return None try: return PatternFile.model_validate_json(path.read_text(encoding="utf-8")) - except Exception: + except (OSError, ValueError): print(f"warning: corrupted pattern file {path.name}", file=sys.stderr) return None @@ -617,7 +620,7 @@ def read_sessions(date: str) -> Iterator[WorkSession]: continue try: yield WorkSession.from_jsonl(line) - except Exception: + except ValueError: print( f"warning: skipping corrupted session line {line_num} in {path.name}", file=sys.stderr, @@ -1150,14 +1153,16 @@ def read_group_file(path: Path) -> GroupFile: """Read and parse a group file. Return empty GroupFile if missing. Raises ValueError on malformed JSON so callers can present - a user-friendly error without losing the corrupt file on disk. + a user-friendly error without losing the corrupt file on disk. It does + not print: every caller either reports the error itself or skips the + scope on purpose, and a second message here made the user read the same + failure twice. """ if not path.exists(): return GroupFile() try: return GroupFile.model_validate_json(path.read_text(encoding="utf-8")) - except Exception as e: - print(f"error: cannot read {path}: {e}", file=sys.stderr) + except (OSError, ValueError) as e: raise ValueError(f"Malformed data in {path}") from e @@ -1196,7 +1201,7 @@ def read_vars_file() -> VarsFile: return VarsFile() try: return VarsFile.model_validate_json(VARS_FILE.read_text(encoding="utf-8")) - except Exception: + except (OSError, ValueError): print( f"warning: corrupted vars file {VARS_FILE}, treating as empty", file=sys.stderr, @@ -1249,7 +1254,7 @@ def read_agent_access() -> AgentAccess: return AgentAccess() try: return AgentAccess.model_validate_json(path.read_text(encoding="utf-8")) - except Exception: + except (OSError, ValueError): print( f"warning: corrupted agent file {path.name}, treating as disabled", file=sys.stderr, @@ -1289,7 +1294,7 @@ def read_agent_audit() -> Iterator[AgentAuditEntry]: continue try: yield AgentAuditEntry.from_jsonl(line) - except Exception: + except ValueError: print( f"warning: skipping corrupted line {line_num} in {path.name}", file=sys.stderr, diff --git a/src/mem/variables.py b/src/mem/variables.py index 6fe194f..6b712a1 100644 --- a/src/mem/variables.py +++ b/src/mem/variables.py @@ -537,6 +537,18 @@ def detect_credentials(cmd: str) -> list[tuple[str, str, str]]: raw = asyncio.run(_detect_credentials_async(cmd)) return _deduplicate_detections(raw, cmd) except Exception: + # Broad on purpose: this is a best-effort suggestion, and the failures + # it absorbs have no common base class. Concretely: whatever the SDK's + # @generable decorator raises while `mem._generable` is first imported + # (that module swallows only ImportError, so a TypeError from schema + # inspection propagates out of the import); any apple_fm_sdk + # FoundationModelsError from LanguageModelSession() or respond() — + # GuardrailViolationError, RefusalError, AssetsUnavailableError, + # RateLimitedError, ConcurrentRequestsError, DecodingFailureError, + # ExceededContextWindowSizeError, UnsupportedLanguageOrLocaleError, + # InvalidGenerationSchemaError, all GenerationError subclasses; the + # SDK's own ValueError for a bad `generating` argument; and RuntimeError + # from asyncio.run() when a loop is already running on this thread. return [] From 959b6dd58a5cdcf905b45b3afa25006d7ebf17c8 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:37:56 -0300 Subject: [PATCH 09/40] refactor(storage): _append_line was _append_lines with a list of one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two appenders were the same nine lines — mkdir, harden, open with O_APPEND, write, close, re-harden — differing only in whether the payload was one string or a joined list. Two copies of the owner-only append path is one more place for a permissions fix to be applied to one and forgotten in the other, and this codebase has already paid for that pattern three times. The single-line callers now append a batch of one; the bytes written are identical. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 5a1cbd33c74c17a5e753556b3c6a378201c2d033) --- src/mem/storage.py | 31 +++++++++---------------------- 1 file changed, 9 insertions(+), 22 deletions(-) diff --git a/src/mem/storage.py b/src/mem/storage.py index 2dfb9d8..2cea516 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -111,27 +111,14 @@ def try_sync_lock() -> bool: return True -def _append_line(path: Path, line: str) -> None: - """Append one line to a JSONL file, creating it owner-only.""" - path.parent.mkdir(parents=True, exist_ok=True) - _harden_dir(path.parent) - existed = path.exists() - fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, FILE_MODE) - try: - os.write(fd, (line + "\n").encode("utf-8")) - finally: - os.close(fd) - if existed: - _harden_file(path) - - def _append_lines(path: Path, lines: list[str]) -> None: - """Append many lines to a JSONL file in a single write. + """Append lines to a JSONL file in a single write, creating it owner-only. - Separate from :func:`_append_line` because a shell history import writes - tens of thousands of entries at once: opening, writing and closing the - file per entry turns a sub-second operation into a visible pause, and - leaves a partially written import if the process dies halfway. + One write for the whole batch, never one per line: a shell history import + writes tens of thousands of entries at once, and opening, writing and + closing the file per entry turns a sub-second operation into a visible + pause — and leaves a partially written import if the process dies + halfway. A capture is simply a batch of one. """ if not lines: return @@ -353,7 +340,7 @@ def append_command(cmd: CapturedCommand) -> None: # acquisition in the migration is free. with exclusive_lock(): path = repo_file(resolve_repo_key(cmd.repo)) - _append_line(path, cmd.to_jsonl()) + _append_lines(path, [cmd.to_jsonl()]) def append_commands(cmds: list[CapturedCommand]) -> int: @@ -605,7 +592,7 @@ def append_session(session: WorkSession) -> None: date = dt.strftime("%Y-%m-%d") path = session_file(date) with exclusive_lock(): - _append_line(path, session.to_jsonl()) + _append_lines(path, [session.to_jsonl()]) def read_sessions(date: str) -> Iterator[WorkSession]: @@ -1279,7 +1266,7 @@ def append_agent_audit(entry: AgentAuditEntry) -> None: """ ensure_dirs() with exclusive_lock(): - _append_line(agent_audit_file(), entry.to_jsonl()) + _append_lines(agent_audit_file(), [entry.to_jsonl()]) def read_agent_audit() -> Iterator[AgentAuditEntry]: From 9e1ea03e24de92abe335f10d168c2d32c5abf364 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:42:09 -0300 Subject: [PATCH 10/40] fix(storage): a JSONL line holding `42` crashed rotate, forget and `mem save !` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The JSONL rewriters caught JSONDecodeError and then called `.get` on whatever decoded, so a line that is valid JSON but not an object — `42`, `"x"`, `[]`, `null` — raised AttributeError, while the readers skipped the same line with a warning. rotate() runs inside the background `_sync`, which swallows the exception: from the moment such a line appeared, every sync exited 0, printed nothing, and retention silently stopped for that file and every file sorted after it. `mem forget` died with a traceback after rewriting only the files sorted before the bad one, and `mem save !` on such a last line raised TypeError instead of its own message. One helper now decodes JSONL for every rewriter and for the legacy migration and `mem save !`; a non-object line is kept verbatim, like a line that is not JSON at all. The Pydantic readers keep their own parser: they already handled this, and decoding twice would double the cost of the search hot path. Eight tests pin the crash; all were red before the change. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 7a17543470175cd0a5c76e1e1f78ba3de83597cb) --- src/mem/groups.py | 17 +++---- src/mem/storage.py | 81 ++++++++++++++++--------------- tests/test_groups.py | 19 ++++++++ tests/test_storage_destructive.py | 79 ++++++++++++++++++++++++++++++ 4 files changed, 147 insertions(+), 49 deletions(-) diff --git a/src/mem/groups.py b/src/mem/groups.py index 543d28b..3d98976 100644 --- a/src/mem/groups.py +++ b/src/mem/groups.py @@ -145,23 +145,20 @@ def get_last_captured_command(repo: str | None) -> str: "No captured history found. Run some commands first." ) - last_line = None + last: tuple[str, dict | None] | None = None with path.open("r", encoding="utf-8") as f: - for line in f: - stripped = line.strip() - if stripped: - last_line = stripped + for last in storage.iter_jsonl_objects(f): + pass - if last_line is None: + if last is None: raise click.ClickException( "No captured history found. Run some commands first." ) - try: - data = json.loads(last_line) - return data["command"] - except (json.JSONDecodeError, KeyError): + _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"] def list_all(repo_path: Path | None, global_path: Path) -> dict: diff --git a/src/mem/storage.py b/src/mem/storage.py index 2cea516..6eefea9 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -134,6 +134,34 @@ def _append_lines(path: Path, lines: list[str]) -> None: _harden_file(path) +def iter_jsonl_objects(lines: Iterable[str]) -> Iterator[tuple[str, dict | None]]: + """Walk JSONL text as ``(stripped_line, obj)`` pairs, skipping blank lines. + + ``obj`` is the decoded object, or None when the line is not JSON *or* is + JSON that is not an object — ``42``, ``"x"``, ``[]``, ``null``. That second + case is the reason this exists: the readers already skipped such a line, + but every rewriter (``rotate``, ``forget``, the audit scrub) caught only + JSONDecodeError and then called ``.get`` on an int. ``rotate`` runs inside + the silent background sync, so one such line stopped retention with exit + code 0 and no message. + + What a None means is the caller's decision — the rewriters keep the line + verbatim, because a line they cannot interpret is not theirs to delete. + The Pydantic readers do not go through here: they parse with the model's + own JSON parser, and decoding every line twice would double the cost of + the one path this module measures in milliseconds. + """ + for raw in lines: + line = raw.strip() + if not line: + continue + try: + data = json.loads(line) + except json.JSONDecodeError: + data = None + yield line, data if isinstance(data, dict) else None + + def repo_file(repo: str) -> Path: """Path to a repo's command history file.""" return MEM_DIR / "repos" / f"{repo}.jsonl" @@ -271,11 +299,8 @@ def _migrate_legacy_repo_file_locked(legacy: Path, fallback_key: str) -> None: # Seeded with the requesting repo so an empty legacy file still migrates # (and keeps existing) instead of being silently deleted. buckets: dict[str, list[str]] = {fallback_key: []} - for line in raw.splitlines(): - line = line.strip() - if not line: - continue - buckets.setdefault(_owner_key_of_line(line, fallback_key), []).append(line) + for line, entry in iter_jsonl_objects(raw.splitlines()): + buckets.setdefault(_owner_key_of_entry(entry, fallback_key), []).append(line) destination = repo_file(fallback_key) if list(buckets) == [fallback_key] and not destination.exists(): @@ -294,13 +319,11 @@ def _migrate_legacy_repo_file_locked(legacy: Path, fallback_key: str) -> None: _fsync_dir(legacy.parent) -def _owner_key_of_line(line: str, fallback_key: str) -> str: - """Storage key of the repo that produced one legacy JSONL line.""" - try: - entry = json.loads(line) - owner = entry.get("repo") - except (ValueError, AttributeError): +def _owner_key_of_entry(entry: dict | None, fallback_key: str) -> str: + """Storage key of the repo that produced one decoded legacy JSONL line.""" + if entry is None: return fallback_key + owner = entry.get("repo") return repo_key(owner) if isinstance(owner, str) and owner else fallback_key @@ -651,14 +674,9 @@ def rotate( lines_kept = [] lines_total = 0 with path.open("r", encoding="utf-8") as f: - for line in f: - line_stripped = line.strip() - if not line_stripped: - continue + for line_stripped, data in iter_jsonl_objects(f): lines_total += 1 - try: - data = json.loads(line_stripped) - except json.JSONDecodeError: + if data is None: lines_kept.append(line_stripped) # keep corrupted lines continue ts = data.get("ts") @@ -726,13 +744,8 @@ def forget_commands(query: str) -> int: lines_kept = [] matched = 0 with path.open("r", encoding="utf-8") as f: - for line in f: - line_stripped = line.strip() - if not line_stripped: - continue - try: - data = json.loads(line_stripped) - except json.JSONDecodeError: + for line_stripped, data in iter_jsonl_objects(f): + if data is None: lines_kept.append(line_stripped) continue if query in data.get("command", ""): @@ -757,13 +770,8 @@ def forget_commands(query: str) -> int: sessions_kept = [] matched = False with path.open("r", encoding="utf-8") as f: - for line in f: - line_stripped = line.strip() - if not line_stripped: - continue - try: - data = json.loads(line_stripped) - except json.JSONDecodeError: + for line_stripped, data in iter_jsonl_objects(f): + if data is None: sessions_kept.append(line_stripped) continue cmds = [c for c in data.get("commands", []) if query not in c] @@ -968,13 +976,8 @@ def _scrub_agent_audit(query: str) -> None: kept: list[str] = [] matched = 0 with path.open("r", encoding="utf-8") as f: - for line in f: - stripped = line.strip() - if not stripped: - continue - try: - data = json.loads(stripped) - except json.JSONDecodeError: + for stripped, data in iter_jsonl_objects(f): + if data is None: kept.append(stripped) continue args = data.get("arguments") or {} diff --git a/tests/test_groups.py b/tests/test_groups.py index c9e9125..a5b1af3 100644 --- a/tests/test_groups.py +++ b/tests/test_groups.py @@ -293,6 +293,25 @@ def test_no_history_raises(self, tmp_mem_dir: Path): with pytest.raises(click.ClickException, match="No captured history"): groups.get_last_captured_command("/nonexistent") + def test_last_line_that_is_json_but_not_an_object_is_reported( + self, tmp_mem_dir: Path + ): + """``42`` as the last line is "could not read", not a TypeError. + + The reader caught JSONDecodeError and KeyError, so a line that decoded + to an int reached ``data["command"]`` and ``mem save !`` died with a + traceback instead of its own message. + """ + path = storage.repo_file(storage.repo_key("/test-repo")) + path.parent.mkdir(parents=True, exist_ok=True) + from conftest import make_command + + first = make_command(command="first", repo="/test-repo") + path.write_text(first.to_jsonl() + "\n42\n", encoding="utf-8") + + with pytest.raises(click.ClickException, match="Could not read last command"): + groups.get_last_captured_command("/test-repo") + # --------------------------------------------------------------------------- # list_all diff --git a/tests/test_storage_destructive.py b/tests/test_storage_destructive.py index 961b3f6..0a3cb6e 100644 --- a/tests/test_storage_destructive.py +++ b/tests/test_storage_destructive.py @@ -34,6 +34,7 @@ from conftest import make_command from mem import _fsutil, capture, patterns, search, storage from mem.models import ( + AgentAuditEntry, CommandPattern, Group, GroupCommand, @@ -577,6 +578,29 @@ def test_file_of_entries_without_ts_is_not_deleted(self, tmp_mem_dir, frozen_now assert path.exists(), "rotate() deleted a history file it could not date" + @pytest.mark.parametrize("scalar", ["42", '"x"', "[]", "null"]) + def test_valid_json_that_is_not_an_object_is_preserved( + self, tmp_mem_dir, frozen_now, scalar + ): + """A line that is JSON but not an object is kept like any corrupt line. + + The readers skip such a line with a warning, but rotate() only caught + JSONDecodeError and then called ``.get`` on whatever decoded — an + AttributeError. rotate() runs inside the background ``_sync``, which + swallows the exception, so from the moment such a line appeared every + sync exited 0 and retention silently stopped for that file and every + file sorted after it. + """ + now = frozen_now + path = write_repo_file( + tmp_mem_dir, "w-app", [command_line("old", now - 200 * DAY), scalar] + ) + + removed, _ = storage.rotate() + + assert removed == 1 + assert read_commands_raw(path) == [scalar] + # --- forget: every destination -------------------------------------------- @@ -837,6 +861,61 @@ def test_no_match_preserves_corrupted_lines(self, tmp_mem_dir): assert read_commands_raw(path) == ["NOT JSON"] +class TestForgetKeepsNonObjectLines: + """A JSONL line that decodes to something other than an object is opaque. + + Every rewriter kept lines that were not JSON and crashed on lines that + were JSON of the wrong shape (``42``, ``"x"``, ``[]``): the rewrite caught + JSONDecodeError and then called ``.get`` on an int. For ``mem forget`` + that is a traceback instead of a scrub — on a privacy command, the user + is told nothing was done when in fact the matching files before the bad + one were already rewritten. + """ + + def test_repo_file(self, tmp_mem_dir): + path = write_repo_file(tmp_mem_dir, "w-app", [command_line("ls", 1), "42"]) + + assert storage.forget_commands("ls") == 1 + assert read_commands_raw(path) == ["42"] + + def test_session_file(self, tmp_mem_dir): + path = write_session_file( + tmp_mem_dir, + days_ago_date(0), + [ + { + "id": "s1", + "summary": "work", + "started_at": 1, + "ended_at": 2, + "dir": "/w/app", + "repo": "/w/app", + "commands": ["ls -la", "git status"], + } + ], + ) + with path.open("a", encoding="utf-8") as f: + f.write("42\n") + + storage.forget_commands("ls -la") + + kept = read_commands_raw(path) + assert kept[-1] == "42" + assert json.loads(kept[0])["commands"] == ["git status"] + + def test_agent_audit_log(self, tmp_mem_dir): + storage.append_agent_audit( + AgentAuditEntry(ts=1, tool="search", arguments={"query": "hunter2"}) + ) + path = storage.agent_audit_file() + with path.open("a", encoding="utf-8") as f: + f.write("42\n") + + storage.forget_commands("hunter2") + + assert read_commands_raw(path) == ["42"] + + # --- concurrency (P0-10) --------------------------------------------------- From b6f63852c85a99bafa60fa785e130371c414957f Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:44:16 -0300 Subject: [PATCH 11/40] docs: every unexplained number now says where it came from, or that it did not MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retention (90/30 days, 86400), the sync threshold, the credential regexes' length floors and the lock test's hold time were bare literals. A reader deciding whether to change one had no way to tell a measured constant from a guess, and this codebase's measured constants (the 3-character needle floor, the 8-hex repo suffix) look exactly like its guesses. Each now cites its basis — ADR-003 for the threshold, the vendor's published token length where the count is exact, the v1 README promise for retention — or says literally "chosen by eye, not measured". Comments only; no value changed. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit b67ef36e7e8424c2566a537d55158dfa2a6ecc35) --- src/mem/storage.py | 8 ++++++++ src/mem/variables.py | 19 ++++++++++++++++--- tests/test_storage_destructive.py | 3 +++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/mem/storage.py b/src/mem/storage.py index 6eefea9..d25b952 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -660,6 +660,10 @@ def rotate( """ import time + # The 90/30-day defaults are the retention the README has promised since + # v1 (commit f0164c5); there is no measurement behind either number — + # chosen by eye, not measured. 86400 is seconds per day: retention is + # whole days, and a leap second's worth of drift does not matter here. now = int(time.time()) cmd_cutoff = now - (keep_commands_days * 86400) session_cutoff = now - (keep_sessions_days * 86400) @@ -1091,6 +1095,10 @@ def note(label: str, condition: bool) -> None: # --- Sync counter --- SYNC_COUNTER_FILE = MEM_DIR / ".sync_counter" +# Captures between background syncs. ADR-003 ("Why 20 captures?"): often +# enough that patterns stay fresh, rare enough that the detached process is +# not spawned constantly; the pattern cache makes each sync cheaper than the +# last, so the number was not tuned further. SYNC_THRESHOLD = 20 diff --git a/src/mem/variables.py b/src/mem/variables.py index 6b712a1..b31feba 100644 --- a/src/mem/variables.py +++ b/src/mem/variables.py @@ -300,6 +300,12 @@ def _command_may_contain_credentials(cmd: str) -> bool: # an option. Each entry is a shape that is a credential essentially whenever it # appears — a keyword assigned a non-trivial value, a bearer token, a vendor # key with its documented prefix, or a password embedded in a connection URL. +# +# The length floors — {6,} for an assigned value, {4,} for a URL password, +# {10,}/{20,} after a vendor prefix — are chosen by eye, not measured: low +# enough to catch `hunter2`, high enough that `--token yes` and `:8080@` are +# not credentials. Exact counts ({16} after AKIA) are the vendor's published +# fixed length. _CREDENTIAL_SHAPES: tuple[re.Pattern[str], ...] = ( # KEY=value / key: value where the key names a secret. re.compile( @@ -417,7 +423,9 @@ def _deduplicate_detections( Removes: - Values not actually present in the command (AI hallucinations) - URLs and hostnames (not credentials) - - Very short values (< 8 chars, not plausible secrets) + - Very short values (< 8 chars, not plausible secrets — the 8 is chosen + by eye, not measured; it is what rejects `no` and `prod` while letting + `hunter2`-length passwords through) - Duplicate original_value entries - Values that are substrings of other detected values @@ -700,7 +708,9 @@ def _redact_userinfo(match: re.Match[str]) -> str: # qualified (see _QUALIFIED_SECRET_NAME), it must not be a `$VAR` # reference (`curl -u $USER:$DEPLOY_TOKEN https://…` would otherwise # swallow the URL that follows), and the value must be neither a path - # nor a URL, so `grep api_key ./src/config.py` survives intact. + # nor a URL, so `grep api_key ./src/config.py` survives intact. The + # eight-character floor (one char plus \S{7,}) is chosen by eye, not + # measured — enough to keep a bare `yes`/`true` from being redacted. ( re.compile( rf"(?i)(? str: _redact_tail, ), # 9. Vendor tokens with a documented prefix, anywhere they appear. The - # prefix exists precisely so that scanners can recognise them. + # prefix exists precisely so that scanners can recognise them. Exact + # counts ({35} after AIza, {36} after npm_, {16} after AKIA) are the + # vendor's published fixed length; the open-ended floors ({10,}, + # {16,}, {20,}) are chosen by eye, not measured. ( re.compile( r"\b(?:" diff --git a/tests/test_storage_destructive.py b/tests/test_storage_destructive.py index 0a3cb6e..223db45 100644 --- a/tests/test_storage_destructive.py +++ b/tests/test_storage_destructive.py @@ -953,6 +953,9 @@ def test_exclusive_lock_serializes_processes(self, tmp_mem_dir): intersect, the lock is not excluding anything. """ storage.ensure_dirs() + # Long enough, against ~100 ms of interpreter start-up jitter between + # the two children, that both are alive at once and would overlap if + # the lock excluded nothing; the figure is chosen by eye, not measured. hold = 0.25 procs = [ start_in_process(_worker_hold_lock, str(tmp_mem_dir), tag, hold) From 17fc59e7525f795cb99f577a43c7121a694fad00 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:33:15 -0300 Subject: [PATCH 12/40] docs(cli,render,tui): six comments and docstrings described code that does something else A comment promised yellow placeholders above a line that styles white; the Keychain no-fallback note cited ADR-009 (ranking) instead of ADR-010; the `_sync` docstring said the user cannot call it when it is merely hidden; the `tui` subcommand claimed to behave like every other subcommand while Click eats the `--` that `_entry.py` passes through, so the same argv searches for a different query on the two paths; `render.fit` called a `len()` count an "exact display width"; `history_files` claimed its mtime order helps the empty-query view when `_most_recent` starts at the least recent file; and `read_key` said it collapses escape sequences when it collapses at most three bytes. None of these change behaviour, but each one sends the next reader to fix the wrong thing. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 873e5abebd36be1687cc9f59eb6279224f1128c8) --- src/mem/cli.py | 19 +++++++++++-------- src/mem/render.py | 6 +++++- src/mem/tui.py | 14 ++++++++++---- 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/src/mem/cli.py b/src/mem/cli.py index bbf678f..09b4be9 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -145,7 +145,6 @@ def cli(ctx: click.Context, pattern: bool, as_json: bool, limit: int) -> None: return console.print(f'\nPatterns for "{query}":\n') for p in patterns: - # Highlight placeholders in yellow text = Text(f" {p.pattern}") console.print(text, style="white") console.print() @@ -268,11 +267,14 @@ def concepts() -> None: def tui(query: tuple[str, ...]) -> None: """Interactive history finder (bound to Ctrl+R by the shell hook). - Registered here so it shows up in ``mem --help`` and behaves like every - other subcommand. It is not normally reached through this path: - ``mem/_entry.py`` dispatches ``mem tui`` before Click is imported, - because the finder's entire latency budget is smaller than that import. - Reaching it through Click still works — it is just slower to appear. + Registered here so it shows up in ``mem --help``. It is not normally + reached through this path: ``mem/_entry.py`` dispatches ``mem tui`` + before Click is imported, because the finder's entire latency budget is + smaller than that import. Reaching it through Click still works — it is + slower to appear, and it does not see the same arguments: Click consumes + a literal ``--`` before ``tui_main`` runs, so ``mem tui -- -la`` searches + for ``-la`` through ``_entry.py`` but for ``""`` through this command, + which drops every dash-prefixed word it is handed. """ from mem.tui import main as tui_main @@ -284,7 +286,8 @@ def sync_cmd() -> None: """Internal: background pattern extraction and data rotation. Triggered automatically every 20 captured commands. Runs silently — - no output, no errors. Never called by the user directly. + no output, no errors. Hidden from ``--help`` rather than blocked: a user + who types ``mem _sync`` gets a synchronous run, which is harmless. """ from mem import storage @@ -1876,7 +1879,7 @@ def vars_set(name: str, value: str | None) -> None: try: storage.set_var(name, value) except keychain.KeychainError as exc: - # No plaintext fallback, deliberately. See ADR-009: a tool that + # No plaintext fallback, deliberately. See ADR-010: a tool that # promises the Keychain and quietly writes cleartext when the Keychain # is busy is more dangerous than one that never promised anything. raise click.ClickException( diff --git a/src/mem/render.py b/src/mem/render.py index 3c532be..103545b 100644 --- a/src/mem/render.py +++ b/src/mem/render.py @@ -64,7 +64,11 @@ def no_matches(query: str) -> None: def fit(value: str, width: int) -> str: - """Pad or truncate to an exact display width, with an ellipsis if cut. + """Pad or truncate to *width* code points, with an ellipsis if cut. + + Measured with ``len()``, not in terminal columns, so a value containing + CJK or emoji (two columns each) misaligns the row. ``tui.display_width`` + does the column arithmetic properly; this surface has not needed it yet. Applied to the raw string before escaping: escaping inserts backslashes that are not displayed, so measuring afterwards would misalign columns. diff --git a/src/mem/tui.py b/src/mem/tui.py index e93e0c0..51bb629 100644 --- a/src/mem/tui.py +++ b/src/mem/tui.py @@ -102,8 +102,10 @@ class Result(NamedTuple): def history_files(mem_dir: str) -> list[str]: """Every history file, newest-modified first. - Ordering by mtime means the repo the user is actually working in tends to - be read first, which matters for the empty-query view. + The ordering is only about which file is read first. It does not help the + empty-query view: ``_most_recent`` walks the concatenated lines from the + end, so on a multi-file store it starts in the *least* recently modified + file and stops before reaching the newest one. """ repos = os.path.join(mem_dir, "repos") try: @@ -504,10 +506,14 @@ def __init__(self, fd: int) -> None: self._decoder = codecs.getincrementaldecoder("utf-8")("replace") def read_key(self) -> str: - """Read one keypress, collapsing escape sequences into a single token. + """Read one keypress, collapsing a short escape sequence into one token. Arrow keys arrive as three bytes. Reading them one at a time would - move the selection and then insert ``[A`` into the query. + move the selection and then insert ``[A`` into the query. Only up to + three bytes are collapsed (ESC, ``[`` or ``O``, one final): longer + sequences such as ``ESC [ 1 ; 5 C`` (Ctrl+Right) or ``ESC [ 3 ~`` + (Delete) come back as their first three bytes, and the remainder is + read as ordinary keypresses. """ first = self._read_char() if first != _ESC: From 2f9585e22c4943716cbf33edc28244ea0233c44d Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:34:48 -0300 Subject: [PATCH 13/40] test(tui,groups): two tests could not fail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `test_the_prefilter_agrees_with_the_storage_layer` wrote `assert [inlined] if inlined else [] == official`, which Python parses as `[inlined] if inlined else ([] == official)` — a non-empty list, so it passed for every term that produced a needle regardless of what storage said. Parenthesised, it still passes: the two implementations agree on all eleven inputs today, and now a divergence would show. Mutating `_MIN_NEEDLE_LEN` in tui.py turns it red on 'ab'. `TestValidateGroupName::test_valid_names` called the validator and asserted nothing. It now asserts the call returns None, which is the contract: a valid name is accepted silently and rejection is only ever an exception. Mutating the validator to `return True` turns it red. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 75d294bca60776c6a96892b5f382d3d152bea087) --- tests/test_groups.py | 6 +++++- tests/test_tui.py | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/test_groups.py b/tests/test_groups.py index a5b1af3..b402e5a 100644 --- a/tests/test_groups.py +++ b/tests/test_groups.py @@ -158,7 +158,11 @@ def test_malformed_json_raises(self, tmp_mem_dir: Path): class TestValidateGroupName: @pytest.mark.parametrize("name", ["deploy", "my-group", "a1", "test-123-abc"]) def test_valid_names(self, name: str): - groups.validate_group_name(name) # should not raise + # A valid name is accepted silently: no exception and no value. The + # invalid-name test below proves rejection raises, so a mutation that + # returned a flag instead of raising would slip past both without + # this assertion. + assert groups.validate_group_name(name) is None @pytest.mark.parametrize( "name", diff --git a/tests/test_tui.py b/tests/test_tui.py index d85d8e4..0265e9f 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -168,7 +168,7 @@ def test_the_prefilter_agrees_with_the_storage_layer(self): inlined = tui._stable_run(term) official = storage.prefilter_needles([term]) - assert [inlined] if inlined else [] == official, f"disagree on {term!r}" + assert ([inlined] if inlined else []) == official, f"disagree on {term!r}" def test_every_term_must_match(self): lines = [line_of("docker compose up"), line_of("docker build .")] From 12fc91f9b52c75817406a4213989bc4ffe6efd38 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:36:50 -0300 Subject: [PATCH 14/40] fix(cli): a failed capture left no trace anywhere MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `mem _capture` swallowed every exception with a bare `pass`, so a store that stopped being writable, a corrupt state file, or a git subprocess error meant history silently stopped accumulating with exit code zero on every prompt and nothing to switch on to see why. The shell still sees nothing — that is the contract — but the failure now goes to the `mem.capture` logger at DEBUG with the traceback, exactly as `_sync` already reported its own failures. The comment names what actually reaches that handler; session tracking and the sync trigger swallow their own errors inside `capture_command`. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit cb7647f36647d42c521b2ecabf357be2ea09ac24) --- src/mem/cli.py | 12 ++++++++++-- tests/test_cli.py | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/mem/cli.py b/src/mem/cli.py index 09b4be9..924f89f 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -196,8 +196,16 @@ def capture_cmd(command: str, dir: str, exit_code: int, duration_ms: int) -> Non capture_command(command, dir, exit_code, duration_ms) except Exception: - # Silent failure — never disrupt the user's shell - pass + # Silent toward the shell — this runs inside the prompt — but not + # invisible: with a logging handler configured (a test's caplog, or a + # basicConfig in a debugging session) the traceback is there, the + # same way `_sync` reports. What actually reaches here: OSError from + # the store (disk full, permissions, a lock that never came free), a + # pydantic ValueError when the hook hands over an argument the model + # rejects, and an OSError other than FileNotFoundError from the git + # subprocess. Session tracking and the sync trigger swallow their + # own failures inside capture_command. + logging.getLogger("mem.capture").debug("capture failed", exc_info=True) # Shells mem can emit a capture hook for. Deliberately distinct from diff --git a/tests/test_cli.py b/tests/test_cli.py index f7ad875..57db2e8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -16,6 +16,7 @@ from __future__ import annotations import json +import logging import time from typing import Iterator from unittest.mock import patch @@ -546,6 +547,27 @@ def test_capture_never_fails_the_shell( assert result.exit_code == 0 assert result.stdout == "" + def test_capture_failure_is_logged_at_debug( + self, tmp_mem_dir, runner: CliRunner, outside_repo: None, caplog + ) -> None: + """Silent toward the shell, but the traceback reaches the logger. + + Before this, a capture failing on every prompt left no trace anywhere: + exit code zero, no output, and nothing to turn on to find out why. + """ + with ( + caplog.at_level(logging.DEBUG, logger="mem.capture"), + patch("mem.capture.capture_command", side_effect=OSError("disk full")), + ): + result = runner.invoke(cli, ["_capture", "git status", "/tmp", "0", "12"]) + + assert result.exit_code == 0 + assert result.stdout == "" + [record] = [r for r in caplog.records if r.name == "mem.capture"] + assert record.levelno == logging.DEBUG + assert record.exc_info is not None + assert "disk full" in caplog.text + # --------------------------------------------------------------------------- # --json across the CLI From 7f1afd20ae4183db2cb0f459518fff47c7c2bac0 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:39:57 -0300 Subject: [PATCH 15/40] docs(cli,tui): every magic number now says where it came from Result limits, column widths, the preview row cap, the clipboard timeout, the rule width, the escape-sequence wait, the metadata and command column floors and the terminal-size fallback all sat in the code as bare literals. A reader tuning one of them could not tell a measured threshold from a guess, and in this codebase that distinction has mattered: the ranking weights and the promote limit carry measurements (ADR-009, ADR-012), and treating an unmeasured number the same way would be lending it an authority it never had. `git log -S` on each literal found no stated basis for any of them beyond the 24x80 fallback (the VT100 default) and tui's `_MIN_NEEDLE_LEN`, which mirrors storage's and now carries its sentence, so the rest say literally "chosen by eye, not measured". Values unchanged. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 6e5da4f00e308c356ace9d525127e4a5fe005eb8) --- src/mem/cli.py | 18 ++++++++++++++++++ src/mem/tui.py | 16 +++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/mem/cli.py b/src/mem/cli.py index 924f89f..73dd2e8 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -110,6 +110,8 @@ def _relative_time(ts: int) -> str: "--pattern", "-p", is_flag=True, help="Show extracted patterns instead of commands" ) @click.option("--json", "as_json", is_flag=True, help="Output as JSON") +# 10 results: chosen by eye, not measured. `mem fix` shows 3 and `mem agent +# log` 20 on the same basis; only `mem promote` (5) has a stated one, ADR-012. @click.option("--limit", "-n", default=10, help="Maximum results") @click.pass_context def cli(ctx: click.Context, pattern: bool, as_json: bool, limit: int) -> None: @@ -175,6 +177,9 @@ def cli(ctx: click.Context, pattern: bool, as_json: bool, limit: int) -> None: for i, (cmd, score) in enumerate(results, 1): rank = f" {i:>2}" + # Column widths — 40 for a command, 12 for a repo here, and the 20 and + # 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) time_text = _relative_time(cmd.ts) @@ -402,6 +407,7 @@ def stats(as_json: bool) -> None: repos.append(cmd.repo) total = len(commands) + # 10 commands and 5 repos: chosen by eye, not measured. cmd_freq = Counter(commands).most_common(10) repo_freq = Counter(repos).most_common(5) @@ -416,6 +422,7 @@ def stats(as_json: bool) -> None: console.print(f"Commands: {total:,} total\n") + # Column widths: chosen by eye, see the search listing. if cmd_freq: console.print("Top commands:") for i, (cmd, count) in enumerate(cmd_freq, 1): @@ -465,6 +472,7 @@ def _fix_evidence(entry: dict) -> str: @cli.command(name="fix") @click.argument("query", nargs=-1) @click.option("--json", "as_json", is_flag=True, help="Output as JSON") +# 3 fixes: chosen by eye, not measured. @click.option("--limit", "-n", default=3, help="Maximum fixes to show") def fix_cmd(query: tuple[str, ...], as_json: bool, limit: int) -> None: """Show what fixed a failed command the last time it broke. @@ -576,6 +584,7 @@ def _promote_steps(entry: dict) -> None: # character class. Aligned under the label column of _fix_line. console.print(Text(f" {step}")) for variable in entry["variables"]: + # Three sample values: chosen by eye, not measured. shown = ", ".join(variable["values"][:3]) more = " …" if len(variable["values"]) > 3 else "" console.print(_fix_detail(f"${variable['name']} was {shown}{more}")) @@ -741,6 +750,8 @@ def forget(query: str, yes: bool) -> None: if not yes: console.print(f"Found {len(matches)} matching commands:") + # 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" time_text = _relative_time(cmd.ts) @@ -943,6 +954,8 @@ def list_cmd( console.print( " [dim](global group with same name exists — use --global to see it)[/]" ) + # 50 columns of rule, here and in the group view: chosen by eye, not + # measured. console.print(" " + "─" * 50) # Load variable store for status display @@ -1260,6 +1273,8 @@ def _read_from_clipboard() -> str | None: try: # macOS if shutil.which("pbpaste"): + # 5 s: chosen by eye, not measured. pbpaste answers at once or + # hangs; the bound only decides how long a hang holds the prompt. result = sp.run(["pbpaste"], capture_output=True, text=True, timeout=5) if result.returncode == 0 and result.stdout.strip(): return result.stdout @@ -1946,6 +1961,7 @@ def vars_list(as_json: bool) -> None: where = "[yellow]plaintext[/]" else: where = "[green]keychain [/]" + # Column width: chosen by eye, see the search listing. console.print(f" {safe(fit(name, 20))} {where} {time_str}") if plaintext: @@ -2076,6 +2092,7 @@ def agent_status(as_json: bool) -> None: @agent_grp.command(name="log") +# 20 entries: chosen by eye, not measured. @click.option("--limit", "-n", default=20, help="Maximum entries (newest last)") @click.option("--json", "as_json", is_flag=True, help="Output as JSON") def agent_log(limit: int, as_json: bool) -> None: @@ -2096,6 +2113,7 @@ def agent_log(limit: int, as_json: bool) -> None: for entry in entries: args = " ".join(f"{k}={v}" for k, v in entry.arguments.items()) mark = "[green]✓[/]" if entry.ok else "[yellow]✗[/]" + # Column widths: chosen by eye, see the search listing. detail = entry.error or f"{entry.results} result(s)" console.print( f" {mark} {safe(fit(entry.tool, 16))} {safe(fit(args, 40))}" diff --git a/src/mem/tui.py b/src/mem/tui.py index 51bb629..802d13d 100644 --- a/src/mem/tui.py +++ b/src/mem/tui.py @@ -205,6 +205,9 @@ def candidate_lines(lines: Sequence[str], terms: Sequence[str]) -> Iterator[str] _STABLE = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-") +# Below this length a needle matches almost every line, so the scan costs more +# than it saves. Mirrors ``storage._MIN_NEEDLE_LEN`` (this module cannot +# import storage); a test pins the two implementations against each other. _MIN_NEEDLE_LEN = 3 @@ -421,11 +424,14 @@ def _render_row(result: Result, is_selected: bool, columns: int, now: float) -> age = relative_time(entry.ts, now) repo = os.path.basename(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. meta = _visible(f"{repo} {age}".strip(), min(22, max(columns // 3, 0))) meta_width = display_width(meta) # The -1 reserves the single-column gap below. Without it a maximally long # command leaves no room for the gap, the `max(..., 1)` adds one anyway, - # and the row runs one column past the edge and wraps. + # and the row runs one column past the edge and wraps. The floor of 8 + # command columns is chosen by eye, not measured. command = _visible(entry.command, max(columns - _PREFIX_WIDTH - meta_width - 1, 8)) gap = max(columns - _PREFIX_WIDTH - display_width(command) - meta_width, 1) @@ -539,6 +545,10 @@ def _read_char(self) -> str: def _read_char_if_ready(self) -> str: """Read another character only if the terminal already sent it.""" + # 50 ms: chosen by eye, not measured. A local terminal delivers the + # rest of a sequence in the same write, so anything above a few ms + # works there; the margin is for a slow ssh hop. Too short and an + # arrow key over ssh becomes Escape plus "[A" typed into the query. ready, _, _ = select.select([self.fd], [], [], 0.05) if not ready: return "" @@ -647,8 +657,12 @@ def _terminal_size(stream: IO[str]) -> tuple[int, int]: """Rows and columns, with a usable fallback when there is no terminal.""" try: size = os.get_terminal_size(stream.fileno()) + # The floor of 20 columns is chosen by eye, not measured; the + # prototype crashed at narrow widths until every computed width + # was clamped (ADR-008). return max(size.lines, _CHROME_ROWS + 1), max(size.columns, 20) except (OSError, ValueError): + # The VT100 default, and what shutil.get_terminal_size falls back to. return 24, 80 From 552f2ee89e0f44f1f4305947a0b7c8465317724d Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:41:22 -0300 Subject: [PATCH 16/40] refactor(cli,groups): the group-file path was sanitised twice at five call sites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `storage.group_file_path` already runs `sanitize_repo_name` on whatever it is given, and every caller in cli.py and `groups.resolve_scope` sanitised the repo path first and handed over the slug. The slug is a fixed point of the sanitiser, so the on-disk name is byte-identical either way — the `resolve_scope` test now pins that name literally so a future change to either function that moved the file would show. What the duplication cost was the reading: five sites implied the callee did not sanitise, which is exactly the kind of wrong belief that gets a sixth site written without the call. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit a68d1473ad950b35d2585d0fa94047aa6839859c) --- src/mem/cli.py | 12 ++++-------- src/mem/groups.py | 3 +-- tests/test_groups.py | 8 ++++++-- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/mem/cli.py b/src/mem/cli.py index 73dd2e8..f018c29 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -913,8 +913,7 @@ def list_cmd( repo_path = None if not global_flag and repo: - sanitized = storage.sanitize_repo_name(repo) - repo_path = storage.group_file_path(sanitized) + repo_path = storage.group_file_path(repo) # Show a specific group's commands if group_name is not None: @@ -1100,8 +1099,7 @@ def run( repo_path = None repo = _current_repo() if repo: - sanitized = storage.sanitize_repo_name(repo) - repo_path = storage.group_file_path(sanitized) + repo_path = storage.group_file_path(repo) grp, scope_label, _file_path, shadows = groups.resolve_group( group_name, @@ -1350,8 +1348,7 @@ def export(group_name: str, fmt: str, global_flag: bool, use_stdout: bool) -> No repo_path = None repo = _current_repo() if repo: - sanitized = storage.sanitize_repo_name(repo) - repo_path = storage.group_file_path(sanitized) + repo_path = storage.group_file_path(repo) grp, _, _, _ = groups.resolve_group( group_name, @@ -1773,8 +1770,7 @@ def group_copy(name: str, global_flag: bool, repo_flag: bool) -> None: if repo is None: raise click.ClickException("Not in a git repository.") - sanitized = storage.sanitize_repo_name(repo) - repo_path = storage.group_file_path(sanitized) + repo_path = storage.group_file_path(repo) global_path = storage.GROUPS_GLOBAL_FILE if global_flag: diff --git a/src/mem/groups.py b/src/mem/groups.py index 3d98976..c68e0f1 100644 --- a/src/mem/groups.py +++ b/src/mem/groups.py @@ -44,8 +44,7 @@ def resolve_scope(global_flag: bool) -> Path: repo = get_git_repo(os.getcwd()) if repo is None: return storage.GROUPS_GLOBAL_FILE - sanitized = storage.sanitize_repo_name(repo) - return storage.group_file_path(sanitized) + return storage.group_file_path(repo) def validate_group_name(name: str) -> None: diff --git a/tests/test_groups.py b/tests/test_groups.py index b402e5a..e1e4054 100644 --- a/tests/test_groups.py +++ b/tests/test_groups.py @@ -1368,8 +1368,12 @@ def test_global_flag(self, tmp_mem_dir: Path): def test_in_repo(self, tmp_mem_dir: Path): with patch("mem.groups.get_git_repo", return_value=FAKE_REPO): path = groups.resolve_scope(global_flag=False) - expected_name = storage.sanitize_repo_name(FAKE_REPO) - assert path == storage.group_file_path(expected_name) + assert path == storage.group_file_path(FAKE_REPO) + # The on-disk name is pinned literally: callers used to sanitise the + # path themselves before handing it to group_file_path, which + # sanitises again, and the file must not move now that they do not. + assert path.name == storage.sanitize_repo_name(FAKE_REPO) + ".json" + assert path.name == "Users-test-projects-myapp.json" def test_outside_repo_falls_back_to_global(self, tmp_mem_dir: Path): with patch("mem.groups.get_git_repo", return_value=None): From 437d2d3a42ef63b08f47553e0d393259b35bcf97 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:42:59 -0300 Subject: [PATCH 17/40] refactor(cli): the clipboard helpers carried Linux branches nothing could reach MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_read_from_clipboard` and `_copy_to_clipboard` fell through from pbpaste/pbcopy to xclip and then xsel — 26 lines that no test exercised and that no user runs, because mem is a macOS tool by decision (ADR-010: the variable store already does not work anywhere else). Untested fallback code is where the next silent bug lives, so the helpers now do exactly one thing each, and the seven tests added pin all of it: the bytes handed to pbcopy, a blank pasteboard, a missing binary running nothing, a hung pbpaste and a failed pbcopy. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit b145828f382b5d7ee3de92a676252ddb90ca4e6d) --- src/mem/cli.py | 63 +++++++++++---------------------- tests/test_cli.py | 89 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 42 deletions(-) diff --git a/src/mem/cli.py b/src/mem/cli.py index f018c29..3242fb0 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -1264,64 +1264,43 @@ def run( def _read_from_clipboard() -> str | None: - """Read text from system clipboard. Returns None if unavailable or empty.""" + """Read text from the macOS pasteboard. None if unavailable or empty. + + ``pbpaste`` only: mem is a macOS tool by decision (ADR-010), and the + ``xclip``/``xsel`` branches that used to follow were never exercised by + any test or any user. + """ import shutil import subprocess as sp + if not shutil.which("pbpaste"): + return None try: - # macOS - if shutil.which("pbpaste"): - # 5 s: chosen by eye, not measured. pbpaste answers at once or - # hangs; the bound only decides how long a hang holds the prompt. - result = sp.run(["pbpaste"], capture_output=True, text=True, timeout=5) - if result.returncode == 0 and result.stdout.strip(): - return result.stdout - # Linux (X11) - if shutil.which("xclip"): - result = sp.run( - ["xclip", "-selection", "clipboard", "-o"], - capture_output=True, - text=True, - timeout=5, - ) - if result.returncode == 0 and result.stdout.strip(): - return result.stdout - if shutil.which("xsel"): - result = sp.run( - ["xsel", "--clipboard", "--output"], - capture_output=True, - text=True, - timeout=5, - ) - if result.returncode == 0 and result.stdout.strip(): - return result.stdout + # 5 s: chosen by eye, not measured. pbpaste answers at once or hangs; + # the bound only decides how long a hang holds the prompt. + result = sp.run(["pbpaste"], capture_output=True, text=True, timeout=5) except (sp.CalledProcessError, sp.TimeoutExpired): return None + if result.returncode == 0 and result.stdout.strip(): + return result.stdout return None def _copy_to_clipboard(text: str) -> bool: - """Copy text to system clipboard. Returns True on success.""" + """Copy text to the macOS pasteboard. True on success. + + ``pbcopy`` only, for the same reason as :func:`_read_from_clipboard`. + """ import shutil import subprocess as sp + if not shutil.which("pbcopy"): + return False try: - # macOS - if shutil.which("pbcopy"): - sp.run(["pbcopy"], input=text.encode(), check=True) - return True - # Linux (X11) - if shutil.which("xclip"): - sp.run( - ["xclip", "-selection", "clipboard"], input=text.encode(), check=True - ) - return True - if shutil.which("xsel"): - sp.run(["xsel", "--clipboard", "--input"], input=text.encode(), check=True) - return True + sp.run(["pbcopy"], input=text.encode(), check=True) except sp.CalledProcessError: return False - return False + return True @cli.command() diff --git a/tests/test_cli.py b/tests/test_cli.py index 57db2e8..857d6e8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -17,6 +17,7 @@ import json import logging +import subprocess import time from typing import Iterator from unittest.mock import patch @@ -913,3 +914,91 @@ def test_unicode_survives_json_roundtrip( assert result.exit_code == 0 assert [entry["command"] for entry in json.loads(result.stdout)] == [command] + + +# --------------------------------------------------------------------------- +# Clipboard helpers +# --------------------------------------------------------------------------- + + +class TestClipboard: + """``pbcopy``/``pbpaste`` only: mem is a macOS tool by decision (ADR-010). + + The helpers used to fall through to ``xclip`` and ``xsel``, twenty-odd + lines no test reached. What remains is small enough to pin completely. + """ + + def test_read_returns_pasteboard_text(self) -> None: + from mem.cli import _read_from_clipboard + + completed = subprocess.CompletedProcess(["pbpaste"], 0, stdout="ls -la\n") + with ( + patch("shutil.which", return_value="/usr/bin/pbpaste"), + patch("subprocess.run", return_value=completed) as run, + ): + assert _read_from_clipboard() == "ls -la\n" + assert run.call_args.args[0] == ["pbpaste"] + + @pytest.mark.parametrize("stdout", ["", " \n"]) + def test_read_treats_blank_pasteboard_as_empty(self, stdout: str) -> None: + from mem.cli import _read_from_clipboard + + completed = subprocess.CompletedProcess(["pbpaste"], 0, stdout=stdout) + with ( + patch("shutil.which", return_value="/usr/bin/pbpaste"), + patch("subprocess.run", return_value=completed), + ): + assert _read_from_clipboard() is None + + def test_read_without_pbpaste_is_none_and_runs_nothing(self) -> None: + from mem.cli import _read_from_clipboard + + with ( + patch("shutil.which", return_value=None), + patch("subprocess.run") as run, + ): + assert _read_from_clipboard() is None + run.assert_not_called() + + def test_read_survives_a_hung_pbpaste(self) -> None: + from mem.cli import _read_from_clipboard + + with ( + patch("shutil.which", return_value="/usr/bin/pbpaste"), + patch( + "subprocess.run", side_effect=subprocess.TimeoutExpired("pbpaste", 5) + ), + ): + assert _read_from_clipboard() is None + + def test_copy_feeds_pbcopy_the_bytes(self) -> None: + from mem.cli import _copy_to_clipboard + + with ( + patch("shutil.which", return_value="/usr/bin/pbcopy"), + patch("subprocess.run") as run, + ): + assert _copy_to_clipboard("héllo") is True + assert run.call_args.args[0] == ["pbcopy"] + assert run.call_args.kwargs["input"] == "héllo".encode() + + def test_copy_without_pbcopy_is_false_and_runs_nothing(self) -> None: + from mem.cli import _copy_to_clipboard + + with ( + patch("shutil.which", return_value=None), + patch("subprocess.run") as run, + ): + assert _copy_to_clipboard("x") is False + run.assert_not_called() + + def test_copy_reports_a_failed_pbcopy(self) -> None: + from mem.cli import _copy_to_clipboard + + with ( + patch("shutil.which", return_value="/usr/bin/pbcopy"), + patch( + "subprocess.run", side_effect=subprocess.CalledProcessError(1, "pbcopy") + ), + ): + assert _copy_to_clipboard("x") is False From 06c4ffdd322864d8b1131fdea67ea754e27e3b2a Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:49:52 -0300 Subject: [PATCH 18/40] fix(tui): the empty-query view showed the least recent repo, not the newest commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ctrl+R with nothing typed is meant to list what you ran last. `_most_recent` walked the concatenation of every history file from its end and stopped after MAX_RESULTS distinct commands — and `history_files` orders the files newest-modified first, so the walk started at the end of the *least* recently modified file and, on any store with a few hundred commands, never reached the others. A stale repo with 300 commands hid a fresh one with 5; every user with more than one repo saw the wrong list before typing a character. The test reproduces exactly that and failed before the change. The files are now walked backwards together, always taking the newest of their heads (a heap merge), so the result is the globally newest `limit` distinct commands at any dedup depth after about `limit` parses plus one per file. `read_history` returns the index at which each file begins and `Finder`/`rank` carry it; `read_raw_lines` is unchanged for callers that only want the text. Measured on 20k lines across 8 files: 0.42 ms against 0.39 ms for the old walk, so first-frame cost is unchanged. Sorting the whole list by a regex-extracted `ts` was rejected at 5.7 ms — a quarter of ADR-008's budget — and reordering the files oldest-first was rejected because it still shows one file at a time when two repos are in use. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit b79aa8df2e749d3f5347ed202b0b734d7c2e4fef) --- src/mem/tui.py | 108 +++++++++++++++++++++++++++++++++------------- tests/test_tui.py | 65 ++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 29 deletions(-) diff --git a/src/mem/tui.py b/src/mem/tui.py index 802d13d..9bd0fca 100644 --- a/src/mem/tui.py +++ b/src/mem/tui.py @@ -26,6 +26,7 @@ from __future__ import annotations import codecs +import heapq import json import os import select @@ -102,10 +103,9 @@ class Result(NamedTuple): def history_files(mem_dir: str) -> list[str]: """Every history file, newest-modified first. - The ordering is only about which file is read first. It does not help the - empty-query view: ``_most_recent`` walks the concatenated lines from the - end, so on a multi-file store it starts in the *least* recently modified - file and stops before reaching the newest one. + The order only breaks ties: ``_most_recent`` merges every file by + timestamp, and two commands captured in the same second in different + repos are shown with the more recently written file first. """ repos = os.path.join(mem_dir, "repos") try: @@ -123,20 +123,30 @@ def _mtime(path: str) -> float: return 0.0 -def read_raw_lines(paths: Sequence[str]) -> list[str]: - """Read every history line as text, without parsing any of it. +def read_history(paths: Sequence[str]) -> tuple[list[str], list[int]]: + """Every history line as text, and the index at which each file begins. - ``errors="replace"`` because a history file is whatever the user typed, - and a single undecodable byte must not take down the finder. + Nothing is parsed here. ``errors="replace"`` because a history file is + whatever the user typed, and a single undecodable byte must not take down + the finder. The starts are what let :func:`_most_recent` walk the files + separately without the list being copied per file. """ lines: list[str] = [] + starts: list[int] = [] for path in paths: try: with open(path, "r", encoding="utf-8", errors="replace") as handle: - lines.extend(handle.read().splitlines()) + text = handle.read() except OSError: continue - return lines + starts.append(len(lines)) + lines.extend(text.splitlines()) + return lines, starts + + +def read_raw_lines(paths: Sequence[str]) -> list[str]: + """Every history line as text, files concatenated in the order given.""" + return read_history(paths)[0] def parse_entry(line: str) -> Entry | None: @@ -238,15 +248,18 @@ def rank( current_repo: str | None, now: float, limit: int = MAX_RESULTS, + starts: Sequence[int] = (0,), ) -> list[Result]: """Rank history against a query, deduplicated by command text. With an empty query there is nothing to rank, so the most recent commands are returned instead — which is what Ctrl+R means before you type. + *starts* is where each history file begins in *lines*, as + :func:`read_history` reports it; only the empty query needs it. """ terms = terms_of(query) if not terms: - return _most_recent(lines, limit) + return _most_recent(lines, limit, starts) # Read once for the whole page: it is one small file, and reading it per # candidate would turn every keystroke into thousands of stat() calls. @@ -285,22 +298,52 @@ def rank( return results[:limit] -def _most_recent(lines: Sequence[str], limit: int) -> list[Result]: - """The newest distinct commands, without scoring anything. - - Walks backwards so the scan stops as soon as ``limit`` distinct commands - have been seen — the whole point of not ranking an empty query. +def _most_recent( + lines: Sequence[str], limit: int, starts: Sequence[int] = (0,) +) -> list[Result]: + """The newest distinct commands across every file, without scoring anything. + + Each history file is append-only, so its newest line is its last. The + files are walked backwards *together*, always taking the newest of their + heads — a k-way merge — so the scan stops after about ``limit`` parses + plus one per file, which is the whole point of not ranking an empty + query. It used to walk the concatenation from its end, which on a + multi-repo store meant the end of whichever file was read last, and the + ``limit`` distinct commands were found before the other files were + reached: a stale repo with 300 commands hid a fresh one with 5. + + *starts* is where each file begins in *lines*; ``(0,)`` is one file. + Ties on the timestamp go to the earlier file, which :func:`history_files` + makes the more recently written one. """ + ends = [*starts[1:], len(lines)] + # Next index to read in each file, walking backwards. + cursors = [end - 1 for end in ends] + # (-ts, file, -index, entry): the newest line is the smallest tuple, and + # (file, index) is unique so the entry itself is never compared. + heap: list[tuple[int, int, int, Entry]] = [] + + def push_head(file: int) -> None: + index = cursors[file] + while index >= starts[file]: + entry = parse_entry(lines[index]) + if entry is not None: + heapq.heappush(heap, (-entry.ts, file, -index, entry)) + index -= 1 + break + index -= 1 + cursors[file] = index + + for file in range(len(starts)): + push_head(file) + seen: dict[str, Entry] = {} - for line in reversed(lines): - entry = parse_entry(line) - if entry is None or entry.command in seen: - continue - seen[entry.command] = entry - if len(seen) >= limit: - break - ordered = sorted(seen.values(), key=lambda e: e.ts, reverse=True) - return [Result(entry=entry, score=0.0, frequency=1) for entry in ordered] + while heap and len(seen) < limit: + _, file, _, entry = heapq.heappop(heap) + if entry.command not in seen: + seen[entry.command] = entry + push_head(file) + return [Result(entry=entry, score=0.0, frequency=1) for entry in seen.values()] # --- Rendering --------------------------------------------------------------- @@ -578,13 +621,20 @@ def __init__( current_repo: str | None, query: str = "", now: float | None = None, + starts: Sequence[int] = (0,), ) -> None: self.lines = lines + self.starts = starts self.current_repo = current_repo self.query = query self.selected = 0 self.now = time.time() if now is None else now - self.results = rank(self.lines, self.query, self.current_repo, self.now) + self.results = self._rank() + + def _rank(self) -> list[Result]: + return rank( + self.lines, self.query, self.current_repo, self.now, starts=self.starts + ) def apply(self, action: Action) -> str | None: """Apply an action. Returns "accept"/"cancel" when the session ends.""" @@ -610,7 +660,7 @@ def apply(self, action: Action) -> str | None: return None if self.query != previous: - self.results = rank(self.lines, self.query, self.current_repo, self.now) + self.results = self._rank() # Any edit to the query invalidates the position: keeping index 7 # over a completely different result set selects an unrelated # command, which is how a finder makes you run the wrong thing. @@ -685,8 +735,8 @@ def main(argv: Sequence[str] | None = None) -> int: return 0 query = " ".join(a for a in args if not a.startswith("-")) mem_dir = os.environ.get("MEM_DIR") or os.path.join(os.path.expanduser("~"), ".mem") - lines = read_raw_lines(history_files(mem_dir)) - finder = Finder(lines, _current_repo(), query=query) + lines, starts = read_history(history_files(mem_dir)) + finder = Finder(lines, _current_repo(), query=query, starts=starts) try: tty_in = open("/dev/tty", "rb", buffering=0) diff --git a/tests/test_tui.py b/tests/test_tui.py index 0265e9f..d4091eb 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -255,6 +255,71 @@ def test_the_empty_query_view_is_deduplicated(self): assert len(tui.rank(lines, "", None, now=now)) == 1 + def test_the_empty_query_view_is_the_newest_across_every_repo(self, tmp_path: Path): + """Ctrl+R with nothing typed must show what you ran last, in any repo. + + The walk used to start at the end of the concatenated files and stop + after ``MAX_RESULTS`` distinct commands — which, with several repos, + meant the end of whichever file was read last. A stale repo with 300 + commands hid a fresh one with 5 completely: every user with more than + one repo saw the wrong list without typing a character. + """ + now = int(time.time()) + repos = tmp_path / "repos" + repos.mkdir() + stale = repos / "stale.jsonl" + stale.write_text( + "".join( + line_of(f"stale-{i}", ts=now - 100_000 + i, repo="/w/stale") + "\n" + for i in range(300) + ), + encoding="utf-8", + ) + fresh = repos / "fresh.jsonl" + fresh.write_text( + "".join( + line_of(f"fresh-{i}", ts=now - 5 + i, repo="/w/fresh") + "\n" + for i in range(5) + ), + encoding="utf-8", + ) + os.utime(stale, (now - 100_000, now - 100_000)) + os.utime(fresh, (now, now)) + + lines, starts = tui.read_history(tui.history_files(str(tmp_path))) + results = tui.rank(lines, "", None, now=now, starts=starts) + shown = [r.entry.command for r in results] + + assert shown[:5] == ["fresh-4", "fresh-3", "fresh-2", "fresh-1", "fresh-0"] + assert shown[5] == "stale-299" + assert len(shown) == tui.MAX_RESULTS + assert shown == sorted(shown, key=lambda c: -results[shown.index(c)].entry.ts) + + def test_the_empty_query_view_interleaves_repos_by_time(self): + """Two repos worked in turn: the list is by time, not file by file. + + Exact at any depth, not only for the first ``MAX_RESULTS`` lines: the + duplicates here force the merge past the first head of each file. + """ + now = int(time.time()) + # The file read first is the one modified last, as history_files orders + # them; the old walk started at the end of the *second* one. + first = [ + line_of("b", ts=now - 30, repo="/b"), + line_of("c", ts=now - 10, repo="/b"), + ] + second = [ + line_of("d", ts=now - 50, repo="/d"), + line_of("a", ts=now - 40, repo="/d"), + line_of("d", ts=now - 20, repo="/d"), + ] + lines = first + second + + results = tui.rank(lines, "", None, now=now, limit=3, starts=[0, len(first)]) + + assert [r.entry.command for r in results] == ["c", "d", "b"] + assert [r.entry.ts for r in results] == [now - 10, now - 20, now - 30] + def test_results_are_capped(self): lines = [line_of(f"cmd-{i}", ts=i) for i in range(tui.MAX_RESULTS + 50)] From 624ea65b64ba980ab8a410bec5235bbe2f3c0f89 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:52:38 -0300 Subject: [PATCH 19/40] fix(tui): the initial query could retitle the window and wrap the header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every result row goes through `_visible`, which replaces control characters and clamps to the terminal width, because history is whatever somebody pasted into a shell. The header wrote the initial query raw. That query is the live `$BUFFER` the hook hands to `mem tui`, so a buffer holding an OSC sequence (`ESC ] 0 ; … BEL`) retitled the window the moment Ctrl+R was pressed, and a buffer longer than the row wrapped the header and pushed the last result row off the alternate screen. The query now takes the same path as the rows, clamped to the columns left after the `mem` label and the match counter. The test fed the OSC through and failed before the change. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit e39bed43f2dbc0e7281232fdff075ff007cb245b) --- src/mem/tui.py | 10 ++++++++-- tests/test_tui.py | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/mem/tui.py b/src/mem/tui.py index 9bd0fca..ec9f533 100644 --- a/src/mem/tui.py +++ b/src/mem/tui.py @@ -430,9 +430,15 @@ def render( window = results[first : first + height] out = [_CLEAR] + counter = f"{len(results)}/{total}" + # The query is untrusted too: the hook passes the live $BUFFER, and a + # pasted OSC title sequence in it retitled the window from the header + # while every result row scrubbed it. Clamped as well — "mem " before it, + # "▏ " and the counter after — because a header that wraps pushes the + # last result row off the alternate screen. + shown = _visible(query, columns - 4 - 3 - len(counter)) out.append( - f"{_BOLD}mem{_RESET} {query}" - f"{_DIM}▏{_RESET} {_DIM}{len(results)}/{total}{_RESET}\r\n" + f"{_BOLD}mem{_RESET} {shown}{_DIM}▏{_RESET} {_DIM}{counter}{_RESET}\r\n" ) out.append(f"{_DIM}{'─' * max(columns, 1)}{_RESET}\r\n") diff --git a/tests/test_tui.py b/tests/test_tui.py index d4091eb..99f3c84 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -525,6 +525,32 @@ def test_a_command_cannot_repaint_the_terminal(self): assert "\x1b]0;" not in body assert "gotcha" in body + @pytest.mark.parametrize("columns", [20, 40, 80, 120]) + def test_the_query_cannot_repaint_the_terminal_or_wrap_the_header( + self, columns: int + ): + """The initial query is the live ``$BUFFER`` — as untrusted as history. + + Every result row was scrubbed and clamped; the header wrote the query + raw. A pasted OSC title sequence in the buffer retitled the window on + Ctrl+R, and a long buffer wrapped the header, pushing the last result + row off the alternate screen. + """ + hostile = "echo \x1b]0;pwned\x07\x1b[2J" + "y" * 300 + finder = tui.Finder([line_of("ls")], None, query=hostile) + + header = finder.frame(rows=24, columns=columns).split("\r\n")[0] + # Every frame opens with the finder's own clear-screen sequence; what + # follows it is the header and must contain no sequence of its own. + assert header.startswith(tui._CLEAR) + header = header[len(tui._CLEAR) :] + + assert "\x1b]0;" not in header + assert "\x07" not in header + assert "\x1b[2J" not in header + assert "echo" in header + assert tui.display_width(strip_ansi(header)) <= columns, repr(header) + @pytest.mark.parametrize("columns", [20, 40, 80, 120]) def test_long_commands_are_truncated_to_the_terminal_width(self, columns: int): """One column too many and every row wraps, doubling the list height.""" From 774ca5f6c6c27dd5439472a17b0bde18d559cd79 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:54:01 -0300 Subject: [PATCH 20/40] test(cli): `_relative_time` read the wall clock itself, so its thresholds were untestable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CLI's "5m ago" formatter took only a timestamp and subtracted `time.time()` inside, so no test could assert its output beyond the presence of "ago", and a boundary that slipped by a second would pass every ordering test. It now takes `now` with a wall-clock default, and eleven cases pin every threshold one second either side; moving the first boundary by one turns the test red. `tui.relative_time` shares the thresholds but not the wording and is deliberately left separate — the finder has four columns for an age and the CLI has a sentence — which the docstring now says so nobody unifies them into an output change. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 4ce4f0beaa4e9e69aea6e4d95cf84602214a99e2) --- src/mem/cli.py | 13 ++++++++++--- tests/test_cli.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/mem/cli.py b/src/mem/cli.py index 3242fb0..4a124e7 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -82,11 +82,18 @@ def _is_interactive() -> bool: return sys.stdin.isatty() -def _relative_time(ts: int) -> str: - """Format a timestamp as a human-readable relative time.""" +def _relative_time(ts: int, now: float | None = None) -> str: + """Format a timestamp as a human-readable relative time. + + *now* defaults to the wall clock; a test passes a fixed instant so every + threshold below can be asserted on exactly rather than as an ordering. + ``tui.relative_time`` shares the thresholds but not the wording ("5m" + against "5m ago"), and the two are deliberately not unified: the finder + has four columns for the age and the CLI has a sentence. + """ import time - delta = int(time.time()) - ts + delta = int(time.time() if now is None else now) - ts if delta < 60: return "just now" if delta < 3600: diff --git a/tests/test_cli.py b/tests/test_cli.py index 857d6e8..124cf13 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -801,6 +801,42 @@ def test_preview_shows_the_command_that_will_be_deleted( # --------------------------------------------------------------------------- +class TestRelativeTime: + """Every threshold of ``_relative_time`` at a fixed instant. + + The function read the wall clock itself, so nothing could assert on its + output beyond "contains 'ago'". Values, not orderings: each boundary is + pinned one second either side. + """ + + NOW = 1_800_000_000 + + @pytest.mark.parametrize( + ("age", "expected"), + [ + (0, "just now"), + (59, "just now"), + (60, "1m ago"), + (3599, "59m ago"), + (3600, "1h ago"), + (86399, "23h ago"), + (86400, "1d ago"), + (6 * 86400, "6d ago"), + (7 * 86400, "1w ago"), + (400 * 86400, "57w ago"), + ], + ) + def test_each_threshold(self, age: int, expected: str) -> None: + from mem.cli import _relative_time + + assert _relative_time(self.NOW - age, now=self.NOW) == expected + + def test_defaults_to_the_wall_clock(self) -> None: + from mem.cli import _relative_time + + assert _relative_time(int(time.time())) == "just now" + + class TestStats: """Stats must degrade gracefully on a brand-new install.""" From a7c90444db60e3e5be8b47f10c8a72b352081229 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:32:08 -0300 Subject: [PATCH 21/40] refactor: five pieces of code that could never run were still being maintained `SessionTracker._clear_state` had no caller; `_generate_summary` took a `repo` it never read; `mcp._dispatch` re-tested `is_notification` on a branch the line above had already returned from for every notification; `promote.command_shape` guarded against an empty token that the `(...)+` regex cannot produce; and `history.build_plan` defaulted a timestamp to 0 after `resolve_timestamps` had already dated every entry. None of it was wrong, which is the problem: each one reads as a case the code handles, and a reader who trusts it (a session that gets cleared, a `repo`-aware summary, an undated import) is reasoning about behaviour that does not exist. Dead branches are where the next divergent copy starts. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 70151e118d20330a7fe593e52f3d6b1ba3d2ba14) --- src/mem/capture.py | 9 ++------- src/mem/history.py | 4 +++- src/mem/mcp.py | 3 +-- src/mem/promote.py | 2 +- 4 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/mem/capture.py b/src/mem/capture.py index f2ecbf7..074d9f0 100644 --- a/src/mem/capture.py +++ b/src/mem/capture.py @@ -175,11 +175,6 @@ def _save_state(self, state: SessionState) -> None: storage.ensure_dirs() self._state_path.write_text(state.model_dump_json(), encoding="utf-8") - def _clear_state(self) -> None: - """Remove session state file.""" - if self._state_path.exists(): - self._state_path.unlink() - def update(self, cmd: CapturedCommand) -> None: """Process a new command and update session state. @@ -227,7 +222,7 @@ def _close_session(self, state: SessionState) -> None: return # Generate summary — use first command as fallback when AI unavailable - summary = self._generate_summary(state.commands, state.last_repo) + summary = self._generate_summary(state.commands) session = WorkSession( id=state.session_id, @@ -241,7 +236,7 @@ def _close_session(self, state: SessionState) -> None: ) storage.append_session(session) - def _generate_summary(self, commands: list[str], repo: str | None) -> str: + def _generate_summary(self, commands: list[str]) -> str: """Generate a session summary. Uses Apple FM SDK if available, otherwise falls back to diff --git a/src/mem/history.py b/src/mem/history.py index 824c00f..084c79c 100644 --- a/src/mem/history.py +++ b/src/mem/history.py @@ -553,7 +553,9 @@ def build_plan(sources: list[tuple[str, Path]]) -> ImportPlan: file_plan.commands.append( CapturedCommand( command=entry.command, - ts=entry.ts or 0, + # Always an int here: resolve_timestamps() above dated + # every entry, so there is no None left to default. + ts=entry.ts, # A history file records no directory, so there is no repo # to attribute the command to. Guessing the current one # would be a lie that the ranking's context term then acts diff --git a/src/mem/mcp.py b/src/mem/mcp.py index 08ade75..7489167 100644 --- a/src/mem/mcp.py +++ b/src/mem/mcp.py @@ -733,8 +733,7 @@ def handle_message(message: Any) -> dict[str, Any] | None: handler = _METHODS.get(method) if handler is None: - if is_notification: - return None + # Not a notification: the line above already returned for those. return _error(request_id, METHOD_NOT_FOUND, f"unknown method: {method}") try: diff --git a/src/mem/promote.py b/src/mem/promote.py index 0fdd14a..3200e25 100644 --- a/src/mem/promote.py +++ b/src/mem/promote.py @@ -287,7 +287,7 @@ def command_shape(command: str) -> tuple[str, ...]: protected = _protected_prefix_length(tokens) shape: list[str] = [] for index, token in enumerate(tokens): - if index < protected or not token.text: + if index < protected: shape.append(token.text) elif _is_flag(token.text): name, sep, _value = token.text.partition("=") From f812e39afc1d19d6d3b30d7e17376f12f0d94826 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:33:29 -0300 Subject: [PATCH 22/40] docs(search): score_command still documented the formula ADR-009 replaced MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docstring on `search.score_command` described four features weighted 0.35/0.35/0.15/0.15 and called frequency 35% of the score; the code has called `ranking.score` with picks at 0.40 and frequency at 0.21 since ADR-009. `history.py` made the same claim twice more ("the strongest term", "40% of the ranking"). A contributor tuning or debugging the ranking from the prose would have been reasoning about a formula that no longer runs — the exact drift that ADR-009 and commit 413dbf6 were written to end. The docstring now points at `ranking.py` and the ADR, and history's idempotency rationale says only what is true: frequency is a ranking term, so a doubled count is a lie the ranking acts on. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 67be08a34b45eee2a9c6949976160b8a9960cd57) --- src/mem/history.py | 8 ++++---- src/mem/search.py | 47 +++++++++++----------------------------------- 2 files changed, 15 insertions(+), 40 deletions(-) diff --git a/src/mem/history.py b/src/mem/history.py index 084c79c..73c491f 100644 --- a/src/mem/history.py +++ b/src/mem/history.py @@ -16,8 +16,8 @@ entries with no recorded timestamp are back-dated rather than stamped "now" — stamping them now would make years of old commands outrank everything the user actually ran today. -2. **Idempotency.** Frequency is the strongest term in the ranking formula, so - importing the same file twice must not double it. See :func:`build_plan`. +2. **Idempotency.** Frequency is a term in the ranking formula, so importing + the same file twice must not double it. See :func:`build_plan`. 3. **Not crashing.** Real history files contain invalid UTF-8, truncated entries and formats from shell versions that no longer exist. Every parser here degrades to "treat the line as a bare command" or "count it as @@ -521,8 +521,8 @@ def build_plan(sources: list[tuple[str, Path]]) -> ImportPlan: Counting against *every* stored command, not just previously imported ones, is deliberate: a user who installs mem and imports a month later has the same commands in both places, and inflating frequency is worse than - under-counting it — frequency is 40% of the ranking, and it is the term - that decides what surfaces first. + under-counting it — frequency is a ranking term, and a doubled count is + a lie the ranking then acts on. """ stored = _stored_command_counts() seen: Counter[str] = Counter() diff --git a/src/mem/search.py b/src/mem/search.py index 295ae2c..162da51 100644 --- a/src/mem/search.py +++ b/src/mem/search.py @@ -33,43 +33,18 @@ def score_command( ) -> float: """Score a command for search relevance. - A linear combination of four features, each normalised to [0, 1]: - - score = 0.35*frequency + 0.35*recency + 0.15*prefix + 0.15*context - - Why the normalisation matters more than the weights: the previous formula - was ``0.4*frequency + 0.4*recency + 0.2*context`` with ``frequency`` as a - *raw count*. Recency and context are bounded by 1, so a command run ten - times scored 4.0 against a ceiling of 0.6 for everything else — the two - signals the docstring described as equally weighted could not move the - ranking at all. mem was sorting by frequency and calling it a formula. The - weights are a design choice; that was a bug. - - - **Frequency** (35%): ``log1p(n) / log1p(50)``, capped at 1. Logarithmic - because the jump from 1 run to 5 says much more than 100 to 105, and - capped so one pathologically repeated command cannot own every result. - - **Recency** (35%): exponential decay with a 7-day half-life, - ``exp(-days * ln(2) / 7)``. Today scores 1.0, a week ago 0.5, two weeks - 0.25. Human memory fades the same way: older commands need a stronger - signal to surface. - - **Prefix** (15%): 1.0 when the command starts with the query. Someone - typing ``mem git push`` wants ``git push origin main``, not the - ``echo "remember to git push"`` they ran more often. Nothing else in the - formula could express "this is what you meant", because every result - already contains every term. - - **Context** (15%): 1.0 for the current repo, 0.5 for a sibling sharing a - parent directory. A refinement, not a driver. - - Why exit code is NOT included: a failed command is often deliberate — + The formula is :func:`mem.ranking.score` — one implementation, over plain + strings and ints, because the interactive finder has to rank without + paying Pydantic's import and two copies of a ranking formula drift until + the same history sorts differently depending on how you asked. The + weights, the features and the measurement behind them are in + ``docs/decisions/009-ranking-learns-from-selections.md``; this function + only unwraps the model and passes the fields through. + + Why exit code is NOT a feature: a failed command is often deliberate — checking whether a service is down, or probing until something works. The - useful version of this signal is the *pair* (what failed, what fixed it), - which is a different feature, not a penalty term here. - - The arithmetic itself lives in :mod:`mem.ranking`, which imports nothing - but the standard library. The interactive finder has to rank without - paying Pydantic's ~58ms import, and two implementations of a ranking - formula would drift until the same history sorted differently depending - on how you asked for it. + useful version of that signal is the *pair* (what failed, what fixed it), + which is ``mem fix``, not a penalty term here. """ return ranking.score( command=cmd.command, From 985957775a910b89e778256fb0f583b361458aa8 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:34:28 -0300 Subject: [PATCH 23/40] docs(ranking): the ADR-009 measurement was restated in two modules without citing it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `ranking.py` and `picks.py` both quote the 1,200-episode simulation (MRR@10 0.039 -> 0.575, the learned weights, the 3.3% pair-keying result) as if the module were the source. The numbers match ADR-009 today, but a restated measurement with no pointer is one that gets re-run and quietly disagrees with the decision record — or, more likely, gets edited in one place when the ADR is superseded and left stale in the other two. Both comments now name the ADR as the source and, in picks.py, carry its own caveat that the figure is a simulation rather than a field study. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit d86afa2177dd96f211a34ca3f5e3ec1168e431b7) --- src/mem/picks.py | 6 ++++-- src/mem/ranking.py | 5 ++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/mem/picks.py b/src/mem/picks.py index 8702bf9..77c9320 100644 --- a/src/mem/picks.py +++ b/src/mem/picks.py @@ -11,10 +11,12 @@ and top-1 from 0.025 to 0.477. The learned weights are more startling than the score — they converge to picks ≈ +3.0 while frequency and recency land at roughly *minus* 0.05. Once you have selection feedback, the two signals mem's -entire scoring was built on are worth approximately nothing. +entire scoring was built on are worth approximately nothing. The measurement +is ADR-009's (docs/decisions/009-ranking-learns-from-selections.md), which +also records what it does *not* show: it is a simulation, not a field study. Three findings from that work are encoded here, each of which is easy to get -backwards: +backwards (all three are decided in ADR-009): - **The counter belongs to the command, not to the (query, command) pair.** Keying by pair measured 3.3% *worse*: it fragments the evidence across every diff --git a/src/mem/ranking.py b/src/mem/ranking.py index f46e15b..ed18561 100644 --- a/src/mem/ranking.py +++ b/src/mem/ranking.py @@ -32,7 +32,10 @@ # `picks` takes the largest share because it is the only feature that is not # an inference: it is the user having already answered, for this command, the # question the rest of the formula is guessing at. Measured over 1,200 -# retrieval episodes, adding it moves MRR@10 from 0.039 to 0.575. +# retrieval episodes, adding it moves MRR@10 from 0.039 to 0.575. The +# measurement, the alternatives rejected and the cost of this choice are in +# ADR-009 (docs/decisions/009-ranking-learns-from-selections.md); the numbers +# here are restated from it, not a second source. # # The remaining 0.60 is split in exactly the proportions the four original # features had among themselves (35/35/15/15). That is deliberate: with no From 0b622a73918f604e9ef9e816134a5ca21e7c7f18 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:36:14 -0300 Subject: [PATCH 24/40] docs: nine comments described behaviour the code next to them does not have Each one was checked against the code and found false: patterns.py is not "the ONLY place" that runs inference (variables.py classifies credentials with the same model); SESSION_SUMMARY_PROMPT is not "used by capture" (capture imports the function, never the constant); `run_pattern_extraction` does not return "commands sent to the model" (the heuristic path sends none and returns every unseen command); `sync_all_patterns` requires >= 5 commands, not > 5, and returns tool counts, not pattern counts, with the "updated" side incrementing even when nothing was written; promote's evidence ladder is 6/3, not "the same ladder as mem fix" (3/2); the inspection list is not "every entry read-only" (it holds vim, nano, code, open, mem); mcp's `repo` IS passed to `search.search`, as `current_repo`; and MAX_SCAN is the over-fetch depth for the repo filter, which the comment over MAX_LIMIT did not say. A false comment is worse than none: it is trusted precisely by the reader who did not read the code, and every one of these sits at a decision point (a threshold, a return value, a contract) where being misled has a cost. Text only; no behaviour changes. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit e870fc201dd4efd27ae3501df60ff35c16706e3d) --- src/mem/mcp.py | 21 +++++++++++++-------- src/mem/patterns.py | 26 ++++++++++++++++++-------- src/mem/promote.py | 13 +++++++++---- 3 files changed, 40 insertions(+), 20 deletions(-) diff --git a/src/mem/mcp.py b/src/mem/mcp.py index 7489167..95d7348 100644 --- a/src/mem/mcp.py +++ b/src/mem/mcp.py @@ -105,10 +105,15 @@ INVALID_PARAMS = -32602 INTERNAL_ERROR = -32603 -# Upper bound on how many stored commands a single tool call may consider. -# Not a performance guard — a guard against a `limit: 100000` turning one -# request into a full dump of the user's shell history. +# Upper bound on how many results a single tool call may return. Not a +# performance guard — a guard against a `limit: 100000` turning one request +# into a full dump of the user's shell history. MAX_LIMIT = 50 + +# How deep `search_history` over-fetches when a `repo` filter is given, since +# the ranking engine scores every repository and the filter is applied to its +# output afterwards. Deep enough that a repo with a modest share of the history +# still fills MAX_LIMIT; never returned to the client as such. MAX_SCAN = 500 DISABLED_MESSAGE = ( @@ -237,11 +242,11 @@ def _optional_limit(args: dict[str, Any], default: int) -> int: def _tool_search_history(args: dict[str, Any]) -> dict[str, Any]: """Rank the user's captured commands against a query. - ``repo`` is applied here as a filter rather than passed to - ``search.search``, which treats the repo as a *ranking* signal and always - scans every history file. Over-fetching and filtering keeps the tool's - contract honest ("only commands from this repo") without changing the - ranking engine. + ``repo`` is passed to ``search.search`` as ``current_repo`` — where it is + only a *ranking* signal; the engine always scans every history file — and + then applied here as a filter on the result. Over-fetching ``MAX_SCAN`` + and filtering keeps the tool's contract honest ("only commands from this + repo") without changing the ranking engine. """ from mem.search import search diff --git a/src/mem/patterns.py b/src/mem/patterns.py index 36e5c9e..2c9f0e2 100644 --- a/src/mem/patterns.py +++ b/src/mem/patterns.py @@ -1,9 +1,10 @@ """ AI-powered pattern extraction using Apple Foundation Models. -This module is the ONLY place in mem that uses AI inference. Everything -else is deterministic. Pattern extraction exists because no regex or -heuristic can reliably generalize commands like: +This module and the credential classifier in :mod:`mem.variables` are the +only places in mem that run AI inference; everything else is deterministic. +Pattern extraction exists because no regex or heuristic can reliably +generalize commands like: kubectl get pods, kubectl get services, kubectl get deployments into the abstract pattern: kubectl get @@ -104,7 +105,8 @@ } ) -# Session summary prompt (used by capture module). +# Session summary prompt, consumed by generate_session_summary() below (which +# is what capture.SessionTracker calls; it never sees this constant). SESSION_SUMMARY_PROMPT = ( "Summarize this shell session in one short sentence:\n{commands}" ) @@ -374,8 +376,12 @@ def run_pattern_extraction( into O(tools x history): 50 tools over a 100k-command history meant five million line parses, every 20 captures, in a background process. - Returns the number of commands sent to the model, so a caller can spend a - shared budget across tools. + Returns how many commands this run added to the cache. With the model + that is the number of commands sent to it, which is what lets a caller + spend a shared budget across tools; on the heuristic path nothing is sent + and every unseen command is cached at once, so the same number charges + the budget for work the model never did. Harmless, because without a + model there is no per-command cost to bound. """ import asyncio @@ -416,12 +422,16 @@ def sync_all_patterns(silent: bool = False) -> tuple[int, int]: """Extract patterns for ALL tools with sufficient command history. Detects unique tools (first token of each command), runs extraction - for each tool with >5 commands. Skips tools with insufficient data. + for each tool with at least 5 commands. Skips tools with fewer. Args: silent: If True, suppress all output (for background auto-sync). - Returns (new_patterns, updated_patterns) counts. + Returns ``(new_tools, revisited_tools)``: how many tools had no pattern + file before this run, and how many already had one. Counts tools, not + patterns, and a revisited tool is counted whether or not its run wrote + anything — `run_pattern_extraction` returns 0 without writing when the + cache already covers every command. """ # Collect all commands grouped by tool (first token). Read once: passing # each tool's slice down avoids re-reading the whole history per tool. diff --git a/src/mem/promote.py b/src/mem/promote.py index 3200e25..71eba54 100644 --- a/src/mem/promote.py +++ b/src/mem/promote.py @@ -182,8 +182,10 @@ #: Most variables a single candidate may carry. MAX_VARIABLES = 2 -#: Occurrence counts at which the wording of the claim changes. Same ladder as -#: ``mem fix``, because it is the same kind of claim about the same evidence. +#: Occurrence counts at which the wording of the claim changes. The same +#: three-word ladder as ``mem fix`` (strong / moderate / weak) but higher +#: rungs: 6/3 here against fix's 3/2, because an occurrence here is a whole +#: session, not a single pair, and the sequences worth a runbook recur often. STRONG_EVIDENCE = 6 MODERATE_EVIDENCE = 3 @@ -402,8 +404,11 @@ def split_sessions( # # A deliberately short, deliberately boring list. Its job is not to be # complete — it is to remove the handful of commands that make up most of a -# real history and none of a runbook. Every entry is read-only and -# unconditionally safe to skip; anything with an argument that could make it +# real history and none of a runbook. The rule for membership is that the +# command does not advance a procedure: most entries only look (`ls`, `cat`, +# `git status`), and the rest — editors, `open`, `code`, `mem` itself — are +# interactive detours whose effect is not in the command line, so they carry +# no step a runbook could replay. Anything with an argument that could make it # write (a redirection, a pipe) is excluded by is_inspection() before the list # is consulted at all. From 5c65d51587ed9b2bcd085dd8aca6472e00901ea3 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:38:25 -0300 Subject: [PATCH 25/40] test: four tests passed no matter what the code under them did Two MCP tests asserted `count <= MAX_LIMIT` after planting 30 and 4 rows against a cap of 50, so deleting the clamp in `_optional_limit` left them green; they now plant more rows than the cap and assert equality. The tokenizer test asserted `tokenize(...) is not None` on a function that returns a list, which is never None; it now asserts the four tokens, including the unbalanced `"wip` kept literally. The missing-audit-log test had no assertion at all; it now checks the return value and that no file was created. Each was verified to go red under a one-line mutation (clamp removed, quote alternative dropped from `_TOKEN`, existence guard removed from `_scrub_agent_audit`) before being restored. A test that cannot fail is a claim of coverage with nothing behind it, which is worse than an honest gap. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 7e96ea23845671aa894eb05d985b3e39ffb63a39) --- tests/test_mcp.py | 23 ++++++++++++++++++----- tests/test_promote.py | 5 ++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/tests/test_mcp.py b/tests/test_mcp.py index df919a9..3d0c4bb 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -452,7 +452,14 @@ def test_returns_ranked_matching_commands(self, home: Path, workdir: Path) -> No def test_limit_is_honoured_and_capped(self, home: Path, workdir: Path) -> None: """`limit` bounds the result set; an absurd one is clamped, not obeyed.""" enable(home, workdir) - plant(home, [{"command": f"npm run task{i}", "ts": NOW - i} for i in range(30)]) + # More rows than the cap, or the clamp is never what bounds the count. + plant( + home, + [ + {"command": f"npm run task{i}", "ts": NOW - i} + for i in range(mcp.MAX_LIMIT + 10) + ], + ) limited = serve( [INIT, call(2, "search_history", {"query": "npm", "limit": 3})], @@ -466,7 +473,7 @@ def test_limit_is_honoured_and_capped(self, home: Path, workdir: Path) -> None: home, workdir, ) - assert tool_payload(by_id(absurd, 2))["count"] <= mcp.MAX_LIMIT + assert tool_payload(by_id(absurd, 2))["count"] == mcp.MAX_LIMIT def test_repo_argument_filters_results(self, home: Path, workdir: Path) -> None: """`repo` is a filter, not merely a ranking hint.""" @@ -1682,8 +1689,13 @@ def test_search_repo_filter_and_limit_clamp(self, agent_enabled: Path) -> None: ], repo="work-api", ) + # More rows than MAX_LIMIT in total, or the clamp has nothing to clamp. local_history( - [{"command": "make other", "ts": NOW, "repo": "/work/web"}], repo="work-web" + [ + {"command": f"make other{i}", "ts": NOW - i, "repo": "/work/web"} + for i in range(mcp.MAX_LIMIT + 5) + ], + repo="work-web", ) responses, _ = drive( @@ -1696,7 +1708,7 @@ def test_search_repo_filter_and_limit_clamp(self, agent_enabled: Path) -> None: filtered = json.loads(responses[0]["result"]["content"][0]["text"]) assert {r["repo"] for r in filtered["results"]} == {"/work/api"} clamped = json.loads(responses[1]["result"]["content"][0]["text"]) - assert clamped["count"] <= mcp.MAX_LIMIT + assert clamped["count"] == mcp.MAX_LIMIT def test_a_parse_error_does_not_end_the_session(self, agent_enabled: Path) -> None: """The loop continues after an unparseable line, in-process too.""" @@ -1799,7 +1811,8 @@ def test_scrubbing_removes_the_file_when_nothing_survives( def test_scrubbing_a_missing_log_is_a_no_op(self, tmp_mem_dir: Path) -> None: """`mem forget` on a machine that never served an agent does nothing.""" - storage._scrub_agent_audit("anything") # must not raise + assert storage._scrub_agent_audit("anything") is None + assert not storage.agent_audit_file().exists() def test_scrubbing_preserves_unparseable_lines(self, tmp_mem_dir: Path) -> None: """A line we cannot read is a line we cannot judge — so we keep it.""" diff --git a/tests/test_promote.py b/tests/test_promote.py index d19f8fb..2f6c51d 100644 --- a/tests/test_promote.py +++ b/tests/test_promote.py @@ -606,7 +606,10 @@ def test_an_empty_command_line_is_not_a_step(self) -> None: def test_unbalanced_quotes_do_not_crash_the_tokenizer(self) -> None: assert promote.command_shape("echo 'unterminated") - assert promote.tokenize('git commit -m "wip') is not None + # The unbalanced quote is kept as literal text, not raised on and not + # silently dropped from the middle of the line. + tokens = [t.text for t in promote.tokenize('git commit -m "wip')] + assert tokens == ["git", "commit", "-m", '"wip'] class TestCredentials: From d08f8d137f77ec991f2465972096a0a06d40f042 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:39:51 -0300 Subject: [PATCH 26/40] refactor(concepts): two names for one filename, and a min() that could never choose `CONCEPTS_FILENAME` and `USER_CONCEPTS_FILENAME` were both the string "concepts.json", so a reader would look for the difference between the shipped map and the user's, find none, and wonder which one a rename should track. One name now, with the shared-name-under-~/.mem fact in its comment. In `expand`, `min(MAX_CONCEPT_WORDS, data.max_words)` always returned `data.max_words`, because `_parse` already refuses any key longer than the cap; the min read as a second, independent limit and there is only one. The constant itself stays, because the parse-time cap is real, and its comment now says which of the two jobs it does. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 52af0c28b626f823b42b2bffdae20cf3a5c87d32) --- src/mem/concepts.py | 18 ++++++++++-------- src/mem/search.py | 2 +- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/mem/concepts.py b/src/mem/concepts.py index 3110989..d55fd7f 100644 --- a/src/mem/concepts.py +++ b/src/mem/concepts.py @@ -39,20 +39,22 @@ # resolution that works identically for an editable checkout, a wheel and a # zipimport. A previous version of the hook loader walked ``__file__`` upwards # instead, and shipped a stale copy to every pip user for four months. +# +# The user's own map has the same name under ``~/.mem``. Not a *replacement* +# for the shipped file — a layer over it, so an upgrade still delivers new +# concepts to someone who added one. CONCEPTS_FILENAME = "concepts.json" -# A user map lives here. Not a *replacement* for the shipped file — a layer -# over it, so an upgrade still delivers new concepts to someone who added one. -USER_CONCEPTS_FILENAME = "concepts.json" - # Keys starting with an underscore are metadata, not concepts. JSON has no # comment syntax, and a map meant to be read and edited by hand needs one. _RESERVED_PREFIX = "_" _STOPWORDS_KEY = "_stopwords" -# The longest concept key, in words. Multi-word keys ("disk space", "pull -# request") are matched against consecutive query words, longest first, so -# "disk space" never decays into "disk" AND "space". +# The longest concept key accepted at parse time, in words. Multi-word keys +# ("disk space", "pull request") are matched against consecutive query words, +# longest first, so "disk space" never decays into "disk" AND "space". The +# phrase scan itself uses the loaded map's real maximum (``ConceptData. +# max_words``), which this cap bounds from above. MAX_CONCEPT_WORDS = 3 @@ -303,7 +305,7 @@ def expand(terms: list[str], data: ConceptData) -> list[QueryGroup]: """ groups: list[QueryGroup] = [] index = 0 - span = min(MAX_CONCEPT_WORDS, data.max_words) + span = data.max_words while index < len(terms): for width in range(min(span, len(terms) - index), 0, -1): phrase = " ".join(terms[index : index + width]) diff --git a/src/mem/search.py b/src/mem/search.py index 162da51..91ee9bc 100644 --- a/src/mem/search.py +++ b/src/mem/search.py @@ -193,7 +193,7 @@ def _expanded_search( on these questions, because the words a person uses to describe a command are usually not in the command. """ - data = concepts.load(storage.MEM_DIR / concepts.USER_CONCEPTS_FILENAME) + data = concepts.load(storage.MEM_DIR / concepts.CONCEPTS_FILENAME) groups = concepts.expand(terms, data) admitted = list(_read_history(current_repo, line_filter=_any_variant(groups))) From 6e5d778d9e9c2e893ae5bb9aa3f05f2352d88c48 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:43:02 -0300 Subject: [PATCH 27/40] refactor: every `except Exception` now names what it catches, and two are narrowed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ten broad catches across capture, patterns, concepts and mcp said "never fail" without saying what failing looks like, which is how the dead background sync hid for four months behind one of them. Two are narrowed because their failure set is closed: `SessionTracker._load_state` (read, decode, validate) now catches `(OSError, ValueError)` and validates with `model_validate` so a state file hand-edited into a JSON list is a ValidationError rather than an uncaught TypeError; `concepts._load_shipped` catches the same pair, `_parse` having been checked to return None instead of raising. The rest stay broad on purpose — the two in the capture hook because an uncaught anything prints a traceback after every command, the two around the Apple SDK because it raises plain ValueError/TypeError from argument checks and pointer decoding that share no base with its FoundationModelsError tree, and the three in the MCP server because a tool bug must answer with an error frame, not a dead process — and each comment now lists the concrete exceptions it expects. The pyproject TODO(0.16) asks for exactly this per-site judgement before BLE001 lands. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 0390f5897bc9bf9d263c9ab57483fb97f14954fc) --- src/mem/capture.py | 25 +++++++++++++++++++++---- src/mem/concepts.py | 8 +++++--- src/mem/mcp.py | 10 ++++++++++ src/mem/patterns.py | 11 +++++++++++ 4 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/mem/capture.py b/src/mem/capture.py index 074d9f0..66c4153 100644 --- a/src/mem/capture.py +++ b/src/mem/capture.py @@ -92,14 +92,22 @@ def capture_command(raw: str, directory: str, exit_code: int, duration_ms: int) ) storage.append_command(cmd) - # Update session tracking + # Update session tracking. What can fail here: OSError from the lock, the + # state file or the sessions file; ValueError (Pydantic's ValidationError) + # building a WorkSession from a state that was hand-edited into an + # impossible shape. Deliberately broader than that list: this runs from a + # shell precmd hook, and an uncaught anything prints a traceback after + # every command the user types. try: tracker = SessionTracker() tracker.update(cmd) except Exception: pass # Session tracking failure should never block capture - # Auto-sync: trigger background pattern extraction every N captures + # Auto-sync: trigger background pattern extraction every N captures. What + # can fail here: OSError from the lock or the counter file, and OSError + # from Popen when the `mem` executable found by `which` is no longer + # runnable. Broad for the same reason as above — a hook must not print. try: count = storage.increment_sync_counter() if count >= storage.SYNC_THRESHOLD: @@ -166,8 +174,12 @@ def _load_state(self) -> SessionState | None: return None try: data = json.loads(self._state_path.read_text(encoding="utf-8")) - return SessionState(**data) - except Exception: + # model_validate, not **data: a file hand-edited into a JSON list + # is a ValidationError (a ValueError) instead of a TypeError. + return SessionState.model_validate(data) + except (OSError, ValueError): + # Unreadable, not JSON, not UTF-8, or not a SessionState. A lost + # session boundary is the whole cost; the next command starts one. return None def _save_state(self, state: SessionState) -> None: @@ -250,6 +262,11 @@ def _generate_summary(self, commands: list[str]) -> str: if result: return result except Exception: + # RuntimeError from asyncio.run when a loop is already running in + # this thread; the SDK's FoundationModelsError tree and its own + # ValueError/TypeError if generate_session_summary's catch ever + # narrows. Broad because this runs inside the capture hook, where + # a traceback costs more than a plain summary does. pass # Fallback: first command + count diff --git a/src/mem/concepts.py b/src/mem/concepts.py index d55fd7f..3efdcd7 100644 --- a/src/mem/concepts.py +++ b/src/mem/concepts.py @@ -176,9 +176,11 @@ def _load_shipped() -> ConceptData: .read_text(encoding="utf-8") ) parsed = _parse(json.loads(raw)) - except Exception as exc: # noqa: BLE001 - a packaging fault, not a user one - # Unreachable through any supported install; a broken shipped map must - # still degrade to plain literal search rather than break `mem `. + except (OSError, ValueError) as exc: + # OSError: the file is missing from the package; ValueError: not UTF-8 + # or not JSON. `_parse` returns None rather than raising. Unreachable + # through any supported install; a broken shipped map must still + # degrade to plain literal search rather than break `mem `. _warn(f"built-in concept map could not be read ({exc}); expansion is off") return ConceptData(concepts={}, stopwords=frozenset()) if parsed is None: diff --git a/src/mem/mcp.py b/src/mem/mcp.py index 95d7348..02f1a35 100644 --- a/src/mem/mcp.py +++ b/src/mem/mcp.py @@ -572,6 +572,9 @@ def _audit(tool: str, args: dict[str, Any], results: int, error: str | None) -> ) ) except Exception: # pragma: no cover - defensive, see docstring + # OSError from the lock or the audit file; ValueError if a future + # entry field does not serialise. Broad because the docstring's + # promise is "never raising", and a new failure mode must keep it. pass @@ -660,6 +663,9 @@ def _handle_tools_call(params: dict[str, Any]) -> dict[str, Any]: _audit(name, args, 0, exc.message) raise except Exception as exc: # noqa: BLE001 - a tool bug must not kill the server + # OSError reading a history or group file, ValueError from a corrupt + # JSON line that got past the storage layer's per-line skip, and any + # genuine bug in a tool. Only the type name reaches the client. _audit(name, args, 0, type(exc).__name__) raise RpcError( INTERNAL_ERROR, f"mem failed to read its store: {type(exc).__name__}" @@ -746,6 +752,10 @@ def handle_message(message: Any) -> dict[str, Any] | None: except RpcError as exc: return _error(request_id, exc.code, exc.message, exc.data) except Exception as exc: # noqa: BLE001 - see class docstring for RpcError + # Anything a handler raised that is not already an RpcError: a bug in + # initialize/tools handling, or a storage OSError/ValueError that + # _handle_tools_call did not see. The reply is an error frame, not a dead + # server, and only the type name is disclosed. return _error( request_id, INTERNAL_ERROR, f"internal error: {type(exc).__name__}" ) diff --git a/src/mem/patterns.py b/src/mem/patterns.py index 2c9f0e2..5e1f097 100644 --- a/src/mem/patterns.py +++ b/src/mem/patterns.py @@ -215,6 +215,13 @@ async def _generalize_commands(tool: str, unique_commands: list[str]) -> dict[st result = await session.respond(prompt, generating=GeneralizedCommand) pattern = (result.pattern or "").strip() except Exception: + # The SDK raises FoundationModelsError > GenerationError > + # {ExceededContextWindowSizeError, AssetsUnavailableError, + # GuardrailViolationError, RefusalError, RateLimitedError, ...} for + # the model, but plain ValueError/TypeError from its own argument + # checks and C-pointer decoding, which share no base with those. + # Catching the tree alone would let a decoding failure abort the + # whole sync, so this stays broad. logger.debug("generalization failed for %r", cmd, exc_info=True) pattern = "" @@ -322,6 +329,10 @@ async def generate_session_summary(commands: list[str]) -> str | None: result = await session.respond(prompt) return str(result) except Exception: + # Same reasoning as _generalize_commands: FoundationModelsError and + # its subclasses from the model, plus the SDK's own ValueError and + # TypeError, which are not under that base. None is the documented + # answer for "no summary", and the caller has a fallback. return None From d35f6fc84fe38397bd608f592870f02a9fa819c2 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:45:28 -0300 Subject: [PATCH 28/40] docs: nineteen constants now say whether they were measured, and most were not Every threshold in the mining and ranking modules read as if it had a basis, and `git log -S` on each finds none beyond the commit that introduced it. The capture docstring went further and invented one: "chosen by observing that most developers maintain focus for at least 5 minutes" cites no observation, and ADR-012's finding is that the value is not what matters about that number. Each site now says "chosen by eye, not measured" where that is the truth, names the one measurement that exists where it does (ADR-012 measured MIN_OCCURRENCES and the display limit, not the evidence ladder), and corrects the one arithmetic claim that was wrong: `_PRUNE_BELOW` is not "roughly six months" for a pick, it is 21 * log2(50), about 118 days. The `< 5` written twice in patterns.py becomes `MIN_COMMANDS_PER_TOOL`, so it cannot be tuned in one place and not the other. Values unchanged throughout: the point is that the next person to tune one knows they are the first to measure it. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit af45fac0d258a38b76a3aaa7a9af180512fd3b9c) --- src/mem/capture.py | 16 ++++++++++------ src/mem/fix.py | 9 ++++++++- src/mem/mcp.py | 8 +++++++- src/mem/patterns.py | 11 +++++++++-- src/mem/picks.py | 8 ++++++-- src/mem/promote.py | 9 ++++++++- src/mem/ranking.py | 3 ++- src/mem/search.py | 2 ++ 8 files changed, 52 insertions(+), 14 deletions(-) diff --git a/src/mem/capture.py b/src/mem/capture.py index 66c4153..8c24b72 100644 --- a/src/mem/capture.py +++ b/src/mem/capture.py @@ -37,6 +37,8 @@ def get_git_repo(directory: str) -> str | None: ["git", "-C", directory, "rev-parse", "--show-toplevel"], capture_output=True, text=True, + # rev-parse answers in milliseconds; the timeout only guards a + # hung filesystem (a dead network mount). Chosen by eye. timeout=5, ) if result.returncode == 0: @@ -156,10 +158,10 @@ class SessionTracker: Why 300 seconds: Five minutes is long enough that brief interruptions (reading docs, bathroom breaks) don't split a session, but short - enough that genuine context switches are detected. This threshold - was chosen by observing that most developers maintain focus on a - single task for at least 5 minutes, and breaks longer than that - typically indicate a task switch. + enough that genuine context switches are detected. Chosen by eye, not + measured. ADR-012 keeps the same number for re-deriving sessions in + ``mem promote`` — it found that what matters is measuring think time + against it, not the value itself — so changing it here changes both. State is persisted in ~/.mem/.session_state.json so sessions survive shell restarts. @@ -239,8 +241,10 @@ def _close_session(self, state: SessionState) -> None: session = WorkSession( id=state.session_id, summary=summary, - started_at=state.last_command_ts - - (len(state.commands) * 10), # approximate + # The state keeps no per-command timestamps, so the start is + # fabricated at ten seconds a command: a placeholder chosen by + # eye, not measured, which is why ADR-012 refuses to read it. + started_at=state.last_command_ts - (len(state.commands) * 10), ended_at=state.last_command_ts, dir="", # not tracked in state for simplicity repo=state.last_repo, diff --git a/src/mem/fix.py b/src/mem/fix.py index 97f7ee7..9395786 100644 --- a/src/mem/fix.py +++ b/src/mem/fix.py @@ -228,6 +228,9 @@ def iter_failures( # --- textual comparison ---------------------------------------------------- +# 4096 entries is chosen by eye, not measured: comfortably above the distinct +# command lines one mining pass compares, and small enough that the cache is +# never what a `mem fix` run's memory is made of. @lru_cache(maxsize=4096) def normalized_tokens(command: str) -> tuple[str, ...]: """Split a command line into comparison tokens. @@ -721,7 +724,11 @@ class FixReport: def build_report( query: str | None = None, current_repo: str | None = None, limit: int = 3 ) -> FixReport: - """Mine the store and answer one ``mem fix`` invocation.""" + """Mine the store and answer one ``mem fix`` invocation. + + Three fixes by default: the answer to "what fixed this" is usually one + command, and a fourth candidate is noise. Chosen by eye, not measured. + """ corrections, failures = mine_all() failure = select_failure(failures, query=query, current_repo=current_repo) if failure is None: diff --git a/src/mem/mcp.py b/src/mem/mcp.py index 02f1a35..8fdc908 100644 --- a/src/mem/mcp.py +++ b/src/mem/mcp.py @@ -113,7 +113,8 @@ # How deep `search_history` over-fetches when a `repo` filter is given, since # the ranking engine scores every repository and the filter is applied to its # output afterwards. Deep enough that a repo with a modest share of the history -# still fills MAX_LIMIT; never returned to the client as such. +# still fills MAX_LIMIT; never returned to the client as such. 500 is chosen +# by eye, not measured. MAX_SCAN = 500 DISABLED_MESSAGE = ( @@ -409,6 +410,9 @@ def _tool_recent_failures(args: dict[str, Any]) -> dict[str, Any]: if cmd.exit_code == 0: succeeded_later.setdefault(cmd.command, index) + # Two lines of "what was run next", where `mem fix` reads three: this + # tool reports context rather than mining a correction, and an agent + # reading a list needs less of it. Chosen by eye, not measured. for failure in iter_failures(commands, lookahead=2): retry = succeeded_later.get(failure.command.command) failures.append( @@ -556,6 +560,8 @@ def _audit(tool: str, args: dict[str, Any], results: int, error: str | None) -> already computed and refusing to return it helps nobody. The write itself goes through the storage layer's lock and 0600 permissions. """ + # No tool takes more than three arguments; ten caps what a hostile client + # can make the audit log store per call. Chosen by eye. safe_args = { str(k): redact_secrets(v if isinstance(v, str) else json.dumps(v)) for k, v in list(args.items())[:10] diff --git a/src/mem/patterns.py b/src/mem/patterns.py index 5e1f097..760e667 100644 --- a/src/mem/patterns.py +++ b/src/mem/patterns.py @@ -53,6 +53,11 @@ # what keeps enabling it from being an incident; the next run continues. SYNC_BUDGET = 50 +# Fewer commands than this and a tool gets no pattern file: with one or two +# examples there is no repetition to abstract over. Chosen by eye, not +# measured. +MIN_COMMANDS_PER_TOOL = 5 + # Per-command generalization prompt. # Why this design: # - One command at a time avoids dedup/counting errors from the LLM @@ -346,6 +351,8 @@ def _heuristic_patterns(tool: str, commands: list[str]) -> PatternExtractionResu for cmd in commands: freq[cmd] += 1 + # The ten most repeated commands stand in for patterns. Ten is chosen by + # eye, not measured; it is what fits in a `mem patterns` listing. patterns = [ CommandPattern(pattern=cmd, example=cmd, frequency=count) for cmd, count in sorted(freq.items(), key=lambda x: x[1], reverse=True)[:10] @@ -406,7 +413,7 @@ def run_pattern_extraction( if cmd.command.split()[:1] == [tool] ] - if len(commands) < 5: + if len(commands) < MIN_COMMANDS_PER_TOOL: return 0 # Not enough data for meaningful patterns cache = _load_cache(tool) @@ -461,7 +468,7 @@ def sync_all_patterns(silent: bool = False) -> tuple[int, int]: for tool, commands in sorted( tool_commands.items(), key=lambda kv: len(kv[1]), reverse=True ): - if len(commands) < 5: + if len(commands) < MIN_COMMANDS_PER_TOOL: continue # Skip tools with too few commands if remaining <= 0: break # Out of budget; the next sync picks up where this stopped diff --git a/src/mem/picks.py b/src/mem/picks.py index 77c9320..13651f8 100644 --- a/src/mem/picks.py +++ b/src/mem/picks.py @@ -51,11 +51,13 @@ HALF_LIFE_DAYS = 21.0 # Below this decayed weight an entry no longer affects any ranking, so keeping -# it only grows the file. Roughly six months of not being chosen. +# it only grows the file. A single pick reaches it after 21 * log2(50), about +# 118 days; a command picked ten times takes about 188. Chosen by eye. _PRUNE_BELOW = 0.02 # A hard cap so a script hammering the finder cannot grow this file without -# bound. Far above any human's working set of commands. +# bound. Far above any human's working set of commands; the exact figure is +# chosen by eye, not measured. MAX_ENTRIES = 5_000 _SECONDS_PER_DAY = 86400.0 @@ -150,6 +152,8 @@ def record(command: str, now: float | None = None) -> None: ): count, stamp = 0.0, moment entries[command] = { + # Six decimals keeps a hand-readable file; a difference below + # that never moves a ranking. Chosen by eye. "count": round(_decay(float(count), moment - float(stamp)) + 1.0, 6), "ts": int(moment), } diff --git a/src/mem/promote.py b/src/mem/promote.py index 71eba54..0b337b5 100644 --- a/src/mem/promote.py +++ b/src/mem/promote.py @@ -172,7 +172,9 @@ #: Longest think-time gap between two consecutive steps of one procedure. MAX_STEP_GAP_SECONDS = 900 -#: Shortest and longest sequence that may be proposed as a group. +#: Shortest and longest sequence that may be proposed as a group. The +#: reasoning is in the module docstring; the exact upper bound is chosen by +#: eye, not measured. MIN_SEQUENCE_LENGTH = 2 MAX_SEQUENCE_LENGTH = 8 @@ -186,6 +188,8 @@ #: three-word ladder as ``mem fix`` (strong / moderate / weak) but higher #: rungs: 6/3 here against fix's 3/2, because an occurrence here is a whole #: session, not a single pair, and the sequences worth a runbook recur often. +#: Not measured: ADR-012 measured MIN_OCCURRENCES and the display limit, not +#: where the wording changes. STRONG_EVIDENCE = 6 MODERATE_EVIDENCE = 3 @@ -963,6 +967,9 @@ def mine_all() -> list[Candidate]: # --- naming ---------------------------------------------------------------- +# The same six-character ceiling on an extension as ``_FILENAME`` above, +# without its leading-letter rule: this one strips, it does not classify, so +# ``run.v2`` should lose its suffix too. Six is chosen by eye, not measured. _TRAILING_EXTENSION = re.compile(r"\.[A-Za-z0-9]{1,6}$") diff --git a/src/mem/ranking.py b/src/mem/ranking.py index ed18561..b80d9fa 100644 --- a/src/mem/ranking.py +++ b/src/mem/ranking.py @@ -59,7 +59,8 @@ # not the mechanism that protects literal matches. It is deliberately mild: # make it severe and a command matching only a vague literal word ("fix") # outranks the one that matched a precise concept ("certificate" -> openssl), -# which is the opposite of what the map is for. +# which is the opposite of what the map is for. 0.8 is chosen by eye, not +# measured; only "mild" is a considered choice. LITERAL_CREDIT = 1.0 EXPANDED_CREDIT = 0.8 diff --git a/src/mem/search.py b/src/mem/search.py index 91ee9bc..6c41204 100644 --- a/src/mem/search.py +++ b/src/mem/search.py @@ -292,6 +292,8 @@ def search( """Search command history for commands matching a query. Returns a list of (command, score) tuples, ranked by score descending. + Ten by default because it fits a terminal without scrolling; chosen by + eye, not measured. **The matching rule.** A command matches when every word of the query appears in it. If nothing does, and only then, the query is re-read From 3825ee3d33ba26a29db20fe1f1ddf9bdad58e907 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:47:42 -0300 Subject: [PATCH 29/40] refactor: five helpers were copied across fix, promote and mcp instead of shared MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_iso`, `_redact`, `_is_flag`, `_PRIVILEGE_PREFIXES` and `_think_seconds` existed two or three times each, byte-identical or nearly so, and promote.py carried a comment defending its `_is_flag` copy on the grounds that shlex tokens and raw spans are "not the same kind of value" — for a function whose whole body is "starts with a dash and is longer than one character", which is true of both. Both promote.py and mcp.py already import from fix.py, so the definitions now live there once, public (`iso_utc`, `redact_payload`, `is_flag`, `PRIVILEGE_PREFIXES`, `think_seconds`), and the copies are deleted. The one real difference is decided once: `think_seconds` clamps at zero, as promote's copy did. fix's copy did not, but its only caller skips a candidate whose timestamp precedes the failure before ever calling it, so a negative gap was already unreachable there and the clamp changes no result. This codebase has paid for a duplicated hook, a duplicated ranking formula and duplicated mining logic; the redactor in particular is a choke point that must not fork, because a fix to it has to reach every exit — `mem fix --json`, `mem promote --json` and every MCP tool result — at once. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 3695fe4b71d5209d49efe6f8115e2731a8cb07f5) --- src/mem/fix.py | 78 ++++++++++++++++++++++------------ src/mem/mcp.py | 38 ++--------------- src/mem/promote.py | 103 +++++++++------------------------------------ 3 files changed, 74 insertions(+), 145 deletions(-) diff --git a/src/mem/fix.py b/src/mem/fix.py index 9395786..63b20e8 100644 --- a/src/mem/fix.py +++ b/src/mem/fix.py @@ -49,7 +49,7 @@ Sixty seconds. A correction written while the error message is still on screen is typed in seconds; past a minute the user has read docs, opened a browser or switched task, and any causal link is a guess. The gap is - measured as *think time* — see :func:`_think_seconds` — because mem + measured as *think time* — see :func:`think_seconds` — because mem timestamps a command when it *completes*, so a fix that itself takes two minutes to run would otherwise fall out of a window it never left. @@ -161,7 +161,8 @@ MODERATE_EVIDENCE = 2 #: Program names that are a modifier rather than the command being run. -_PRIVILEGE_PREFIXES = frozenset({"sudo", "doas"}) +#: Shared with :mod:`mem.promote`, whose protected prefix slides past them. +PRIVILEGE_PREFIXES = frozenset({"sudo", "doas"}) # --- shared history scanning ---------------------------------------------- @@ -259,16 +260,17 @@ def normalized_tokens(command: str) -> tuple[str, ...]: except ValueError: tokens = command.split() start = 0 - while start < len(tokens) and tokens[start] in _PRIVILEGE_PREFIXES: + while start < len(tokens) and tokens[start] in PRIVILEGE_PREFIXES: start += 1 return tuple(tokens[start:]) -def _is_flag(token: str) -> bool: +def is_flag(token: str) -> bool: """True if a token is an option rather than a thing being operated on. A bare ``-`` is not a flag: it means stdin, and dropping it changes what - the command reads. + the command reads. Applied to ``shlex`` tokens here and to raw quoted + spans in :mod:`mem.promote`; a leading dash means the same in both. """ return len(token) > 1 and token.startswith("-") @@ -365,7 +367,7 @@ def is_near_variant(failed: Sequence[str], fix: Sequence[str]) -> bool: if tag == "equal" or tag == "insert": continue if tag == "delete": - if not all(_is_flag(token) for token in failed[i1:i2]): + if not all(is_flag(token) for token in failed[i1:i2]): return False continue # tag == "replace" @@ -403,7 +405,7 @@ def _replacement_is_admissible( substitutions += 1 for leftover in removed[len(added) :]: - if not _is_flag(leftover): + if not is_flag(leftover): return None return substitutions @@ -439,23 +441,36 @@ def is_plausible_correction(failed: str, fix: str, exit_code: int | None) -> boo return is_near_variant(failed_tokens, fix_tokens) -def _think_seconds(failed: CapturedCommand, candidate: CapturedCommand) -> int: - """Seconds between *failed* finishing and *candidate* being typed. +def think_seconds(previous: CapturedCommand, command: CapturedCommand) -> int: + """Seconds the user paused between *previous* finishing and typing *command*. mem timestamps a command when the shell hook fires, i.e. when it *completes*. Naively subtracting timestamps therefore charges the - candidate's own runtime to the user's thinking time, and a correction that + command's own runtime to the user's thinking time, and a correction that happens to be a four-minute ``docker build`` would be discarded for being slow rather than for being unrelated. Subtracting the known duration - measures what the window is actually about: how long the human paused. + measures what a window is actually about: how long the human paused. + + **Read this before writing anything else that reasons about elapsed + time.** A bare ``b.ts - a.ts`` is not think time — it includes however + long ``b`` took to run. This has bitten three times: the shell hooks, the + correction window here, and session splitting in :mod:`mem.promote`, + where it silently cut every deploy sequence in half at its slowest step. + Any new comparison against a duration threshold has to go through this. + + Clamped at zero. A command whose recorded duration exceeds the gap (clock + adjustment, or a duration measured by a different clock than the + timestamp) is a pause of nothing, not a negative one. Imported commands + carry no duration, so for them the gap is the raw one — the best + available answer, not a guess dressed up as one. Integer seconds against millisecond durations, so the result can land one second low; that slack is harmless against a 60-second window. """ - gap = candidate.ts - failed.ts - if candidate.duration_ms: - gap -= candidate.duration_ms // 1000 - return gap + gap = command.ts - previous.ts + if command.duration_ms: + gap -= command.duration_ms // 1000 + return max(gap, 0) def _same_terminal(failed: CapturedCommand, candidate: CapturedCommand) -> bool: @@ -529,7 +544,7 @@ def _find_fix(failure: Failure) -> CapturedCommand | None: for candidate in failure.following: if candidate.ts < failure.command.ts: continue # out-of-order line; a fix cannot precede its failure - if _think_seconds(failure.command, candidate) > WINDOW_SECONDS: + if think_seconds(failure.command, candidate) > WINDOW_SECONDS: break # the window only widens from here if not _same_terminal(failure.command, candidate): continue @@ -740,8 +755,14 @@ def build_report( ) -def _iso(ts: int) -> str: - """Format an epoch timestamp as UTC ISO-8601, for machine consumers.""" +def iso_utc(ts: int) -> str: + """Format an epoch timestamp as UTC ISO-8601, for machine consumers. + + Alongside the raw epoch, never instead of it: a model reads dates far + more reliably than it does integers, and a caller that wants to sort + still gets the number. Shared by ``mem fix``, ``mem promote`` and the + MCP server so that all three emit the same shape. + """ return ( datetime.fromtimestamp(ts, tz=timezone.utc) .isoformat(timespec="seconds") @@ -749,21 +770,22 @@ def _iso(ts: int) -> str: ) -def _redact(value: Any) -> Any: +def redact_payload(value: Any) -> Any: """Recursively redact every string in a JSON-shaped structure. Applied to the whole payload at one choke point rather than field by - field, for the same reason ``mem.mcp`` does it: a per-field call is a rule - a future field can forget, and the cost of forgetting is a printed - credential. ``mem fix`` in particular quotes commands the user has - forgotten they ran. + field: a per-field call is a rule a future field can forget, and the cost + of forgetting is a printed credential. ``mem fix`` and ``mem promote`` + quote commands the user has forgotten they ran; the MCP server hands them + to a model. One implementation for all three, so a fix to it reaches + every exit at once. """ if isinstance(value, str): return redact_secrets(value) if isinstance(value, dict): - return {k: _redact(v) for k, v in value.items()} + return {k: redact_payload(v) for k, v in value.items()} if isinstance(value, list): - return [_redact(v) for v in value] + return [redact_payload(v) for v in value] return value @@ -783,7 +805,7 @@ def report_payload(report: FixReport) -> dict[str, Any]: "command": failure.command, "exit_code": failure.exit_code, "ts": failure.ts, - "when": _iso(failure.ts), + "when": iso_utc(failure.ts), "repo": failure.repo, "dir": failure.dir, }, @@ -795,11 +817,11 @@ def report_payload(report: FixReport) -> dict[str, Any]: "confidence": c.confidence, "first_seen": c.first_seen, "last_seen": c.last_seen, - "last_seen_iso": _iso(c.last_seen), + "last_seen_iso": iso_utc(c.last_seen), "failed_since": c.fix_failures, "repo": c.repo, } for c in report.fixes ], } - return _redact(payload) + return redact_payload(payload) diff --git a/src/mem/mcp.py b/src/mem/mcp.py index 8fdc908..959a02a 100644 --- a/src/mem/mcp.py +++ b/src/mem/mcp.py @@ -82,10 +82,10 @@ import os import sys import time -from datetime import datetime, timezone from typing import Any, Callable, TextIO from mem import __version__, storage +from mem.fix import iso_utc, redact_payload from mem.models import AgentAuditEntry from mem.variables import redact_secrets @@ -156,20 +156,6 @@ def __init__(self, code: int, message: str, data: Any = None) -> None: # --- helpers --------------------------------------------------------------- -def _iso(ts: int) -> str: - """Format an epoch timestamp as UTC ISO-8601. - - Alongside the raw epoch, never instead of it: a model reads dates far - more reliably than it does integers, and a caller that wants to sort - still gets the number. - """ - return ( - datetime.fromtimestamp(ts, tz=timezone.utc) - .isoformat(timespec="seconds") - .replace("+00:00", "Z") - ) - - _repo_cache: list[str | None] = [] @@ -187,22 +173,6 @@ def _current_repo() -> str | None: return _repo_cache[0] -def _redact(value: Any) -> Any: - """Recursively redact every string in a JSON-shaped structure. - - Applied once to a whole tool payload rather than field by field: a - per-field call is a rule a future tool can forget, and the failure mode - of forgetting is a leaked credential. - """ - if isinstance(value, str): - return redact_secrets(value) - if isinstance(value, dict): - return {k: _redact(v) for k, v in value.items()} - if isinstance(value, list): - return [_redact(v) for v in value] - return value - - def _require_str(args: dict[str, Any], name: str) -> str: """Read a required non-empty string argument or raise INVALID_PARAMS.""" value = args.get(name) @@ -277,7 +247,7 @@ def _tool_search_history(args: dict[str, Any]) -> dict[str, Any]: "command": cmd.command, "repo": cmd.repo, "ts": cmd.ts, - "when": _iso(cmd.ts), + "when": iso_utc(cmd.ts), "exit_code": cmd.exit_code, "duration_ms": cmd.duration_ms, "score": round(score, 4), @@ -420,7 +390,7 @@ def _tool_recent_failures(args: dict[str, Any]) -> dict[str, Any]: "command": failure.command.command, "repo": failure.command.repo, "ts": failure.command.ts, - "when": _iso(failure.command.ts), + "when": iso_utc(failure.command.ts), "exit_code": failure.command.exit_code, "followed_by": [ {"command": nxt.command, "exit_code": nxt.exit_code} @@ -679,7 +649,7 @@ def _handle_tools_call(params: dict[str, Any]) -> dict[str, Any]: _audit(name, args, int(payload.get("count", 0)), None) # The single choke point: nothing reaches the client without passing here. - return _text_content(json.dumps(_redact(payload), indent=2)) + return _text_content(json.dumps(redact_payload(payload), indent=2)) def _text_content(text: str, is_error: bool = False) -> dict[str, Any]: diff --git a/src/mem/promote.py b/src/mem/promote.py index 0b337b5..7ff46e6 100644 --- a/src/mem/promote.py +++ b/src/mem/promote.py @@ -149,12 +149,18 @@ import re from dataclasses import dataclass -from datetime import datetime, timezone from pathlib import Path from typing import Any, Iterable, Sequence from mem import storage -from mem.fix import iter_histories +from mem.fix import ( + PRIVILEGE_PREFIXES, + is_flag, + iso_utc, + iter_histories, + redact_payload, + think_seconds, +) from mem.models import CapturedCommand, GroupFile from mem.variables import EXCLUDED_SHELL_VARS, looks_like_credential, redact_secrets @@ -193,10 +199,6 @@ STRONG_EVIDENCE = 6 MODERATE_EVIDENCE = 3 -#: Programs that modify the command they precede rather than being it. The -#: protected prefix (argv[0] plus the subcommand) slides past them. -_PRIVILEGE_PREFIXES = frozenset({"sudo", "doas"}) - #: Shell grammar. A command containing any of these is matched literally and #: never generalised — see the module docstring. _SHELL_GRAMMAR = ("|", ">", "<", "&&", "||", ";", "`", "$(", "&") @@ -240,18 +242,6 @@ def tokenize(command: str) -> list[Token]: return [Token(m.group(0), m.start(), m.end()) for m in _TOKEN.finditer(command)] -def _is_flag(token: str) -> bool: - """True if a token is an option rather than a thing being operated on. - - The same rule :mod:`mem.fix` applies, deliberately restated rather than - imported: that module classifies ``shlex`` tokens with the quotes already - stripped, this one classifies raw spans, and a shared helper would have to - pretend those are the same kind of value. A bare ``-`` means stdin, not a - flag. - """ - return len(token) > 1 and token.startswith("-") - - def _protected_prefix_length(tokens: Sequence[Token]) -> int: """How many leading tokens may never become a variable. @@ -266,7 +256,7 @@ def _protected_prefix_length(tokens: Sequence[Token]) -> int: runbook step of ``cd $ARG`` says nothing at all. """ offset = 0 - while offset < len(tokens) and tokens[offset].text in _PRIVILEGE_PREFIXES: + while offset < len(tokens) and tokens[offset].text in PRIVILEGE_PREFIXES: offset += 1 return offset + 2 @@ -295,7 +285,7 @@ def command_shape(command: str) -> tuple[str, ...]: for index, token in enumerate(tokens): if index < protected: shape.append(token.text) - elif _is_flag(token.text): + elif is_flag(token.text): name, sep, _value = token.text.partition("=") shape.append(name + sep + _HOLE if sep else token.text) else: @@ -328,33 +318,6 @@ def _slot_span(command: str, shape: tuple[str, ...], index: int) -> tuple[int, i # --- sessions -------------------------------------------------------------- -def _think_seconds(previous: CapturedCommand, command: CapturedCommand) -> int: - """Seconds the user paused between two commands. - - mem stamps a command when it *finishes*, so a raw timestamp difference - charges a command's own runtime to the user's thinking time. Subtracting - the known duration is what keeps a four-minute ``terraform apply`` from - looking like four minutes of distraction. Same correction, and same - reason, as :mod:`mem.fix`. - - Imported commands carry no duration, so the correction is a no-op for - them and the gap is the raw one — which is the best available answer, not - a guess dressed up as one. - - **Read this before writing anything else that reasons about elapsed - time.** mem records a command's *completion*, so a bare ``b.ts - a.ts`` is - not the time the user spent thinking — it includes however long ``b`` took - to run. This is now the third place that has bitten: the shell hooks, the - correction window in :mod:`mem.fix`, and session splitting here, where it - silently cut every deploy sequence in half at its slowest step. Any new - comparison against a duration threshold has to subtract ``duration_ms``. - """ - gap = command.ts - previous.ts - if command.duration_ms: - gap -= command.duration_ms // 1000 - return max(gap, 0) - - def split_sessions( commands: Sequence[CapturedCommand], ) -> list[list[CapturedCommand]]: @@ -371,8 +334,8 @@ def split_sessions( the sequences this module exists to find are build and deploy procedures, which are made *of* the slowest commands a developer runs: every deploy would be cut in half at its slowest step. The threshold is unchanged; what - is measured against it is think time (:func:`_think_seconds`), the same - correction ``mem fix`` applies for the same reason. + is measured against it is think time (:func:`mem.fix.think_seconds`), the + same correction ``mem fix`` applies for the same reason. Two further additions the tracker does not need: @@ -392,7 +355,7 @@ def split_sessions( if previous.session and command.session: boundary = previous.session != command.session else: - boundary = _think_seconds(previous, command) > SESSION_IDLE_SECONDS + boundary = think_seconds(previous, command) > SESSION_IDLE_SECONDS boundary = boundary or command.repo != previous.repo boundary = boundary or command.ts < previous.ts if boundary: @@ -501,7 +464,7 @@ def is_inspection(command: str) -> bool: if any(marker in command for marker in _SHELL_GRAMMAR): return False tokens = [token.text for token in tokenize(command)] - while tokens and tokens[0] in _PRIVILEGE_PREFIXES: + while tokens and tokens[0] in PRIVILEGE_PREFIXES: tokens = tokens[1:] if not tokens: return True @@ -529,7 +492,7 @@ def steps_of(session: Sequence[CapturedCommand]) -> list[list[CapturedCommand]]: continue if ( previous is not None - and _think_seconds(previous, command) > MAX_STEP_GAP_SECONDS + and think_seconds(previous, command) > MAX_STEP_GAP_SECONDS ): if len(current) >= MIN_SEQUENCE_LENGTH: runs.append(current) @@ -739,7 +702,7 @@ def _variable_name( # Read off the shape directly: those positions are protected, so they are # always literal text and never a hole. offset = 0 - while offset < len(step_shape) and step_shape[offset] in _PRIVILEGE_PREFIXES: + while offset < len(step_shape) and step_shape[offset] in PRIVILEGE_PREFIXES: offset += 1 verb = _sanitize(step_shape[offset + 1] if offset + 1 < len(step_shape) else "") if verb and verb not in EXCLUDED_SHELL_VARS: @@ -986,14 +949,14 @@ def suggest_name(candidate: Candidate, taken: Iterable[str] = ()) -> str: ``mem group rename`` fixes it later. """ tokens = [token.text for token in tokenize(candidate.steps[-1])] - while tokens and tokens[0] in _PRIVILEGE_PREFIXES: + while tokens and tokens[0] in PRIVILEGE_PREFIXES: tokens = tokens[1:] parts: list[str] = [] if tokens: head = _TRAILING_EXTENSION.sub("", tokens[0].rsplit("/", 1)[-1]) parts.append(head) - if len(tokens) > 1 and not _is_flag(tokens[1]) and "$" not in tokens[1]: + if len(tokens) > 1 and not is_flag(tokens[1]) and "$" not in tokens[1]: parts.append(tokens[1].rsplit("/", 1)[-1]) slug = re.sub(r"[^a-z0-9]+", "-", "-".join(parts).lower()).strip("-") @@ -1040,32 +1003,6 @@ def build_report( return PromoteReport(candidates=candidates, names=names) -def _iso(ts: int) -> str: - """Format an epoch timestamp as UTC ISO-8601, for machine consumers.""" - return ( - datetime.fromtimestamp(ts, tz=timezone.utc) - .isoformat(timespec="seconds") - .replace("+00:00", "Z") - ) - - -def _redact(value: Any) -> Any: - """Recursively redact every string in a JSON-shaped structure. - - At one choke point rather than field by field, exactly as ``mem fix`` and - ``mem mcp`` do it: a per-field call is a rule the next field can forget, - and the cost of forgetting is a printed credential. ``mem promote`` quotes - whole sequences of commands the user has stopped thinking about. - """ - if isinstance(value, str): - return redact_secrets(value) - if isinstance(value, dict): - return {k: _redact(v) for k, v in value.items()} - if isinstance(value, list): - return [_redact(v) for v in value] - return value - - def report_payload(report: PromoteReport) -> dict[str, Any]: """Render a report as redacted, JSON-ready data. @@ -1084,7 +1021,7 @@ def report_payload(report: PromoteReport) -> dict[str, Any]: "confidence": candidate.confidence, "first_seen": candidate.first_seen, "last_seen": candidate.last_seen, - "last_seen_iso": _iso(candidate.last_seen), + "last_seen_iso": iso_utc(candidate.last_seen), "repo": candidate.repo, "has_credential": candidate.has_credential, "variables": [ @@ -1097,4 +1034,4 @@ def report_payload(report: PromoteReport) -> dict[str, Any]: ) ], } - return _redact(payload) + return redact_payload(payload) From e3801ad968e1e4170e0b80770d23e0d214879b01 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:49:22 -0300 Subject: [PATCH 30/40] refactor(ranking): the "every word must appear" rule was written three times MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `search._terms`/`_matches`, `tui.terms_of`/`matches` and `fix.matches` were the same two functions, byte for byte in the first two cases, with tui's docstring promising it was "identical to what `mem ` does" — a promise held only by nobody having edited one of them yet. The finder cannot import search.py (Pydantic, ~58 ms against a first-frame budget of tens of milliseconds), which is the reason the copy existed; ranking.py is already standard-library-only and already imported by search, tui and now fix, so the rule lives there as `ranking.terms` and `ranking.matches` and the copies are gone. tui keeps its names as aliases of the shared functions, so the agreement is by construction rather than by assertion. Had the copies drifted, the same history would have matched differently in Ctrl+R than in `mem ` — the class of defect that put a stale shell hook in front of every pip user. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 31b9bda191eb500257aa521b345d6a5a17ba803a) --- src/mem/fix.py | 20 ++++++-------------- src/mem/ranking.py | 26 ++++++++++++++++++++++++++ src/mem/search.py | 24 +++--------------------- src/mem/tui.py | 18 +++++------------- 4 files changed, 40 insertions(+), 48 deletions(-) diff --git a/src/mem/fix.py b/src/mem/fix.py index 63b20e8..dd69768 100644 --- a/src/mem/fix.py +++ b/src/mem/fix.py @@ -123,7 +123,7 @@ from functools import lru_cache from typing import Any, Callable, Iterable, Iterator, Sequence -from mem import storage +from mem import ranking, storage from mem.models import CapturedCommand from mem.variables import redact_secrets @@ -682,17 +682,6 @@ def mine_all( # --- selection ------------------------------------------------------------- -def matches(command: str, terms: Sequence[str]) -> bool: - """True if *command* contains every term, case-insensitively. - - Same all-terms-must-appear contract as ``mem`` search, so that - ``mem fix npm build`` narrows to what the user expects rather than - matching anything mentioning either word. - """ - lowered = command.lower() - return all(term in lowered for term in terms) - - def select_failure( failures: Sequence[CapturedCommand], query: str | None = None, @@ -708,8 +697,11 @@ def select_failure( """ candidates = list(failures) if query: - terms = [t for t in query.lower().split() if t] - candidates = [c for c in candidates if matches(c.command, terms)] + # The same all-terms-must-appear rule as `mem `, so that + # `mem fix npm build` narrows to what the user expects rather than + # matching anything mentioning either word. + terms = ranking.terms(query) + candidates = [c for c in candidates if ranking.matches(c.command, terms)] if not candidates: return None diff --git a/src/mem/ranking.py b/src/mem/ranking.py index b80d9fa..f4a6235 100644 --- a/src/mem/ranking.py +++ b/src/mem/ranking.py @@ -119,6 +119,32 @@ def context_score(repo: str | None, current_repo: str | None) -> float: return 0.0 +# --- matching ---------------------------------------------------------------- +# +# The literal matching rule lives beside the formula for the same reason the +# formula lives here: `mem `, the Ctrl+R finder and `mem fix ` +# all filter before they rank, and three copies of "every word must appear" +# had already been written before this one replaced them. + + +def terms(query: str) -> list[str]: + """Split a query into the terms a command must all contain. + + Multi-word queries used to keep only the first word, so `mem docker + compose` silently answered for `docker` alone — and ranked an unrelated + `docker ps` above the one line that actually matched both words. Matching + every term independently also makes word order irrelevant, which is how + people remember commands. + """ + return [t for t in query.lower().split() if t] + + +def matches(command: str, query_terms: Sequence[str]) -> bool: + """True if every term appears somewhere in the command, case-insensitively.""" + lowered = command.lower() + return all(term in lowered for term in query_terms) + + def score( command: str, ts: int | float, diff --git a/src/mem/search.py b/src/mem/search.py index 6c41204..a47cfb0 100644 --- a/src/mem/search.py +++ b/src/mem/search.py @@ -58,24 +58,6 @@ def score_command( ) -def _terms(query: str) -> list[str]: - """Split a query into the terms a command must all contain. - - Multi-word queries used to keep only the first word, so `mem docker - compose` silently answered for `docker` alone — and ranked an unrelated - `docker ps` above the one line that actually matched both words. Matching - every term independently also makes word order irrelevant, which is how - people remember commands. - """ - return [t for t in query.lower().split() if t] - - -def _matches(command: str, terms: list[str]) -> bool: - """True if every term appears somewhere in the command.""" - lowered = command.lower() - return all(term in lowered for term in terms) - - def _read_history( current_repo: str | None, needles: Sequence[str] | None = None, @@ -152,12 +134,12 @@ def _literal_search( """Rank the commands containing every word the user typed.""" # Cheap substring test on the raw JSONL line, so the expensive parse only # runs for lines that could match. The needles are a *necessary* condition, - # never a sufficient one — `_matches` below is still the real filter. + # never a sufficient one — `ranking.matches` below is still the real filter. needles = storage.prefilter_needles(terms) matched = [ cmd for cmd in _read_history(current_repo, needles) - if _matches(cmd.command, terms) + if ranking.matches(cmd.command, terms) ] return _rank(matched, query, current_repo) @@ -327,7 +309,7 @@ def search( exists so the recall benchmark in ``tests/test_concepts.py`` can measure both halves against one history. """ - terms = _terms(query) + terms = ranking.terms(query) if not terms: return [] diff --git a/src/mem/tui.py b/src/mem/tui.py index ec9f533..26fc700 100644 --- a/src/mem/tui.py +++ b/src/mem/tui.py @@ -181,19 +181,11 @@ def parse_entry(line: str) -> Entry | None: # --- Filtering and ranking --------------------------------------------------- -def terms_of(query: str) -> list[str]: - """Split a query into the terms a command must all contain. - - Matched independently so word order does not matter, which is how people - remember commands. Identical to what ``mem `` does. - """ - return [t for t in query.lower().split() if t] - - -def matches(command: str, terms: Sequence[str]) -> bool: - """True when every term appears somewhere in the command.""" - lowered = command.lower() - return all(term in lowered for term in terms) +# The matching rule is the one `mem ` uses, by construction: both call +# into the standard-library-only ranking module rather than each keeping a +# copy that would drift. +terms_of = ranking.terms +matches = ranking.matches def candidate_lines(lines: Sequence[str], terms: Sequence[str]) -> Iterator[str]: From 4c44bb10734edfac4799b71d5173a0ec3b5bfc75 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:51:32 -0300 Subject: [PATCH 31/40] fix(picks): one hand-edited entry made the finder crash after Enter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `picks.record` validated the entry being recorded and then, while pruning, cast every *other* entry with `float()`. A `~/.mem/picks.json` containing `{"count": "many", "ts": 1}` anywhere — the shape `load` already skipped silently — therefore raised ValueError out of `record`, which the finder calls after the user has pressed Enter and before it prints the chosen command to stdout. The result was a traceback on the prompt and no command, from a function whose docstring promises "silent on failure", to protect a ranking hint. The three readers of that file now share one `_entry_weight` policy: `load` and `_pruned` skip a malformed entry, and `record` treats a malformed previous count as none, so re-picking a broken entry starts it over rather than inheriting the edit. Widening the catch to ValueError would have hidden the same crash in whatever the next reader is; one definition of "well-formed" cannot disagree with itself. The new test was watched failing with the audit's exact ValueError before the fix. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit a38588e632ea84376b933172c947a08e5634e24b) --- src/mem/picks.py | 62 +++++++++++++++++++++++++-------------------- tests/test_picks.py | 37 +++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 28 deletions(-) diff --git a/src/mem/picks.py b/src/mem/picks.py index 13651f8..c84459e 100644 --- a/src/mem/picks.py +++ b/src/mem/picks.py @@ -89,6 +89,25 @@ def _decay(count: float, age_seconds: float) -> float: return count * math.pow(0.5, days / HALF_LIFE_DAYS) +def _entry_weight(entry: object, now: float) -> float | None: + """Decayed weight of one stored entry, or None if it is not one. + + The single place that decides what a well-formed entry is. ``load``, + ``record`` and ``_pruned`` all read the same hand-editable file, and the + finder crashed once because two of them agreed on the shape and the third + cast with ``float()`` — one ``"count": "many"`` anywhere in the file + raised out of ``record`` after Enter and before the command reached the + shell. + """ + if not isinstance(entry, dict): + return None + count = entry.get("count") + stamp = entry.get("ts") + if not isinstance(count, (int, float)) or not isinstance(stamp, (int, float)): + return None + return _decay(float(count), now - float(stamp)) + + def load(now: float | None = None) -> dict[str, float]: """Return ``{command: decayed pick weight}``. @@ -111,14 +130,10 @@ def load(now: float | None = None) -> dict[str, float]: scores: dict[str, float] = {} for command, entry in entries.items(): - if not isinstance(command, str) or not isinstance(entry, dict): - continue - count = entry.get("count") - stamp = entry.get("ts") - if not isinstance(count, (int, float)) or not isinstance(stamp, (int, float)): + if not isinstance(command, str): continue - weight = _decay(float(count), moment - float(stamp)) - if weight > 0: + weight = _entry_weight(entry, moment) + if weight is not None and weight > 0: scores[command] = weight return scores @@ -144,17 +159,13 @@ def record(command: str, now: float | None = None) -> None: # lock that serializes nothing against the other writers is theatre. with _fsutil.exclusive_lock(mem_dir() / ".lock"): entries = _read_entries(path) - previous = entries.get(command, {}) - count = previous.get("count", 0.0) - stamp = previous.get("ts", moment) - if not isinstance(count, (int, float)) or not isinstance( - stamp, (int, float) - ): - count, stamp = 0.0, moment + # A malformed previous entry counts as none: the new pick starts + # over rather than inheriting whatever a hand edit left behind. + previous = _entry_weight(entries.get(command), moment) or 0.0 entries[command] = { # Six decimals keeps a hand-readable file; a difference below # that never moves a ranking. Chosen by eye. - "count": round(_decay(float(count), moment - float(stamp)) + 1.0, 6), + "count": round(previous + 1.0, 6), "ts": int(moment), } _fsutil.atomic_write( @@ -182,24 +193,19 @@ def _pruned(entries: dict[str, dict], now: float) -> dict[str, dict]: Without this the file only ever grows: every command ever chosen stays forever, long after its weight has decayed past the point of changing any - ordering. + ordering. Malformed entries are dropped here too: they were invisible to + ``load`` already, so rewriting the file without them loses nothing. """ - alive = { - command: entry + weights = { + command: weight for command, entry in entries.items() - if _decay(float(entry.get("count", 0)), now - float(entry.get("ts", now))) - >= _PRUNE_BELOW + if (weight := _entry_weight(entry, now)) is not None and weight >= _PRUNE_BELOW } + alive = {command: entries[command] for command in weights} if len(alive) <= MAX_ENTRIES: return alive - ranked = sorted( - alive.items(), - key=lambda item: _decay( - float(item[1].get("count", 0)), now - float(item[1].get("ts", now)) - ), - reverse=True, - ) - return dict(ranked[:MAX_ENTRIES]) + ranked = sorted(alive, key=lambda command: weights[command], reverse=True) + return {command: entries[command] for command in ranked[:MAX_ENTRIES]} def normalize(weight: float) -> float: diff --git a/tests/test_picks.py b/tests/test_picks.py index ae6d2b8..9e45d3f 100644 --- a/tests/test_picks.py +++ b/tests/test_picks.py @@ -146,6 +146,43 @@ def test_entries_of_the_wrong_shape_are_skipped_individually(self, tmp_mem_dir): assert list(picks.load(now=NOW)) == ["good"] + def test_recording_survives_a_hand_edited_entry(self, tmp_mem_dir): + """`record` must tolerate exactly what `load` tolerates. + + It used to validate only the entry being recorded and then cast every + *other* entry with float() while pruning, so one `"count": "many"` + anywhere in the file raised ValueError out of the finder — after the + user had pressed Enter and before the command reached the shell. + """ + storage.ensure_dirs() + picks.picks_file().write_text( + json.dumps( + { + "picks": { + "good": {"count": 2, "ts": NOW}, + "text-count": {"count": "many", "ts": NOW}, + "no-ts": {"count": 1}, + "not-a-dict": 7, + } + } + ), + encoding="utf-8", + ) + + picks.record("git push", now=NOW) + picks.record("text-count", now=NOW) # re-picking the broken entry + picks.record("not-a-dict", now=NOW) + + loaded = picks.load(now=NOW) + assert loaded["good"] == pytest.approx(2.0) + assert loaded["git push"] == pytest.approx(1.0) + # A broken entry is not inherited: the new pick starts the count over. + assert loaded["text-count"] == pytest.approx(1.0) + assert loaded["not-a-dict"] == pytest.approx(1.0) + # And a broken entry that was not re-picked is dropped by the rewrite. + assert "no-ts" not in loaded + assert "no-ts" not in json.loads(picks.picks_file().read_text())["picks"] + def test_a_missing_file_is_not_an_error(self, tmp_mem_dir): assert picks.load(now=NOW) == {} From a357be2c24b49f70fb9a63746ef2bb8346257d9c Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:53:05 -0300 Subject: [PATCH 32/40] refactor(capture): the session idle threshold was defined twice, once as a literal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `SessionTracker` compared against a bare `300` with the number repeated in three docstrings, and promote.py declared its own `SESSION_IDLE_SECONDS = 300` with a comment saying it "mirrors" the tracker "which owns this definition" — a definition that did not exist as a name anywhere. ADR-012's whole point about sessions is that `mem promote` must split them by the same rule as `mem session`, and a mirror that has to be kept in step by hand is how that rule quietly becomes two. The constant now lives in capture.py, the tracker uses it, and promote imports it; promote's structural "cannot execute anything" test still passes because it inspects promote's own source, which gains one import line and no new capability. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 598098195d19e53e76174b7b8b8f70b30c883140) --- src/mem/capture.py | 15 +++++++++++---- src/mem/promote.py | 14 ++++++-------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/mem/capture.py b/src/mem/capture.py index 8c24b72..5d6ca1a 100644 --- a/src/mem/capture.py +++ b/src/mem/capture.py @@ -16,6 +16,12 @@ from mem.models import CapturedCommand, SessionState, WorkSession from mem import 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 +# than restating it, so "a session" cannot mean two things. The value is +# chosen by eye, not measured — see SessionTracker. +SESSION_IDLE_SECONDS = 300 + def get_git_repo(directory: str) -> str | None: """Detect the current git repository's root path. @@ -153,7 +159,8 @@ class SessionTracker: proximity and repository context. Session boundaries are detected when: - 1. More than 300 seconds (5 minutes) of idle time between commands + 1. More than ``SESSION_IDLE_SECONDS`` (300, five minutes) of idle time + between commands 2. The user switches to a different git repository Why 300 seconds: Five minutes is long enough that brief interruptions @@ -193,7 +200,7 @@ def update(self, cmd: CapturedCommand) -> None: """Process a new command and update session state. Detects session boundaries and closes sessions when: - - More than 300 seconds have passed since the last command + - More than ``SESSION_IDLE_SECONDS`` have passed since the last command - The git repo has changed """ state = self._load_state() @@ -212,8 +219,8 @@ def update(self, cmd: CapturedCommand) -> None: idle_time = cmd.ts - state.last_command_ts repo_changed = cmd.repo != state.last_repo - # Session boundary: >300s idle OR repo change - if idle_time > 300 or repo_changed: + # Session boundary: idle past the threshold OR repo change + if idle_time > SESSION_IDLE_SECONDS or repo_changed: self._close_session(state) # Start new session new_state = SessionState( diff --git a/src/mem/promote.py b/src/mem/promote.py index 7ff46e6..f343805 100644 --- a/src/mem/promote.py +++ b/src/mem/promote.py @@ -39,13 +39,14 @@ commands are kept for 90, and ``mem import`` writes none at all — so the user who has just imported ten years of ``.zsh_history`` and has the most to gain would get nothing. Sessions are re-derived here from the command files using -the same rule the tracker uses (:data:`SESSION_IDLE_SECONDS`), against data -that is richer and lives longer. +the same rule the tracker uses (:data:`mem.capture.SESSION_IDLE_SECONDS`), +against data that is richer and lives longer. **A session boundary is 300 idle seconds or a change of repository.** Not a new threshold — :class:`mem.capture.SessionTracker` chose it and this -mirrors it, because a "session" that meant one thing in ``mem session`` and -another in ``mem promote`` would be a lie in one of the two places. +module imports that constant rather than restating it, because a "session" +that meant one thing in ``mem session`` and another in ``mem promote`` would +be a lie in one of the two places. **Inspection commands are removed before mining.** ``ls``, ``cd``, ``cat``, ``git status`` and their kind are how you *look* at a repository, not how you @@ -153,6 +154,7 @@ from typing import Any, Iterable, Sequence from mem import storage +from mem.capture import SESSION_IDLE_SECONDS from mem.fix import ( PRIVILEGE_PREFIXES, is_flag, @@ -171,10 +173,6 @@ # their trust in the whole command, once, permanently. The reasoning for each # is in the module docstring. -#: Idle seconds that end a work session. Mirrors -#: :class:`mem.capture.SessionTracker`, which owns this definition. -SESSION_IDLE_SECONDS = 300 - #: Longest think-time gap between two consecutive steps of one procedure. MAX_STEP_GAP_SECONDS = 900 From e3ea0c32b33efb9eb6c998e0fea316a024dc8ef3 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:55:56 -0300 Subject: [PATCH 33/40] fix(patterns): an installed SDK with the model switched off never reached the heuristic fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_apple_fm_available` tested only `import apple_fm_sdk`. On a machine with the `ai` extra installed but Apple Intelligence disabled, or the model not yet downloaded, the import succeeds, every `respond` raises, `_generalize_commands` swallows each failure and stores the command as its own pattern, and the sync exits 0 — the heuristic path, which is the designed answer for "no model", never ran, and the pattern files looked exactly as if it had. The probe now also asks `SystemLanguageModel().is_available()`, which the SDK returns as `(bool, reason)`, logs the reason at debug level, and answers False so the heuristic runs. A module without that class (the conftest stand-in, an SDK build without the API) keeps the old "importable means usable" answer, guarded with getattr; a probe that itself raises reads as unavailable, since a prompt would fail the same way. Tests: the probe's three answers, plus an end-to-end test with a fake SDK that reports unavailable and counts sessions opened — it asserts zero, and was watched failing with three before the fix, because the identity mapping alone is indistinguishable from the heuristic's output. The opt-in `ai` test no longer accepts "a non-empty string", which the identity mapping satisfied without the model running; it asserts the pattern differs from the input. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit ee378c50109273980a3204b4ea6b1dcfeee141bc) --- src/mem/patterns.py | 35 ++++++++++++-- tests/test_patterns.py | 104 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 134 insertions(+), 5 deletions(-) diff --git a/src/mem/patterns.py b/src/mem/patterns.py index 760e667..22c8480 100644 --- a/src/mem/patterns.py +++ b/src/mem/patterns.py @@ -118,13 +118,40 @@ def _apple_fm_available() -> bool: - """Check if Apple Foundation Models SDK is available.""" + """True when the SDK imports *and* the on-device model can answer. + + Importing ``apple_fm_sdk`` only proves the extra is installed. With Apple + Intelligence switched off, or the model not yet downloaded, the import + succeeds and every request raises — which ``_generalize_commands`` + swallows per command, storing an identity mapping with exit 0. The + heuristic fallback, the designed answer for "no model", never ran on such + a machine. So the probe also asks the model, and says why when it is + turned down. + + ``getattr`` rather than an attribute access: the test suite stands in a + bare module when the SDK is absent, and an SDK without this API is + assumed usable, which is what the probe meant before it asked. + """ try: - import apple_fm_sdk # noqa: F401 - - return True + import apple_fm_sdk as fm except ImportError: return False + model_cls = getattr(fm, "SystemLanguageModel", None) + if model_cls is None: + return True + try: + available, reason = model_cls().is_available() + except Exception: # noqa: BLE001 - the SDK's own errors, or a native library + # that will not load; either way a prompt would fail the same way. + logger.debug("apple-fm-sdk availability probe failed", exc_info=True) + return False + if not available: + logger.debug( + "on-device model unavailable (%s); using heuristic patterns", + getattr(reason, "name", reason), + ) + return False + return True def _get_generable_types() -> type: diff --git a/tests/test_patterns.py b/tests/test_patterns.py index 90b4242..f41923a 100644 --- a/tests/test_patterns.py +++ b/tests/test_patterns.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging import sys import time from dataclasses import dataclass @@ -822,6 +823,38 @@ async def _respond(prompt: str, generating=None): assert sum(p.frequency for p in result.patterns) == len(commands) +def _fake_sdk(available: bool, reason: str | None = None) -> ModuleType: + """An `apple_fm_sdk` whose model reports the given availability. + + `is_available()` returns `(bool, reason)` exactly as the real SDK's + `SystemLanguageModel` does; `reason` is an object with a `.name`, like + the real enum member. Opening a session is counted so a test can prove + the model path was never entered. + """ + fake = ModuleType("apple_fm_sdk") + fake.sessions_opened = 0 # type: ignore[attr-defined] + + class Reason: + name = reason + + class SystemLanguageModel: + def is_available(self): + return available, (None if available else Reason()) + + class LanguageModelSession: + def __init__(self) -> None: + fake.sessions_opened += 1 # type: ignore[attr-defined] + + async def respond(self, *args, **kwargs): + raise RuntimeError("model unavailable") + + fake.SystemLanguageModel = SystemLanguageModel # type: ignore[attr-defined] + fake.LanguageModelSession = LanguageModelSession # type: ignore[attr-defined] + fake.generable = lambda *a, **kw: lambda cls: cls # type: ignore[attr-defined] + fake.guide = lambda *a, **kw: None # type: ignore[attr-defined] + return fake + + class TestAppleFmProbe: """The availability probe decides between the AI and heuristic paths.""" @@ -831,9 +864,75 @@ def test_reports_unavailable_when_the_sdk_cannot_be_imported(self, monkeypatch): assert _REAL_APPLE_FM_AVAILABLE() is False def test_reports_available_when_the_sdk_imports(self, monkeypatch): + """An SDK with no availability API is assumed usable, as before.""" monkeypatch.setitem(sys.modules, "apple_fm_sdk", ModuleType("apple_fm_sdk")) assert _REAL_APPLE_FM_AVAILABLE() is True + def test_reports_unavailable_when_the_model_says_so(self, monkeypatch, caplog): + """Installed is not the same as usable. + + With Apple Intelligence off or the model not downloaded, the SDK + imports fine and every request raises. The probe has to ask the + model, or the heuristic fallback never runs and every command maps + to itself with exit 0. + """ + monkeypatch.setitem( + sys.modules, + "apple_fm_sdk", + _fake_sdk(available=False, reason="MODEL_NOT_READY"), + ) + + with caplog.at_level(logging.DEBUG, logger="mem.patterns"): + assert _REAL_APPLE_FM_AVAILABLE() is False + + assert "MODEL_NOT_READY" in caplog.text + + def test_reports_available_when_the_model_says_so(self, monkeypatch): + monkeypatch.setitem(sys.modules, "apple_fm_sdk", _fake_sdk(available=True)) + assert _REAL_APPLE_FM_AVAILABLE() is True + + def test_a_probe_that_raises_reads_as_unavailable(self, monkeypatch): + """If the model cannot even be asked, it cannot answer a prompt either.""" + fake = _fake_sdk(available=True) + + class Broken: + def __init__(self) -> None: + raise RuntimeError("native library missing") + + fake.SystemLanguageModel = Broken # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "apple_fm_sdk", fake) + + assert _REAL_APPLE_FM_AVAILABLE() is False + + def test_the_heuristic_runs_when_the_model_is_unavailable( + self, tmp_mem_dir, monkeypatch + ): + """The designed fallback, end to end, with the SDK present but the model off. + + Before the probe asked the model, this path went through + `_generalize_commands`, which opened a session per command, caught + the failure per command, and stored an identity mapping — a result + indistinguishable from the heuristic's, produced by the slow path + the heuristic exists to avoid. So the assertion is on the mechanism: + no session is ever opened. + """ + fake = _fake_sdk(available=False, reason="APPLE_INTELLIGENCE_NOT_ENABLED") + monkeypatch.setitem(sys.modules, "apple_fm_sdk", fake) + # The autouse fixture pins the probe to False; this test is about the + # real probe, so put it back. + monkeypatch.setattr(patterns, "_apple_fm_available", _REAL_APPLE_FM_AVAILABLE) + + now = int(time.time()) + for cmd in ["kubectl get pods"] * 3 + ["kubectl get svc", "kubectl get nodes"]: + storage.append_command(make_command(command=cmd, ts=now)) + + patterns.run_pattern_extraction("kubectl") + + result = storage.read_patterns("kubectl") + assert result is not None + assert [p.pattern for p in result.patterns][0] == "kubectl get pods" + assert fake.sessions_opened == 0 + def test_generable_type_declares_the_pattern_field(self, monkeypatch): """Guided generation must ask the model for a single `pattern` string.""" captured: dict[str, object] = {} @@ -1005,7 +1104,10 @@ def test_real_model_generalizes_a_command(self): ) pattern = mapping["git checkout main"] - assert isinstance(pattern, str) and pattern.strip() + # An identity mapping is exactly what the per-command failure path + # stores when the model cannot answer, so "is a non-empty string" was + # satisfied by a model that never ran. The answer must generalise. + assert pattern != "git checkout main", pattern def test_real_model_summarizes_a_session(self): import asyncio From afa011530705aa829ae165504244d81dffa1a895 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:57:48 -0300 Subject: [PATCH 34/40] refactor(patterns): a Counter was re-implemented, and one file was read three times per tool MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_heuristic_patterns` rebuilt a frequency table with `defaultdict(int)` from the same command list its caller had already reduced with `Counter(commands)` two lines earlier; it now takes that Counter and uses `most_common`, whose tie order (first encountered) is the stable sort's. `storage.read_patterns(tool)` was called by `sync_all_patterns` to decide new-versus-updated, again by `_load_cache`, and a third time in the "nothing new" check — three parses of the same JSON per tool per sync, in a background process that runs every twenty captures. `run_pattern_extraction` now reads it once, or accepts it from a caller that already has it. Behaviour is identical; the point is that a reader no longer has to check whether three reads of one file can disagree. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit a367b4ab74e84e6aa8b9a874dfc354f47e856d4a) --- src/mem/patterns.py | 51 ++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/src/mem/patterns.py b/src/mem/patterns.py index 22c8480..1f4bb09 100644 --- a/src/mem/patterns.py +++ b/src/mem/patterns.py @@ -32,6 +32,7 @@ import sys import time from collections import Counter, defaultdict +from typing import Any from mem import storage from mem.models import ( @@ -299,7 +300,7 @@ async def extract_patterns_for_tool( unique_cmds = list(raw_freq.keys()) if not _apple_fm_available(): - return _heuristic_patterns(tool, commands) + return _heuristic_patterns(tool, raw_freq) # Step 2: Generalize only what the cache does not already cover. Most # frequent first, so a budget-limited run spends the model on the commands @@ -368,21 +369,18 @@ async def generate_session_summary(commands: list[str]) -> str | None: return None -def _heuristic_patterns(tool: str, commands: list[str]) -> PatternExtractionResult: +def _heuristic_patterns(tool: str, freq: Counter[str]) -> PatternExtractionResult: """Simple fallback when Apple FM SDK is unavailable. - Groups identical commands and returns them as "patterns". - Not as smart as AI extraction, but still useful for ranking. + Groups identical commands and returns them as "patterns". ``freq`` is the + count the caller already took; not as smart as AI extraction, but still + useful for ranking. """ - freq: dict[str, int] = defaultdict(int) - for cmd in commands: - freq[cmd] += 1 - # The ten most repeated commands stand in for patterns. Ten is chosen by # eye, not measured; it is what fits in a `mem patterns` listing. patterns = [ CommandPattern(pattern=cmd, example=cmd, frequency=count) - for cmd, count in sorted(freq.items(), key=lambda x: x[1], reverse=True)[:10] + for cmd, count in freq.most_common(10) ] # Identity mapping for every command, not just the ten reported: without a @@ -395,24 +393,17 @@ def _heuristic_patterns(tool: str, commands: list[str]) -> PatternExtractionResu ) -def _load_cache(tool: str) -> dict[str, str]: - """Read the {command -> pattern} cache for a tool. - - Files written before ``command_patterns`` existed only recorded which - commands had been seen, with no way to recover what they mapped to. Those - commands are treated as uncached so they get generalized once more, rather - than being resurrected as raw patterns. - """ - existing = storage.read_patterns(tool) - if existing is None: - return {} - return dict(existing.command_patterns) +# Sentinel for "the caller did not read the pattern file", as distinct from +# "the caller read it and there was none". +_UNREAD: Any = object() def run_pattern_extraction( tool: str, commands: list[str] | None = None, budget: int | None = None, + *, + existing: PatternFile | None = _UNREAD, ) -> int: """Extract patterns for a single tool and save to storage. @@ -421,6 +412,10 @@ def run_pattern_extraction( into O(tools x history): 50 tools over a 100k-command history meant five million line parses, every 20 captures, in a background process. + ``existing`` is the tool's current pattern file, for a caller that has + already read it (``sync_all_patterns`` needs it to count new tools); left + out, it is read here, once. + Returns how many commands this run added to the cache. With the model that is the number of commands sent to it, which is what lets a caller spend a shared budget across tools; on the heuristic path nothing is sent @@ -443,9 +438,15 @@ def run_pattern_extraction( if len(commands) < MIN_COMMANDS_PER_TOOL: return 0 # Not enough data for meaningful patterns - cache = _load_cache(tool) + if existing is _UNREAD: + existing = storage.read_patterns(tool) + # The {command -> pattern} cache. Files written before `command_patterns` + # existed only recorded which commands had been seen, with no way to + # recover what they mapped to; those commands are treated as uncached so + # they get generalized once more rather than resurrected as raw patterns. + cache = {} if existing is None else dict(existing.command_patterns) uncached = {c for c in set(commands) if c not in cache} - if not uncached and storage.read_patterns(tool) is not None: + if not uncached and existing is not None: return 0 # Nothing new to process result = asyncio.run( @@ -501,7 +502,9 @@ def sync_all_patterns(silent: bool = False) -> tuple[int, int]: 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) + spent = run_pattern_extraction( + tool, commands=commands, budget=remaining, existing=existing + ) remaining -= max(spent, 0) if existing is None: From c0e94fbcd49635328d1dfa212772f58c12df9cc6 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 00:59:41 -0300 Subject: [PATCH 35/40] fix(capture): the session state file was the one file mem wrote world-readable and unlocked MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `SessionTracker._save_state` used `Path.write_text`: the file was created with the process umask (0644 on a default macOS account) while every other file under ~/.mem is 0600 through `_fsutil.atomic_write`; it was overwritten in place, so a crash mid-write left a truncated JSON the next capture silently discarded; and it took no lock, while `storage._scrub_session_state` rewrites the same file atomically under the lock for `mem forget` — one file with a guarded and an unguarded writer, where the unguarded one carries the user's last commands and the guarded one exists to remove a secret from them. The write now goes through `storage.atomic_write` under `storage.exclusive_lock`, which is re-entrant, so the nested `append_session` lock inside a boundary is unaffected. Only the write is locked, not the whole update: a boundary may call the on-device model for a summary, and holding the global lock for those seconds would stall every other shell's capture. The new test sets a permissive umask and was watched failing with 0o644 before the fix. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 7c83f28f25ce29bc4878fb7393a3d40b265dfd96) --- src/mem/capture.py | 15 +++++++++++++-- tests/test_capture.py | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/mem/capture.py b/src/mem/capture.py index 5d6ca1a..4e6abc6 100644 --- a/src/mem/capture.py +++ b/src/mem/capture.py @@ -192,9 +192,20 @@ def _load_state(self) -> SessionState | None: return None def _save_state(self, state: SessionState) -> None: - """Persist session state to disk.""" + """Persist session state to disk: atomically, owner-only, under the lock. + + The same write path as every other file under ~/.mem. This used to + be a bare ``write_text``: created with the umask (0644 on a default + macOS account) while everything else is 0600, replaced in place + rather than renamed, and taken with no lock — while + ``storage._scrub_session_state`` rewrites the same file atomically + under the lock for ``mem forget``. One file, two writers, one of + them unguarded: a scrub and a capture landing together could leave + the forgotten command in the state the next boundary flushes. + """ storage.ensure_dirs() - self._state_path.write_text(state.model_dump_json(), encoding="utf-8") + with storage.exclusive_lock(): + storage.atomic_write(self._state_path, state.model_dump_json()) def update(self, cmd: CapturedCommand) -> None: """Process a new command and update session state. diff --git a/tests/test_capture.py b/tests/test_capture.py index 8302403..6406fe6 100644 --- a/tests/test_capture.py +++ b/tests/test_capture.py @@ -508,6 +508,31 @@ def test_empty_commands_not_persisted(self, tmp_mem_dir): sessions = list(storage.read_all_sessions()) assert len(sessions) == 0 + def test_state_file_is_owner_only_and_written_atomically(self, tmp_mem_dir): + """The one file mem wrote with `write_text` and the umask. + + Every other file under ~/.mem is 0600 via `atomic_write`, and + `storage._scrub_session_state` rewrites this same file atomically + under the lock — so the tracker was the one unlocked, non-atomic, + world-readable writer of a file holding the user's last commands. + """ + import os + import stat + + old_umask = os.umask(0o022) + try: + tracker = SessionTracker() + tracker.update(make_command(command="export TOKEN=hunter2", ts=1000)) + finally: + os.umask(old_umask) + + mode = stat.S_IMODE(tracker._state_path.stat().st_mode) + assert mode == 0o600, f"session state is readable by others: {oct(mode)}" + leftovers = [ + p.name for p in tracker._state_path.parent.iterdir() if ".tmp" in p.name + ] + assert leftovers == [] + def test_state_survives_reload(self, tmp_mem_dir): """State persisted to disk can be loaded by a new tracker instance.""" tracker1 = SessionTracker() From dfc178a98e93d0d7c8e33665cf36c4adaebb878d Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 01:01:00 -0300 Subject: [PATCH 36/40] fix(capture): a command running longer than the idle threshold ended its own session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `SessionTracker.update` compared `cmd.ts - state.last_command_ts` against the 300-second threshold. Timestamps in mem are completion times, so that difference includes the command's own runtime: a `docker build` that took six minutes read as six minutes of idleness and closed the session the moment it finished, splitting every build-and-deploy procedure at exactly its slowest step. ADR-012 documents this as the reason `mem promote` re-derives sessions from the command files instead of reading the tracker's — the third appearance of this bug class after the shell hooks and `mem fix`'s correction window, and the one place left that still had it. The idle time is now think time: the gap minus the command's `duration_ms`, clamped at zero, the same arithmetic as `fix.think_seconds` (inlined, because that helper takes two commands and the hook path cannot afford fix.py's imports on every prompt). The new test pins both directions at one timestamp pair: last command at t=1000, next finishing at t=1400 with 200 s of runtime stays in the session, with 0 s it does not. The first case was watched failing before the fix; the existing exact-boundary test has no duration and is unchanged. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit b94976d5012abb54644c0f9772b1fe3b998e815e) --- src/mem/capture.py | 10 ++++++++++ tests/test_capture.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/mem/capture.py b/src/mem/capture.py index 4e6abc6..11af8d7 100644 --- a/src/mem/capture.py +++ b/src/mem/capture.py @@ -227,7 +227,17 @@ def update(self, cmd: CapturedCommand) -> None: self._save_state(new_state) return + # Think time, not the raw gap. mem stamps a command when it *finishes*, + # so `cmd.ts - last_ts` includes cmd's own runtime, and a build that + # ran longer than the threshold ended its own session when it + # completed (ADR-012 records this as the tracker being wrong). The + # same arithmetic as `mem.fix.think_seconds`, inlined: that helper + # takes two commands and the state keeps only a timestamp, and the + # capture hook cannot afford fix.py's imports on every prompt. idle_time = cmd.ts - state.last_command_ts + if cmd.duration_ms: + idle_time -= cmd.duration_ms // 1000 + idle_time = max(idle_time, 0) repo_changed = cmd.repo != state.last_repo # Session boundary: idle past the threshold OR repo change diff --git a/tests/test_capture.py b/tests/test_capture.py index 6406fe6..dc9839d 100644 --- a/tests/test_capture.py +++ b/tests/test_capture.py @@ -428,6 +428,36 @@ def test_idle_boundary_is_exactly_300_seconds( assert sessions == [] assert state.commands == ["cmd1", "cmd2"] + @pytest.mark.parametrize( + ("duration_ms", "expect_closed"), + [(200_000, False), (0, True)], + ) + def test_idle_is_think_time_not_the_raw_gap( + self, tmp_mem_dir, duration_ms: int, expect_closed: bool + ): + """A command that ran longer than the threshold must not end its own session. + + Timestamps are completion times. Last command at t=1000, next one + finishing at t=1400: if it *ran* for 200 s the user paused 200 s and + the session continues; if it ran for 0 s they paused 400 s and it + splits. `mem fix` and `mem promote` both subtract `duration_ms`; the + tracker did not, which ADR-012 records as the tracker being wrong. + """ + tracker = SessionTracker() + tracker.update(make_command(command="cmd1", ts=1000, duration_ms=0)) + tracker.update( + make_command(command="docker build .", ts=1400, duration_ms=duration_ms) + ) + + sessions = list(storage.read_all_sessions()) + state = tracker._load_state() + if expect_closed: + assert [s.commands for s in sessions] == [["cmd1"]] + assert state.commands == ["docker build ."] + else: + assert sessions == [] + assert state.commands == ["cmd1", "docker build ."] + def test_session_summary_fallback(self, tmp_mem_dir): """Session summary falls back to first command when AI unavailable.""" tracker = SessionTracker() From 1ac39be8f58fc6d67d25b1f28f0eb93a876e4c3a Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 01:02:39 -0300 Subject: [PATCH 37/40] fix(mcp): recent_failures said a command was never retried when it had succeeded before failing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_tool_recent_failures` filled `succeeded_later` with `setdefault`, so it held the index of the *first* success per command, and `retried_successfully = retry > failure.index` compared the failure against a success that came before it. For the history success@100, fail@200, success@300 — the ordinary shape of a flaky test run — the tool answered False, while its description promises "whether the same command later succeeded". An agent reading that would conclude the failure was never resolved and propose a fix for a command that already works. The map now records the last success per command, so the single comparison means what it says. Two tests pin both directions; the success-before-and-after case was watched failing before the fix. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit a353f3ccdfbe6e5e063e0d98848803c90b1b5031) --- src/mem/mcp.py | 10 +++++++--- tests/test_mcp.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/mem/mcp.py b/src/mem/mcp.py index 959a02a..42a6b94 100644 --- a/src/mem/mcp.py +++ b/src/mem/mcp.py @@ -375,16 +375,20 @@ def _tool_recent_failures(args: dict[str, Any]) -> dict[str, Any]: failures: list[dict[str, Any]] = [] for _key, commands in iter_histories(include): - succeeded_later: dict[str, int] = {} + # The *last* success per command, so "did it succeed after this + # failure" is one comparison. Keeping the first (as `setdefault` did) + # answered no for success -> failure -> success, the ordinary shape of + # a flaky run, because the recorded success preceded the failure. + last_success: dict[str, int] = {} for index, cmd in enumerate(commands): if cmd.exit_code == 0: - succeeded_later.setdefault(cmd.command, index) + last_success[cmd.command] = index # Two lines of "what was run next", where `mem fix` reads three: this # tool reports context rather than mining a correction, and an agent # reading a list needs less of it. Chosen by eye, not measured. for failure in iter_failures(commands, lookahead=2): - retry = succeeded_later.get(failure.command.command) + retry = last_success.get(failure.command.command) failures.append( { "command": failure.command.command, diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 3d0c4bb..ccd1a71 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -635,6 +635,48 @@ def test_failure_carries_what_was_run_next(self, home: Path, workdir: Path) -> N # The same command succeeded afterwards: that is the proof it was fixed. assert failure["retried_successfully"] is True + def test_a_success_before_the_failure_does_not_hide_the_one_after( + self, home: Path, workdir: Path + ) -> None: + """`retried_successfully` means "succeeded *later*", as the tool promises. + + The index of the first success per command was being kept, so for + success -> failure -> success the retry was found *before* the + failure and reported as no retry at all — for the most ordinary + shape a flaky test run has. + """ + enable(home, workdir) + plant( + home, + [ + {"command": "pytest -q", "ts": NOW - 300}, + {"command": "pytest -q", "ts": NOW - 200, "exit_code": 1}, + {"command": "pytest -q", "ts": NOW - 100}, + ], + ) + + result = serve([INIT, call(2, "recent_failures")], home, workdir) + + failure = tool_payload(by_id(result, 2))["failures"][0] + assert failure["retried_successfully"] is True + + def test_a_success_only_before_the_failure_is_not_a_retry( + self, home: Path, workdir: Path + ) -> None: + enable(home, workdir) + plant( + home, + [ + {"command": "pytest -q", "ts": NOW - 300}, + {"command": "pytest -q", "ts": NOW - 200, "exit_code": 1}, + ], + ) + + result = serve([INIT, call(2, "recent_failures")], home, workdir) + + failure = tool_payload(by_id(result, 2))["failures"][0] + assert failure["retried_successfully"] is False + def test_successful_commands_are_not_reported( self, home: Path, workdir: Path ) -> None: From 849b86d3516f5d9119ad2552ddfac4d58f4f2218 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 01:03:54 -0300 Subject: [PATCH 38/40] test(e2e): two auto-sync tests spent eight seconds reaching a counter they could have written `test_threshold_capture_resets_the_sync_counter` and `test_capture_cycle_triggers_a_real_background_sync` each ran twenty `mem _capture` subprocesses at ~0.2 s apiece purely to walk `.sync_counter` up to SYNC_THRESHOLD. The counter is a bare integer in a file the storage layer writes under its lock; writing `SYNC_THRESHOLD-1` into it before the binary starts contends with nothing, and one real capture then reaches the threshold. What the tests exist to prove is unchanged and still asserted: the counter resets to 0, and the detached sync really runs (the ancient command is rotated out). Measured: 3.4 s and 4.5 s per test down to 0.18 s and 0.39 s. Co-Authored-By: Claude Fable 5.1 (cherry picked from commit 436b772dac91b8ae5ef19da2278d052602d33a16) --- tests/test_e2e.py | 48 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 3f9ab87..c1989f1 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -32,6 +32,8 @@ class of defects invisible: entry points that are never reached, console import pytest +from mem import storage + REPO_ROOT = Path(__file__).resolve().parent.parent # The hooks live inside the package so the wheel ships them. Before that they # sat at the repo root, were unreachable from an installed wheel, and `mem @@ -149,6 +151,22 @@ def plant_commands(home: Path, entries: list[tuple[str, int]]) -> None: path.write_text("\n".join(lines) + "\n", encoding="utf-8") +def prime_sync_counter(home: Path) -> None: + """Put the capture counter one short of the sync threshold. + + Same file and format `storage.increment_sync_counter` writes (a bare + integer in ``~/.mem/.sync_counter``), written before the binary runs so + no lock is contended. Reaching the threshold with real captures cost + twenty subprocesses at ~0.2 s each per test; one capture is enough to + prove the trigger, and the reset and the spawned sync are still asserted. + """ + mem_dir = home / ".mem" + mem_dir.mkdir(parents=True, exist_ok=True) + (mem_dir / ".sync_counter").write_text( + str(storage.SYNC_THRESHOLD - 1), encoding="utf-8" + ) + + def history_commands(home: Path) -> list[str]: """Read back the command strings currently stored in global history.""" path = global_history(home) @@ -220,11 +238,12 @@ def test_threshold_capture_resets_the_sync_counter( auto-sync pipeline is reached, isolating the defect to the spawned entry point rather than the trigger. """ - for i in range(20): - result = run_mem( - ["_capture", f"tool{i} run", str(workdir), "0", "10"], home, workdir - ) - assert result.returncode == 0 + prime_sync_counter(home) + + result = run_mem( + ["_capture", "tool0 run", str(workdir), "0", "10"], home, workdir + ) + assert result.returncode == 0 counter = (home / ".mem" / ".sync_counter").read_text(encoding="utf-8").strip() assert counter == "0" @@ -234,19 +253,20 @@ def test_capture_cycle_triggers_a_real_background_sync( ) -> None: """Capturing SYNC_THRESHOLD commands must produce a real sync. - Full-cycle contract, straight through the binary: after 20 captures - the detached background process must do the work `_sync` promises. - Each captured command uses a distinct tool name so pattern extraction - stays below its 5-command floor and no AI inference is attempted. + Full-cycle contract, straight through the binary: the capture that + reaches the threshold must spawn a detached background process that + does the work `_sync` promises. The one captured command has a tool + name of its own so pattern extraction stays below its 5-command floor + and no AI inference is attempted. """ now = int(time.time()) plant_commands(home, [("zzancient --flag", now - ANCIENT_AGE)]) + prime_sync_counter(home) - for i in range(20): - result = run_mem( - ["_capture", f"tool{i} run", str(workdir), "0", "10"], home, workdir - ) - assert result.returncode == 0 + result = run_mem( + ["_capture", "tool0 run", str(workdir), "0", "10"], home, workdir + ) + assert result.returncode == 0 # The sync is detached, so poll instead of sleeping a fixed amount. deadline = time.time() + 5 From 173043b05095494b7a0dcf1b7695b966b4974b5b Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 01:28:21 -0300 Subject: [PATCH 39/40] docs: the September audit, what it changed, and how to defend the rest AUDIT-2026-09.md records what was reproduced on the owner's machine (mouse noise in the store, options after a query swallowed as text, 268 warnings from one Click attribute, a perf benchmark failing under the coverage tracer, a new-user walkthrough with 17 findings), the per-module review, and the twenty improvements that landed one commit each, with every deviation from the list stated. DEFENSE.md is the thirty-minute guide: eight decisions at three levels, fifteen uncomfortable questions with the honest answer and the file that backs it, and the three things to say would change. BACKLOG.md is where feature ideas went so they did not become changes. The first thing either document says is that 0.5.0 was never tagged or published; every install channel still serves 0.4.1. Co-Authored-By: Claude Fable 5.1 --- docs/AUDIT-2026-09.md | 849 ++++++++++++++++++++++++++++++++++++++++++ docs/BACKLOG.md | 17 + docs/DEFENSE.md | 414 ++++++++++++++++++++ 3 files changed, 1280 insertions(+) create mode 100644 docs/AUDIT-2026-09.md create mode 100644 docs/BACKLOG.md create mode 100644 docs/DEFENSE.md diff --git a/docs/AUDIT-2026-09.md b/docs/AUDIT-2026-09.md new file mode 100644 index 0000000..0ed33b8 --- /dev/null +++ b/docs/AUDIT-2026-09.md @@ -0,0 +1,849 @@ +# Audit, September 2026 + +Branch `audit/2026-09`, run on 2026-09-21 against `77f57b3` (the 0.5.0 release +commit). Scope: does the tool work on the owner's machine with real data, and +can every non-obvious decision be defended from the repository alone. No +features were added. Line numbers are from the tree at the time of reading and +drift by a few lines as the Phase 2 commits land; function names do not. + +Method: five reproduction tasks on this machine (Phase 0), then a read-only +audit of every module in `src/mem/` by four reviewers working in parallel, +each with an `ast` walker for length and nesting, `ruff --select +F401,F841,ARG,C901 --preview`, a reference scanner over `src/` and `tests/`, +branch coverage per module, and `python -X importtime`. Every claim below +carries a file and a line or a command that reproduces it. + +Baseline before any change: Python 3.11.7 in `.venv`, macOS 26.3.1, +`ruff check` clean, **1450 passed, 4 skipped, 18 deselected, 268 warnings, +69 s**, 91 % branch coverage. + +--- + +## Phase 0: does it work on this machine + +| # | Task | Outcome | Commit | +|---|---|---|---| +| 1 | Mouse-report garbage stored as failed commands | Fixed at capture; two real lines still in the store, cleanup command below | `5c03f11` | +| 2 | `mem ` with no results prints nothing | Bug, two of them; fixed | `4d0e7a0` | +| 3 | 268 warnings in the suite | One source, fixed in code, zero warnings | `53137b1` | +| 4 | The 18 deselected tests | All three groups run by hand; `ai` passes, `perf` had a real failure, fixed | `a609be6` | +| 5 | New-user walkthrough | Done; 17 findings, none fixed here (all behaviour, hook or release changes) | — | + +### 0.1 Terminal noise captured as commands + +Two lines in `~/.mem/repos/Users-matinsaurralde-Documents-repos-investigations-1f37839d.jsonl` +had commands `65;50;35M` and a 1,689-character `35;165;16M35;160;16M…`, both +exit 127, both from 2026-09-10 15:09. They are SGR mouse reports +(`CSI < button ; column ; row M`) with the `ESC [ <` prefix gone. The entry +right before them is `claude`, which ran 19.6 hours and exited **139** +(SIGSEGV). A program that dies with mouse tracking on never sends the disable +sequence, so the terminal (Ghostty, no tmux) kept reporting every mouse move +to the idle prompt; button codes 35 (motion) and 64–67 (wheel) are exactly +"scrolled and moved the mouse over a prompt". Eighteen minutes later the +payload reached the command line, Enter ran it, zsh split on every `;` +(exit 127 per piece, 703 ms for ~170 words), and `mem.zsh:36` (preexec stores +`$1` verbatim) plus `mem.zsh:48` (precmd calls `mem _capture`) stored it. +`fix.py` then selected it as the last failure because it selects any non-zero +exit code. + +**The finder is not the source.** `tui.py` writes only alt-screen and cursor +sequences; no `?1000h`/`?1002h`/`?1003h`/`?1006h` anywhere; restore is a bare +`finally`. The owner's `.zshrc` also sources `fzf --zsh` after `mem init zsh`, +so Ctrl+R in that shell is fzf's and `mem tui` was likely never invoked there. + +Caveat on the record: feeding raw `ESC [ < 35;165;16 M` to an interactive +zsh 5.9 on a pty in eight variants (single write, byte by byte, gaps, vi +keymap, the owner's own rc with autosuggestions/syntax-highlighting/starship/ +fzf) always made zle discard the whole report. Something upstream of zle +delivered the payload without its prefix; that step was not reproduced. The +capture-side filter is the right defence regardless. + +**Fix.** `capture.looks_like_terminal_noise` matches a line that is nothing but +mouse reports (`(?:(?:\x1b\[<|\[<)?\d+;\d+;\d+[Mm])+`, full match on the +stripped line) and `capture_command` returns before the git subprocess, the +session tracker and the sync counter, silently, like every other skip on the +capture path. `echo 65;50;35M`, `awk '{print $1;$2}'`, `sleep 1;ls` are kept. +Bracketed-paste markers and X10 reports are deliberately left out (the shells +handle the former; the latter is not printable). Tests use both real strings +verbatim (`TestTerminalNoise`, 21 cases) and were watched go red with the +predicate inverted. No hook change was needed. + +**Existing entries: not migrated by code.** `mem forget` already does this +safely: substring match, preview and a `Delete all 2?` prompt defaulting to +No, rewrite under `exclusive_lock` via `atomic_write`, the one session whose +only command is noise removed whole, `picks.json` untouched (and absent on +this machine), patterns/groups/vars/audit verified no-ops. A custom migration +would duplicate `forget_commands`. The only thing `forget` lacks is a backup, +which is one `cp`. The backup was taken (`~/.mem.bak-2026-09-21`, verified +identical with `diff -rq`); the sandbox refused to run the deletion, so it is +left to the owner: + +```bash +mem forget '65;50;35M' # answer y at "Delete all 2?" +grep -rc '65;50;35M' ~/.mem # every count 0 +mem fix # no longer reports the noise +# rollback: rm -rf ~/.mem && mv ~/.mem.bak-2026-09-21 ~/.mem +``` + +Loose end, recorded: `mem import --from-shell-history` bypasses +`capture_command`, so the same garbage in a history file would be imported. +The owner's `~/.zsh_history` does not contain it today. + +### 0.2 No results printed nothing + +Two separate defects. + +- **`mem zzz --json` printed nothing: option parsing, not the empty branch.** + The JSON branch already emitted `[]` for `mem --json zzz`. But Click stops + reading the group's options at the first positional, and the implicit-search + router joined everything after it into the query, so a trailing `--json` + became the text "zzz --json" and took the human path. Same for a trailing + `-n 3`, `-p`, `--help`. The README documents `mem deploy --json` and + `mem deploy -n 20` (lines 126–127); neither worked. The router now re-parses + the line once it knows the first positional is not a subcommand, with mem's + own options allowed anywhere and unknown dash-words kept as query text + (`mem git commit -m` still searches for what it says; `--` forces literal + text). Visible consequence: `mem grep -n` with no value is now a Click usage + error (exit 2) rather than a silent search for "grep -n"; quote it or use + `--`. +- **Human path silence was never a decision.** The `return # Empty results, + no error (exit 0)` dates from the first commit (`f0164c5`) with no rationale + beyond the exit code; `specs/001-v1-core/spec.md:30-32` talks about the exit + status, not muteness; the pinning test from `7d235db` only asserted + `stdout == ""`; no ADR, CHANGELOG or PHILOSOPHY line covers it; every other + command prints something when it has nothing. Silence is indistinguishable + from a broken hook, an empty store, or a swallowed flag, all three of which + have happened. Now: one dim line on stderr, `no matches for "…"`, stdout + empty, exit 0. `mem --help` says so. + +Not fixed, for the record: `session`, `fix`, `promote`, `list`, `forget` and +`-p` print their no-data message on **stdout**, contradicting Philosophy III +and now the search path; and the three JSON "nothing" shapes differ (`[]`, a +stats envelope, a fix envelope with `failure: null`). + +### 0.3 The warnings + +All 268 had one origin: `MemGroup` reading `ctx.protected_args`, which Click +8.2 turned into a warn-on-access property backed by `_protected_args` (248 +from one read, 20 from `.clear()`). No ResourceWarning, no unraisable +exception, nothing from a dependency. The router now reads the private list +where it exists and falls back to the public name on Click 8.1, still inside +the pin. `pytest -q` reports **0 warnings**; the suite also passes under +`-W error`. No `filterwarnings` was added. Not applied, the owner's call: +`filterwarnings = ["error"]` in pyproject would lock this in, but the `ai` and +`keychain_live` groups were not run under it. + +### 0.4 The deselected groups, run by hand + +Environment: Python 3.11.7, macOS 26.3.1 (25D771280a), `apple-fm-sdk` 0.1.1 +already installed in `.venv` (inside the `<0.2` pin; its `__version__` string +says 0.1.0, a cosmetic drift in the SDK), Apple Intelligence available +(`SystemLanguageModel().is_available()` returned `(True, None)`; a raw prompt +answered in 1.37 s). + +| Group | Test | Outcome | Time | +|---|---|---|---| +| ai | `test_real_model_generalizes_a_command` | passed | ~1.5 s | +| ai | `test_real_model_summarizes_a_session` | passed | ~1.5 s | +| perf | `TestHookPerformance[zsh]` | passed (+0.515 s over 12 commands, threshold 1.0 s) | 0.90 s | +| perf | `TestHookPerformance[bash]` | passed (+0.472 s, threshold 1.0 s) | 0.81 s | +| perf | `test_a_selective_query_is_much_faster_than_a_full_parse` | **failed 5/5** with coverage, passed 5/5 with `--no-cov` | 0.20 s | +| perf | `test_a_field_name_query_is_not_slower_than_no_filter` | passed, but failed 1 of 5 reruns with coverage | 0.20 s | +| keychain_live | `test_real_round_trip` ×10, `test_real_migration`, `test_real_secret_is_absent_from_the_process_table` | 12 passed | 2.3 s | + +**`ai`: the on-device demo works on this machine.** Nothing to do. The real +user path also works: 7 kubectl commands captured through `mem _capture` in a +throwaway HOME, `mem _sync`, and `patterns/kubectl.json` holds four +generalised patterns, e.g. `kubectl get -n ` with +frequency 3; 5.9 s wall for 7 commands. Two findings, both silent-failure +shaped: + +- `patterns._apple_fm_available()` only tests `import apple_fm_sdk`. With the + SDK installed but Apple Intelligence off or the model not downloaded, every + `session.respond` raises, `_generalize_commands` swallows it, every command + maps to itself, exit 0, and the designed heuristic fallback never runs. + Phase 2 item 16. +- `test_real_model_generalizes_a_command` cannot fail on model unavailability, + because that identity mapping satisfies "a non-empty string". Same item. + +**`perf`: the failure was the coverage tracer.** `addopts` keeps +`--cov --cov-branch` on when `-m perf` replaces the mark expression. The +prefilter is a per-line Python loop, which the tracer instruments; the +`json.loads` it races is C, which the tracer does not touch. Instrumented, +the prefilter measured 1.1–1.3× instead of 3.4–7.3× uninstrumented. Both perf +classes now carry pytest-cov's `no_cover` mark; `pytest -m perf` passed 3/3 +afterwards. The 3× threshold is thin: even uninstrumented the warm rep landed +at 3.44×. + +The hook benchmark's number is worth stating plainly: **~40 ms added per +command** in both shells (0.52 s and 0.47 s over 12 commands), under the 1 s +threshold. That is interpreter start plus the Click/Rich/Pydantic import for +`mem _capture`, in the background. It is not the "<5 ms" that README, +ARCHITECTURE and ADR-003 claim, and no test measures 5 ms; see DEFENSE.md, +question 14. All three benchmarks state their basis in docstrings; none cites +an ADR. + +**`keychain_live`: safe, and it cleaned up.** Verified before running that +every `security` call in `keychain.py` carries the `MEM_KEYCHAIN` path as its +trailing argument, that the autouse `fake_keychain` fixture stubs `_run` for +every test not marked `keychain_live`, and that `create-keychain` does not +touch the search list. After: `security list-keychains` byte-identical, no +`mem-test.keychain*` file left, no `mem-cli-vars` item in the login keychain. + +### 0.5 New-user walkthrough + +Method: the dev checkout's `.venv/bin/mem` inside a throwaway `HOME`, a real +`/bin/zsh -i` driven through a pty (stdlib `pty.fork`; the suite's own +helper pipes stdin, which cannot exercise Ctrl+R), a four-line `.zshrc` +ending in `eval "$(mem init zsh)"`, variable values in a throwaway keychain +via `MEM_KEYCHAIN`. The scratch home and keychain were deleted afterwards; +the real `~/.mem` and the login keychain were verified untouched. Raw pty +bytes and driver scripts are in the session scratchpad +(`walkthrough/logs/`). + +**What is installed on this Mac, and why it matters.** `/opt/homebrew/bin/mem` +is not Homebrew's: it is a pip editable console script installed into +Homebrew's python@3.11 on 12 March (dist-info frozen at 0.3.4, `.pth` +pointing at `src/`), so `mem --version` says 0.5.0 and **the code that runs +is whatever is checked out in this repository, uncommitted edits included**. +Homebrew's own `mem` 0.4.1 was installed a day later into its Cellar venv +(python@3.12) and never linked over the pip file; it is dormant. +`brew upgrade` would do nothing (tap, Cellar and formula all say 0.4.1), and +Homebrew 5.1 refuses the tap as untrusted (`brew trust matinsaurralde/tap` +is needed; the README does not say so). The owner's `~/.zshrc:81` evaluates +`mem init zsh`, so the running hook is the checkout's 0.5.0 hook; the Cellar +0.4.1 hook has no Ctrl+R widget, no leading-space rule and uses `$SECONDS`. +Consequence, observed tonight: between 00:16 and 00:21 a `git stash pop` +during this audit left `<<<<<<< Updated upstream` markers in `cli.py`, every +`mem` invocation died with `SyntaxError`, and for those five minutes the +owner's own hook spawned a crashing `mem _capture` at every prompt, +silenced by `2>/dev/null &!`, dropping every capture with exit 0. Relinking +`/opt/homebrew/bin/mem` to the Cellar build, or moving the editable install +into a venv that is not on `PATH`, separates the developer's tool from the +developer's checkout. Owner's decision. + +**And 0.5.0 was never released.** No `v0.5.0` tag locally or on `origin`, +latest GitHub release v0.4.1 (2026-03-13), last `release.yml` run v0.4.1, +PyPI `cli-mem` latest 0.4.1, tap formula v0.4.1, while `CHANGELOG.md:8` says +`[0.5.0] — 2026-08-04` and master carries `77f57b3 chore: release 0.5.0`. +A user who follows the README gets a `mem` with none of `fix`, `promote`, +`import --from-shell-history`, `agent`, `mcp` or the finder, and pressing +Ctrl+R gives zsh's own search with nothing saying why. Owner's decision. + +| # | Step | What the user sees | Verdict | +|---|---|---|---| +| 1 | `mem init zsh` | Exit 0, 80 lines byte-identical to the shipped hook plus one trailing newline. `mem init` alone: bare Click error; `mem init --help` names no shells and does not say to `eval` it (the hook's first comment line is the only place that does). | needs source | +| 2 | 17 real commands through the hook | Nothing printed. 15 of 17 landed: the leading-space line was not recorded (correct); `cd sub` is filed under the directory **after** the cd (`$PWD` is read in precmd); `export FOO=bar` recorded; **every `mem` invocation recorded** (`mem fix`, `mem stats`, `mem list`, the search itself). Exit codes and durations correct (1212 ms for `sleep 1.2`). `"session": null` on every record and `sessions/` stayed empty all night: a session closes only after 300 s idle **and** one more command. After the 20th capture `patterns/mem.json` appeared with patterns equal to the commands (no SDK in that HOME's view). | needs source | +| 3 | Ctrl+R | First frame: alt screen + cursor hide, bold `mem`, dim `18/20`, rows with `▸`/`✗`, footer `↑↓ select · ⏎ accept · ^U clear · esc cancel`. No mouse-tracking or bracketed-paste sequences anywhere. Enter puts the command on the line and does not run it; Esc restores. `picks.json` written. The `18/20` counter is unique commands over total records, explained nowhere. Over 407 records the default view opened with 21 consecutive `mem …` rows. | clear; counter and self-captured rows need source | +| 4 | `mem fix` after `pytset --version` → `pytest --version` | `failed pytset --version / exit 127 · just now / fixed by pytest --version / seen once … mem does not run it for you.` With no correction: `mem has no record of anything fixing this.` `--json` carries `confidence: "weak"`. | clear | +| 5 | `save`, `list`, `run` with `$NAME`, `vars set`, `run` again, `export`, `rename`, `remove` | `mem save 'echo hello $NAME' -t greet -c 'say hi'` **stops at a hidden prompt** `Description for 'greet' (optional):` (hangs under a pipe; `save` has no `-y`). `mem save '!'` saved the most recent *captured* record, which was `echo $MEM_KEYCHAIN`, not the last command typed. `mem save 'curl -H "Authorization: Bearer eyJ…"'` stored the token verbatim with no message (no SDK → no detection, nothing says so). `mem run greet` asks `Run all? [y/N] or pick [1-2]:` **before** the variable prompt, whose empty default renders as `$NAME []:`. `mem vars set NAME` hides input and says `Stored: NAME (macOS Keychain)`; `vars.json` holds `value: null`; the value is in the throwaway keychain and not in the login one. `mem vars set DB_HOST staging.db` warns about `ps` although the README recommends exactly that form for non-sensitive values. `mem run greet -y` then resolves from the store. Export, rename, remove all clear. | needs source | +| 6 | `mem import --from-shell-history` on a synthetic 301-line extended history, then search and stats | Dry run and real run print a clear summary (`299 new · 2 already known · 1 withheld as credentials · 0 unparsed`); second run says `Nothing new to import`. **`export AWS_SECRET_ACCESS_KEY=…` and `PGPASSWORD=hunter2 psql` were imported**; only the `Bearer ghp_…` line was withheld, while the MCP redactor redacts all three: `looks_like_credential` and `redact_secrets` are two different tables. A backslash-continued entry became two records and counted as 0 unparsed. `mem kubectl -n 3` ranks `mem kubectl` (the search itself) first. Natural-language queries work: `check disk space` → `du -sh * \| sort -h`; `the command I used to fix the certificate` → `openssl x509 …`. `mem stats` and `mem stats --json` back to back disagree by one (the first was captured). `mem session kubectl` → `No matching sessions found.` | needs source | +| 7 | `mem promote` on seeded sessions | Two candidates, `kubectl-rollout` with `$CONFIG_ARG was prod, staging, dev` and `terraform-apply`, `git status` correctly dropped, `mem promote 1` previews and asks, `n` saves nothing, `--name` respected. | clear | +| 8 | MCP over stdio with a stdlib client, before and after `mem agent enable` | Before: `initialize` answers with an `instructions` field explaining access is disabled, `tools/list` is **empty**, every `tools/call` is `isError: true`. After: four tools with schemas; `search_history` returns redacted rows with `score`; `recent_failures` and `list_runbooks` work; `mem agent log` shows the refused and the served calls. `mem agent enable` prints to stderr with empty stdout. The README's `claude mcp add mem -- mem mcp` matches Claude Code 2.1.278's syntax (not executed). | needs source | +| 9 | `--help` everywhere | Every README command exists; nothing in the help lies. `mem tui --help` is the only mention of `MEM_NO_KEYBINDING`; `mem saved --help` exposes only `edit`; `mem concepts --help` leaks an implementation note about wheels. | mostly clear | +| 10 | `mem forget 'rollout status'` | Preview, `Delete all 5? [y/N]`, then `Deleted 7 commands.` on the second run because the first `mem forget` and a `mem "rollout status"` search had been captured in between; one prompt later the string is back in the repo file and `.session_state.json`, so **`mem forget` cannot forget its own argument**. | needs source | + +Not automated: clipboard import (reads the real clipboard), `group edit`/ +`saved edit` (`$EDITOR`), session replay (no session ever closed), the +legacy `vars.json` migration, `brew install`/`brew trust`/`claude mcp add` +(forbidden by the brief). Ctrl+R first-frame latency was not measured. + +**Findings, ranked by how badly a new user is confused** + +1. Every install channel delivers 0.4.1 while the README describes 0.5.0 + (`CLAUDE.md` release step 4 never run; `release.yml` triggers on tags only). +2. Homebrew 5.1 refuses the tap as untrusted; README line 40 does not + mention `brew trust`. +3. `mem` records its own invocations and they win the ranking (`mem.zsh:48` + sends every line; `capture.py` has no exclusion for the program's own + name). Consequences: 21 `mem …` rows at the top of Ctrl+R, `mem stats` + dominated by `mem`, `stats` and `stats --json` disagreeing, and `forget` + unable to forget its own argument. **Hook or capture change; owner's + decision.** +4. `"session": null` on every record and `sessions/` empty: + `capture.py:85` builds the record without the tracker's id; a session is + written only after 300 s idle plus another command; `mem session` on day + one says `No matching sessions found.` with no hint. ARCHITECTURE shows + the field populated. +5. `mem save -t ` blocks on a hidden description prompt + (`cli.py`, `save`); no `-y`; hangs under a pipe. +6. Nothing says Apple Intelligence is unavailable: `-p` prints `No patterns + found` after 400 commands, `patterns/*.json` is written with degenerate + patterns, a Bearer token is saved verbatim with no message + (`patterns._apple_fm_available` returns False on ImportError and nothing + surfaces it). +7. Import's credential filter is weaker than the MCP redactor + (`looks_like_credential` vs `redact_secrets`, two tables in + `variables.py`): `AWS_SECRET_ACCESS_KEY=` and `PGPASSWORD=` imported. + README says credential-looking commands are skipped. **Behaviour change; + owner's decision** (also AUDIT Phase 1, `variables.py`). +8. The same repository is rendered four ways: truncated absolute path + (`mem `), basename (Ctrl+R), full path (`mem list`), slug + (`mem run`, MCP `list_runbooks`). +9. `cd` is filed under the destination directory (`$PWD` read in precmd); + a `cd` from repo A into repo B lands in B's file. Undocumented. +10. `mem forget X` prints `Deleted N commands.` and the hook re-records `X` + at the next prompt (consequence of 3). +11. The Ctrl+R counter `18/20` (unique over total) is explained nowhere. +12. `mem save '!'` takes the most recent *captured* record, which with + asynchronous capture can be a different command than the last one + typed; README says "the last command you ran". +13. `mem init --help` names no shells and never says `eval`. +14. Before `mem agent enable`, `tools/list` is empty and the reason lives + only in `initialize.instructions`, which Claude Code does not display; + `mem agent enable` confirms on stderr with empty stdout. +15. `mem vars set NAME value` warns about `ps` although README recommends + that form for non-sensitive values. +16. A backslash-continued zsh history entry imports as two records and + counts as 0 unparsed (`history.py` zsh parser). +17. `mem run` asks which commands to run before asking for variables, and + the empty default renders as `$NAME []:`. + +None of these were fixed in Phase 0: every one is either a behaviour change, +a hook change, or a release action, and the brief reserves those for the +owner. Items 5, 11, 13, 14 and 15 are one-line text or prompt changes and +are the cheapest to take first. + +--- + +## Phase 1: the modules + +### Where the code and the documents disagree + +- **ARCHITECTURE.md's component diagram omits 12 of the 21 modules**: + `ranking`, `picks`, `concepts`, `fix`, `promote`, `history`, `mcp`, `tui`, + `_entry`, `render`, `keychain`, `_fsutil`. Its CLI box lists neither `fix`, + `promote`, `concepts` nor `tui`. Its filesystem box omits `.lock`, + `.sync.lock`, `picks.json` and the user `concepts.json`, draws `vars.json`, + `.sync_counter` and `.session_state.json` inside the `groups/` column + (they live at `~/.mem/` root), and implies `index.db`, which no code writes: + `grep -rn sqlite src/` hits nothing. ADR-005 is a permission with + conditions, not shipped code, and the document does not say so. +- The `<5 ms` capture claim (README:618, ARCHITECTURE.md:106, ADR-003:8) is + the cost of forking a disowned job; the measured cost of `mem _capture` is + 150–170 ms of CPU per prompt. +- The hook runs `mem tui` through `_entry.py`, which never touches `cli.py`; + the diagram's top box says the hook enters `cli.py`. +- ARCHITECTURE.md:309 says groups live at `groups/repos/.json`. That is + the **non-injective slug** ADR-004 replaced for history: + `storage.group_file_path` uses `sanitize_repo_name`, not `repo_key`, so two + repos whose paths collapse to one slug still share one runbook file. Format + change; owner's decision. +- `storage.py:4-5` "the only place in the codebase that touches the + filesystem for data storage": `capture.py` writes `.session_state.json`, + `picks.py` writes `picks.json`, `tui.py` and `groups.py` read JSONL directly. +- Four docstrings cite "ADR-009" for the Keychain move (`cli.py`, + `storage.py`, `models.py` ×2); it is ADR-010. `ranking.py` and `picks.py` + restate ADR-009's measurement without citing it. +- `search.score_command`'s 47-line docstring states the pre-ADR-009 formula + (0.35/0.35/0.15/0.15, "four features"); `history.py:19` says frequency is + the strongest term and `:524` says it is 40 %. The code is + 0.40/0.21/0.21/0.09/0.09 with picks. Commit `413dbf6` fixed README and + ARCHITECTURE but not these. +- ADR-002 says "Pydantic-based guided generation"; `_generable.py` uses + `@fm.generable` classes because the SDK inspects concrete annotations. +- ADR-007 says the hand-rolled server "undoes the work of getting `ssl`, + `socket`, and `asyncio` out of mem's import graph". `import mem.mcp` loads + `socket`, `ssl` and 33 `asyncio` submodules through Pydantic + (`pydantic_core.core_schema → asyncio → ssl → socket`). The guarantee is + behavioural (the socket-dead tests), not structural. +- `ranking.py`, `picks.py`, `concepts.py`, `_fsutil.py` and `tui.py` are + stdlib-only as claimed: verified with `-X importtime`; `mem.tui` is 16.6 ms + cumulative, `mem tui --help` 30–40 ms wall, `mem --version` 140–180 ms. +- The published formula, half-lives (7 d, 21 d), `log1p(n)/log1p(50)`, the + `1 − 2^−w` picks curve and the 1.0/0.5/0.0 context multipliers match + `ranking.py` and `picks.py` line by line. No regression since `413dbf6`. + `search.py` and `tui.py` both call `ranking.score`. + +### Per module + +Format for each: purpose; long/deep functions (>60 lines or >4 levels); dead +code; duplication; broad `except`; names that lie; magic numbers; tests. + +**`_entry.py` (39 lines).** Console-script entry; imports only `mem.tui` when +`argv[1] == "tui"`. Nothing to report. The fast path covers `tui` only; +`_capture`, which runs on every prompt, takes the full import. + +**`render.py` (78).** Two Rich consoles and four helpers. CLAUDE.md calls it +"the single output surface"; `cli.py` issues 190 `console.print` calls with +inline markup directly. `fit` is `len()`-based, so a CJK command is padded to +code points, not columns; `tui.py` already has the correct `display_width`. +Coverage 85 % (`fit` width ≤ 1 branches). + +**`cli.py` (2,123).** 30 Click commands, each importing its module lazily. +Long: `run` 197 lines (C901 34, 37 branches), `list_cmd` 162 (depth 5), +`import_cmd` 143, `promote_cmd` 102, `save` 89, `fix_cmd` 72, `cli` 71, +`session` 62 (depth 6, the replay block). Dead on the declared platform: +`xclip`/`xsel` branches in `_read_from_clipboard`/`_copy_to_clipboard` (26 +untested lines). Options not read on some paths: `--limit` ignored under +`--pattern`; `import --yes` does not skip the `Merge or Replace?` prompt +(no `_is_interactive` guard, so `mem import f.json -t x --yes` on a pipe +prompts on a closed stdin); the `tui` subcommand loses a literal `--` to +Click, so `mem tui -- -la` via Click searches for `""` and via `_entry.py` +for `-la`. Comment at `:148` says yellow, code says white. Duplication: +`_relative_time` vs `tui.relative_time` (same thresholds, different output); +`group_file_path(sanitize_repo_name(repo))` written four times plus once in +`groups.py`; the group header block and the numbered-listing loop written +two and three times; the search-result row layout twice; the `$EDITOR` +launch twice; the variable-name regex `^[A-Z][A-Z0-9_]+$` six times across +`cli.py`, `models.py`, `variables.py`, `promote.py`; seven calls into the +private `groups._load_group_file`. Broad `except`: `:199` `capture_cmd` +(justified in intent, discards the traceback while `sync_cmd` logs it); +`:307` `sync_cmd` (justified, logs). Magic numbers without basis: `--limit` +defaults 10/3/20 (promote's 5 cites ADR-012), `fit(…, 40/12/20/16)`, +`most_common(10)`, `matches[:20]`, `timeout=5`, `"─" * 50`. Tests: **32 % +of `cli.py` from `test_cli.py`+`test_tui.py`, 47 % from the whole suite**; +`run`, `import`, `session`, `fix`, `promote`, `concepts`, every `group *`, +`saved edit`, every `vars *`, every `agent *` and `mcp` are never invoked by +a test file (the underlying modules are tested; the Click layer is not). +Reads cold: **worst file in the repo**. Nine mini-modules in one file +separated by banner comments, helpers defined just before the one command +that uses them, 48 in-function imports so the dependency graph is invisible +at the top, three functions of 140–200 lines that parse argv, compute paths, +print, prompt, resolve variables, build an env and execute in one body. + +**`tui.py` (749).** Stdlib finder. No long or deep functions; every constant +named. Bugs: `_most_recent` walks `reversed(lines)` over files ordered +newest-first, so it starts at the **least** recently modified file and breaks +at 200; reproduced with a stale repo of 300 commands and a fresh one of 5: +the empty-query view shows `old299…old100`, none of the new. `read_key` +collapses at most 3 bytes: Delete `\x1b[3~` inserts `~` into the query, +Ctrl+Up inserts `;5A`, F5 inserts `5~`; `test_tui.py:294` asserts a 4-byte +token the reader never produces. `render` writes the initial query (the +shell's `$BUFFER`) raw into the header, so `\x1b]0;…\a` retitles the window, +and the header is not width-clamped. Terminal modes: raw + alt screen + +cursor hide, restored in one unfiltered `finally`; mouse tracking and +bracketed paste never enabled; a pasted newline is Enter. Unrestored path: +SIGTERM/SIGHUP from another process (`signal` never imported), which leaves +the shell in raw mode on the alt screen. Resize is re-read on the next key +only. No redraw throttle: every key ranks and repaints the full frame. Magic +numbers without basis: `0.05` escape timeout, `22`/`columns // 3`, `8`, `20`, +`24, 80`; the ADR-008 first-frame budget has no constant and no timed test. +Duplication: `terms_of`/`matches` byte-identical with `search._terms`/ +`_matches` (and `fix.py:667`); the prefilter needle rule inlined from +`storage.prefilter_needles` with its own `_MIN_NEEDLE_LEN`; `_current_repo` +exists three times under one name. `Result.frequency` and `.score` are set +to `1`/`0.0` by `_most_recent` and read by nothing but tests. Coverage 89 %; +`main` and `_with_raw_terminal` are exercised by pty subprocess tests that +coverage cannot see. Reads well cold. + +**`storage.py` (1,503).** Every read and write of `~/.mem` plus retention, +`forget`, legacy migration, the raw-line prefilter and the Keychain +migration. Long/deep: `forget_commands` 87 lines depth 6 (mccabe 19), +`rotate` 76 lines depth 6, `_scrub_vars` 58. Dead: `get_var_value` +(tests only), `rotate`'s two day parameters (no caller passes them), +`_append_line` vs `_append_lines` (differ by `line + "\n"`), `_scrub_groups` +reassigning the same dict. **JSONL is parsed at ten sites with three +policies**: readers skip a corrupt line with a warning; `rotate`, both halves +of `forget_commands` and `_scrub_agent_audit` keep it silently and catch only +`JSONDecodeError`; `_owner_key_of_line` and `_file_holds` have their own. They +disagree on a line that is valid JSON but not an object (`42`): readers skip +it, the rewrite loops call `.get` on it and **raise `AttributeError`**, +reproduced for `rotate()` and `forget_commands("ls")`. `rotate` runs inside +the background `_sync` with stderr discarded, so it fails every 20 captures +with exit 0. Broad `except` ×7 (`:550, :589, :616, :1151, :1183, :1236, +:1276`): every one wraps `read_text` and a Pydantic `model_validate_json`; +none names the failure; all narrow to `ValueError` (ValidationError is one) +plus `OSError`. `read_group_file` prints **and** raises, and +`groups._load_group_file` prints again. `read_vars_file` returns an empty +store on a corrupt file and every writer does read-modify-write, so a +corrupt `vars.json` followed by any `mem vars set` or a `mem run` that +touches a variable **replaces it with a one-entry index**, orphaning every +other Keychain item and losing any unmigrated plaintext value; the docstring +says "treating as empty". Names that lie: `resolve_repo_key` migrates files; +`ensure_dirs` chmods six directories on every capture; `forget_commands` +"returns total removed" but counts repo lines only; `write_group_file`'s +docstring describes `atomic_write`; `try_sync_lock` leaks its fd on purpose. +Path helpers are half functions (`repo_file()`, `agent_file()`) and half +import-time constants (`VARS_FILE`, `GROUPS_DIR`…), with a comment at +`:1205-1211` explaining why the constants are wrong; `conftest.py:94-102` +pays for it with five `monkeypatch.setattr` calls a new constant would +silently miss. `MEM_DIR = Path.home() / ".mem"` ignores `$MEM_DIR`, which +`picks.py` and `tui.py` honour: with it set, the finder reads and writes one +directory and every other command another, and the two lock different +`.lock` files while sharing `_fsutil._lock_depth`. Magic numbers without +basis: 90/30 retention days, bare `86400`, `SYNC_THRESHOLD = 20` (basis is in +ADR-003, not cited). Locking: every write goes through `exclusive_lock` + +`atomic_write` or `O_APPEND`, with one inconsistency (`_append_lines` calls +`resolve_repo_key` outside the lock where `append_command` puts it inside on +purpose). Coverage 91 %; `_scrub_agent_audit` and the agent-flag functions +are covered only through `test_mcp.py`; no test feeds `rotate` a non-object +line. Reads cold: **second worst file**. Nine concerns under banner comments; +four copies of the same rewrite loop; the corrupt-line policy has to be +discovered by reading ten sites. + +**`_fsutil.py` (153).** Atomic write, lock, hardening. Docstring claims +`mem.storage` re-exports everything under historical names; it imports five +of seven and nothing uses them through `storage.`. `except BaseException` +at `:98` cleans up and re-raises: the one correct use. `_lock_depth` is one +process-global integer regardless of path, documented as a caller +obligation and violated by `picks.py` when `$MEM_DIR` is set. 89 % coverage +(the four `except OSError: pass` arms). + +**`models.py` (249).** 15 Pydantic models. `VarDeclaration.name` has +`min_length=2` redundant with its pattern. `SavedCommand` and `GroupCommand` +are identical; `PatternExtractionResult` is `PatternFile` minus two fields; +`to_jsonl`/`from_jsonl` copy-pasted three times. `CommandPattern.example` +and `CapturedCommand.imported` are read by nothing in `src/` (rotate reads +the raw dict). `StoredVariable.backend` is documented as the single source +of "which backend"; storage re-derives it three times with +`entry.value is not None`. `CapturedCommand.session` is never written by +capture or import (ARCHITECTURE's schema shows it populated). 98 %. + +**`groups.py` (399).** Scope resolution, save/list, Markdown/JSON +import-export. Dead: an inner `if … continue` followed by `continue` +(`:350-353`); an unreachable `else` (`:359`). `resolve_scope` sanitises +twice. `get_last_captured_command` parses JSONL with its own policy and +crashes on a non-object line with `TypeError`, not the `KeyError` it +catches; it also calls `resolve_repo_key`, so `mem save !` can rename and +split history files. `save_command` docstring says "Returns True/False"; +returns a tuple. `list_all` returns an untyped dict consumed by string keys +in `cli.py`. 94 %. Reads fine. + +**`variables.py` (753).** Two modules under one name: `$VAR` mechanics +(`:1-262`) and three credential detectors (`:265-753`). `resolve_variables` +95 lines. `merge_var_declarations` has an if/else whose two arms do the same +assignment. **Three vendor-regex tables that disagree**: `_CREDENTIAL_SHAPES` +(used by `looks_like_credential`, imported by `history.py` and +`promote.py`) and `_REDACTIONS` (used by `redact_secrets`, imported by +`mcp.py`, `fix.py`, `promote.py`) encode Slack, OpenAI, Google and AWS with +different character classes and lengths (`xox[baprs]-…{10,}` vs +`xox[abposr]-…{10,}`; `sk-[A-Za-z0-9_-]{16,}` vs `sk-[A-Za-z0-9]{20,}`; +`AKIA[0-9A-Z]{16}` vs `(?:A3T…|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}`), and the +keyword lists differ (`bearer` in one, `passphrase` in the other); +`promote.py:809` works around it by calling both. `_CREDENTIAL_KEYWORDS` is +rebuilt on every call. Broad `except` at `:542` around the SDK call, named +nowhere. Magic numbers without basis: `{6,}`, `{4,}`, `{8,}` (vs `{16,}` for +the same shape in the other table), `\S{7,}`, vendor lengths, `len < 8`. +86 % (the SDK path). Reads cold: **third worst file** by the reviewer's +judgement; a reader holds four regexes for "variable name" and two for +"Slack token". + +**`keychain.py` (352).** `security(1)` driver over stdin with hex encoding. +Every number has its basis next to it (`_ITEM_NOT_FOUND = 44`, +`_MAX_COMMAND_LINE = 3900`, `_TIMEOUT_SECONDS = 60`). Dead: `is_available` +(tests only). `_fail` returns an exception rather than raising. 99 %. Reads +fine; the module docstring explains why it exists. + +**`capture.py` (263 after 0.1).** `mem _capture`: append, session tracker, +sync trigger. **Fourth instance of the completion-timestamp bug**: +`SessionTracker.update` computes idle as `cmd.ts - state.last_command_ts` +without subtracting `duration_ms`, so a command running 301 s closes the +session when it completes; `fix.py` and `promote.py` both subtract, and +ADR-012 documents the tracker as wrong and works around it; +`test_capture.py:403` pins the raw difference with no duration, so the test +protects the bug. `_save_state` writes `.session_state.json` with +`Path.write_text`: no lock, not atomic, created with the umask (0644) while +`storage._scrub_session_state` rewrites the same file atomically under the +lock. Dead: `_clear_state` (zero references), `_generate_summary`'s `repo` +parameter. The 300 s rule is a bare literal here and a named constant in +`promote.py` that "mirrors SessionTracker, which owns this definition"; the +owner has nothing to import. `started_at` is fabricated as +`last_command_ts − 10 × len(commands)` and `search_sessions` sorts on it; +`dir=""`. The class docstring says 300 s was "chosen by observing that most +developers maintain focus for at least 5 minutes"; no such observation exists +in the repo. Broad `except` ×4 (`:99, :108, :170, :257`), two with a comment, +none narrowed. 93 %. + +**`history.py` (575).** Shell-history import. `resolve_timestamps` 63 lines, +`build_plan` 62. Dead: `ts=entry.ts or 0` (always an int by then). Every +`except` narrowed. For a zsh `EXTENDED_HISTORY` entry `: start:elapsed;cmd` +the parser stores the **start** time as `ts` and discards `elapsed`, so the +stored `ts` is a start time labelled as a completion with `duration_ms` +`None`; `test_import.py:564` pins discarding elapsed on purpose and the +docstring does not mention the mismatch. Formula claims at `:19` and `:524` +are wrong (see above). 99 %; the test module is `test_import.py` (name +convention broken). Reads fine. + +**`search.py` (397).** Literal pass, concept-expanded fallback, dedup, rank. +`_expanded_search` 68 lines. `score_command` reads `time.time()` per +candidate while `ranking.score` documents `now` as "one consistent instant" +(`tui.py` passes one); `test_search.py` freezes the clock to compensate. +`_read_history` calls `resolve_repo_key` and `repo_key` for the same value. +`tui.py` does not import `concepts`, so `mem certificate` and Ctrl+R with +"certificate" return different sets; documented nowhere. No broad `except`. +`limit=10` no basis. 99 %. + +**`ranking.py` (216).** The formula. Matches ADR-009 and ARCHITECTURE line by +line. Restates the measurement without citing the ADR. `LITERAL_CREDIT`/ +`EXPANDED_CREDIT = 0.8` "deliberately mild", not measured. No +`tests/test_ranking.py` exists (100 % via `test_search.py`/`test_concepts.py`; +values asserted with `pytest.approx`, two ordering-only assertions). +`mem.ranking` costs 10.3 ms to import, of which `mem.picks` 9.4 ms. + +**`picks.py` (217).** Decayed selection counter. **Crashes the finder on a +hand-edited entry**: `_pruned` casts every entry with `float()`/`int()` and +`record` catches only `OSError`; with `{"count": "many", "ts": 1}` in +`picks.json`, `load()` skips it but `record("git push")` raises `ValueError`, +and `tui.py` calls `record` before `print(choice)`, so the chosen command +never reaches the shell. Docstring: "Silent on failure". `_PRUNE_BELOW = +0.02` comment says "roughly six months"; for one pick it is 118 days. +`MAX_ENTRIES` cap branch never executed by a test. `mem_dir()` honours +`$MEM_DIR`; `storage.MEM_DIR` does not. 90 %. + +**`concepts.py` (334) + `concepts.json`.** 224 concepts, 1,078 synonyms, 127 +stopwords, longest key 2 words. `CONCEPTS_FILENAME` and +`USER_CONCEPTS_FILENAME` are two names for one string; `MAX_CONCEPT_WORDS = +3` is always overridden by `data.max_words`. `_cache` keyed on (path, mtime, +size) never evicts. `except Exception # noqa: BLE001` at `:177` could be +`(OSError, ValueError)`. 100 %; the ADR-011 curation rules are enforced +mechanically. + +**`fix.py` (798).** Failure → near-variant-success mining. No long or deep +functions; 100 % coverage; every constant has its reasoning in a docstring +(`WINDOW_SECONDS = 60`, `MAX_LOOKAHEAD = 3`, the measured difflib ratios that +are the reason there is no similarity threshold). Subtracts `duration_ms` +correctly. Duplicated into `promote.py`/`mcp.py`: `_iso`, `_redact` +(identical), `_is_flag`, `_PRIVILEGE_PREFIXES`, `_think_seconds` (promote +clamps negatives, fix does not), `confidence()`. `lru_cache(4096)` and +`limit=3` have no basis. Reads well; the module docstring is 115 lines. + +**`promote.py` (1,088).** Sequence mining. `_collect` depth 4. Dead: +`or not token.text`; the session-id branch (nothing writes `session`). +`STRONG/MODERATE_EVIDENCE` 6/3 with a comment claiming parity with fix +(3/2). `_INSPECTION_PROGRAMS` is described as "read-only and unconditionally +safe to skip" and contains `vim`, `nvim`, `nano`, `emacs`, `code`, `open`, +`mem`. `MIN_OCCURRENCES = 3` and the inspection filter have their measured +basis (97→223 pool, 0 %→80 % FP) in ADR-012 only; the code does not cite it. +The privilege-prefix strip loop appears four times inline. Shape encoding +uses `\x00`/`\x01` markers implicit at four sites. `MAX_STEP_GAP_SECONDS` +split has no executing test; `_TRAILING_EXTENSION {1,6}` differs from +`_FILENAME {0,5}` with no basis. 96 %. + +**`patterns.py` (464).** Apple FM pattern extraction. `extract_patterns_for_tool` +78 lines. Docstring line 4 "the ONLY place in mem that uses AI inference" is +false (`variables.py` calls the model). `_apple_fm_available` is an import +check only (see 0.4). "Returns the number of commands sent to the model" is +false in the fallback branch, which sends nothing and returns every unseen +command, so without the SDK one sync exhausts `SYNC_BUDGET` on commands it +never processed. `>5 commands` in prose, `>= 5` in code, written twice. +`storage.read_patterns(tool)` is read three times per tool per sync. +`_heuristic_patterns` reimplements `Counter` while the caller already built +one. Broad `except` ×2 around the SDK; the SDK's tree is +`FoundationModelsError > GenerationError > {ExceededContextWindowSizeError, +AssetsUnavailableError, GuardrailViolationError, …}` plus 25 bare +`ValueError` raises, so the broad catch stays but must say so. 95 %. + +**`mcp.py` (834).** Hand-rolled JSON-RPC over stdio. Verified against +ARCHITECTURE: four tools in `TOOLS` and `_TOOL_IMPLS`; stdout rebound at +`:795` and restored in `finally` at `:819`; the access flag read at every +request; `_redact(payload)` covers every tool payload. The one unredacted +exit is JSON-RPC `error.message`, which echoes the agent's own input +(`runbook 'x' not found`), never history. **`recent_failures.retried_successfully` +is wrong**: `succeeded_later` is filled with `setdefault`, so it holds the +first success; `success@100, fail@200, success@300` reports `False` +(reproduced). `lookahead=2` here vs `MAX_LOOKAHEAD = 3` in fix. Unreachable: +`:735-737`. `_repo_cache` is a one-slot mutable list that a test fixture +exists to reset. `readline()` has no size bound. Protocol `2025-06-18` with +two older versions negotiated; no external conformance suite, no test +against a real client. 92 %; 49 of 100 tests spawn subprocesses that +coverage cannot see. + +**`_generable.py` (35).** Two `@fm.generable` classes. 0 % coverage (imported +only with the real SDK); the `None` fallbacks are never read because +`variables.py` imports it inside the SDK-only path. + +### Duplication across modules, consolidated + +| Rule | Copies | +|---|---| +| Query → terms; all-terms-match | `search._terms`/`_matches`, `tui.terms_of`/`matches`, `fix.py:667` | +| Prefilter needle rule and `_MIN_NEEDLE_LEN` | `storage.prefilter_needles`, `tui._stable_run` | +| Session boundary (300 s, repo change) | `capture.SessionTracker`, `promote.SESSION_IDLE_SECONDS` (+ `_think_seconds` in fix and promote, capture lacks it) | +| `_iso`, `_redact` | `fix`, `promote`, `mcp` (identical) | +| `_is_flag`, `_PRIVILEGE_PREFIXES`, `confidence()` | `fix`, `promote` | +| Variable-name regex | `cli.py` ×3, `models.py`, `variables.py` ×2, `promote.py` | +| Vendor credential regexes | `variables._CREDENTIAL_SHAPES` vs `_REDACTIONS` (disagree) | +| Relative-time formatter | `cli._relative_time`, `tui.relative_time` | +| Repo group-file path | `groups.resolve_scope`, `cli.py` ×4 | +| `_current_repo` | `cli`, `tui`, `mcp` | +| JSONL line parsing | ten sites in `storage.py`, plus `groups.py`, `tui.py` | +| `to_jsonl`/`from_jsonl` | `models.py` ×3 | +| Data-directory resolution (`$MEM_DIR`) | `storage.MEM_DIR` (ignores it), `picks.mem_dir`, `tui.py` | + +### Every broad `except` + +20 `except Exception` sites in `src/` (storage 7, capture 4, mcp 3, cli 2, +patterns 2, concepts 1, variables 1), one `except BaseException` that +re-raises (`_fsutil.py:98`), zero bare `except:`. Verdict per site is in the +module notes; the disposition is Phase 2 item 7. The `TODO(0.16)` in +`pyproject.toml` describes exactly this work and was never revisited. + +### Tests + +Coverage ascending (full suite): `_generable` 0 %, `render` 46 % / `cli` 47 % +(in-process only; both are exercised further by subprocess tests coverage +cannot see), `_fsutil` 89 %, `tui` 89 %, `picks` 90 %, `storage` 91 %, `mcp` +92 %, `capture` 93 %, `groups` 94 %, `variables` 94 %, `patterns` 95 %, +`promote` 96 %, `history` 99 %, `keychain` 99 %, the rest 100 %. + +Tests that cannot fail: `test_tui.py:170` (`assert [inlined] if inlined else +[] == official` parses as `[inlined] if inlined else ([] == official)`, the +only test backing the claim that the inlined prefilter agrees with storage's); +`test_tui.py:294` (asserts a key token the reader never yields); +`test_mcp.py:469` and `:1699` (`count <= MAX_LIMIT` with 30 and 2 rows +against 50); `test_promote.py:609` (`tokenize(...) is not None`); +`test_groups.py:160` and `test_mcp.py:1800` (no assertion); +`test_patterns.py::test_real_model_generalizes_a_command` (identity mapping +satisfies it). + +Coupled to implementation: `test_groups.py` patches `mem.cli._is_interactive` +/ `_current_repo` / `_copy_to_clipboard` 28 times; `test_patterns.py` +patches `patterns._get_generable_types` 13 times; `test_cli.py:67-70` patches +four dotted names for "where does repo detection live"; `test_groups.py` +asserts `call_args[0][0][-1]` (argv layout of `mem run`); +`test_storage_destructive.py` reads `_fsutil._lock_depth`; `conftest.py` +monkeypatches five storage constants. No test asserts exact Rich markup. + +Slow tests and why: `test_e2e` background-sync tests (3.4–4.5 s) spawn 20 +`mem _capture` subprocesses at ~0.2 s each to reach `SYNC_THRESHOLD`, then +poll; the 20 spawns are an artefact (pre-write the counter). `test_hooks_e2e` +(0.5–1.7 s each) start a real interactive shell, inherent, plus a 0.6 s +quiescence floor on every negative test, chosen. `test_mcp` (0.3–0.6 s each): +49 of 100 tests spawn 2–4 interpreters at 0.14–0.23 s each; an in-process +`drive()` harness exists and ~40 of them could use it. +`test_storage_destructive` (1.2 s, 0.7 s): a deliberate 1.0 s negative wait +and 0.5 s of `sleep`, inherent to lock contention, unexplained inline. + +The 4 skips are environment: fish not installed (×2), macOS bash 3.2 (×2). + +`conftest.py` autouse fixtures: `tmp_mem_dir` (redirects `MEM_DIR` and four +sibling constants plus `$HOME`/`$MEM_DIR`), `_no_real_inference` (stubs +`patterns._apple_fm_available` unless marked `ai`), `fake_keychain` (replaces +`keychain._run` unless marked `keychain_live`). Global state that survives +between tests: `mcp._repo_cache`, `fix.normalized_tokens`'s `lru_cache`. + +### The three files that read worst cold + +1. **`cli.py`**: 2,123 lines, eight functions over 60 lines, three over 140 + (24 % of the file at C901 24–34), each mixing argv parsing, path + computation, printing, prompting, Keychain I/O and `subprocess` in one + body; helpers defined next to their single caller; 48 in-function imports. +2. **`storage.py`**: nine concerns under banner comments; the corrupt-line + policy discoverable only by reading ten sites; `read_vars_file`'s + data-loss consequence and `group_file_path`'s slug collision invisible + from their docstrings; path helpers half functions, half constants, with a + comment explaining why the constants are wrong. +3. **`variables.py`**: two modules under one name; two vendor-regex tables + that encode the same secrets differently 340 lines apart; four regexes for + "variable name" and two for "Slack token" to hold in one head. + +--- + +## Prioritised improvements + +Impact on clarity × risk, lowest risk first, simplifications and deletions +only. All twenty landed on `audit/2026-09` (34 commits, one per improvement, the +full suite and both e2e files green after each). Deviations from the letter +of an item are listed under "Phase 2 results" below. + +1. ~~Delete no-op branches: `variables.merge_var_declarations` if/else, `storage._scrub_groups` self-assignment, `groups.import_from_markdown_str` dead `if`/unreachable `else`, `models.VarDeclaration` `min_length=2`.~~ +2. ~~Delete dead code: `storage.get_var_value`, `keychain.is_available`, `capture.SessionTracker._clear_state`, `_generate_summary`'s `repo`, `mcp.py` unreachable notification branch, `promote.py` `or not token.text`, `history.py` `ts or 0`.~~ +3. ~~Docstrings that state the pre-ADR-009 formula: `search.score_command`, `history.py:19`, `:524`.~~ +4. ~~Wrong ADR citations: ADR-009 → ADR-010 in `cli.py`, `storage.py`, `models.py` ×2; cite ADR-009 from `ranking.py` and `picks.py`.~~ +5. ~~Comments that state something false: `cli.py:148`, `sync_cmd`/`tui` docstrings, `render.fit`, `tui.history_files`/`read_key`, `storage.py:4-5`, `_fsutil.py:14-15`, `groups.save_command`, `storage.forget_commands`/ `write_group_file`/`read_vars_file`, `patterns.py` ×5, `promote.py` ×3, `mcp.py` ×2.~~ +6. ~~Tests that cannot fail: `test_tui.py:170`, `test_mcp.py:469`/`:1699`/ `:1800`, `test_promote.py:609`, `test_groups.py:160`.~~ +7. ~~Every `except Exception` narrowed or justified with the concrete failure (storage ×7 → `ValueError`/`OSError`; capture ×4; cli ×2 with debug logging in `_capture`; patterns ×2 naming the SDK tree; concepts ×1; variables ×1; mcp ×3).~~ +8. ~~Every magic number gets its basis next to it, or "chosen by eye, not measured" (rule 8 of the audit brief): retention days, `86400`, `SYNC_THRESHOLD`, capture `300`/`10`/`timeout=5`, cli defaults and widths, tui `0.05`/`22`/`8`/`20`/`24,80`, fix `4096`/`3`, promote `6/3`/`8`, patterns `5`/`10`, mcp `500`/`10`/`2`, picks `6`/`5000`/`_PRUNE_BELOW` comment, search `10`, ranking `0.8`, variables regex bounds.~~ +9. ~~`concepts.py`: one filename constant; delete `MAX_CONCEPT_WORDS`.~~ +10. ~~`storage._append_line` → `_append_lines(path, [line])`.~~ +11. ~~Redundant `sanitize_repo_name` before `group_file_path` (`groups.py`, `cli.py` ×4).~~ +12. ~~Delete the `xclip`/`xsel` branches in `cli.py`.~~ +13. ~~One `_iso`/`_redact`/`_is_flag`/`_PRIVILEGE_PREFIXES`/`_think_seconds` in `fix.py`, imported by `promote.py` and `mcp.py`.~~ +14. ~~`terms`/`matches` into `ranking.py`; delete the copies in `search.py`, `tui.py`, `fix.py`.~~ +15. ~~`picks._pruned` skips a malformed entry instead of crashing the finder.~~ +16. ~~`patterns._apple_fm_available` probes `is_available()` and falls through to the heuristic; `Counter` reuse; read the pattern file once per tool.~~ +17. ~~One JSONL reader in `storage.py` with one corrupt-line policy, which also stops `rotate`/`forget` crashing on a non-object line (pinning test first).~~ +18. ~~`capture.py`: `.session_state.json` written atomically under the lock at 0600; `SESSION_IDLE_SECONDS` named here and imported by `promote.py`.~~ +19. ~~`capture.SessionTracker` measures think time (subtract `duration_ms`), per CLAUDE.md and ADR-012; `mcp.recent_failures.retried_successfully` checks for a success **after** the failure.~~ +20. ~~`tui._most_recent` shows the newest commands across files; the header goes through `_visible`; `test_e2e` reaches `SYNC_THRESHOLD` with one capture.~~ + +## Phase 2 results + +38 commits on `audit/2026-09` after the release commit: 4 from Phase 0, 34 +from the list above. Each was cherry-picked onto the branch one at a time and +followed by `ruff check`, `ruff format --check` and the full suite including +`test_e2e.py` and `test_hooks_e2e.py`; none went red. Final state: +**1,520 passed, 4 skipped, 18 deselected, 0 warnings, ~60 s, 92 % branch +coverage** (from 1,450, 268 warnings, 69 s and 91 %), and the suite passes +under `-W error`. Run again by hand on the final tree: `ai` 2 passed, `perf` +4 passed, `keychain_live` 12 passed. + +Deviations, stated because the list said what it said: + +- Item 8 (magic-number comments) touched eight files in one commit, and items + 5 and 7 touched four; all three are comment-only with values unchanged. The + brief's three-file limit was read as applying to code. +- Item 9: `MAX_CONCEPT_WORDS` was kept, because it is also the parse-time cap + in `concepts._parse` and deleting it would have admitted four-word keys; the + redundant `min()` and the duplicate filename constant went. +- Item 14: in `tui.py` the two functions became aliases of `ranking.terms` + and `ranking.matches` rather than being deleted, so their call sites did + not move. +- Item 17: the three Pydantic readers (`read_commands`, `read_sessions`, + `read_agent_audit`) were not routed through the new `iter_jsonl_objects`, + because they parse with the model's own JSON parser and already skip a + non-object line; decoding twice would double the cost of the one path the + module measures in milliseconds. The four rewriters, the migration and + `groups.get_last_captured_command` are on the helper; eight pinning tests + went red before the fix. Also found: `rotate` writes each file as it goes, + so a bad line stopped retention only for that file and every file sorted + after it, which is why the stall was never global. +- Item 18: only the write in `_save_state` is under the lock, not the whole + of `update()`, because a session boundary calls the on-device summary + model and holding the global lock for those seconds would stall every + other shell's capture. The read-modify-write race between two shells is + unchanged. +- Item 13: `think_seconds` clamps at zero (promote's behaviour); `fix`'s only + caller already skipped negative gaps, so no `mem fix` result changes. +- Item 16: with the SDK installed but the model off, `sync_all_patterns` now + falls through to the heuristic and prints the "install AI support" tip, + which is wrong for that user; one-line follow-up. +- Item 7: `detect_credentials` and the two SDK calls in `patterns.py` keep + `except Exception`, with the comment naming the SDK's exception tree + (`FoundationModelsError > GenerationError > …`) and the bare `ValueError`s + the SDK raises outside it. `_load_state` now validates with + `model_validate` so a JSON list is a `ValueError`, not an uncaught + `TypeError`. +- Item 19: the session-boundary change is a behaviour change to `mem + session`; it is the fourth instance of the bug CLAUDE.md names and ADR-012 + already records the tracker as wrong, so it was made with a test rather + than deferred. The 300 s boundary test with no duration is untouched. +- Item 20: the `tui` fix keeps first-frame cost flat (heap merge over file + starts: 0.42 ms vs 0.39 ms for the wrong walk on 20k lines; extracting + `ts` from every line would have cost 5.7 ms, a quarter of the ADR-008 + budget). + +During the work, one thing went wrong that the owner should know: a +`git stash pop` conflict left merge markers in `cli.py` for about five +minutes, and because the `mem` on this machine's `PATH` is an editable +install of this checkout, the shell hook spawned a crashing `mem _capture` +at every prompt in that window, silently. Captures from 00:16 to 00:21 on +2026-09-21 are lost. See the walkthrough section for the install state that +makes this possible. + +Recorded, not on the list (behaviour or format changes, or larger than three +files; the owner decides): + +- `storage.MEM_DIR` ignores `$MEM_DIR` while `picks.py` and `tui.py` honour + it (split store, split lock). Either honour it everywhere or delete it from + the two. +- `read_vars_file` should raise on a corrupt file the way `read_group_file` + does, so a writer cannot replace a damaged index with a one-entry one. +- `group_file_path` uses the non-injective slug ADR-004 retired for history + (format change; needs the same migration). +- `import --yes` should skip the `Merge or Replace?` prompt, and the no-data + messages of `session`/`fix`/`promote`/`list`/`forget`/`-p` belong on + stderr like search's. +- `tui.read_key` handling of `~`-terminated and `;`-modified sequences + (Delete, F-keys, Ctrl+arrows), a SIGTERM handler, bracketed paste: listed + in ADR-008 as owned, not written. +- `cli.run` (197 lines), `list_cmd` (162), `import_cmd` (143): split into + select / resolve / execute after one `CliRunner` test per command exists; + `forget_commands`/`rotate` split into the `_scrub_*` shape. +- The two vendor-regex tables in `variables.py` merged into one. +- `~40` `test_mcp.py` tests moved to the in-process harness (≈15 s of 28 s). +- `_capture` on the fast path (150–170 ms per prompt today); see DEFENSE.md. +- `history.py` labels a zsh start time as a completion time. +- Replace the import-time path constants in `storage.py` with functions and + delete `conftest.py:96-102`. diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md new file mode 100644 index 0000000..ecdfbb5 --- /dev/null +++ b/docs/BACKLOG.md @@ -0,0 +1,17 @@ +# Backlog + +One line per idea. Nothing here is planned; it is where a feature idea goes +so it does not turn into a change during an audit or a bug fix. + +- `mem forget --noise`: remove lines matching `capture.looks_like_terminal_noise` from an existing store, for users who captured mouse reports before 0.5.1. +- `mem import` runs the same noise predicate as capture, so a polluted `~/.zsh_history` is not re-imported verbatim. +- Put `mem _capture` on the `_entry.py` fast path (stdlib-only append), taking the per-prompt cost from ~150 ms to a few tens of ms; only then is the "<5 ms" claim about more than `fork`. +- `MEM_DIR` honoured by `storage.py` as well as by `picks.py`/`tui.py`, and documented, or removed from the two. +- The concept-map fallback in the finder (`tui.py` does not import `concepts`, so Ctrl+R and `mem ` answer a question differently). +- `read_key` support for `~`-terminated and `;`-modified escape sequences (Delete, F-keys, Ctrl+arrows), bracketed paste, and a SIGTERM handler that restores the terminal. +- A `mem doctor` that reports what `mem` on `$PATH` actually is (Cellar version vs `--version`), whether the rc hook matches `mem init`, and whether the installed hooks are the shipped ones. +- Runbook files keyed by `repo_key` (hash-suffixed) with the same migration ADR-004 did for history. +- `mem vars` refusing to overwrite a corrupt `vars.json` (raise like `read_group_file`), plus a `mem vars repair`. +- A timed first-frame assertion for the finder in a real pty, so ADR-008's 50 ms budget is a test and not a sentence. +- Run the `perf` group in CI on a schedule, uninstrumented, with the numbers recorded. +- PyPI Trusted Publishing instead of the long-lived `PYPI_TOKEN` (standing TODO in CLAUDE.md). diff --git a/docs/DEFENSE.md b/docs/DEFENSE.md new file mode 100644 index 0000000..28b2826 --- /dev/null +++ b/docs/DEFENSE.md @@ -0,0 +1,414 @@ +# Defending mem in thirty minutes + +A guide for the owner. A reviewer opens the repository, picks a file, and +asks "why is it like this?" three levels down. Every answer below can be +given without a transcript: level 1 is what it does, level 2 is why this +and not the obvious alternative, level 3 is what would break, what was tried +and failed, and the number that backs it. Every number has a source in the +repo. Nothing here is a claim the repo cannot support; where the repo cannot +support an answer, it says so. + +Facts to have in hand (measured 2026-09-21 on the owner's machine, Python +3.11.7, warm cache): + +| Fact | Value | Source | +|---|---|---| +| Source / test lines | 11,594 / 18,631 | `wc -l src/mem/*.py tests/*.py` | +| Tests | 1,520 passed, 4 skipped, 18 deselected by mark, 0 warnings, ~60 s, also green under `-W error` | `pytest -q` on `audit/2026-09` | +| Branch coverage | 92 % (91 % before the audit) | `pytest --cov` | +| `mem --version` / `mem tui --help` | 140–180 ms / 30–40 ms | measured | +| `mem _capture` per prompt | 150–170 ms, in the background | measured | +| `import mem.cli` | 112 ms, of which `mem.models` (Pydantic) 58 ms, click 6.5, rich.console 8.6 | `python -X importtime` | +| `except Exception` sites | 20 in `src/` before the audit; after it every one is narrowed to the real type or names the concrete failure next to it (AUDIT-2026-09.md item 7) | grep | +| Latest tag / PyPI / Homebrew tap | **v0.4.1 everywhere; 0.5.0 is merged to master and never tagged** | `git tag`, `pip index versions cli-mem`, `Formula/mem.rb` | + +That last row is the first thing to say out loud, before a reviewer finds it. + +--- + +## The eight decisions + +### 1. JSONL files, not SQLite + +**Level 1.** Every captured command is one JSON line appended to +`~/.mem/repos/-.jsonl`. Sessions, patterns, groups and the +variable index are plain JSON or JSONL too. + +**Level 2.** ADR-001 (2026-03-08): `cat`, `grep`, `tail -f` and `jq` work on +every file; a single-line append is atomic at the OS level so concurrent +shells need no coordination for the common case; zero dependencies. JSON +arrays were rejected because every append is a rewrite; flat text because +timestamps, exit codes and repo context would be parsed out of prose. +ADR-005 (2026-08-04) corrected ADR-001 on the record: SQLite is **not** a +compiled dependency (it is stdlib), and the remaining arguments are against +SQLite as storage, not as an index. PHILOSOPHY.md Principle III was amended +the same day from "no database of any kind" to "no second source of truth", +which is a stronger rule. + +**Level 3.** What was measured (ADR-005): at 100k commands a query costs +140 ms, of which `json.loads` per line is 110 ms, 82 % of the total, and +Pydantic validation adds 2 ms on top. The linear scan grows ~1.45 ms per +1,000 commands. An FTS5 index with one row per unique command would cost +9.6 MB and 0.67 s to rebuild at 100k, 90.8 MB and 8.4 s at 1M, with queries +of 1–15 ms; one row per capture was measured at 190 MB, larger than the JSONL +it indexes, and rejected. What was shipped instead: the byte prefilter that +skips `json.loads` on lines that cannot match (commit `2450c64`, 242 → 49 ms +on 100k; commit `97ced8e` fixed it matching JSON field names). **The index +does not exist in code**: `grep -rn sqlite3 src/` hits nothing; ADR-005 is a +conditional permission. What would break under SQLite: 138 storage tests that +assume line-append semantics, crash mid-write, corrupt-line skipping; `mem +forget` rewriting by line; the ADR-004 collision migration that re-files +lines by their `repo` field; the stdlib-only finder that reads raw text +(~20 ms per 100k) without importing anything; and the user's ability to +`cat` their own history. Retention keeps 90 days of captured commands, so +1M is reachable only by import. + +### 2. A shell hook, not a daemon + +**Level 1.** `eval "$(mem init zsh)"` installs a preexec/precmd pair; precmd +runs `mem _capture … &!`, disowned; every 20 captures the capture process +spawns a detached `mem _sync` that extracts patterns and rotates, then exits. + +**Level 2.** ADR-003: launchd needs a plist, an approval dialog and idle +resources; cron has one-minute granularity and no shell awareness; fswatch +is a running process for an append-only file; the original manual `mem sync` +was never run by anyone, so patterns rotted (commit `fb86000`). ADR-006 +records that anything bundle-shaped is "a second distribution channel and a +second language in the build, i.e. a different project". + +**Level 3.** The hooks produce every record mem stores, and they were wrong +in five ways until commit `08879cf` (CHANGELOG 0.5.0): `mem init` looked for +them at a checkout-only path so every pip and brew install ran a stale inline +copy; `$SECONDS` gave integer durations so two thirds of a real history had +`duration_ms == 0`; a leading space was not honoured; bash stored the first +simple command of a pipeline; installation captured itself. Now the hooks are +package data, CI and the release workflow diff `mem init ` from an +installed wheel against source, and 30 tests spawn real interactive +zsh/bash/fish. The background sync was dead for four months because the +spawn used `python -m mem.cli` with no `__main__` block, inside +`except Exception: pass` (commit `e7f311e`). Honest number: `mem _capture` +costs **150–170 ms of CPU per prompt** (interpreter start plus the +Click/Rich/Pydantic import plus one `git rev-parse`), in the background. The +"<5 ms" in README, ARCHITECTURE and ADR-003 is the foreground cost of forking +a disowned job, and no test measures it; the only perf test asserts ≤ 1 s +added over 12 commands and measured +0.5 s on this machine. + +### 3. A fixed formula, not a model + +**Level 1.** `score = 0.40·picks + 0.21·frequency + 0.21·recency + +0.09·prefix + 0.09·context`, every feature in [0, 1], in one stdlib module +(`ranking.py`) shared by `mem ` and the finder. + +**Level 2.** ADR-009: the finder produces the one signal that is not an +inference about the user, an actual selection, and it was being thrown away. +The 0.60 that is not picks keeps the old 35/35/15/15 proportions so that +with no picks the ordering is byte-identical, which is why the whole existing +suite passed unchanged. ADR-011: a model for query understanding was +measured and lost (decision 6). Determinism and a 120-line formula a +contributor can read are the point. + +**Level 3.** Simulation over 1,200 retrieval episodes with a Zipf intent +distribution: MRR@10 0.039 → 0.575, top-1 0.025 → 0.477, 14× better and 1.6× +faster. The learned weights converge to `picks +3.02, freq −0.06, recency +−0.05`, i.e. frequency and recency are worth nothing once picks exist; they +were **not** adopted wholesale because they are optimal only after picks +accumulate and would make day one worse. Keying picks by (query, command) +measured 3.3 % worse; a logarithmic pick curve let one pick lose to twenty +runs, hence `1 − 2^−w`; online learning measured no gain. Both ADR-009 and +CHANGELOG say plainly this is a simulation, not a field study. The failure +this formula replaced: frequency entered as a raw count while the other +terms were bounded by 1, so ten runs scored 4.0 against a 0.6 ceiling and +recency could not change any ranking, and every ordering test passed for +months (commit `2450c64`). The docs then drifted from the code two releases +later (commit `413dbf6`), which is why `test_e2e.py` now reads every weight +from `mem.ranking` and requires it in the published formula. What would +break: 37 exact-score tests, the finder/search agreement test, and the +22 ms first-frame budget (a model on the hot path, or 2,086 ms out of +process). + +### 4. The Keychain, not a file + +**Level 1.** `mem vars set` stores the value as a macOS Keychain generic +password (service `mem-cli-vars`, account = the name); `~/.mem/vars.json` is +an index with `value: null`. + +**Level 2.** ADR-010: 0600 stops other users and nothing else. Time Machine, +a synced folder, a dotfiles repo that globbed too widely, an `npm install` +postinstall, and a disk image all read a plaintext file. For a project whose +first principle is privacy, a plaintext file of API tokens was the weakest +thing in it. `keyring`/`pyobjc` were rejected as dependencies; a +passphrase-encrypted file was rejected because the stdlib has no reviewed +AEAD and it would prompt on every `mem run`. + +**Level 3.** The `security(1)` sharp edges were established by running it: +`-w ` puts the secret in `argv` where `ps` sees it; `-w` as the last +option needs a tty and, omitted, silently stores an empty password; +`find-generic-password -w` prints printable and binary data identically so a +32-character hex key decodes to garbage, hence reads use `-g`; `security -i` +truncates a line at 4096 characters **and executes the truncated head**, so +mem refuses a value over ~2 KB (`KeychainValueTooLong`) rather than store a +truncated secret under a name that claims to be intact. Migration is +confirm-then-delete per variable under the existing lock, idempotent, and +every failure leaves the plaintext where it was. There is deliberately no +plaintext fallback: a machine without a usable Keychain cannot store new +values at all, and CHANGELOG says so. The suite never touches the login +keychain: `conftest.FakeKeychain` replaces the one function that spawns +`security`; the 12 `keychain_live` tests run against a throwaway keychain +and were verified today to leave `security list-keychains` byte-identical. + +### 5. MCP over stdio, never HTTP + +**Level 1.** `mem mcp` reads newline-delimited JSON-RPC 2.0 on stdin and +writes it on stdout, spawned by the client as a child; four read-only tools; +off until `mem agent enable`; every result redacted; every call audited. + +**Level 2.** ADR-007: a listener is a network whether or not it binds to +127.0.0.1. The official Python SDK transitively installs `uvicorn`, +`starlette` and `httpx`, an HTTP server and client present in the process +even on the stdio transport, which is exactly what Principle I forbids. A +Unix socket is a listener with a lifecycle and reintroduces the daemon +ADR-003 rejected. So the protocol is hand-rolled: read a line, `json.loads`, +dispatch, write a line. + +**Level 3.** `tests/test_e2e.py` installs a `sitecustomize` whose +`socket.socket` raises, proves the stub blocks (`test_stub_actually_blocks_sockets`), +then runs capture, search, import and the MCP server under it; +`test_mcp.py` also asserts structurally that no networking library is in the +`mcp` module's import graph. Protocol version `2025-06-18`, negotiating two +older ones. `serve()` rebinds `sys.stdout` to stderr for its lifetime so a +stray print cannot corrupt a frame. Honest limits: conformance is tested +only by the project's own 100 wire-level tests, there is no test against a +real client, and `import mem.mcp` does load `socket`/`ssl`/`asyncio` +through Pydantic, so ADR-007's sentence about the import graph is a +behavioural guarantee, not a structural one. + +### 6. Apple Foundation Models, not a cloud API + +**Level 1.** The on-device model is used for two things only: generalising +commands into patterns, and suggesting credentials at `mem save` time. Search, +ranking, `mem fix` and `mem promote` are deterministic. + +**Level 2.** ADR-002: a cloud API violates Principle I; regex fails on novel +tools; Ollama needs a server process. PHILOSOPHY Principle II reserves +inference for tasks no deterministic approach matches. ADR-006 records the +strategic caveat in writing: "on-device AI stops being a moat this year"; +the differentiator has to be what mem infers, not where the model runs. + +**Level 3.** The model was tried for query understanding and lost (ADR-011): +substring search 0/10 at 9.6 ms, the on-device model expanding the query +2/10 at 2,086 ms (it suggested `certutil /rebuild`, a Windows tool), a +30-line synonym map 8/10 at 3.9 ms, the shipped 224-concept map 10/10 on the +fixture. `NLContextualEmbedding` scored 0/5 because shell commands are out +of distribution for a natural-language BERT. Non-determinism is stated: +three of four identical runs produced the ideal pattern. Verified today on +this machine: Apple Intelligence available, both `ai` tests pass, a seeded +sync produced `kubectl get -n ` in 5.9 s for 7 +commands. Known gap (AUDIT 0.4): the availability probe is an import check, +so a machine with the SDK but no usable model silently maps every command to +itself instead of running the heuristic fallback; Phase 2 item 16. + +### 7. Pydantic, not dataclasses (no ADR) + +**Level 1.** `models.py` holds 15 Pydantic v2 models for every on-disk shape; +every read goes through `model_validate_json`, every write through +`model_dump_json`. + +**Level 2, honestly.** This was inherited from the v1 scaffold (commit +`f0164c5`), never argued in an ADR, and never benchmarked against an +alternative. The stated purposes were validation on read, serialisation, and +guided-generation schemas for the SDK; the third is no longer true, because +`_generable.py` uses `@fm.generable` classes (the SDK inspects concrete +annotations), and ADR-002 still says "Pydantic-based guided generation". + +**Level 3.** Two measurements settle what Pydantic costs. Per record it is +nothing: 2 ms on top of `json.loads` at 100k lines (ADR-005, "Pydantic is +not the culprit"). Per process it is the largest import in the tree: 58 ms +of `mem.cli`'s 112 ms today, 63 of 125 when ADR-008 measured it. That import +is why a parallel stdlib-only world exists (`tui.py`, `ranking.py`, +`picks.py`, `concepts.py`, `_fsutil.py`; CLAUDE.md "Some modules must not +import Pydantic"), enforced by tests that assert click/rich/pydantic are +absent from `sys.modules` on the finder path. What Pydantic is doing today: +schema evolution by defaults (`imported: bool = False`, nullable +`exit_code`/`duration_ms`) so every legacy line still validates, and one +validation policy at seven corrupt-line sites. The defensible sentence: +"inherited, not chosen; 2 ms per 100k records and 58 ms per process; we paid +the 58 ms by moving the hot path onto the standard library rather than +replacing the layer that validates seven file formats." Replacing it would +shorten every `mem` invocation by ~58 ms and is a bounded refactor, not a +correctness risk. + +### 8. Click, not argparse (no ADR) + +**Level 1.** Click drives 30 subcommands; the console script enters through +`_entry.py`, which dispatches `mem tui` before importing Click at all. + +**Level 2, honestly.** Also inherited and never re-argued. Its import cost +is the smallest of the three dependencies (6–11 ms). Its real cost has been +API churn around the one non-standard thing mem does with it, treating an +unknown first argument as a search query: three routing commits in the first +two days (`6362e17`, `0a0d67b`, `724757b`), a `mix_stderr` removal for Click +9, an upper bound after `protected_args` was slated for removal (commit +`60e8bc3`, "the 87 DeprecationWarnings in the test suite are the advance +notice"), and, this audit, a shim for the 8.2 rename that was producing 268 +warnings per run and a re-parse so that `mem deploy --json` works as the +README says. + +**Level 3.** `_entry.py` exists precisely so a fast path can exist: "A +second console script would have been simpler but splits one tool into two +names." It covers `tui` only; `_capture` still pays the full import on every +prompt. What would break under argparse: nine test modules drive the CLI +through `CliRunner`; `MemGroup.parse_args` and the hidden `_capture`/`_sync` +commands would be rewritten; `--help` for 30 subcommands regenerated by +hand. + +--- + +## Fifteen uncomfortable questions + +**1. Twelve ADRs and 1,500 tests for a CLI nobody uses. Over-engineered?** +The tests exist because the July audit measured a 39 % mutation score on 258 +green tests, with `_capture` as a no-op and `rotate()` deleting the whole +history both undetected. The ADRs exist because four of them are +constitutional amendments the code would otherwise contradict. +Evidence: commit `7d235db`; ADR-005 consequences; CHANGELOG 0.5.0 preamble. +Usage numbers: not answerable, by design (no telemetry). + +**2. `picks.json` cannot be rebuilt. Is that your backup story?** +Yes, said in three places: it is the one file worth backing up and there is +no per-pick undo. Putting it in a derived index would have made +`rm index.db` lose data silently. No backup tooling exists; it is a 0600 JSON +file. Evidence: ADR-009 "Where it is stored"; CHANGELOG known limitations; +`picks.py` docstring. + +**3. The 0.575 MRR is a simulation you designed yourself.** +Correct, and both ADR-009 and CHANGELOG say "not a field study". The design +choices it drove are each pinned by a test, and with no picks the ordering is +identical to before, so the downside on day one is zero. A field measurement +has not been done. Evidence: ADR-009 context and cost sections; +`tests/test_picks.py`. + +**4. macOS-only. That is a large share of developers.** +By decision, with the seam named: `keychain.py` is the whole platform +backend and `unavailable_reason()` is where another platform's answer goes; +`apple-fm-sdk` is optional. Capture, search, groups, import and MCP have no +macOS dependency in code, and nothing tests them off macOS: CI runs on +`macos-latest` only. Evidence: ADR-010 consequences; `ci.yml:17,44`. + +**5. The ranking weights sum to 1.0 but were chosen by hand.** +Yes. The commit that fixed the normalisation says "the weights are a +judgement call and are documented as one; the normalisation is not, that was +the defect". The learned weights were measured and deliberately not adopted +because they are optimal only after picks accumulate. Evidence: `2450c64`; +ADR-009 "Adopt the learned weights wholesale"; `ranking.py`. + +**6. The concept map is English-only.** +Yes, stated in the ADR: "English until someone translates it". Concepts and +stopwords are data layered from `~/.mem/concepts.json`, so a translation is +a JSON edit, but none exists and the recall fixture is English. Evidence: +ADR-011 consequences; `src/mem/concepts.json` (224 concepts, 127 stopwords). + +**7. The MCP server is hand-rolled. What spec version, and who tests conformance?** +`2025-06-18`, with `2024-11-05` and `2025-03-26` accepted on negotiation. +Conformance is tested by the project's own 100 wire-level tests only; there +is no external suite and no test against a real client. Evidence: +`mcp.py:96-97`; `tests/test_mcp.py`; ADR-007 consequences ("we own protocol +conformance"). + +**8. 62 `xfail(strict)` bugs in one release. What was the process failure?** +Eight days in March, 60 commits, 14 version bumps, features shipped with no +CLI tests, no `~/.mem` isolation in tests (a test that forgot the fixture +read the developer's real history), and a background spawn that never +executed anything. The July audit turned 151 findings into 62 strict xfails +so the roadmap lived in CI, then closed them. Zero xfail markers remain. +Evidence: `7d235db`, `e7f311e`; CHANGELOG 0.5.0. + +**9. Hooks ship as package data. What about users on the old install?** +Their rc line re-evaluates `mem init zsh` on every shell start, so upgrading +the binary is the whole migration. But no user has the new hooks, because +0.5.0 was never published (question 11). Evidence: `08879cf`; README install +section; the tag/PyPI/tap state above. + +**10. You catch `Exception` in twenty places.** +Twenty sites, dispositioned one by one in AUDIT-2026-09.md item 7: seven in +`storage.py` wrap Pydantic validation and narrow to `ValueError`; four in +`capture.py` protect the capture path and now name what they absorb; the +rest carry the concrete failure in a comment. The `TODO(0.16)` in +`pyproject.toml` described this work and sat for eight weeks. Evidence: +`pyproject.toml`; `60e8bc3` (the `except: pass` that hid the dead sync). + +**11. The Homebrew formula is stuck at 0.4.1 while PyPI is at 0.5.0.** +The premise is wrong in the other direction: PyPI is also 0.4.1, the latest +GitHub release is v0.4.1 (2026-03-13), and no `v0.5.0` tag exists locally or +on `origin`. The release commit is on master; the tag that triggers +`release.yml` was never pushed. Nothing in the 0.5.0 changelog has reached +any user through any channel. Why the tag was not pushed is not answerable +from the repo. Evidence: `git tag`, `git ls-remote --tags origin`, +`pip index versions cli-mem`, `gh release list`, the tap's `Formula/mem.rb`. + +**12. Coverage is 91 % but `fail_under` is disabled with a TODO.** +`pyproject.toml` says "enable once the follow-up branches land the missing +tests; target 80". The branches landed (PRs #9–#29), the TODO was not +revisited, and today the floor would pass by 11 points. Evidence: +`pyproject.toml` coverage section; `7d235db`. + +**13. No Windows or Linux, and no fish keybinding?** +Fish has the keybinding (`mem.fish` binds `\cr` in both key tables) and +fish's `$CMD_DURATION` was the reference the other shells were brought up +to. Windows is out of scope by design; Linux is untested rather than +excluded, with the Keychain the one subsystem that hard-fails. Evidence: +`src/mem/hooks/mem.fish`; README platform table; ADR-010. + +**14. Capture spawns a Python interpreter on every prompt. What is the real cost?** +150–170 ms wall per prompt in the background: ~112 ms importing `mem.cli` +(58 ms Pydantic) plus one `git rev-parse`. The "<5 ms" in three documents is +the foreground cost of forking a disowned job; no test measures 5 ms, and +the one perf test asserts ≤ 1 s over 12 commands and has failed on CI at +1.39 s. `_entry.py`'s fast path covers `tui` only. Evidence: measured today; +`tests/test_hooks_e2e.py::TestHookPerformance`; `_entry.py:27`. + +**15. What happens at one million commands?** +Retention keeps 90 days of captures and exempts imports, so 1M is reachable +only by a large import. ADR-005 measured the scan at ~1.45 ms per 1,000 +(~1.45 s at 1M before the prefilter; 814 → 293 ms at 500k with it) and the +unbuilt index at 6–15 ms per query, 8.4 s to rebuild, 90.8 MB. The finder +reads raw text at ~20 ms per 100k, so ~200 ms per keystroke at 1M. Not +measured in the current code beyond the 20k perf fixture. Evidence: ADR-005; +`storage.py` `rotate`; `803bf7a`. + +--- + +## Three things the owner should say they would change + +**1. Put `_capture` on the fast path, or make it stdlib-only.** The same +ADR that set the finder's 22 ms budget states the import floor is 120 ms, +and `_capture` runs through that floor on every prompt: 150–170 ms of CPU +per command plus a `git` subprocess, background or not. The perf test +already documents "~150 ms of Python interpreter startup" and has failed on +CI. The commit that built the fast path said a second dispatch target is +four lines. This is also the only thing that would make the "<5 ms" claim in +three documents honest. Evidence: `_entry.py`; `tests/test_hooks_e2e.py`; +ADR-005, ADR-008; the measurement above. + +**2. Push the v0.5.0 tag, then fix the release process that let a merged +release commit sit unpublished for seven weeks.** Every feature the defence +rests on is unreleased. `CLAUDE.md` step 4 of the release process is manual; +`release.yml` runs only on a tag; the PyPI token is a long-lived secret with a +standing TODO to move to Trusted Publishing. The release path has the least +automation of anything in the repository. Evidence: the tag/PyPI/tap state; +`CLAUDE.md` Release Process; `release.yml`. + +**3. Turn the two TODOs from July into mechanical guards: re-enable +`fail_under` and adopt ruff's BLE001/S110 with per-site `noqa`.** Both were +written in the same week (`7d235db`, `60e8bc3`), both name exact sites, both +were deferred to "the follow-up branches", all of which merged. The pattern +that hid the dead sync for four months (`except Exception: pass`, exit 0) +is the pattern CHANGELOG says dominated this codebase ("most of these were +silent"), and a lint is cheaper than a second audit. Evidence: +`pyproject.toml` TODOs; CHANGELOG 0.5.0 "Fixed" preamble; AUDIT-2026-09.md +item 7. + +Considered and not chosen, for the record: replacing Pydantic (the 58 ms is +real, but the query-time cost is 2 ms and the hot path already avoids it), +and building the ADR-005 index (the ADR itself says the index without the +fast path "fixes the part of the latency the user notices least", and +retention caps captured history at 90 days). From cb19e7498b33a8c5eeab8d7f2a7ff930a60bf1c0 Mon Sep 17 00:00:00 2001 From: Matias Date: Mon, 21 Sep 2026 01:53:32 -0300 Subject: [PATCH 40/40] chore: release 0.5.1 The 0.5.0 release commit was merged on 2026-08-04 and never tagged, so no channel ever served it. 0.5.1 is the first release of the line, carrying the 0.5.0 changes plus the September audit repairs. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 90 +++++++++++++++++++++++++++++++++++++++++++++ docs/DEFENSE.md | 2 +- pyproject.toml | 2 +- src/mem/__init__.py | 2 +- 4 files changed, 93 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce1928e..1037a88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,96 @@ 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.1] — 2026-09-21 + +The first release of the 0.5 line to reach a user. The 0.5.0 entry below was +merged on 2026-08-04 and never tagged, so PyPI, the Homebrew tap and the +GitHub releases page all still served 0.4.1 until this one. Everything under +0.5.0 ships here for the first time, plus the repairs from a full audit of +the repository against real data on the owner's machine +(`docs/AUDIT-2026-09.md`; the decisions are defended in `docs/DEFENSE.md`). + +### Fixed + +- **Terminal mouse reports were stored as failed commands.** A program that + dies with mouse tracking on leaves the terminal reporting every mouse move + to the shell; the SGR payload (`65;50;35M`, or hundreds of them in one + line) runs, fails with 127, and was captured. `mem fix` then offered it as + the last failure. Capture now drops a line that is nothing but mouse + reports; `echo 65;50;35M` is still kept. +- **Options after a query were searched for as text.** `mem deploy --json` + and `mem deploy -n 20`, the forms the README documents, searched for the + literal text and, finding nothing, printed nothing with exit 0. The router + now re-parses the line with mem's own options allowed anywhere; unknown + dash-words stay query text and `--` still forces literal text. `mem grep + -n` with no value is now a usage error rather than a silent search. +- **A query with no matches printed nothing.** Now one dim line on stderr, + `no matches for "…"`; stdout stays empty so pipes see nothing; exit 0. +- **A JSONL line holding `42` crashed `rotate` and `forget`.** Valid JSON + that is not an object made every rewriter call `.get` on an int. `rotate` + runs inside the silent background sync, so retention stopped for that file + and every file after it, with exit 0 and no message. One JSONL reader with + one corrupt-line policy now serves every rewriter. +- **A hand-edited `picks.json` entry crashed the finder after Enter**, so the + chosen command never reached the shell. Malformed entries are skipped. +- **An installed Apple SDK with the model unavailable never reached the + heuristic fallback.** The availability probe was an import check, so every + generalisation raised, was swallowed, and every command mapped to itself + with exit 0. The probe now asks the model whether it is available. +- **A command running longer than the idle threshold ended its own session.** + The session tracker compared completion timestamps without subtracting + `duration_ms`, the fourth instance of the bug the code base warns about; a + six-minute build was read as six minutes of idle time. +- **`.session_state.json` was the one file mem wrote world-readable and + without the lock.** It now goes through the same atomic 0600 write as + everything else. +- **`recent_failures` (MCP) reported `retried_successfully: false`** for a + command that had succeeded before failing and again after; it recorded + only the first success. +- **The empty-query view of Ctrl+R showed the least recently modified repo**, + not the newest commands; with a stale repo of 300 commands and a fresh one + of 5, none of the new ones appeared. The initial query (the shell buffer) + could also retitle the window through an escape sequence, and a long one + wrapped the header off the screen. +- **Every CLI invocation emitted a Click deprecation warning** (268 per test + run), and the `perf` benchmarks ran under the coverage tracer and one + always failed. Zero warnings; the suite passes under `-W error`. + +### Changed + +- Every `except Exception` is narrowed to the real type or names the concrete + failure it absorbs; every numeric threshold says where it came from, or + that it was chosen by eye and not measured. +- Helpers that existed three times (`iso`, `redact`, `is_flag`, + `think_seconds`, the "every word must appear" rule, the session idle + threshold) exist once. Dead branches, two test-only functions and the + Linux clipboard paths are gone. Seven tests that could not fail now can. +- Auto-sync tests reach the threshold by writing the counter instead of + spawning twenty processes: the suite runs in about 60 s instead of 69 s + with 70 more tests. + +### Known limitations + +Carried over from 0.5.0 unless stated, and found by the walkthrough in +`docs/AUDIT-2026-09.md`: + +- `mem` records its own invocations. `mem forget X` therefore re-records + `X` at the next prompt, and `mem …` rows rank high in a fresh store. +- The credential filter used by `mem import` (`looks_like_credential`) is a + different, weaker table than the redactor used at the MCP boundary: + `export AWS_SECRET_ACCESS_KEY=…` and `PGPASSWORD=… psql` are imported. +- `mem save -t ` prompts for a description and hangs under a + pipe; `save` has no `-y`. +- `mem session` shows nothing until a session has closed (300 s idle and + one more command), and captured records carry `"session": null`. +- `$MEM_DIR` is honoured by the finder and by `picks.json` but not by the + rest of the storage layer. +- Homebrew 5.1 refuses the tap as untrusted until `brew trust + matinsaurralde/tap` is run. +- `mem _capture` costs 150–170 ms of CPU per prompt in the background; the + "<5 ms" in the documentation is the foreground cost of forking a disowned + job. + ## [0.5.0] — 2026-08-04 A full audit of the codebase, and the repairs it turned up. 151 findings were diff --git a/docs/DEFENSE.md b/docs/DEFENSE.md index 28b2826..a53f985 100644 --- a/docs/DEFENSE.md +++ b/docs/DEFENSE.md @@ -20,7 +20,7 @@ Facts to have in hand (measured 2026-09-21 on the owner's machine, Python | `mem _capture` per prompt | 150–170 ms, in the background | measured | | `import mem.cli` | 112 ms, of which `mem.models` (Pydantic) 58 ms, click 6.5, rich.console 8.6 | `python -X importtime` | | `except Exception` sites | 20 in `src/` before the audit; after it every one is narrowed to the real type or names the concrete failure next to it (AUDIT-2026-09.md item 7) | grep | -| Latest tag / PyPI / Homebrew tap | **v0.4.1 everywhere; 0.5.0 is merged to master and never tagged** | `git tag`, `pip index versions cli-mem`, `Formula/mem.rb` | +| Latest tag / PyPI / Homebrew tap | **v0.4.1 everywhere at the start of the audit; 0.5.0 was merged to master on 2026-08-04 and never tagged.** 0.5.1 was tagged and published the day the audit closed | `git tag`, `pip index versions cli-mem`, `Formula/mem.rb` | That last row is the first thing to say out loud, before a reviewer finds it. diff --git a/pyproject.toml b/pyproject.toml index a0a9d4d..527cf37 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cli-mem" -version = "0.5.0" +version = "0.5.1" 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 67830c7..d342810 100644 --- a/src/mem/__init__.py +++ b/src/mem/__init__.py @@ -1,3 +1,3 @@ """mem — your shell history, understood.""" -__version__ = "0.5.0" +__version__ = "0.5.1"