Repository navigation
audit: September 2026 — make it work on real data, simplify, and release 0.5.1 - #30
Conversation
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…ch printed nothing `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 <noreply@anthropic.com>
…ys 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 <noreply@anthropic.com>
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 <noreply@anthropic.com> (cherry picked from commit 14986717e89a394307ce02ba60b5bfa72f89d3f6)
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 <noreply@anthropic.com> (cherry picked from commit dcfbd197a268684611a0b2703860ce89ed341e66)
…de 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 <noreply@anthropic.com> (cherry picked from commit 62fac76eb2390cef026769b425eb62afecc5f4cd)
…file is bad" 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 <noreply@anthropic.com> (cherry picked from commit 67b38d1d40c18241b95846165622cf25e62e22a9)
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 <noreply@anthropic.com> (cherry picked from commit 5a1cbd33c74c17a5e753556b3c6a378201c2d033)
…em save !` 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 <noreply@anthropic.com> (cherry picked from commit 7a17543470175cd0a5c76e1e1f78ba3de83597cb)
…t did not 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 <noreply@anthropic.com> (cherry picked from commit b67ef36e7e8424c2566a537d55158dfa2a6ecc35)
… 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 <noreply@anthropic.com> (cherry picked from commit 873e5abebd36be1687cc9f59eb6279224f1128c8)
`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 <noreply@anthropic.com> (cherry picked from commit 75d294bca60776c6a96892b5f382d3d152bea087)
`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 <noreply@anthropic.com> (cherry picked from commit cb7647f36647d42c521b2ecabf357be2ea09ac24)
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 <noreply@anthropic.com> (cherry picked from commit 6e5da4f00e308c356ace9d525127e4a5fe005eb8)
… call sites `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 <noreply@anthropic.com> (cherry picked from commit a68d1473ad950b35d2585d0fa94047aa6839859c)
…ould reach `_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 <noreply@anthropic.com> (cherry picked from commit b145828f382b5d7ee3de92a676252ddb90ca4e6d)
…newest commands 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 <noreply@anthropic.com> (cherry picked from commit b79aa8df2e749d3f5347ed202b0b734d7c2e4fef)
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 <noreply@anthropic.com> (cherry picked from commit e39bed43f2dbc0e7281232fdff075ff007cb245b)
…olds were untestable 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 <noreply@anthropic.com> (cherry picked from commit 4ce4f0beaa4e9e69aea6e4d95cf84602214a99e2)
…aintained `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 <noreply@anthropic.com> (cherry picked from commit 70151e118d20330a7fe593e52f3d6b1ba3d2ba14)
…aced
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 <noreply@anthropic.com>
(cherry picked from commit 67be08a34b45eee2a9c6949976160b8a9960cd57)
…thout citing it `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 <noreply@anthropic.com> (cherry picked from commit d86afa2177dd96f211a34ca3f5e3ec1168e431b7)
…t 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 <noreply@anthropic.com> (cherry picked from commit e870fc201dd4efd27ae3501df60ff35c16706e3d)
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 <noreply@anthropic.com> (cherry picked from commit 7e96ea23845671aa894eb05d985b3e39ffb63a39)
…d 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 <noreply@anthropic.com> (cherry picked from commit 52af0c28b626f823b42b2bffdae20cf3a5c87d32)
… are narrowed 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 <noreply@anthropic.com> (cherry picked from commit 0390f5897bc9bf9d263c9ab57483fb97f14954fc)
… 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 <noreply@anthropic.com> (cherry picked from commit af45fac0d258a38b76a3aaa7a9af180512fd3b9c)
…d of shared `_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 <noreply@anthropic.com> (cherry picked from commit 3695fe4b71d5209d49efe6f8115e2731a8cb07f5)
…e times `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 <query>` 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 <query>` — the class of defect that put a stale shell hook in front of every pip user. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commit 31b9bda191eb500257aa521b345d6a5a17ba803a)
`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 <noreply@anthropic.com>
(cherry picked from commit a38588e632ea84376b933172c947a08e5634e24b)
… as a literal `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 <noreply@anthropic.com> (cherry picked from commit 598098195d19e53e76174b7b8b8f70b30c883140)
…ched the heuristic fallback `_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 <noreply@anthropic.com> (cherry picked from commit ee378c50109273980a3204b4ea6b1dcfeee141bc)
…ad three times per tool `_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 <noreply@anthropic.com> (cherry picked from commit a367b4ab74e84e6aa8b9a874dfc354f47e856d4a)
…-readable and unlocked `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 <noreply@anthropic.com> (cherry picked from commit 7c83f28f25ce29bc4878fb7393a3d40b265dfd96)
…its own session `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 <noreply@anthropic.com> (cherry picked from commit b94976d5012abb54644c0f9772b1fe3b998e815e)
…d succeeded before failing `_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 <noreply@anthropic.com> (cherry picked from commit a353f3ccdfbe6e5e063e0d98848803c90b1b5031)
… 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 <noreply@anthropic.com> (cherry picked from commit 436b772dac91b8ae5ef19da2278d052602d33a16)
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cb19e7498b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| while heap and len(seen) < limit: | ||
| _, file, _, entry = heapq.heappop(heap) | ||
| if entry.command not in seen: | ||
| seen[entry.command] = entry | ||
| push_head(file) |
There was a problem hiding this comment.
Do not assume history files are timestamp-sorted
When an older record is appended after a newer one—which can happen when mem import --from-shell-history appends historical records to the global file, or when detached captures complete out of order—the heap exposes only the file's tail and stops after limit distinct commands. For a single file containing timestamps [200, 100, 150], limit=2 returns the records at 150 and 100 and never reaches the newest record at 200; without the limit it still returns them in the wrong order. The empty-query Ctrl+R view therefore needs to tolerate non-monotonic timestamps rather than treating each file as a sorted merge input.
Useful? React with 👍 / 👎.
…ase 0.5.1 (#30) audit: September 2026 — make it work on real data, simplify, and release 0.5.1
Summary
The September audit, run against real data, and the 0.5.1 release.
mem deploy --json/-n 20(documented, broken) now parse; a query with no matches says so on stderr; 268 warnings → 0 (-W errorpasses); theperfgroup no longer runs under the coverage tracer.42crashedrotate/forgetsilently in the background sync; a hand-editedpicks.jsoncrashed the finder; the Apple SDK availability probe was an import check; the session tracker ignoredduration_ms(fourth instance);.session_state.jsonwas written 0644 and unlocked; MCPretried_successfullywas wrong; the empty-query Ctrl+R view showed the stalest repo; everyexcept Exceptionnarrowed or justified; every magic number sourced; three-way duplicated helpers unified; seven tests that could not fail now can.Test plan
ruff check .andruff format --check .cleanpytest -q: 1520 passed, 4 skipped, 18 deselected, 0 warnings, 92 % branch coverage; also green under-W errorpytest -m ai(2),-m perf(4),-m keychain_live(12) run by hand on macOS 26.3.1 with apple-fm-sdk 0.1.1v0.5.1on the merge commit;release.ymlpublishes to PyPI, GitHub Releases and the Homebrew tap🤖 Generated with Claude Code