From 1b09e737370be6d737f2c523eba03222bf3209b0 Mon Sep 17 00:00:00 2001 From: Matias Date: Tue, 4 Aug 2026 02:43:43 -0300 Subject: [PATCH 1/2] feat(promote): turn the sequences you repeat into runbooks, with the variable already found MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mem captures everything and replays named groups, but nothing connected the two: a group only exists if you remembered to run `mem save` while busy doing the thing. `mem promote` mines the history instead — sequences recurring across three separate sessions, with the argument that changed between runs already turned into a $VAR. Calibrated on eight hand-designed 45-day histories: 0 false positives in the default five-candidate listing, 88% of planted workflows surfaced. The measurements that set the thresholds are pinned as tests, notably that removing the inspection-command filter takes the false-positive rate to 80%, and that ranking on occurrences alone puts a deploy's own prefix above the deploy. Also fixes a session-splitting defect found on the way: elapsed time was measured from completion timestamps, so a slow `docker build` read as idle time and cut every deploy sequence in half at its slowest step. Refs ADR-012 --- README.md | 65 + ...12-promote-mines-sequences-not-commands.md | 96 ++ src/mem/cli.py | 163 +++ src/mem/promote.py | 1088 +++++++++++++++++ tests/test_promote.py | 903 ++++++++++++++ 5 files changed, 2315 insertions(+) create mode 100644 docs/decisions/012-promote-mines-sequences-not-commands.md create mode 100644 src/mem/promote.py create mode 100644 tests/test_promote.py diff --git a/README.md b/README.md index e1e70d2..b5210af 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ mem silently captures every command you type, then lets you search, save, and re Ctrl+R # interactive finder, ranked mem deploy # or search from the command line mem fix # what fixed the last thing that broke +mem promote # sequences you repeat, ready to become runbooks mem save "cmd" -t ops # save a command to a group mem run ops # run the group interactively mem vars set API_KEY # store a secret for saved commands @@ -270,6 +271,68 @@ Credentials are removed from the output using the same redaction that guards the --- +## Promote + +Groups are the most useful thing mem does and the least used, because building one means remembering to run `mem save` at the exact moment you're busy doing the thing. `mem promote` closes that gap: it reads the history you already have, finds sequences you repeat across separate work sessions, and works out which argument changed between runs. + +```bash +mem promote # what looks promotable +mem promote 1 # save candidate 1 as a group (asks first) +mem promote 1 --name ship +mem promote --json +``` + +``` +$ mem promote + + 1. kubectl-rollout + 6 times · last 2d ago · strong + kubectl config use-context $CONFIG_ARG + kubectl apply -f deploy.yaml -n $CONFIG_ARG + kubectl rollout status deploy/api -n $CONFIG_ARG + $CONFIG_ARG was staging, prod, dev + + 2. terraform-apply + 4 times · last 6d ago · moderate + terraform fmt -recursive + terraform plan -out plan.tfplan + terraform apply plan.tfplan + + mem promote saves one as a group. It runs nothing. +``` + +``` +$ mem promote 1 --name deploy-staging + + group deploy-staging + kubectl config use-context $CONFIG_ARG + kubectl apply -f deploy.yaml -n $CONFIG_ARG + kubectl rollout status deploy/api -n $CONFIG_ARG + $CONFIG_ARG was staging, prod, dev + +Save these 3 commands as 'deploy-staging'? [y/N]: y +Saved group deploy-staging with 3 commands. + mem run deploy-staging +``` + +The variable is the point. A sequence that recurs with a changing namespace or branch is worth *more* than an identical one, because that difference is precisely the parameter the runbook should take. `$CONFIG_ARG` above is a name mem derived, not a name it understood — rename it with `mem group edit`. + +### What it will and won't propose + +A sequence has to recur in **three separate sessions**. Repetitions inside one session don't count: a build loop run eight times in one afternoon is one episode of work, not eight. + +Commands that only *look* at things — `ls`, `cd`, `cat`, `git status` — are dropped before mining, so an inspection command between two steps doesn't break the sequence. Failed commands are dropped too: a command that exited non-zero isn't part of a working procedure. + +A token becomes a `$VAR` only in an argument position — never the program, never the subcommand after it, never a flag name. That's the rule that separates `git checkout main` / `git checkout staging` (a branch, so a variable) from `git push` / `git pull` (a different intent, so not the same sequence at all). Commands containing a pipe or a redirection are never generalised, because mem doesn't parse shell and won't guess inside one. + +**It will sometimes suggest `git add -A; git commit -m $MSG; git push`.** That really is a sequence you repeat, and it really is a poor runbook — the whole point is the message you type fresh each time. mem can't tell the difference from the outside. On the calibration corpus this was about one in eight suggestions. Skip it; it isn't a sign anything is broken. + +**Nothing is written without confirmation and nothing is ever executed.** A sequence containing something credential-shaped is shown with a warning and refused for promotion outright — there's no `--force`, because a secret in a saved runbook is a second copy of it on disk. Use `mem save --var` to save those steps with the secret as a variable instead. + +By default the five best candidates are shown. That number is calibrated, not cosmetic: ranking is what keeps the list trustworthy, and going deeper costs accuracy. See [ADR-012](docs/decisions/012-promote-mines-sequences-not-commands.md) for the corpus and the measurements. + +--- + ## Groups Groups are named collections of commands — like runbooks you can execute. @@ -520,6 +583,8 @@ Every request is appended to `~/.mem/agent-audit.jsonl`, redacted, and shown by ```bash mem fix # what fixed the last failure (see Fix) mem fix kubectl --json # ...for a specific one, machine-readable +mem promote # repeated sequences worth saving (see Promote) +mem promote 1 --name deploy # ...turn one into a group, after confirming mem stats # top commands, repos, totals mem stats --json # machine-readable stats mem forget "API_KEY=sk-..." # permanently delete matching commands diff --git a/docs/decisions/012-promote-mines-sequences-not-commands.md b/docs/decisions/012-promote-mines-sequences-not-commands.md new file mode 100644 index 0000000..9106504 --- /dev/null +++ b/docs/decisions/012-promote-mines-sequences-not-commands.md @@ -0,0 +1,96 @@ +# ADR-012: Promote Mines Sequences, and Ranking Is What Makes It Trustworthy + +**Status**: Accepted +**Date**: 2026-08-04 + +## Context + +mem has two halves that never met. One captures every command you type. The other — named groups — replays runbooks with variables filled in, and is the most original thing in the product. It is also barely used, because creating a group requires remembering to run `mem save` at exactly the moment you are busy doing the thing it would save. The sequence you repeat six times a month never becomes a runbook, because you only recognise it as a sequence in hindsight. + +`mem promote` is the hindsight: find command sequences that recur across separate work sessions, work out which argument changed between runs, and offer the result as a group with that argument already a `$VAR`. + +The failure mode that matters is not missing a sequence. It is proposing junk. A suggestion list that offers nonsense is dismissed once and never opened again, and no amount of correct behaviour afterwards recovers it. So this was built the way `mem fix` was: pick the thresholds from a measurement, and report the false-positive rate rather than asserting one. + +## The measurement + +Eight hand-designed 45-day histories, ~1,100 commands each. Every session is one or two *activities*, each labelled by hand: + +- **workflow** — a deliberate ordered procedure with varying arguments (deploy, release, migrations, plan-and-apply, namespace check). The ground truth. +- **habit** — a fixed-shape sequence genuinely repeated but a poor runbook, because its content is typed fresh each time. `git add -A; git commit -m …; git push` is the archetype. +- **ad-hoc** — debugging, container poking, log trawling. Modelled as a random-length, random-order draw from a pool of related commands, **because that is what makes it ad-hoc**: real exploration has a stable vocabulary and no stable shape. Anything mined out of one of these is a false positive. + +35% of sessions run two activities back to back with no idle gap, so the miner gets every opportunity to splice the tail of one onto the head of the next. + +| configuration | FP rate, top 5 | workflows surfaced | +|---|---|---| +| **as shipped** | **0.0%** (0/40) | **88%** | +| whole mined list (~12/history) | 42.3% | — | +| top 8 instead of top 5 | 12.5% | — | +| **without the inspection-command filter** | **80.0%** | collapses | +| `MIN_OCCURRENCES = 2` | 0.0% shown, but the mined pool goes 97 → 223 and its FP rate 42% → 75% | — | +| ranking on occurrences alone | 0.0% | 80% | + +Mining costs ~15 ms per history. + +## Decision + +### Sessions are re-derived from the command files, not read from the session files + +`SessionTracker` already writes `WorkSession` records and they are the obvious input. They are not used, for four reasons that all point the same way: they carry no exit codes (so a sequence of *failed* commands would be proposed as a runbook), their `started_at` is documented in `capture.py` as "approximate", they are rotated after 30 days while commands are kept for 90, and `mem import` writes none at all — so the user who has just imported ten years of `.zsh_history`, the one with most to gain, would get nothing. + +The boundary rule is the tracker's — 300 idle seconds or a change of repository — with one correction that is not cosmetic. **mem timestamps a command's completion, so a bare timestamp difference charges a command's own runtime to the user's idle time.** A six-minute `docker build` read as six minutes of distraction and ended the session, which cut every deploy sequence in half at precisely its slowest step — that is, cut exactly the sequences this feature exists to find. The threshold is unchanged; what is measured against it is think time. This is the third place this bug class has appeared, after the shell hooks and `mem fix`'s correction window, and it is now called out in the code. + +### Inspection commands are deleted, and the survivors must be strictly contiguous + +This is how "interleaved noise does not break a sequence" is implemented, and the alternative was measured. Allowing *gaps* means any two commands can be called adjacent if enough unrelated ones separate them. Deleting the noise instead keeps the contiguity requirement intact, and the list is deliberately short, boring, and read-only — with a guard that matters more than the list: a command containing a pipe, a redirection or a separator is never called noise, because `cat x` looks but `cat x > y` is a step. + +**Removing this filter takes the top-5 false-positive rate from 0% to 80%.** The feature stops working. It is the one result a future contributor is most likely to undo by simplifying, so it is pinned as a test. + +### "The same sequence" is decided by shape, then by the values observed + +A command is reduced to a shape where argument positions become holes. Two rules decide which positions may be holes: + +- **Never `argv[0]`, never the token after it, never a flag name.** That single rule separates `git checkout main` / `git checkout staging` (index 2 varies — a branch, so a variable) from `git push` / `git pull` (index 1 varies — a different intent, so not the same sequence at all). The subcommand is the verb; the verb is not a parameter. `sudo`/`doas` shift the window right. +- **A command containing shell grammar is never generalised.** mem does not parse shell, so it cannot know which side of a pipe an operand belongs to. Such commands still match themselves byte for byte. + +Which holes *actually* varied is then read off the occurrences: a hole with one observed value is a literal. Surviving holes are grouped into variables **by the value vector they take, not by position**. `kubectl config use-context prod`, `apply -n prod` and `rollout status -n prod` have three varying positions that all change together to the same value — that is one parameter used three times, and counting positions would reject the single most useful shape this feature has. At most two variables: three independent holes is a template with more holes than content. + +### Three distinct sessions, not three repetitions + +The same number `mem fix` calls strong evidence. Repetitions *inside* one session are not counted — a build loop run eight times in one afternoon is one episode of work — so "you ran this 6 times" means six separate occasions. Dropping to two does not hurt the shown list, but more than doubles the mined pool (97 → 223) and takes its FP rate to 75%, which is a listing that only survives because ranking hides it. + +### Ranking is `occurrences × length`, and the obvious choice is wrong + +Every prefix of a six-step deploy recurs *at least as often as the deploy does*. So an occurrence-first order puts `docker build` / `docker push` (7 times) above the whole deploy it belongs to (6 times), and the listing fills with fragments of one workflow. Multiplying by length asks the question the user is actually asking — how much typing would this have saved — and the whole sequence wins it. Measured: 88% of planted workflows surfaced, against 80% for occurrence-first. Pinned as a test, because this reasoning is exactly the kind that is lost the moment it is not written down. + +Two further passes: *closed* drops a sequence contained in an equally-attested longer one (it carries no evidence of its own), and *dominant* keeps one representative per family of overlapping sequences (it carries no attention of its own). A sequence that merely shares a command with another, without containing it, is a different procedure and both are shown. + +### The default limit of 5 is part of the design + +**0% false positives at 5; 12.5% at 8; 42% across the whole mined list.** Ranking, not filtering, is what makes this output trustworthy, so the limit is load-bearing and raising it trades directly against the one property the feature cannot afford to lose. Said in a comment on the option itself, where someone changing it will read it. + +### Nothing is written without confirmation, nothing is ever executed + +`mem promote` lists. `mem promote ` prints what it would save and asks. The module imports nothing that could run a command, and that is asserted structurally, as in `mem fix`. + +A candidate whose text trips either of `variables.py`'s detectors — `looks_like_credential` or a difference under `redact_secrets` — is shown with a warning and **cannot be promoted**. There is no `--force`: a secret in a saved runbook is a second copy of it on disk, and the right answer is `mem save --var`. Displayed text goes through one redaction choke point, so there is exactly one place a command string can escape. + +## Cost of this decision (stated plainly) + +- **It proposes the commit dance.** 12.5% of shown candidates were the `git add -A; git commit -m $MSG; git push` class: genuine repetition, poor runbook, because the whole point is the message you type fresh each time. mem cannot tell the difference from the outside, and it is documented in the README rather than hidden, because a user who sees it and is not warned will conclude the feature is broken. +- **The corpus is hand-designed, not a field study.** The activity mix and the noise ratio are informed guesses. The *mechanism* by which ad-hoc work differs from a procedure — no stable shape — is real, but nobody has yet run this against a stranger's actual year of history. +- **Variable names are derived, not understood.** A long flag names itself (`--namespace` → `$NAMESPACE`), version- and filename-shaped values are recognised, and everything else becomes `$CHECKOUT_ARG`-style: honest about knowing nothing. `-n` is deliberately not read as "namespace", because it is a line count to `head`. Users will rename. +- **Two-token commands can never be parameterised.** `cd $DIR`, `ssh $HOST` are unreachable, because protecting index 1 is what keeps `git push`/`git pull` apart. A knowingly paid price. +- **Evidence is not merged across repositories.** A runbook is made of *this* repository's branch names and script paths, so adding two repositories' counts would claim one workflow recurred six times when two workflows recurred three times each. + +## Alternatives rejected + +**Read `WorkSession` records.** Four independent reasons above; the decisive one is that imported history has no sessions. + +**Allow gaps between steps instead of deleting noise.** Lets any two commands be called adjacent given enough unrelated ones between them — the coincidence this feature must refuse. + +**Fuzzy similarity between command lines.** Already measured and rejected in `mem fix` (ADR-less, but pinned in `test_fix.py`): `test_a.py`/`test_b.py` scores *above* the genuine typo `psuh`/`push`, so no threshold on it separates a parameter from a different intent. The shape-based rule here is the same lesson applied to a different problem. + +**Rank by occurrences.** Measured 8 points worse on workflow coverage, for the structural reason that fragments always out-count the whole. + +**A `--force` to promote a candidate containing a credential.** Defeats the check entirely; `mem save --var` already does the right thing. diff --git a/src/mem/cli.py b/src/mem/cli.py index 62b8a27..50b40a6 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -491,6 +491,169 @@ def fix_cmd(query: tuple[str, ...], as_json: bool, limit: int) -> None: console.print() +def _promote_scopes(global_flag: bool) -> tuple[Path, list[Path]]: + """Return the group file to write to, and every file to compare against. + + Both scopes are always compared, even when only one is the target: a + sequence already promoted globally should stop being suggested inside a + repository too, or ``mem promote`` spends its first slot re-offering + something the user has already accepted. + """ + from mem import groups, storage + + target = groups.resolve_scope(global_flag) + scopes = [groups.resolve_scope(False), storage.GROUPS_GLOBAL_FILE] + return target, list(dict.fromkeys(scopes)) + + +def _existing_group_names(paths: list[Path]) -> set[str]: + """Every group name already in use, so a suggestion does not collide.""" + from mem import storage + + names: set[str] = set() + for path in paths: + try: + names |= set(storage.read_group_file(path).groups.keys()) + except ValueError: + continue + return names + + +def _promote_steps(entry: dict) -> None: + """Print one candidate's commands and the variables mem would extract.""" + for step in entry["steps"]: + # Text, not markup: these are command lines the user typed, and a + # `sed 's/[a-z]//'` interpolated into a styled string loses its + # character class. Aligned under the label column of _fix_line. + console.print(Text(f" {step}")) + for variable in entry["variables"]: + shown = ", ".join(variable["values"][:3]) + more = " …" if len(variable["values"]) > 3 else "" + console.print(_fix_detail(f"${variable['name']} was {shown}{more}")) + if entry["has_credential"]: + console.print( + _fix_detail("contains something credential-shaped — cannot be saved") + ) + + +@cli.command(name="promote") +@click.argument("index", required=False, type=int) +@click.option("--json", "as_json", is_flag=True, help="Output as JSON") +# Five is load-bearing, not a display preference. Measured on the calibration +# corpus (ADR-012): the top five candidates carried 0 false positives out of +# 40, the top eight carried 12.5%, and the whole mined list — about twelve +# candidates per history — carried 42%. Ranking, not filtering, is what makes +# this output trustworthy, so raising the default trades directly against the +# one property the feature cannot afford to lose. +@click.option("--limit", "-n", default=5, help="Maximum candidates to show") +@click.option( + "--global", "-g", "global_flag", is_flag=True, help="Save into the global scope" +) +@click.option("--name", "new_name", default=None, help="Name for the new group") +def promote_cmd( + index: int | None, + as_json: bool, + limit: int, + global_flag: bool, + new_name: str | None, +) -> None: + """Turn a sequence you keep repeating into a named group. + + With no argument, lists the command sequences that recur across separate + work sessions, with the argument that changes between runs already turned + into a ``$VAR``. With INDEX, offers to save that one as a group. + + Nothing is written without an explicit yes, and nothing is ever run. + """ + from mem import groups, promote as mining + + target, scopes = _promote_scopes(global_flag) + report = mining.build_report( + scopes=scopes, limit=limit, existing_names=_existing_group_names(scopes) + ) + payload = mining.report_payload(report) + + if as_json: + click.echo(json.dumps(payload, indent=2)) + return + + if not payload["candidates"]: + console.print( + "No repeated sequences yet — mem needs to see one three times " + "in three separate sessions." + ) + return + + if index is None: + console.print() + for entry in payload["candidates"]: + times = entry["occurrences"] + console.print( + _fix_line(f"{entry['index']:>2}.", "bold cyan", entry["name"]) + ) + console.print( + _fix_detail( + f"{times} times · last {_relative_time(entry['last_seen'])} " + f"· {entry['confidence']}" + ) + ) + _promote_steps(entry) + console.print() + console.print( + _fix_detail("mem promote saves one as a group. It runs nothing.") + ) + console.print() + return + + if not 1 <= index <= len(payload["candidates"]): + raise click.ClickException( + f"No candidate {index}. Run `mem promote` to see what there is." + ) + + entry = payload["candidates"][index - 1] + candidate = report.candidates[index - 1] + name = new_name or entry["name"] + + if candidate.has_credential: + # No --force. A secret written into a runbook is a second copy of the + # thing on disk, and the right answer is `mem save --var`, which turns + # it into a variable instead of storing it. + raise click.ClickException( + "This sequence contains something credential-shaped. mem will not " + "store it as a group — use `mem save --var` to save the steps with " + "the secret replaced by a variable." + ) + + groups.validate_group_name(name) + if name in _existing_group_names(scopes): + raise click.ClickException( + f"Group '{name}' already exists. Pass --name to choose another." + ) + + console.print() + console.print(_fix_line("group", "bold cyan", name)) + _promote_steps(entry) + console.print() + if not click.confirm(f"Save these {len(candidate.steps)} commands as '{name}'?"): + console.print("Nothing saved.") + return + + description = f"Promoted from {candidate.occurrences} repeated runs" + written = 0 + for step in candidate.steps: + saved, _vars = groups.save_command( + target, + step, + comment=None, + group_name=name, + description_callback=lambda _n: description, + ) + written += 1 if saved else 0 + + console.print(f"Saved group {safe(name)} with {written} commands.") + console.print(_fix_detail(f"mem run {name}")) + + @cli.command() @click.argument("query") @click.option("--yes", "-y", is_flag=True, help="Skip confirmation") diff --git a/src/mem/promote.py b/src/mem/promote.py new file mode 100644 index 0000000..0fdd14a --- /dev/null +++ b/src/mem/promote.py @@ -0,0 +1,1088 @@ +"""Sequence mining — the runbook you already have but never wrote down. + +``mem`` has two halves that never met. One captures every command you type. +The other, :mod:`mem.groups`, replays *named runbooks* with variables filled +in — the most original thing in the product, and the least used, because +building one requires remembering to run ``mem save`` at the exact moment you +are busy doing the thing. The sequence you repeat six times a month never +becomes a group, because you only notice it is a sequence in hindsight. + +This module is the hindsight. It reads the history that is already on disk, +finds command sequences that recur across separate work sessions, works out +which argument changed between runs, and offers the result as a group with +that argument already turned into a ``$VAR``. + +Why "the argument changed" is the point +--------------------------------------- + +A sequence that recurs *identically* is worth saving. A sequence that recurs +with one thing different every time — a namespace, a branch, a release tag — +is worth more, because that difference is precisely the parameter the runbook +should take. Generalising is therefore not a convenience here, it is the +feature. + +It is also the danger. Generalise one token too eagerly and two unrelated +workflows collapse into one runbook that describes neither. ``git push`` and +``git pull`` differ by one token; so do ``kubectl delete pod a`` and +``kubectl delete pod b``. The first pair must never merge and the second +must. + +The rules, and why each number is what it is +-------------------------------------------- + +**Sessions come from the history, not from the session files.** +:class:`mem.capture.SessionTracker` already writes ``WorkSession`` records, +and they are the obvious input. They are not used, for four reasons that all +point the same way: they carry no exit codes (so a sequence of commands that +*failed* would be proposed as a runbook), their ``started_at`` is documented +in ``capture.py`` as "approximate", they are rotated after 30 days while +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. + +**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. + +**Inspection commands are removed before mining.** ``ls``, ``cd``, ``cat``, +``git status`` and their kind are how you *look* at a repository, not how you +change it. They are also the overwhelming majority of a real history, and +mining with them in place produces runbooks whose steps are mostly ``ls``. +Removing them is what implements "interleaved noise does not break a +sequence": rather than allowing gaps — which lets any two commands be called +adjacent if enough unrelated ones separate them — the noise is deleted and +the remainder must be strictly contiguous. See :func:`is_inspection`, which +refuses to call anything noise if it contains a pipe, a redirection or a +command separator, because ``cat x > y`` is not an inspection. + +**Failed commands are removed too.** A command that exited non-zero is not a +step in a working procedure. Commands with no exit code at all (imported +history) are kept: absence of evidence is not evidence of failure, and +excluding them would make this feature useless on imported history, which is +the opposite of the intent. + +**Steps more than :data:`MAX_STEP_GAP_SECONDS` apart are not one procedure.** +Fifteen minutes. The session rule bounds the gap between *adjacent* commands +at five minutes, but once inspection commands are removed, two surviving +steps can be an hour of poking around apart. Measured as think time — the +gap minus the command's own runtime — for the reason :mod:`mem.fix` measures +it that way: a ten-minute ``docker build`` is a slow command, not a pause. + +**A sequence is between :data:`MIN_SEQUENCE_LENGTH` and +:data:`MAX_SEQUENCE_LENGTH` steps.** Two, because ``terraform plan`` then +``terraform apply`` is a genuine runbook and a single command is what +``mem save`` is already for. Eight, because past that it is not a runbook, +it is a description of your afternoon — and nobody confirms a suggestion to +save eighteen commands they do not recognise. + +**A sequence must recur in :data:`MIN_OCCURRENCES` distinct sessions.** +Three, the same number :mod:`mem.fix` calls strong evidence, and the single +most important false-positive control in this file. Two is entirely +compatible with coincidence: two commands that often follow one another will +follow one another twice. Repetitions *within* one session are deliberately +not counted — running a build loop eight times in one afternoon is one +episode of work, not eight — so "you ran this 6 times" means six separate +occasions. + +**At most :data:`MAX_VARIABLES` variables.** Two. One variable is the +overwhelmingly common shape (an environment, a branch, a version). Two covers +``deploy $ENV $VERSION``. A "sequence" needing three independent holes to +match itself is a template with more holes than content, and the evidence +that those runs were the same workflow has evaporated. + +**Only argument positions may become variables.** Never ``argv[0]``, never +the token after it, and never a flag name. That single rule is what separates +``git checkout main`` / ``git checkout staging`` (index 2 varies — a branch, +so a variable) from ``git push`` / ``git pull`` (index 1 varies — a different +intent, so not the same sequence at all). The subcommand is the verb; the +verb is not a parameter. ``sudo``/``doas`` shift the protected window right, +so ``sudo systemctl restart nginx`` protects ``systemctl restart``. + +**A command containing shell grammar is never generalised.** A pipe, a +redirection, ``&&``, a subshell: mem does not parse shell, so it cannot know +which side of a pipe an operand belongs to. Such commands still match +themselves byte for byte and can still be steps; they simply never grow a +hole. Guessing here would be guessing about the one construct where being +wrong rewrites what the command does. + +**Positions are grouped into variables by the values they take, not by where +they are.** ``kubectl config use-context prod``, ``kubectl apply -n prod`` +and ``kubectl rollout status -n prod`` have three varying positions, but all +three change together and to the same value, so they are *one* variable used +three times — which is exactly what the runbook needs. Counting positions +instead would reject the single most useful case this module has. + +Overlapping candidates +---------------------- + +Every sub-sequence of a recurring sequence also recurs, at least as often. A +five-step deploy generates four four-step candidates, and offering all of +them is how a suggestion list becomes unreadable. Only *closed* candidates +survive :func:`closed`: a shorter sequence contained in a longer one with the +same occurrence count carries no evidence the longer one does not, so it is +dropped. If it occurs strictly more often it is kept, because then it really +is a more common workflow than its parent. + +What this deliberately does not do +---------------------------------- + +- **It never creates anything.** :func:`build_report` reads. Writing a group + happens only in the CLI, only for a numbered candidate, and only after an + explicit confirmation. +- **It never executes anything.** As with ``mem fix``, there is no import in + this module that could. +- **It refuses to store a credential.** A candidate whose text trips + :func:`mem.variables.looks_like_credential` or the redactor is shown with a + warning and cannot be promoted. There is no override flag: a secret in a + saved runbook is a secret written to disk in a second place, and the right + fix is ``mem save --var``, not a ``--force``. +- **Names are a starting point.** The suggested group and variable names are + derived deterministically from the commands themselves (see + :func:`suggest_name` and :func:`_variable_name`). They are not an attempt to + understand what you were doing; ``mem group rename`` exists. +""" + +from __future__ import annotations + +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.models import CapturedCommand, GroupFile +from mem.variables import EXCLUDED_SHELL_VARS, looks_like_credential, redact_secrets + +# --- thresholds ------------------------------------------------------------ +# +# Every number here trades a missed runbook against an invented one. A missed +# runbook costs the user nothing they had before; an invented one costs them +# 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 + +#: Shortest and longest sequence that may be proposed as a group. +MIN_SEQUENCE_LENGTH = 2 +MAX_SEQUENCE_LENGTH = 8 + +#: Distinct sessions a sequence must recur in before it is proposed. +MIN_OCCURRENCES = 3 + +#: 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. +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 = ("|", ">", "<", "&&", "||", ";", "`", "$(", "&") + +#: Marker for a token position that may vary between occurrences. +_HOLE = "\x00" + +#: Prefix marking a shape that stands for one exact command line. +_OPAQUE = "\x01" + + +# --- tokenizing ------------------------------------------------------------ +# +# Not ``shlex.split``. mem has to be able to rebuild the command line it +# proposes, byte for byte apart from the holes it punches, and shlex discards +# the quotes: ``git commit -m "wip thing"`` comes back as four tokens that +# rejoin into a five-word command that means something else. Spans are kept +# instead, so a template is the original text with substrings replaced. + +_TOKEN = re.compile(r"""(?:[^\s"']|"[^"]*"|'[^']*'|["'])+""") + + +@dataclass(frozen=True) +class Token: + """One command-line token and where it sits in the original string.""" + + text: str + start: int + end: int + + +def tokenize(command: str) -> list[Token]: + """Split a command line into tokens, keeping quoted runs intact. + + A balanced quoted run is one token including its quotes, so + ``--message="a b"`` stays a single token and can be reassembled exactly. + An unbalanced quote — ordinary in a half-typed history line — is matched + literally rather than raising, because discarding the command would lose + a step from the middle of an otherwise good sequence. + """ + 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. + + Two — the program and the token after it — pushed right by any + ``sudo``/``doas`` in front, so ``sudo systemctl restart nginx`` protects + ``systemctl restart`` rather than ``sudo systemctl``. + + Protecting the second token is the rule that keeps ``git push`` and + ``git pull`` apart. It costs the case where the second token really is a + parameter (``cd $DIR``, ``ssh $HOST``), and that price is paid knowingly: + for a two-token command the argument *is* the entire meaning, and a + runbook step of ``cd $ARG`` says nothing at all. + """ + offset = 0 + while offset < len(tokens) and tokens[offset].text in _PRIVILEGE_PREFIXES: + offset += 1 + return offset + 2 + + +def command_shape(command: str) -> tuple[str, ...]: + """Reduce a command line to the pattern it would match. + + Literal tokens keep their text; a position that is allowed to vary becomes + :data:`_HOLE`. A ``--flag=value`` token becomes ``--flag=`` plus a hole, + so the flag name stays structure while its value may move. + + Two commands with equal shapes are candidates to be *the same step*; the + decision of which holes actually vary is made later, from the values + observed across occurrences (:func:`_analyse_slots`), because a hole that + never changes is a literal and should stay one. + + A command containing shell grammar gets a one-element opaque shape and can + therefore only ever match itself. + """ + if any(marker in command for marker in _SHELL_GRAMMAR): + return (_OPAQUE + command,) + + tokens = tokenize(command) + protected = _protected_prefix_length(tokens) + shape: list[str] = [] + for index, token in enumerate(tokens): + if index < protected or not token.text: + shape.append(token.text) + elif _is_flag(token.text): + name, sep, _value = token.text.partition("=") + shape.append(name + sep + _HOLE if sep else token.text) + else: + shape.append(_HOLE) + return tuple(shape) + + +def _slot_value(command: str, shape: tuple[str, ...], index: int) -> str: + """The text occupying one hole of *shape* in *command*. + + For a whole-token hole that is the token; for a ``--flag=`` hole it is + only the half after the ``=``, because the flag name is not part of what + varies. + """ + token = tokenize(command)[index] + entry = shape[index] + if entry == _HOLE: + return token.text + return token.text.partition("=")[2] + + +def _slot_span(command: str, shape: tuple[str, ...], index: int) -> tuple[int, int]: + """Character range of one hole, for rewriting it into ``$VAR``.""" + token = tokenize(command)[index] + if shape[index] == _HOLE: + return token.start, token.end + return token.start + len(shape[index]) - 1, token.end + + +# --- 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]]: + """Group a history file's commands into work sessions, in capture order. + + The boundary rule is :class:`mem.capture.SessionTracker`'s: more than + :data:`SESSION_IDLE_SECONDS` idle, or a change of repository. + + With one correction, and it is not a cosmetic one. The tracker subtracts + raw completion timestamps, which charges a command's own runtime to the + user's idle time — so a six-minute ``docker build`` reads as six minutes + of distraction and ends the session. That is survivable for + ``mem session``, whose job is a rough summary. It is fatal here, because + 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. + + Two further additions the tracker does not need: + + - An explicit ``session`` id, when both commands carry one, wins over the + timing heuristic. Nothing writes that field today, but it is the only + field that actually identifies a terminal, and when it exists it is + right where a gap is a guess. + - A timestamp going backwards starts a new session. Interleaved lines from + two shells appear that way, and stitching them into one sequence would + invent a procedure nobody ran. + """ + sessions: list[list[CapturedCommand]] = [] + current: list[CapturedCommand] = [] + for command in commands: + if current: + previous = current[-1] + if previous.session and command.session: + boundary = previous.session != command.session + else: + boundary = _think_seconds(previous, command) > SESSION_IDLE_SECONDS + boundary = boundary or command.repo != previous.repo + boundary = boundary or command.ts < previous.ts + if boundary: + sessions.append(current) + current = [] + current.append(command) + if current: + sessions.append(current) + return sessions + + +# --- noise ----------------------------------------------------------------- +# +# 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 +# write (a redirection, a pipe) is excluded by is_inspection() before the list +# is consulted at all. + +_INSPECTION_PROGRAMS = frozenset( + { + "ls", + "ll", + "la", + "cd", + "pwd", + "clear", + "cat", + "bat", + "less", + "more", + "head", + "tail", + "tree", + "which", + "whoami", + "whereis", + "type", + "file", + "stat", + "man", + "tldr", + "history", + "echo", + "printf", + "exit", + "logout", + "df", + "du", + "top", + "htop", + "ps", + "env", + "printenv", + "date", + "uptime", + "open", + "code", + "vim", + "nvim", + "vi", + "nano", + "emacs", + "fzf", + "mem", + } +) + +#: ``program subcommand`` pairs that only look. ``git branch`` is absent on +#: purpose — bare it lists, but ``git branch -d x`` deletes, and one entry +#: cannot mean both. +_INSPECTION_SUBCOMMANDS = frozenset( + { + ("git", "status"), + ("git", "log"), + ("git", "diff"), + ("git", "show"), + ("git", "blame"), + ("git", "remote"), + ("docker", "ps"), + ("docker", "images"), + ("brew", "list"), + ("npm", "ls"), + ("pip", "list"), + } +) + + +def is_inspection(command: str) -> bool: + """True if a command looks at the system rather than changing it. + + Inspection commands are dropped before mining, which is how interleaved + noise stops breaking a sequence without any notion of a "gap": the + surviving steps must still be strictly contiguous, so two genuinely + unrelated commands can never be called adjacent merely because enough + other work happened between them. + + The guard clause matters more than the lists. ``cat`` is an inspection; + ``cat template.yaml > out.yaml`` is a step in a procedure, and any shell + grammar at all is enough to disqualify a command from being called noise. + """ + 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: + tokens = tokens[1:] + if not tokens: + return True + if tokens[0] in _INSPECTION_PROGRAMS: + return True + return len(tokens) > 1 and (tokens[0], tokens[1]) in _INSPECTION_SUBCOMMANDS + + +def steps_of(session: Sequence[CapturedCommand]) -> list[list[CapturedCommand]]: + """Reduce one session to the runs of commands a runbook could be made of. + + Inspection commands and explicit failures are removed; what remains is + split wherever two surviving commands are more than + :data:`MAX_STEP_GAP_SECONDS` of think time apart. The split is what stops + the removal step from inventing adjacency: dropping half an hour of + ``ls`` between two commands does not make them consecutive. + """ + runs: list[list[CapturedCommand]] = [] + current: list[CapturedCommand] = [] + previous: CapturedCommand | None = None + for command in session: + if command.exit_code is not None and command.exit_code != 0: + continue + if not command.command.strip() or is_inspection(command.command): + continue + if ( + previous is not None + and _think_seconds(previous, command) > MAX_STEP_GAP_SECONDS + ): + if len(current) >= MIN_SEQUENCE_LENGTH: + runs.append(current) + current = [] + current.append(command) + previous = command + if len(current) >= MIN_SEQUENCE_LENGTH: + runs.append(current) + return runs + + +# --- mining ---------------------------------------------------------------- + + +@dataclass(frozen=True) +class Occurrence: + """One time a sequence shape was observed, in one session.""" + + session: tuple[str, int] + commands: tuple[str, ...] + ts: int + repo: str | None + + +@dataclass(frozen=True) +class Variable: + """One value that changed between runs of an otherwise fixed sequence.""" + + name: str + #: ``(step index, token index)`` positions this variable fills. + positions: tuple[tuple[int, int], ...] + #: Distinct values observed, most recent first. + values: tuple[str, ...] + + +@dataclass(frozen=True) +class Candidate: + """A recurring sequence, ready to be offered as a group. + + ``steps`` is already parameterised: every position that varied between + runs holds a ``$VAR`` token, so the tuple is exactly what would be written + into a group if the user says yes. + """ + + steps: tuple[str, ...] + variables: tuple[Variable, ...] + occurrences: int + first_seen: int + last_seen: int + repo: str | None + has_credential: bool + shape: tuple[tuple[str, ...], ...] + + @property + def confidence(self) -> str: + """``strong`` / ``moderate`` / ``weak``, from :attr:`occurrences`.""" + return confidence(self.occurrences) + + +def confidence(occurrences: int) -> str: + """Label an occurrence count. + + Three separate sessions is where coincidence stops being a reasonable + explanation; six is where the sequence is plainly a habit and the runbook + would already have paid for itself. The label exists so the output can + make a proportionate claim rather than asserting the same certainty for + the minimum and for fifty. + """ + if occurrences >= STRONG_EVIDENCE: + return "strong" + if occurrences >= MODERATE_EVIDENCE: + return "moderate" + return "weak" + + +def _collect( + key: str, commands: Sequence[CapturedCommand] +) -> dict[tuple[tuple[str, ...], ...], list[Occurrence]]: + """Index every mineable sub-sequence of one history file by its shape.""" + found: dict[tuple[tuple[str, ...], ...], list[Occurrence]] = {} + for index, session in enumerate(split_sessions(commands)): + for run in steps_of(session): + shapes = [command_shape(c.command) for c in run] + longest = min(MAX_SEQUENCE_LENGTH, len(run)) + for length in range(MIN_SEQUENCE_LENGTH, longest + 1): + for start in range(len(run) - length + 1): + window = run[start : start + length] + shape = tuple(shapes[start : start + length]) + found.setdefault(shape, []).append( + Occurrence( + session=(key, index), + commands=tuple(c.command for c in window), + ts=window[-1].ts, + repo=window[-1].repo, + ) + ) + return found + + +def _one_per_session(occurrences: Sequence[Occurrence]) -> list[Occurrence]: + """Keep the most recent observation from each distinct session. + + Repetition *inside* one session is not independent evidence — a build loop + run eight times in one afternoon is one episode of work — so the + occurrence count this feature quotes has to be a count of occasions. + Keeping the most recent one per session also means the values a variable + is shown to take are the ones the user last used. + """ + latest: dict[tuple[str, int], Occurrence] = {} + for occurrence in occurrences: + current = latest.get(occurrence.session) + if current is None or occurrence.ts >= current.ts: + latest[occurrence.session] = occurrence + return sorted(latest.values(), key=lambda o: o.ts) + + +def _analyse_slots( + shape: tuple[tuple[str, ...], ...], occurrences: Sequence[Occurrence] +) -> dict[tuple[str, ...], list[tuple[int, int]]] | None: + """Work out which holes actually varied, and which of them move together. + + Returns ``{value vector: positions}`` — a mapping from the tuple of values + a position took across occurrences, in occurrence order, to every position + that took exactly that tuple. Positions sharing a vector are one variable: + ``prod`` appearing in three commands and becoming ``dev`` in all three at + once is one parameter used three times, not three parameters, and counting + positions instead would reject the most useful case this module has. + + Holes with a single observed value are literals and are dropped here, so a + shape that never actually varied yields an empty mapping rather than a + fistful of one-valued variables. + + ``None`` means the candidate is refused: more than :data:`MAX_VARIABLES` + independent things changed, which is not one workflow seen several times. + """ + vectors: dict[tuple[str, ...], list[tuple[int, int]]] = {} + for step, step_shape in enumerate(shape): + for index, entry in enumerate(step_shape): + if entry != _HOLE and not entry.endswith(_HOLE): + continue + values = tuple( + _slot_value(o.commands[step], step_shape, index) for o in occurrences + ) + if len(set(values)) == 1: + continue + vectors.setdefault(values, []).append((step, index)) + if len(vectors) > MAX_VARIABLES: + return None + return vectors + + +_VERSION = re.compile(r"^v?\d+(?:\.\d+){0,3}$") +#: A filename, strictly: the extension must start with a letter and the value +#: must carry no ``:``. Both guards were added after calibration, where +#: ``registry.internal/api:1.4.0`` was named ``$FILE`` — its trailing ``.0`` +#: satisfied a laxer rule and produced a name that actively misled. +_FILENAME = re.compile(r"^[^\s:]+\.[A-Za-z][A-Za-z0-9]{0,5}$") + + +def _variable_name( + shape: tuple[tuple[str, ...], ...], + positions: Sequence[tuple[int, int]], + values: Sequence[str], +) -> str: + """Derive a variable name from the evidence, in that order of preference. + + 1. **The flag in front of it.** ``--namespace prod`` and + ``--namespace=prod`` both name themselves; a long flag is the one piece + of self-documentation a command line reliably carries. Short flags are + not used: ``-n`` is a namespace to ``kubectl`` and a line count to + ``head``, and inventing a meaning from an initial is exactly the kind + of confident guess this codebase avoids. + 2. **The shape of the values.** All version-like, or all filename-like. + 3. **The verb it belongs to** — the last protected token of its command, + so ``git checkout main`` yields ``CHECKOUT_ARG``. + + Names that collide with a shell variable mem deliberately ignores (``USER`` + from ``--user``, ``HOME``) fall through to rule 3, because + :func:`mem.variables.parse_variables` would refuse to see them in the + stored command and the group would silently lose its parameter. + """ + # Every position is consulted for a long flag, not just the first: one + # value often appears bare in one command and behind ``--namespace`` in + # the next, and the labelled occurrence is the one that knows its name. + for step, index in positions: + step_shape = shape[step] + flag = None + if step_shape[index].endswith(_HOLE) and step_shape[index] != _HOLE: + flag = step_shape[index].rstrip(_HOLE).rstrip("=") + elif index and step_shape[index - 1].startswith("--"): + flag = step_shape[index - 1] + if flag and flag.startswith("--"): + name = _sanitize(flag[2:]) + if name and name not in EXCLUDED_SHELL_VARS: + return name + + step, index = positions[0] + step_shape = shape[step] + + stripped = [value.strip("\"'") for value in values] + if all(_VERSION.match(value) for value in stripped): + return "VERSION" + if all(_FILENAME.match(value) for value in stripped): + return "FILE" + + # The verb is the token right after any privilege prefix and the program. + # 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: + offset += 1 + verb = _sanitize(step_shape[offset + 1] if offset + 1 < len(step_shape) else "") + if verb and verb not in EXCLUDED_SHELL_VARS: + return f"{verb}_ARG" + return "ARG" + + +def _sanitize(text: str) -> str: + """Fold arbitrary text into a legal ``$VAR`` name, or the empty string.""" + name = re.sub(r"[^A-Za-z0-9]+", "_", text).strip("_").upper() + name = re.sub(r"_+", "_", name) + return name if re.fullmatch(r"[A-Z][A-Z0-9_]+", name) else "" + + +def _build( + shape: tuple[tuple[str, ...], ...], occurrences: Sequence[Occurrence] +) -> Candidate | None: + """Turn one shape and its observations into a parameterised candidate.""" + vectors = _analyse_slots(shape, occurrences) + if vectors is None: + return None + + newest = occurrences[-1] + variables: list[Variable] = [] + used: set[str] = set() + for values, positions in vectors.items(): + base = _variable_name(shape, positions, values) + name = base + suffix = 2 + while name in used: + name = f"{base}_{suffix}" + suffix += 1 + used.add(name) + # Most recent first: the value the user last used is the one that makes + # the variable recognisable, and it is what a default would be. + ordered = list(dict.fromkeys(reversed(values))) + variables.append( + Variable(name=name, positions=tuple(positions), values=tuple(ordered)) + ) + + # Rewrite right to left so earlier spans keep their offsets. + steps: list[str] = list(newest.commands) + rewrites: dict[int, list[tuple[int, int, str]]] = {} + for variable in variables: + for step, index in variable.positions: + start, end = _slot_span(steps[step], shape[step], index) + rewrites.setdefault(step, []).append((start, end, f"${variable.name}")) + for step, edits in rewrites.items(): + text = steps[step] + for start, end, replacement in sorted(edits, reverse=True): + text = text[:start] + replacement + text[end:] + steps[step] = text + + timestamps = [o.ts for o in occurrences] + return Candidate( + steps=tuple(steps), + variables=tuple(variables), + occurrences=len(occurrences), + first_seen=min(timestamps), + last_seen=max(timestamps), + repo=newest.repo, + has_credential=any(_is_sensitive(step) for step in steps), + shape=shape, + ) + + +def _is_sensitive(text: str) -> bool: + """True if a command must never be written into a stored runbook. + + Both of :mod:`mem.variables`' detectors are consulted, and neither is + reimplemented here: ``looks_like_credential`` is the deterministic + shape matcher used for bulk work, and a difference between ``text`` and + its redaction catches everything the MCP boundary would have masked. A + credential that either one recognises is enough to refuse. + """ + return looks_like_credential(text) or redact_secrets(text) != text + + +def mine(key: str, commands: Sequence[CapturedCommand]) -> list[Candidate]: + """Extract every promotable sequence from one history file.""" + candidates: list[Candidate] = [] + for shape, raw in _collect(key, commands).items(): + occurrences = _one_per_session(raw) + if len(occurrences) < MIN_OCCURRENCES: + continue + candidate = _build(shape, occurrences) + if candidate is not None: + candidates.append(candidate) + return candidates + + +def _contains(haystack: Sequence[Any], needle: Sequence[Any]) -> bool: + """True if *needle* appears as a contiguous run inside *haystack*.""" + if len(needle) > len(haystack): + return False + return any( + tuple(haystack[i : i + len(needle)]) == tuple(needle) + for i in range(len(haystack) - len(needle) + 1) + ) + + +def closed(candidates: Sequence[Candidate]) -> list[Candidate]: + """Drop candidates wholly contained in an equally-attested longer one. + + A five-step deploy makes its own four-step prefix recur just as often, and + listing both says the same thing twice while burying everything else. The + shorter one survives only if it occurs *strictly* more often, which means + it genuinely is a more common workflow than the sequence containing it — + the standard closed-sequential-pattern rule, and the reason this list is + readable at all. + """ + return [ + candidate + for candidate in candidates + if not any( + other is not candidate + and len(other.shape) > len(candidate.shape) + and other.occurrences >= candidate.occurrences + and _contains(other.shape, candidate.shape) + for other in candidates + ) + ] + + +def steps_saved(candidate: Candidate) -> int: + """How many command lines this runbook would already have saved. + + ``occurrences × length``. Ranking on occurrences alone was measured on the + calibration corpus and is wrong in a specific, visible way: every prefix of + a six-step deploy recurs at least as often as the deploy does, so an + occurrence-first order puts ``docker build`` / ``docker push`` (7 times) + above the whole deploy it belongs to (6 times), and the list fills up with + fragments of one workflow. Multiplying by length asks the question the user + is actually asking — how much typing would this have saved — and the whole + sequence wins it. + """ + return candidate.occurrences * len(candidate.steps) + + +def rank(candidates: Iterable[Candidate]) -> list[Candidate]: + """Order candidates best-first. + + 1. **Most steps saved** (:func:`steps_saved`) — the value of the runbook. + 2. **Most occurrences.** Between candidates worth the same, prefer the one + with more evidence behind it, for the reason ``mem fix`` sorts on + occurrences: repetition is the only proof this is a workflow at all. + 3. **Most recent**, then the command text, so a tie is broken the same way + twice and ``mem promote 2`` means the same candidate on both runs. + """ + return sorted( + candidates, + key=lambda c: (-steps_saved(c), -c.occurrences, -c.last_seen, c.steps), + ) + + +def dominant(candidates: Sequence[Candidate]) -> list[Candidate]: + """Keep one representative of each family of overlapping sequences. + + :func:`closed` removes candidates that carry no evidence of their own. + This removes candidates that carry no *attention* of their own: a six-step + deploy and its five-step tail are one thing a user would promote once, and + showing both spends two of the five slots on the same workflow while a + different one falls off the list. Measured on the calibration corpus, half + of a ten-candidate listing could be fragments of a single sequence. + + "Family" is deliberately narrow — one sequence containing the other, not + merely sharing a command. Two sequences that overlap in a step without one + containing the other are two different procedures that happen to share a + move, and suppressing either would hide a real answer. + + Input must be ranked; the first member of each family is the one kept. + """ + kept: list[Candidate] = [] + for candidate in candidates: + related = any( + other.repo == candidate.repo + and ( + _contains(other.shape, candidate.shape) + or _contains(candidate.shape, other.shape) + ) + for other in kept + ) + if not related: + kept.append(candidate) + return kept + + +def existing_step_lists(paths: Iterable[Path]) -> set[tuple[str, ...]]: + """Every group already saved in the given scopes, as its list of commands. + + Used to stop ``mem promote`` proposing what the user has already promoted: + the stored commands are byte-identical to the template that produced them, + so exact equality is enough and is the honest test. A group that merely + overlaps a candidate is left alone — mem does not know that the user + considers those the same runbook. + """ + known: set[tuple[str, ...]] = set() + for path in paths: + try: + data: GroupFile = storage.read_group_file(path) + except ValueError: + continue + for group in data.groups.values(): + known.add(tuple(command.cmd for command in group.commands)) + return known + + +def mine_all() -> list[Candidate]: + """Mine every history file, ranked best-first and closed. + + Evidence is counted per repository and never merged across them, which is + the opposite of what ``mem fix`` does with corrections — and deliberately + so. A fix for ``docker`` is a fix in any checkout; a *runbook* is made of + this repository's branch names, service names and script paths, and adding + up two repositories' counts would claim a workflow recurred six times when + what actually happened is two different workflows recurring three times + each. Closure is applied per file for the same reason: a longer sequence + from another repository is not evidence about this one. + """ + candidates: list[Candidate] = [] + for key, commands in iter_histories(): + candidates.extend(closed(mine(key, commands))) + return dominant(rank(candidates)) + + +# --- naming ---------------------------------------------------------------- + +_TRAILING_EXTENSION = re.compile(r"\.[A-Za-z0-9]{1,6}$") + + +def suggest_name(candidate: Candidate, taken: Iterable[str] = ()) -> str: + """Propose a group name for a candidate. + + Derived from the *last* step, because that is what the earlier ones were + for: a sequence ending in ``./scripts/deploy.sh`` is a deploy, whatever it + checked out first. The program's basename supplies the head of the name + and its subcommand, when there is one, the tail — ``terraform apply`` + becomes ``terraform-apply`` and ``./scripts/deploy.sh`` becomes ``deploy``. + + This is a label, not an understanding. ``--name`` overrides it and + ``mem group rename`` fixes it later. + """ + tokens = [token.text for token in tokenize(candidate.steps[-1])] + 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]: + parts.append(tokens[1].rsplit("/", 1)[-1]) + + slug = re.sub(r"[^a-z0-9]+", "-", "-".join(parts).lower()).strip("-") + if not slug or not slug[0].isalpha(): + slug = f"routine-{slug}".strip("-") + + reserved = set(taken) + if slug not in reserved: + return slug + suffix = 2 + while f"{slug}-{suffix}" in reserved: + suffix += 1 + return f"{slug}-{suffix}" + + +# --- report ---------------------------------------------------------------- + + +@dataclass(frozen=True) +class PromoteReport: + """What ``mem promote`` found: ranked candidates, with their names.""" + + candidates: list[Candidate] + names: list[str] + + +def build_report( + scopes: Sequence[Path] = (), limit: int = 5, existing_names: Iterable[str] = () +) -> PromoteReport: + """Mine the store and answer one ``mem promote`` invocation. + + ``scopes`` are the group files to check against, so a sequence the user has + already promoted stops being suggested. Nothing here writes. + """ + already = existing_step_lists(scopes) + candidates = [c for c in mine_all() if c.steps not in already][: max(1, limit)] + + taken = set(existing_names) + names: list[str] = [] + for candidate in candidates: + name = suggest_name(candidate, taken) + taken.add(name) + names.append(name) + 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. + + The single exit from this module. Both ``--json`` and the terminal + rendering read this structure, so there is exactly one place a command + string can escape unredacted, and it is here. + """ + payload: dict[str, Any] = { + "count": len(report.candidates), + "candidates": [ + { + "index": index, + "name": name, + "steps": list(candidate.steps), + "occurrences": candidate.occurrences, + "confidence": candidate.confidence, + "first_seen": candidate.first_seen, + "last_seen": candidate.last_seen, + "last_seen_iso": _iso(candidate.last_seen), + "repo": candidate.repo, + "has_credential": candidate.has_credential, + "variables": [ + {"name": variable.name, "values": list(variable.values)} + for variable in candidate.variables + ], + } + for index, (candidate, name) in enumerate( + zip(report.candidates, report.names), 1 + ) + ], + } + return _redact(payload) diff --git a/tests/test_promote.py b/tests/test_promote.py new file mode 100644 index 0000000..d19f8fb --- /dev/null +++ b/tests/test_promote.py @@ -0,0 +1,903 @@ +"""Contract tests for sequence mining and ``mem promote``. + +The thing under test is a *suggestion engine that writes to disk*, so it has +two ways to fail and only one of them is loud. The quiet one is proposing +junk: a suggestion list nobody trusts is dismissed once and never opened +again, and no amount of correct behaviour afterwards recovers it. The loud one +is creating a group nobody asked for. + +The suite is weighted accordingly. :class:`TestNotTheSameSequence` is the +load-bearing class — every case in it is two commands that share a program, a +shape and a token count and are still not two runs of one thing — and +:class:`TestNothingIsWrittenWithoutConsent` pins the second failure shut. + +:class:`TestCalibration` pins the measurement the whole design rests on. See +ADR-012 for the corpus and the numbers. + +Every test builds its own history; nothing here reads the developer's real +``~/.mem`` (see ``conftest.tmp_mem_dir``, which is autouse). +""" + +from __future__ import annotations + +import json +import time +from pathlib import Path + +import pytest +from click.testing import CliRunner + +from mem import groups, promote, storage +from mem.cli import cli +from mem.models import CapturedCommand + +NOW = int(time.time()) +REPO = "/Users/dev/work/api" +KEY = "work-api" + +#: Comfortably more than SESSION_IDLE_SECONDS, so each run is its own session. +BETWEEN_SESSIONS = 86_400 + + +# --- helpers --------------------------------------------------------------- + + +def cmd( + command: str, + ts: int, + exit_code: int | None = 0, + *, + repo: str | None = REPO, + session: str | None = None, + duration_ms: int | None = 100, +) -> CapturedCommand: + """One captured command, with defaults a candidate would be built from.""" + return CapturedCommand( + command=command, + ts=ts, + dir=repo or "/tmp", + repo=repo, + exit_code=exit_code, + duration_ms=duration_ms, + session=session, + ) + + +def history(*runs: list[str], gap: int = 30) -> list[CapturedCommand]: + """Lay out each run as its own work session, one per day. + + Sessions are a day apart so the idle rule separates them, and commands + within a session are *gap* seconds apart so nothing trips the step-gap + rule. A test that wants either boundary crossed sets it explicitly. + """ + commands: list[CapturedCommand] = [] + for index, run in enumerate(runs): + ts = NOW - (len(runs) - index) * BETWEEN_SESSIONS + for text in run: + commands.append(cmd(text, ts)) + ts += gap + return commands + + +def write_history(commands: list[CapturedCommand], key: str = KEY) -> Path: + """Write commands to a repo history file in capture order. + + Raw file writing rather than ``storage.append_command`` because capture + order and timestamps are the signal under test, and the capture layer + would stamp its own over the ones each test chose. + """ + path = storage.MEM_DIR / "repos" / f"{key}.jsonl" + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + for command in commands: + handle.write(command.to_jsonl() + "\n") + return path + + +def top_of(commands: list[CapturedCommand]) -> list[promote.Candidate]: + """Mine raw commands exactly as ``mine_all`` would, for one history file.""" + candidates = promote.closed(promote.mine(KEY, commands)) + return promote.dominant(promote.rank(candidates)) + + +def mined(*runs: list[str], gap: int = 30) -> list[promote.Candidate]: + """Mine a set of sessions, ranked and de-overlapped as the CLI sees them.""" + return top_of(history(*runs, gap=gap)) + + +def steps_of(candidates: list[promote.Candidate]) -> list[tuple[str, ...]]: + """The templated command lists, for comparing against an expectation.""" + return [candidate.steps for candidate in candidates] + + +DEPLOY = ["make build", "make test", "./scripts/deploy.sh"] + + +@pytest.fixture +def global_scope(monkeypatch: pytest.MonkeyPatch) -> Path: + """Force group writes into the global scope. + + ``groups.resolve_scope`` shells out to ``git`` for the current directory, + which under pytest is whatever checkout the suite is running in. Pinning + it to global removes a subprocess per test and, more importantly, removes + a dependency on where the tests happen to be invoked from. + """ + monkeypatch.setattr(groups, "get_git_repo", lambda directory: None) + return storage.GROUPS_GLOBAL_FILE + + +def run_promote(*args: str, input: str | None = None) -> str: + """Invoke ``mem promote`` and return its stdout.""" + result = CliRunner().invoke(cli, ["promote", *args], input=input) + assert result.exception is None, result.exception + assert result.exit_code == 0, result.output + return result.output + + +# --- the core rule --------------------------------------------------------- + + +class TestCleanRecurringSequence: + """The happy path: the same three commands, three separate days.""" + + def test_a_sequence_repeated_in_three_sessions_is_found(self) -> None: + assert steps_of(mined(DEPLOY, DEPLOY, DEPLOY)) == [tuple(DEPLOY)] + + def test_the_candidate_records_how_often_and_when(self) -> None: + (candidate,) = mined(DEPLOY, DEPLOY, DEPLOY) + assert candidate.occurrences == 3 + assert candidate.last_seen > candidate.first_seen + assert candidate.repo == REPO + assert candidate.variables == () + + def test_two_sessions_are_not_enough(self) -> None: + """Two is compatible with coincidence; three is the threshold.""" + assert mined(DEPLOY, DEPLOY) == [] + + def test_a_sequence_seen_once_yields_nothing(self) -> None: + assert mined(DEPLOY) == [] + + def test_repetition_inside_one_session_is_one_occasion(self) -> None: + """A build loop run three times in an afternoon is one episode. + + The claim ``mem promote`` makes is "you did this on N occasions", so + the count has to be a count of sessions. Counting raw repetitions + would let a single afternoon manufacture the entire evidence base. + """ + assert mined(DEPLOY + DEPLOY + DEPLOY) == [] + + def test_a_single_command_is_not_a_sequence(self) -> None: + """That is what ``mem save`` is for.""" + assert mined(["make build"], ["make build"], ["make build"]) == [] + + +class TestVaryingArgument: + """The case that makes this worth building: one token changes each run.""" + + def test_a_changing_operand_becomes_a_variable(self) -> None: + (candidate,) = mined( + ["git checkout main", "make build"], + ["git checkout staging", "make build"], + ["git checkout hotfix", "make build"], + ) + (variable,) = candidate.variables + assert candidate.steps == (f"git checkout ${variable.name}", "make build") + assert set(variable.values) == {"main", "staging", "hotfix"} + + def test_the_most_recent_value_is_listed_first(self) -> None: + """It is the one that makes the variable recognisable.""" + (candidate,) = mined( + ["git checkout main", "make build"], + ["git checkout staging", "make build"], + ["git checkout hotfix", "make build"], + ) + assert candidate.variables[0].values[0] == "hotfix" + + def test_one_value_used_in_three_commands_is_one_variable(self) -> None: + """Positions are grouped by the values they take, not by where they are. + + All three commands change together and to the same value, so this is + one parameter used three times. Counting positions would reject the + single most useful shape this feature has. + """ + (candidate,) = mined( + *[ + [ + f"kubectl config use-context {ns}", + f"kubectl apply -f app.yaml -n {ns}", + f"kubectl rollout status deploy/api -n {ns}", + ] + for ns in ("prod", "staging", "dev") + ] + ) + (variable,) = candidate.variables + assert len(variable.positions) == 3 + assert all(f"${variable.name}" in step for step in candidate.steps) + + def test_a_long_flag_names_the_variable(self) -> None: + (candidate,) = mined( + *[ + [f"helm upgrade api --namespace {ns}", "make smoke"] + for ns in ("prod", "staging", "dev") + ] + ) + assert candidate.variables[0].name == "NAMESPACE" + + def test_an_attached_flag_value_names_the_variable_too(self) -> None: + (candidate,) = mined( + *[ + [f"helm upgrade api --namespace={ns}", "make smoke"] + for ns in ("prod", "staging", "dev") + ] + ) + assert candidate.variables[0].name == "NAMESPACE" + assert "--namespace=$NAMESPACE" in candidate.steps[0] + + def test_version_shaped_values_are_named_version(self) -> None: + (candidate,) = mined( + *[["npm version " + v, "npm publish"] for v in ("1.2.0", "1.3.0", "2.0.0")] + ) + assert candidate.variables[0].name == "VERSION" + + def test_filename_shaped_values_are_named_file(self) -> None: + (candidate,) = mined( + *[ + ["make build", f"kubectl apply -f {name}.yaml"] + for name in ("api", "web", "worker") + ] + ) + assert candidate.variables[0].name == "FILE" + + def test_a_registry_tag_is_not_called_a_file(self) -> None: + """Found in calibration: ``registry/api:1.4.0`` ends in ``.0``. + + A laxer filename rule called that ``$FILE``, which is a name that + actively misleads — the value is an image reference. The rule now + requires the extension to start with a letter and the value to carry + no ``:``. + """ + assert not promote._FILENAME.match("registry.internal/api:1.4.0") + assert promote._FILENAME.match("deploy.yaml") + + def test_a_name_colliding_with_a_shell_variable_is_avoided(self) -> None: + """``--user`` would yield ``$USER``, which mem deliberately ignores. + + ``parse_variables`` excludes the common shell variables, so a group + storing ``$USER`` would silently have no parameter at all. The name + falls back rather than producing a runbook with a dead hole in it. + """ + (candidate,) = mined( + *[[f"curl -s --user {who} https://api", "make check"] for who in "abc"] + ) + assert candidate.variables[0].name != "USER" + + def test_two_independent_variables_are_allowed(self) -> None: + (candidate,) = mined( + *[ + [f"make deploy {env}", f"make tag {ver}"] + for env, ver in (("prod", "1.0"), ("dev", "2.0"), ("qa", "3.0")) + ] + ) + assert len(candidate.variables) == 2 + + def test_three_independent_variables_are_refused(self) -> None: + """Three holes is a template, not a workflow seen three times. + + The two-step windows inside it still qualify — they only need two + variables — and that is the right outcome: the rule rejects the + over-general candidate, not every sequence containing it. + """ + found = steps_of( + mined( + *[ + [f"make deploy {a}", f"make tag {b}", f"make notify {c}"] + for a, b, c in ( + ("prod", "1.0", "x"), + ("dev", "2.0", "y"), + ("qa", "3.0", "z"), + ) + ] + ) + ) + assert not any(len(steps) == 3 for steps in found) + + +class TestNotTheSameSequence: + """Pairs mem must refuse to unify. The reason this can be trusted. + + Each case is two runs that pass every structural filter — same program, + same token count, same session shape, three separate days — and are still + two different things. + """ + + @pytest.mark.parametrize( + "first,second,third,reason", + [ + ("git push", "git pull", "git fetch", "the subcommand is the verb"), + ("make build", "make test", "make clean", "different targets"), + ("cd api", "cd web", "cd infra", "for two tokens the argument is all"), + ("npm test", "yarn test", "pnpm test", "a different program entirely"), + ( + "docker build --pull .", + "docker build --no-cache .", + "docker build --quiet .", + "the flag name is structure, not a value", + ), + ( + "terraform plan", + "terraform apply", + "terraform destroy", + "the next step is not the same step", + ), + ], + ) + def test_a_shared_shape_is_not_a_shared_intent( + self, first: str, second: str, third: str, reason: str + ) -> None: + assert ( + mined([first, "make check"], [second, "make check"], [third, "make check"]) + == [] + ), reason + + def test_a_privilege_prefix_shifts_the_protected_window(self) -> None: + """``sudo systemctl restart`` protects the verb, not the ``sudo``.""" + assert ( + mined( + *[ + [f"sudo systemctl {verb} nginx", "make check"] + for verb in ("restart", "reload", "stop") + ] + ) + == [] + ) + + def test_but_the_operand_after_it_may_still_vary(self) -> None: + (candidate,) = mined( + *[ + [f"sudo systemctl restart {unit}", "make check"] + for unit in ("nginx", "redis", "postgres") + ] + ) + assert candidate.steps[0].startswith("sudo systemctl restart $") + + def test_a_pipeline_is_never_generalised(self) -> None: + """mem does not parse shell, so it does not guess inside one.""" + assert ( + mined( + *[[f"docker ps | grep api-{n}", "make check"] for n in ("1", "2", "3")] + ) + == [] + ) + + def test_but_an_identical_pipeline_still_matches_itself(self) -> None: + (candidate,) = mined( + *[["docker ps | grep api", "make check"] for _ in range(3)] + ) + assert candidate.steps == ("docker ps | grep api", "make check") + + def test_two_sessions_are_never_spliced_together(self) -> None: + """The tail of one day and the head of the next are not a procedure. + + Both halves recur three times and sit next to each other in capture + order every single time, so the only thing stopping ``make package`` + → ``npm ci`` from being mined is the session boundary between them. + """ + runs = [] + for _ in range(3): + runs.append(["make build", "make package"]) + runs.append(["npm ci", "npm test"]) + found = steps_of(mined(*runs)) + assert ("make package", "npm ci") not in found + assert ("make build", "make package") in found + assert ("npm ci", "npm test") in found + + +class TestInterleavedNoise: + """Looking at things is not a step, and must not break the sequence.""" + + def test_inspection_commands_between_steps_are_skipped(self) -> None: + noisy = [ + "git status", + "make build", + "ls -la", + "cat Makefile", + "make test", + "pwd", + "./scripts/deploy.sh", + "git log", + ] + assert steps_of(mined(noisy, noisy, noisy)) == [tuple(DEPLOY)] + + @pytest.mark.parametrize( + "command", + ["ls", "cd ..", "git status", "git log --oneline", "cat notes.md", "clear"], + ) + def test_these_are_inspection(self, command: str) -> None: + assert promote.is_inspection(command) + + @pytest.mark.parametrize( + "command", + [ + "cat template.yaml > out.yaml", + "echo hi >> log", + "ls | wc -l", + "make build", + "git commit -m wip", + ], + ) + def test_these_are_not(self, command: str) -> None: + """Shell grammar disqualifies a command from being called noise. + + ``cat x`` looks; ``cat x > y`` writes a file, and dropping it would + remove a real step from the middle of a real procedure. + """ + assert not promote.is_inspection(command) + + def test_a_failed_command_is_not_a_step(self) -> None: + """A command that exited non-zero is not part of a working procedure.""" + commands: list[CapturedCommand] = [] + for index in range(3): + ts = NOW - (3 - index) * BETWEEN_SESSIONS + commands.append(cmd("make build", ts)) + commands.append(cmd("make tset", ts + 10, exit_code=2)) + commands.append(cmd("make test", ts + 20)) + commands.append(cmd("./scripts/deploy.sh", ts + 30)) + candidates = promote.dominant( + promote.rank(promote.closed(promote.mine(KEY, commands))) + ) + assert steps_of(candidates) == [tuple(DEPLOY)] + + def test_imported_commands_have_no_exit_code_and_are_kept(self) -> None: + """Absence of an exit code is not evidence of failure. + + ``mem import`` records none, and dropping those would make this + feature useless to the user who has just imported ten years of + history — the one with the most to gain from it. + """ + commands: list[CapturedCommand] = [] + for index in range(3): + ts = NOW - (3 - index) * BETWEEN_SESSIONS + for step in DEPLOY: + commands.append(cmd(step, ts, exit_code=None, duration_ms=None)) + ts += 30 + assert steps_of(top_of(commands)) == [tuple(DEPLOY)] + + def test_steps_far_apart_in_think_time_are_not_one_procedure(self) -> None: + """Removing noise must not invent adjacency across half an hour.""" + gap = promote.MAX_STEP_GAP_SECONDS + 60 + assert mined(DEPLOY, DEPLOY, DEPLOY, gap=gap) == [] + + def test_a_slow_step_is_not_penalised_for_its_own_runtime(self) -> None: + """The gap is think time, not wall clock — as in ``mem fix``. + + This is the case that made the raw-timestamp session rule untenable. + A ``docker build`` that takes twenty minutes is a slow command, not + twenty minutes of distraction, and measuring it as idle time cut every + deploy sequence in half at precisely its slowest step — which is to + say, cut exactly the sequences this feature exists to find. + """ + slow = promote.SESSION_IDLE_SECONDS * 4 + commands: list[CapturedCommand] = [] + for index in range(3): + ts = NOW - (3 - index) * BETWEEN_SESSIONS + commands.append(cmd("make build", ts)) + commands.append( + cmd("docker build .", ts + slow, duration_ms=(slow + 60) * 1000) + ) + assert steps_of(top_of(commands)) == [("make build", "docker build .")] + + def test_but_a_genuine_pause_of_the_same_length_does_end_the_session( + self, + ) -> None: + """The correction is to what is measured, not to the threshold.""" + slow = promote.SESSION_IDLE_SECONDS * 4 + commands: list[CapturedCommand] = [] + for index in range(3): + ts = NOW - (3 - index) * BETWEEN_SESSIONS + commands.append(cmd("make build", ts)) + commands.append(cmd("docker build .", ts + slow, duration_ms=100)) + assert top_of(commands) == [] + + +class TestSessions: + """Boundaries are re-derived from the history, not read from a file.""" + + def test_an_idle_gap_ends_a_session(self) -> None: + commands = [ + cmd("make build", NOW - 1000), + cmd("make test", NOW - 1000 + promote.SESSION_IDLE_SECONDS + 1), + ] + assert len(promote.split_sessions(commands)) == 2 + + def test_a_change_of_repository_ends_a_session(self) -> None: + commands = [ + cmd("make build", NOW - 100), + cmd("make test", NOW - 90, repo="/other"), + ] + assert len(promote.split_sessions(commands)) == 2 + + def test_an_explicit_session_id_wins_over_the_timing_heuristic(self) -> None: + commands = [ + cmd("make build", NOW - 100, session="a"), + cmd("make test", NOW - 95, session="b"), + ] + assert len(promote.split_sessions(commands)) == 2 + + def test_a_backwards_timestamp_starts_a_new_session(self) -> None: + """Two shells interleaving their lines look exactly like this.""" + commands = [cmd("make build", NOW - 50), cmd("make test", NOW - 100)] + assert len(promote.split_sessions(commands)) == 2 + + +class TestOverlappingCandidates: + """Every sub-sequence of a recurring sequence also recurs.""" + + LONG = ["make build", "make test", "make package", "./scripts/deploy.sh"] + + def test_a_sub_sequence_with_no_extra_evidence_is_dropped(self) -> None: + assert steps_of(mined(self.LONG, self.LONG, self.LONG)) == [tuple(self.LONG)] + + def test_a_sub_sequence_seen_more_often_survives_closure(self) -> None: + """Then it really is a more common workflow than its parent.""" + head = self.LONG[:2] + candidates = promote.closed( + promote.mine(KEY, history(self.LONG, self.LONG, self.LONG, head, head)) + ) + assert tuple(head) in steps_of(candidates) + assert tuple(self.LONG) in steps_of(candidates) + + def test_only_one_member_of_a_family_is_shown(self) -> None: + """...and it is the one worth the most, not the one seen the most.""" + head = self.LONG[:2] + shown = mined(self.LONG, self.LONG, self.LONG, head, head) + assert steps_of(shown) == [tuple(self.LONG)] + + def test_ranking_on_occurrences_alone_would_get_this_backwards(self) -> None: + """The measurement that justifies ranking on occurrences × length. + + A four-step procedure makes its own two-step head recur at least as + often as the whole, so an occurrence-first order puts the fragment + above the sequence it belongs to and the listing fills with pieces of + one workflow. Pinned as a test because a future contributor reaching + for "just sort by count" deserves to trip over it. + + On the calibration corpus this cost 8 points of workflow coverage in + the default listing: 88% with ``steps_saved``, 80% without. See + ADR-012. + """ + head = self.LONG[:2] + candidates = promote.closed( + promote.mine(KEY, history(self.LONG, self.LONG, self.LONG, head, head)) + ) + by_count = sorted(candidates, key=lambda c: -c.occurrences) + assert by_count[0].steps == tuple(head), "the fragment wins on count alone" + assert promote.rank(candidates)[0].steps == tuple(self.LONG) + + def test_a_shared_command_is_not_a_shared_family(self) -> None: + """Neither sequence contains the other, so both are real answers.""" + left = ["make build", "./deploy.sh"] + right = ["make build", "./publish.sh"] + shown = mined(left, left, left, right, right, right) + assert sorted(steps_of(shown)) == sorted([tuple(left), tuple(right)]) + + +class TestEmptyHistory: + """Nothing to say, said without inventing anything.""" + + def test_mining_nothing_is_nothing(self) -> None: + assert promote.mine(KEY, []) == [] + + def test_mining_an_empty_store_is_empty(self) -> None: + assert promote.mine_all() == [] + + def test_build_report_on_an_empty_store(self) -> None: + report = promote.build_report() + assert report.candidates == [] and report.names == [] + + def test_the_command_says_so_plainly(self) -> None: + assert "No repeated sequences" in run_promote() + + def test_the_json_payload_is_well_formed_not_an_error(self) -> None: + payload = json.loads(run_promote("--json")) + assert payload == {"count": 0, "candidates": []} + + def test_an_empty_command_line_is_not_a_step(self) -> None: + assert promote.is_inspection(" ") + + 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 + + +class TestCredentials: + """A secret must never become a stored runbook, and never be printed.""" + + SECRET = [ + "make build", + "curl -H 'Authorization: Bearer sk-ant-abcdefghijklmnopqrst' https://api", + "./scripts/deploy.sh", + ] + + def test_a_credential_shaped_step_flags_the_candidate(self) -> None: + (candidate,) = mined(self.SECRET, self.SECRET, self.SECRET) + assert candidate.has_credential + + def test_an_ordinary_candidate_is_not_flagged(self) -> None: + (candidate,) = mined(DEPLOY, DEPLOY, DEPLOY) + assert not candidate.has_credential + + def test_the_listing_redacts_the_secret(self) -> None: + write_history(history(self.SECRET, self.SECRET, self.SECRET)) + output = run_promote() + assert "sk-ant-abcdefghijklmnopqrst" not in output + assert "REDACTED" in output + + def test_the_json_payload_is_redacted_too(self) -> None: + write_history(history(self.SECRET, self.SECRET, self.SECRET)) + assert "sk-ant-abcdefghijklmnopqrst" not in run_promote("--json") + + def test_redaction_happens_in_the_payload_not_the_renderer(self) -> None: + """One choke point, so a new output format cannot leak by omission.""" + write_history(history(self.SECRET, self.SECRET, self.SECRET)) + payload = promote.report_payload(promote.build_report()) + assert "sk-ant-abcdefghijklmnopqrst" not in json.dumps(payload) + + def test_promoting_it_is_refused_outright(self, global_scope: Path) -> None: + write_history(history(self.SECRET, self.SECRET, self.SECRET)) + result = CliRunner().invoke(cli, ["promote", "1"], input="y\n") + assert result.exit_code != 0 + assert "credential-shaped" in result.output + assert not global_scope.exists() + + def test_there_is_no_flag_that_stores_it_anyway(self) -> None: + """A ``--force`` here would defeat the entire point of the check.""" + help_text = CliRunner().invoke(cli, ["promote", "--help"]).output + assert "--force" not in help_text + + def test_both_detectors_are_reused_not_reimplemented(self) -> None: + """``variables`` owns credential detection; this module only calls it.""" + source = Path(promote.__file__).read_text(encoding="utf-8") + assert "looks_like_credential" in source and "redact_secrets" in source + assert "BEGIN" not in source, "a second credential rule set has appeared" + + +class TestNothingIsWrittenWithoutConsent: + """The half of this feature that touches the disk.""" + + def test_listing_writes_nothing(self, global_scope: Path) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + run_promote() + assert not global_scope.exists() + + def test_declining_writes_nothing(self, global_scope: Path) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + output = run_promote("1", input="n\n") + assert "Nothing saved" in output + assert not global_scope.exists() + + def test_accepting_writes_the_group(self, global_scope: Path) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + run_promote("1", input="y\n") + saved = storage.read_group_file(global_scope) + (group,) = saved.groups.values() + assert [c.cmd for c in group.commands] == DEPLOY + assert group.description == "Promoted from 3 repeated runs" + + def test_the_stored_group_carries_the_variable(self, global_scope: Path) -> None: + """The template's ``$VAR`` must arrive as a real declaration. + + Otherwise ``mem run`` would treat it as literal text and the runbook + would deploy to a namespace called ``$NAMESPACE``. + """ + write_history( + history( + *[ + [f"helm upgrade api --namespace {ns}", "make smoke"] + for ns in ("prod", "staging", "dev") + ] + ) + ) + run_promote("1", input="y\n") + (group,) = storage.read_group_file(global_scope).groups.values() + assert group.commands[0].vars is not None + assert [v.name for v in group.commands[0].vars] == ["NAMESPACE"] + + def test_a_promoted_sequence_is_not_suggested_again( + self, global_scope: Path + ) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + run_promote("1", input="y\n") + assert "No repeated sequences" in run_promote() + + def test_the_module_cannot_execute_anything(self) -> None: + """Structural, not behavioural: there is no import that could. + + The same guard ``mem fix`` carries. A suggestion engine that can run + commands is one confirmation prompt away from being a hazard. + """ + source = Path(promote.__file__).read_text(encoding="utf-8") + for forbidden in ("subprocess", "os.system", "popen", "socket", "urllib"): + assert forbidden not in source, forbidden + + +class TestPromoteCommand: + """What the user actually sees.""" + + def test_it_reports_the_sequence_the_count_and_the_variable(self) -> None: + write_history( + history( + *[ + [f"git checkout {branch}", "make build", "./scripts/deploy.sh"] + for branch in ("main", "staging", "hotfix") + ] + ) + ) + output = run_promote() + assert "3 times" in output + assert "make build" in output + assert "./scripts/deploy.sh" in output + assert "$CHECKOUT_ARG" in output + assert "hotfix" in output + + def test_it_never_offers_to_run_anything(self) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + assert "runs nothing" in run_promote() + + def test_the_json_payload_carries_the_evidence(self) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + payload = json.loads(run_promote("--json")) + assert payload["count"] == 1 + (entry,) = payload["candidates"] + assert entry["index"] == 1 + assert entry["steps"] == DEPLOY + assert entry["occurrences"] == 3 + assert entry["confidence"] == "moderate" + assert entry["last_seen_iso"].endswith("Z") + assert entry["has_credential"] is False + + def test_the_limit_caps_the_listing(self) -> None: + left = ["make build", "./deploy.sh"] + right = ["npm ci", "npm run release"] + write_history(history(left, left, left, right, right, right)) + payload = json.loads(run_promote("--json", "-n", "1")) + assert payload["count"] == 1 + + def test_an_out_of_range_index_is_an_error_not_a_guess(self) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + result = CliRunner().invoke(cli, ["promote", "9"]) + assert result.exit_code != 0 + assert "No candidate 9" in result.output + + def test_the_name_can_be_overridden(self, global_scope: Path) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + run_promote("1", "--name", "ship-it", input="y\n") + assert "ship-it" in storage.read_group_file(global_scope).groups + + def test_a_bad_name_is_rejected_before_anything_is_written( + self, global_scope: Path + ) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + result = CliRunner().invoke(cli, ["promote", "1", "--name", "Ship It"]) + assert result.exit_code != 0 + assert not global_scope.exists() + + def test_a_name_already_in_use_is_refused(self, global_scope: Path) -> None: + write_history(history(DEPLOY, DEPLOY, DEPLOY)) + groups.save_command(global_scope, "echo hi", group_name="ship-it") + result = CliRunner().invoke(cli, ["promote", "1", "--name", "ship-it"]) + assert result.exit_code != 0 + assert "already exists" in result.output + + def test_the_suggested_name_comes_from_the_last_step(self) -> None: + candidate = promote.Candidate( + steps=("make build", "./scripts/deploy-staging.sh"), + variables=(), + occurrences=3, + first_seen=0, + last_seen=0, + repo=None, + has_credential=False, + shape=(), + ) + assert promote.suggest_name(candidate) == "deploy-staging" + + def test_a_suggested_name_never_collides(self) -> None: + candidate = promote.Candidate( + steps=("make build", "terraform apply"), + variables=(), + occurrences=3, + first_seen=0, + last_seen=0, + repo=None, + has_credential=False, + shape=(), + ) + assert promote.suggest_name(candidate) == "terraform-apply" + assert ( + promote.suggest_name(candidate, {"terraform-apply"}) == "terraform-apply-2" + ) + + def test_confidence_wording_tracks_the_count(self) -> None: + assert promote.confidence(1) == "weak" + assert promote.confidence(promote.MODERATE_EVIDENCE) == "moderate" + assert promote.confidence(promote.STRONG_EVIDENCE) == "strong" + + +class TestRichMarkupSafety: + """History is untrusted input; Rich reads square brackets as markup.""" + + BRACKETS = ["sed 's/[a-z]//' in.txt", "make build", "awk '{print $1}' out"] + + def test_bracket_syntax_in_a_command_survives_verbatim(self) -> None: + write_history(history(self.BRACKETS, self.BRACKETS, self.BRACKETS)) + assert "sed 's/[a-z]//' in.txt" in run_promote() + + def test_a_bare_closing_tag_does_not_raise(self) -> None: + odd = ["sed 's|[/]|-|'", "make build", "./deploy.sh"] + write_history(history(odd, odd, odd)) + assert "make build" in run_promote() + + def test_quoted_arguments_are_reassembled_exactly(self) -> None: + """shlex would drop the quotes and change what the command means. + + ``git commit -m "wip thing"`` comes back from ``shlex.split`` as four + tokens that rejoin into a five-word command line meaning something + else. The tokenizer keeps the quoted run whole so a template is the + original text with substrings replaced, not a reassembly. + """ + tokens = promote.tokenize('git commit -m "wip thing"') + assert [t.text for t in tokens] == ["git", "commit", "-m", '"wip thing"'] + runs = [['git commit -m "wip thing"', "git push"] for _ in range(3)] + (candidate,) = mined(*runs) + assert candidate.steps[0] == 'git commit -m "wip thing"' + + +class TestCalibration: + """The measurement the whole design rests on, pinned. + + Full numbers and corpus in ADR-012. On eight hand-designed 45-day + histories (~1,100 commands each, five planted workflows against ad-hoc + exploration), the default five-candidate listing scored **0 false + positives out of 40** and surfaced **88%** of the planted workflows. + + Removing the inspection filter took that to **80% false positives** — the + feature stops working entirely. That is the one result a future + contributor is most likely to undo by "simplifying", so it is pinned here + in miniature. + """ + + NOISY = [ + "git status", + "make build", + "ls -la", + "cat Makefile", + "git diff", + "make test", + "pwd", + "ls", + "./scripts/deploy.sh", + "git log", + ] + + def test_with_the_filter_the_workflow_is_the_answer(self) -> None: + assert steps_of(mined(self.NOISY, self.NOISY, self.NOISY)) == [tuple(DEPLOY)] + + def test_without_it_the_answer_is_buried_in_inspection( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setattr(promote, "is_inspection", lambda command: False) + top = mined(self.NOISY, self.NOISY, self.NOISY)[0] + assert top.steps != tuple(DEPLOY) + assert any(step in {"ls", "ls -la", "pwd", "git status"} for step in top.steps) + + def test_the_default_listing_is_five(self) -> None: + """Calibrated: recall of real workflows saturates there, FP is still 0. + + At eight the measured false-positive rate was 12.5%, and over the + whole mined list (about twelve candidates per history) it was 42%. + Ranking, not filtering, is what makes this output trustworthy — which + is exactly why the default limit is part of the design and not a + cosmetic choice. + """ + parameter = next(p for p in cli.commands["promote"].params if p.name == "limit") + assert parameter.default == 5 From 1799c28b86fcd8051da15884abf49d76614a7425 Mon Sep 17 00:00:00 2001 From: Matias Date: Tue, 4 Aug 2026 02:46:23 -0300 Subject: [PATCH 2/2] docs(promote): the corpus, the ablations, and the suggestion we know is bad MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ADR-012 records the calibration rather than asserting a rate: eight hand-designed 45-day histories, 0/40 false positives in the default listing, and the three ablations that set the thresholds — the inspection filter (0% -> 80% without it), MIN_OCCURRENCES (mined pool 97 -> 223 at two), and ranking by occurrences x length rather than occurrences (88% -> 80% workflow coverage). The README says out loud that mem will sometimes propose the commit dance. Someone will see it, recognise a poor runbook, and conclude the feature is broken; better they read that we already know why it happens and cannot tell from the outside. --- ARCHITECTURE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 3b48bdf..479408c 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -436,3 +436,4 @@ See `docs/decisions/` for detailed ADRs: - [009: Ranking Learns From What You Select](docs/decisions/009-ranking-learns-from-selections.md) - [010: The Keychain for Variable Values](docs/decisions/010-keychain-for-variable-values.md) - [011: A Concept Map, Not Embeddings](docs/decisions/011-concept-map-over-embeddings.md) +- [012: Promote Mines Sequences, and Ranking Is What Makes It Trustworthy](docs/decisions/012-promote-mines-sequences-not-commands.md)