diff --git a/README.md b/README.md index 6ef5e99..dc5d534 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,34 @@ mem deploy --json # machine-readable output 3 fly deploy api 3d ago ``` +### Ask in English + +You do not always remember the command. You remember what it was *for*. When a query matches nothing literally, mem re-reads it through a concept map — a dictionary from what people say to what they type — and answers with commands that share the meaning instead of the letters. + +```bash +mem "how do I see what's listening on a port" # -> lsof -i :8080 +mem "the command I used to fix the certificate" # -> openssl x509 -in cert.pem -noout -dates +mem "check disk space" # -> du -sh * | sort -h +``` + +This is a fallback, never a filter. A query that matches literally is answered literally, with the same results in the same order as before — type `openssl` and you get `openssl`, not everything tagged "certificate". Only when substring search finds nothing does the map get a turn, and a synonym that appears everywhere in your history is weighted down to nothing, so a broad entry cannot drag unrelated commands up. + +The map is a plain JSON file you can read, grep and correct. Copy it and make it yours: + +```bash +mem concepts > ~/.mem/concepts.json # then edit it +``` + +```json +{ + "certificate": ["openssl", "x509", "cert", "pem", "tls", "certbot"], + "port": ["lsof", "netstat", "listen", "port", "8080"], + "deploy": ["deploy", "kubectl apply", "fly deploy", "ansible-playbook"] +} +``` + +A concept you define replaces the shipped one of the same name; new concepts are added; everything else is untouched by upgrades. Keys starting with `_` are metadata — `_comment` for the comments JSON does not have, `_stopwords` for the filler words your language uses to ask a question (yours are added to the built-in English ones, so the map translates). A broken file prints a warning and mem falls back to the shipped map; it never stops searching. + ### Patterns mem automatically learns structural patterns from your history using on-device AI. No manual step needed — extraction runs in the background every 20 commands. @@ -562,6 +590,7 @@ beside them, is rebuilt from them, and is safe to delete: repos/ myapp.json # repo-scoped groups and saved commands _global.json # global groups and saved commands + concepts.json # your concept map, layered over the shipped one vars.json # persistent variable store (0600 permissions) agent.json # AI agent access flag (off unless you enabled it) agent-audit.jsonl # append-only record of every agent request diff --git a/docs/decisions/011-concept-map-over-embeddings.md b/docs/decisions/011-concept-map-over-embeddings.md new file mode 100644 index 0000000..dfcf286 --- /dev/null +++ b/docs/decisions/011-concept-map-over-embeddings.md @@ -0,0 +1,61 @@ +# ADR-011: A Hand-Written Concept Map, Not an Embedding and Not an LLM + +**Status**: Accepted +**Date**: 2026-08-04 + +## Context + +mem's search is substring matching: every word of the query must appear in the command. That is exactly right for the way the tool is used most of the time — `mem docker compose`, `mem kubectl apply` — and it is useless for the way people actually remember. Nobody recalls `openssl x509 -in cert.pem -noout -dates`. They recall *"the command I used to fix the certificate"*, and those two strings share no word at all. + +The gap was measured, not assumed. Ten questions phrased the way a person would ask them ("how do I see what's listening on a port", "the command I used to fix the certificate") were run against a real shell history, scoring recall@5 — is the right command in the first five results: + +| approach | recall@5 | latency | +|---|---|---| +| Substring search (what mem shipped) | **0/10** | 9.6 ms | +| Apple Foundation Models expanding the query | 2/10 | 2086 ms | +| Hybrid ranker, no synonyms | 2/10 | 2.4 ms | +| **Hybrid ranker + a ~30-line synonym map** | **8/10** | **3.9 ms** | + +Zero out of ten. Not a ranking problem — the correct answer was not in the result set at all, because it could not be. + +Two model-based approaches were tried against that baseline and both lost. + +**On-device LLM query expansion (2/10, 2086 ms).** Asking the Apple Foundation Model to expand the query costs two seconds — five hundred times the map, and roughly twenty times mem's *entire* interactive budget — for a quarter of the accuracy. It also has no grounding in the user's history and invents accordingly: asked about fixing a certificate it suggested `certutil /rebuild`, a **Windows** tool, on a macOS-only product. A wrong answer delivered confidently after a two-second pause is worse than no answer delivered instantly. + +**`NLContextualEmbedding` (0/5 top-1).** Apple's on-device sentence embedding scored zero on top-1 over five questions. The reason is structural, not a tuning failure: it is a natural-language BERT, and `lsof -i :8080` is not natural language. Shell commands are out of distribution — flags, punctuation, paths and binaries that never appear in the pretraining corpus. It maps "port" and "listening" close together happily; it has no idea `lsof` belongs anywhere near either. + +## Decision + +Ship a **curated concept map** at `src/mem/concepts.json`: ~200 entries from a natural-language concept to the shell vocabulary that expresses it, read through `importlib.resources` exactly like the shell hooks. + +```json +"certificate": ["openssl", "x509", "cert", "pem", "tls", "certbot", "acme"], +"port": ["lsof", "netstat", "listen", "port", "8080"], +"disk space": ["df ", "du ", "ncdu", "diskutil", "df -h", "du -sh"] +``` + +`~/.mem/concepts.json` layers over it: a concept defined there replaces the shipped one, new concepts are added, `_stopwords` are unioned so the map translates. A malformed user file warns on stderr and falls back; it never raises. + +Expansion is a **fallback, not a blend**. The literal pass runs first and unchanged; the map is consulted only when it returns nothing. Within the expanded pass a candidate must satisfy at least one concept *through a synonym*, and its score is scaled by idf-weighted coverage. + +## Why a dictionary beats an embedding here (the general form) + +An embedding is a compressed, lossy, unlabelled guess about a semantic space it was not trained on. A dictionary is 200 lines a developer can read in five minutes. For this problem the dictionary wins on every axis that matters: + +- **It is auditable.** When a query returns the wrong thing you can see *why*, in a file, with `grep`. The embedding's answer is a number. +- **It is fixable.** A wrong synonym is a one-line pull request. A wrong neighbourhood in an embedding is a research project. +- **It is deterministic.** The same query returns the same results forever — the same reason ADR-001 chose JSONL and ADR-003 chose no daemon. +- **It is translatable and contributable.** Concepts and stopwords are both data, so a Spanish speaker adds `"certificado"` and `"para"` without touching Python. +- **It costs nothing.** No model download, no memory, no runtime, no dependency, and nothing that could ever want the network (Principle I). +- **It is small enough to be right.** The vocabulary of a working shell is a few hundred concepts, not a distribution to be learned. This is a domain where the map genuinely fits on a page. + +The honest limit: a dictionary only knows what someone wrote down. That is a real cost, accepted below. + +## Consequences + +- **Curation is now a maintenance duty.** The map is data, and data rots quietly. `tests/test_concepts.py` enforces the curation rules that can be checked mechanically — every synonym must survive the search prefilter, no synonym may be a stopword, no duplicates, keys normalised — and pins recall@5 over a fixture history so the claim this feature rests on is verified rather than remembered. +- **A bad entry is inert, not harmful.** Expansion cannot demote, dilute or reorder anything the literal search returns, and idf weighting drives a synonym that matches half the candidates to a weight below 0.2. The worst a careless entry can do is waste a fallback that would otherwise have returned nothing. +- **A missing entry is silent.** The failure mode is a question with no answer, indistinguishable from a history that never contained one. `mem concepts > ~/.mem/concepts.json` is the escape hatch, and the reason the file is shipped as editable data rather than compiled into Python. +- **English until someone translates it.** The shipped stopwords are English question scaffolding. A user thinking in another language gets literal search until they add their own — which is a JSON edit, not a fork. +- **The fallback path is slower than the literal one**, because it cannot use the AND prefilter: measured at ~60 ms against 20k commands, versus ~11 ms for a literal query. It only runs for queries that would otherwise have returned nothing, so nobody waits for it in the common case — and it is still 30× faster than the LLM that scored a quarter as well. +- **This does not close the door on the model.** It sets the bar. Any future semantic search has to beat 8/10 at 3.9 ms, on device, with an answer a user can inspect. As with ADR-008: this is arithmetic, not optimism. diff --git a/src/mem/cli.py b/src/mem/cli.py index 1e0a6c7..62b8a27 100644 --- a/src/mem/cli.py +++ b/src/mem/cli.py @@ -20,6 +20,7 @@ from rich.text import Text from mem import __version__ +from mem import concepts as mem_concepts from mem.capture import get_git_repo from mem.history import SUPPORTED_SHELLS as IMPORTABLE_SHELLS from mem.history import ImportPlan @@ -201,6 +202,27 @@ def init(shell: str) -> None: click.echo(read_hook(shell)) +@cli.command() +def concepts() -> None: + """Print the concept map that turns questions into shell vocabulary. + + ``mem concepts > ~/.mem/concepts.json`` is the whole customisation story: + the file mem reads is the file it just printed, so editing it needs no + schema, no rebuild and no restart. That is the point of a dictionary over + an embedding — you can see it, and you can fix it. + + Read through ``importlib.resources`` like the shell hooks, for the same + reason: a path walked up from ``__file__`` exists in a checkout and not in + a wheel. + """ + click.echo( + resources.files("mem") + .joinpath(mem_concepts.CONCEPTS_FILENAME) + .read_text(encoding="utf-8"), + nl=False, + ) + + @cli.command( context_settings={"ignore_unknown_options": True, "allow_extra_args": True}, ) diff --git a/src/mem/concepts.json b/src/mem/concepts.json new file mode 100644 index 0000000..3245582 --- /dev/null +++ b/src/mem/concepts.json @@ -0,0 +1,269 @@ +{ + "_comment": "mem's concept map: what a person SAYS -> what they TYPED. Keys are natural language, values are the shell vocabulary that expresses the concept. JSON has no comments, so keys starting with '_' are reserved: '_comment' is ignored and '_stopwords' lists the question scaffolding that carries no shell meaning. Copy this file to ~/.mem/concepts.json to override or extend it: a concept you define there replaces the one shipped here, new concepts are added, and your '_stopwords' are added to these. Curation rule: every value must contain a run of at least two characters that survives JSON encoding (a test enforces it), and a wrong synonym is worse than a missing one - it pollutes a concept that would otherwise have worked.", + + "_stopwords": [ + "a", "about", "after", "again", "all", "also", "am", "an", "and", "any", + "anything", "are", "as", "at", "back", "be", "because", "been", "before", + "being", "but", "by", "can", "cmd", "command", "commands", "could", "did", + "didn't", "do", "does", "doesn't", "doing", "don't", "done", "each", + "figure", "for", "from", "get", "had", "has", "have", "here", "how", + "how's", "i", "i'm", "if", "im", "in", "into", "is", "it", "it's", "its", + "just", "know", "like", "look", "me", "mine", "more", "most", "my", "need", + "needed", "of", "on", "one", "only", "or", "our", "out", "over", "please", + "remember", "same", "see", "should", "so", "some", "something", "stuff", + "such", "tell", "than", "that", "that's", "the", "their", "them", "then", + "there", "there's", "these", "they", "thing", "things", "this", "those", + "through", "to", "use", "used", "using", "want", "wanted", "was", "way", + "we", "were", "what", "what's", "whats", "when", "where", "while", + "who", "whose", "why", "will", "with", "wondering", "would", "you", "your" + ], + + "certificate": ["openssl", "x509", "cert", "pem", "crt", "tls", "ssl", "certbot", "acme", "letsencrypt", "keytool"], + "expired": ["-dates", "notafter", "expiry", "renew", "certbot renew"], + "private key": ["openssl", "pkey", "id_rsa", "id_ed25519", ".key", "keygen"], + "public key": ["id_rsa.pub", "authorized_keys", "ssh-keygen", "gpg --export"], + "fingerprint": ["ssh-keygen -l", "sha256", "md5", "gpg --fingerprint"], + "self signed": ["openssl req", "-x509", "-nodes", "-newkey"], + "keychain": ["security", "keychain", "add-generic-password", "codesign"], + "encrypt": ["openssl enc", "gpg", "age ", "cipher", "encrypt"], + "decrypt": ["openssl enc -d", "gpg -d", "decrypt", "--decrypt"], + + "port": ["lsof", "netstat", "listen", "port", "8080"], + "listening": ["lsof -i", "netstat -an", "ss -tulpn", "listen", "bind"], + "ip address": ["ifconfig", "ipconfig", "ip addr", "ifconfig.me", "hostname"], + "dns": ["dig", "nslookup", "resolv.conf", "dscacheutil", "scutil --dns"], + "ping": ["ping", "traceroute", "mtr ", "nc -z"], + "download": ["curl -O", "curl -L", "wget", "scp", "aria2c", "yt-dlp"], + "upload": ["curl -F", "curl -T", "scp", "rsync", "aws s3 cp"], + "http request": ["curl", "wget", "httpie", "--request"], + "headers": ["curl -I", "curl -H", "--head", "user-agent"], + "proxy": ["http_proxy", "https_proxy", "socks", "ssh -D", "mitmproxy", "ngrok"], + "firewall": ["pfctl", "iptables", "ufw ", "socketfilterfw"], + "tunnel": ["ssh -L", "ssh -R", "ssh -N", "ngrok", "cloudflared", "wireguard"], + "port forward": ["ssh -L", "kubectl port-forward", "docker run -p"], + "port forwarding": ["ssh -L", "kubectl port-forward", "docker run -p"], + "ssh": ["ssh", "scp", "sftp", "ssh-copy-id", "ssh-add", "known_hosts", "ssh-keygen"], + "wifi": ["airport", "networksetup", "wdutil", "ifconfig en0"], + "network": ["curl", "netstat", "ifconfig", "ping", "dig", "nc "], + "hosts file": ["/etc/hosts", "hostname", "dscacheutil"], + "speed": ["speedtest", "iperf", "time ", "hyperfine"], + + "commit": ["git commit", "git commit -m", "amend", "git ci"], + "branch": ["git branch", "git checkout", "git switch", "checkout -b"], + "merge": ["git merge", "git rebase", "git pull", "--no-ff", "mergetool"], + "rebase": ["git rebase", "rebase -i", "--onto", "--continue"], + "stash": ["git stash", "stash pop", "stash list", "stash apply"], + "undo": ["git reset", "git revert", "git restore", "checkout --", "--hard", "reflog"], + "revert": ["git revert", "git reset", "git restore", "--hard"], + "amend": ["git commit --amend", "--no-edit", "rebase -i"], + "remote": ["git remote", "origin", "upstream", "git push", "git fetch"], + "clone": ["git clone", "--depth", "git submodule", "gh repo clone"], + "tag": ["git tag", "git push --tags", "describe"], + "blame": ["git blame", "git log -p", "git log -S", "pickaxe"], + "cherry pick": ["git cherry-pick", "git rebase", "--continue"], + "submodule": ["git submodule", "--recursive", ".gitmodules"], + "conflict": ["git merge", "mergetool", "--ours", "--theirs", "rebase --continue"], + "gitignore": [".gitignore", "git rm --cached", "git check-ignore"], + "pull request": ["gh pr", "git push -u", "--set-upstream", "hub pull-request"], + "history": ["git log", "--oneline", "--graph", "reflog", "history"], + "staged": ["git diff --cached", "git add", "restore --staged", "git status"], + "version control": ["git ", "hg ", "svn ", "jj "], + + "container": ["docker", "podman", "containerd", "nerdctl", "docker ps"], + "image": ["docker build", "docker images", "docker pull", "docker push", "Dockerfile", "buildx"], + "build image": ["docker build", "buildx", "podman build", "Dockerfile"], + "compose": ["docker compose", "docker-compose", "compose.yml", "docker-compose.yml"], + "exec into": ["docker exec", "kubectl exec", "docker run -it", "/bin/bash", "/bin/sh"], + "volume": ["docker volume", "--mount", "bind mount", "pvc"], + "registry": ["docker push", "docker login", "ghcr.io", "ecr", "docker tag"], + "prune": ["docker system prune", "docker image prune", "--volumes", "docker rm"], + + "pod": ["kubectl", "kubectl get pods", "k9s", "kubectl describe pod"], + "deployment": ["kubectl", "deploy", "rollout", "kubectl apply", "helm upgrade"], + "namespace": ["kubectl", "--namespace", "kubens"], + "cluster": ["kubectl", "kubeconfig", "kubectx", "eksctl", "minikube", "kind "], + "rollout": ["kubectl rollout", "restart", "undo", "status"], + "secret": ["kubectl get secret", "sealed-secrets", "vault", "sops", "secretsmanager"], + "configmap": ["kubectl", "configmap", "kubectl apply", "-o yaml"], + "helm": ["helm", "chart", "values.yaml", "helm upgrade", "helm repo"], + "ingress": ["kubectl", "ingress", "nginx", "traefik", "istio"], + "manifest": ["kubectl apply", "apply -f", "kustomize", "yaml"], + + "service": ["systemctl", "launchctl", "brew services", "service ", "systemd"], + "daemon": ["launchctl", "systemctl", "launchd", "plist", "nohup"], + "restart": ["restart", "systemctl restart", "brew services restart", "kickstart", "reboot"], + "start": ["start", "systemctl start", "brew services start", "up -d", "launchctl load", "run "], + "stop": ["stop", "systemctl stop", "kill", "brew services stop", "down", "launchctl unload"], + "enable": ["--enable", "systemctl enable", "launchctl load", "defaults write"], + "status": ["status", "systemctl status", "git status", "ps ", "launchctl list"], + + "process": ["ps ", "top", "htop", "pgrep", "kill", "pidof"], + "kill": ["kill", "pkill", "killall", "kill -9", "docker stop"], + "running": ["ps aux", "pgrep", "top", "docker ps", "kubectl get pods", "jobs"], + "cpu": ["top", "htop", "ps aux", "uptime", "hw.ncpu", "time "], + "memory": ["top", "htop", "vm_stat", "free ", "ps aux", "leaks"], + "background": ["nohup", "screen", "tmux", "disown", "jobs", "bg "], + "pid": ["ps ", "pgrep", "lsof -p", "kill", "pidof"], + + "disk space": ["df ", "du ", "ncdu", "diskutil", "df -h", "du -sh"], + "file size": ["du -sh", "ls -lh", "stat", "wc -c", "-size"], + "largest files": ["du -sh", "sort -h", "ncdu", "-size", "ls -S"], + "mount": ["mount", "diskutil", "umount", "hdiutil", "sshfs"], + "format disk": ["diskutil", "mkfs", "newfs", "dd if="], + "usb": ["diskutil list", "dd if=", "hdiutil", "SPUSBDataType"], + + "list files": ["ls ", "ls -la", "find", "tree", "fd ", "eza"], + "hidden files": ["ls -a", "ls -la", "AppleShowAllFiles"], + "find file": ["find", "fd ", "locate", "mdfind", "which", "ls -R"], + "rename": ["mv ", "rename", "git mv"], + "copy": ["cp ", "rsync", "scp", "cp -r", "ditto"], + "move": ["mv ", "rsync", "git mv"], + "delete": ["rm ", "rm -rf", "rmdir", "unlink", "trash", "git rm", "-delete"], + "symlink": ["ln -s", "readlink", "unlink", "stow"], + "permissions": ["chmod", "chown", "ls -l", "umask", "chgrp", "755", "644", "xattr"], + "owner": ["chown", "ls -l", "stat", "id ", "whoami"], + "executable": ["chmod +x", "which", "file ", "PATH", "install "], + "directory": ["mkdir", "cd ", "rmdir", "pwd", "ls ", "tree"], + "create folder": ["mkdir", "mkdir -p", "install -d"], + "temp file": ["mktemp", "/tmp", "TMPDIR"], + "watch file": ["tail -f", "watch ", "fswatch", "entr", "inotifywait"], + + "archive": ["tar ", "zip", "gzip", "7z ", "unzip", "tar -czf"], + "extract": ["tar -xzf", "unzip", "gunzip", "7z x", "tar xvf", "bsdtar"], + "compress": ["tar -czf", "zip -r", "gzip", "zstd", "xz "], + + "search text": ["grep", "rg ", "ag ", "ack", "grep -r", "git grep"], + "replace text": ["sed", "sed -i", "perl -pi", "--replace", "tr "], + "sort": ["sort", "sort -u", "sort -n", "uniq", "sort_by"], + "count": ["wc -l", "grep -c", "uniq -c", "wc ", "uniq"], + "columns": ["awk", "cut ", "column -t", "paste", "tr "], + "json": ["jq", "json.tool", "json", "yq"], + "yaml": ["yq", "yaml", "-o yaml"], + "csv": ["csvkit", "awk -F,", "cut -d,", "mlr "], + "diff": ["diff", "git diff", "delta", "vimdiff", "colordiff", "cmp"], + "patch": ["patch", "git apply", "format-patch", "diff -u"], + "base64": ["base64", "openssl base64", "--decode"], + "checksum": ["shasum", "sha256sum", "md5", "md5sum", "cksum"], + "encoding": ["iconv", "file -I", "uconv", "LANG=", "LC_ALL"], + "line endings": ["dos2unix", "tr -d", "sed -i", "file "], + + "logs": ["log ", "tail", "journalctl", "docker logs", "kubectl logs", ".log", "less"], + "tail logs": ["tail -f", "docker logs -f", "kubectl logs -f", "journalctl -f", "log stream"], + "system log": ["log show", "log stream", "journalctl", "dmesg", "/var/log"], + "crash": ["log show", "crashreporter", "dmesg", "lldb", "gdb"], + + "environment variable": ["export", "env ", "printenv", "setenv", "PATH", ".env", "direnv"], + "path": ["PATH", "export PATH", "which", "whereis", "type ", "hash -r"], + "alias": ["alias", "unalias", ".zshrc", ".bashrc", "function "], + "shell config": [".zshrc", ".bashrc", ".profile", ".zprofile", "source ", "chsh"], + "reload shell": ["source ~/.zshrc", "exec $SHELL", "source "], + "which command": ["which", "type ", "command -v", "whereis"], + "sudo": ["sudo", "doas", "visudo", "sudoers"], + "cron": ["crontab", "cron", "launchd", "at ", "timer"], + "schedule": ["crontab", "at ", "launchctl", "sleep ", "systemd-run"], + "exit code": ["echo $?", "exit ", "set -e", "status"], + "terminal multiplexer": ["tmux", "screen", "zellij", "attach"], + "clipboard": ["pbcopy", "pbpaste", "xclip"], + "repeat": ["watch ", "for ", "while ", "xargs", "seq "], + "benchmark": ["time ", "hyperfine", "ab -", "wrk ", "perf "], + + "install package": ["brew install", "apt install", "pip install", "npm install", "cargo install"], + "uninstall": ["brew uninstall", "pip uninstall", "npm uninstall", "apt remove", "rm -rf"], + "update packages": ["brew upgrade", "brew update", "apt upgrade", "pip install -U", "npm update"], + "search package": ["brew search", "apt search", "npm search", "cargo search"], + "homebrew": ["brew", "brew install", "Brewfile", "brew services", "tap "], + "dependency": ["pip install", "npm install", "requirements.txt", "package.json", "Cargo.toml", "go mod", "poetry", "uv "], + "lockfile": ["package-lock.json", "poetry.lock", "Cargo.lock", "uv.lock", "yarn.lock", "pnpm-lock"], + + "virtualenv": ["venv", "virtualenv", "conda", "activate", "poetry", "uv venv", ".venv"], + "python": ["python", "python3", "pip ", "pytest", "uv ", "poetry", ".py"], + "pip install": ["pip install", "pip3", "uv pip", "requirements.txt"], + "notebook": ["jupyter", "ipython", "nbconvert", ".ipynb"], + "test": ["pytest", "npm test", "cargo test", "go test", "make test", "unittest", "jest"], + "coverage": ["--cov", "coverage", "nyc ", "tarpaulin", "-cover"], + "lint": ["ruff", "flake8", "eslint", "clippy", "pylint", "golangci-lint", "shellcheck"], + "format code": ["ruff format", "black", "prettier", "gofmt", "rustfmt", "clang-format"], + "type check": ["mypy", "pyright", "tsc "], + + "node": ["node", "npm", "npx", "nvm", "yarn", "pnpm", "package.json"], + "run script": ["npm run", "yarn ", "pnpm ", "make ", "just ", "task "], + "dev server": ["npm run dev", "vite", "next dev", "http.server", "serve", "runserver"], + "build": ["npm run build", "make", "cargo build", "go build", "docker build", "xcodebuild"], + "bundle": ["webpack", "vite build", "esbuild", "rollup", "parcel"], + "typescript": ["tsc ", "ts-node", "tsx ", "tsconfig.json"], + + "rust": ["cargo", "rustc", "rustup", "clippy", "Cargo.toml"], + "go": ["go build", "go run", "go test", "go mod", "gofmt"], + "compile": ["gcc", "clang", "make", "cargo build", "go build", "cmake", "javac"], + "debugger": ["lldb", "gdb", "pdb", "delve", "--inspect", "breakpoint"], + "profile": ["perf ", "py-spy", "instruments", "pprof", "flamegraph", "sample "], + + "database": ["psql", "mysql", "sqlite3", "redis-cli", "mongosh", "pgcli", "duckdb", "pg_dump", "mysqldump"], + "postgres": ["psql", "pg_dump", "pg_restore", "postgres", "createdb", "pgcli", "pg_ctl"], + "mysql": ["mysql", "mysqldump", "mariadb", "my.cnf"], + "redis": ["redis-cli", "redis-server", "FLUSHALL", "KEYS "], + "sqlite": ["sqlite3", ".db", ".sqlite", ".schema"], + "mongo": ["mongosh", "mongo ", "mongodump", "mongorestore"], + "dump database": ["pg_dump", "mysqldump", "mongodump", ".dump", "backup"], + "restore database": ["pg_restore", "psql <", "mysql <", "mongorestore"], + "migration": ["alembic", "migrate", "flyway", "prisma migrate", "db:migrate", "diesel"], + "query": ["psql -c", "mysql -e", "SELECT", "jq ", "kubectl get"], + + "aws": ["aws ", "s3 ", "ec2", "aws-vault", "eksctl", "sam ", "cdk "], + "s3": ["aws s3", "s3 cp", "s3 sync", "s3api", "minio"], + "cloud": ["aws ", "gcloud", "az ", "fly ", "heroku", "doctl", "terraform"], + "gcp": ["gcloud", "gsutil", "bq ", "kubectl"], + "terraform": ["terraform", "tofu", "tfstate", "terraform plan", "terraform apply"], + "infrastructure": ["terraform", "ansible", "pulumi", "cloudformation", "helm"], + "deploy": ["deploy", "kubectl apply", "fly deploy", "heroku", "ansible-playbook", "rsync", "vercel"], + "credentials": ["aws configure", "gcloud auth", "docker login", "vault", "keychain", ".aws"], + "authenticate": ["login", "auth", "gh auth", "aws sso", "token", "ssh-add"], + + "macos": ["defaults", "brew", "launchctl", "osascript", "sw_vers", "softwareupdate"], + "open app": ["open ", "open -a", "osascript", "shortcuts run"], + "spotlight": ["mdfind", "mdls", "mdutil"], + "quarantine": ["xattr", "spctl", "com.apple.quarantine", "codesign"], + "code sign": ["codesign", "notarytool", "spctl", "security", "xcrun"], + "screenshot": ["screencapture", "sips"], + "image resize": ["sips", "convert ", "magick", "ffmpeg"], + "video": ["ffmpeg", "ffprobe", "yt-dlp", "HandBrakeCLI"], + "audio": ["ffmpeg", "afplay", "sox ", "say "], + "xcode": ["xcodebuild", "xcrun", "simctl", "swift ", "pod install"], + "simulator": ["simctl", "xcrun simctl", "Simulator"], + + "editor": ["vim", "nvim", "nano", "code ", "emacs", "EDITOR", "zed "], + "vim": ["vim", "nvim", ".vimrc", "init.lua"], + + "reboot": ["reboot", "shutdown", "halt"], + "uptime": ["uptime", "who ", "last ", "kern.boottime"], + "user": ["whoami", "id ", "useradd", "dscl", "passwd", "sudo -u"], + "hostname": ["hostname", "scutil --set", "uname -n"], + "system info": ["uname -a", "sw_vers", "system_profiler", "neofetch", "sysctl"], + "version": ["--version", "sw_vers", "uname -r"], + "help": ["--help", "man ", "tldr", "info "], + "documentation": ["man ", "tldr", "--help", "cheat.sh"], + + "generate": ["openssl rand", "uuidgen", "ssh-keygen", "generate"], + "random": ["openssl rand", "uuidgen", "shuf", "RANDOM"], + "date": ["date", "date +", "gdate", "TZ="], + "timestamp": ["date +%s", "date -r", "stat", "touch -t"], + "sleep": ["sleep", "wait", "timeout"], + "timeout": ["timeout", "--timeout", "gtimeout"], + "retry": ["until ", "while ", "--retry", "curl --retry"], + "parallel": ["xargs -P", "parallel", "make -j"], + + "backup": ["rsync", "tar -czf", "cp -a", "tmutil", "restic", "borg", "pg_dump"], + "sync files": ["rsync", "unison", "s3 sync", "rclone", "scp -r"], + "wipe": ["rm -rf", "shred", "srm ", "eraseDisk", "git clean"], + "clean": ["make clean", "cargo clean", "git clean", "docker system prune", "node_modules"], + + "fix": ["--fix", "repair", "rebuild", "reinstall", "fix"], + "reset": ["reset", "git reset", "--hard", "reinstall", "defaults delete"], + "verify": ["verify", "--check", "shasum -c", "codesign -v", "openssl verify"], + "trace": ["dtruss", "strace", "ltrace", "traceroute", "--trace", "set -x"], + "verbose": ["-vvv", "--verbose", "--debug", "set -x"], + "dry run": ["--dry-run", "--check", "plan", "--diff"], + "force": ["--force", "--yes", "--no-confirm", "-rf"], + "recursive": ["--recursive", "-rf", "find", "cp -r"], + "quiet": ["--quiet", "--silent", "/dev/null"] +} diff --git a/src/mem/concepts.py b/src/mem/concepts.py new file mode 100644 index 0000000..3110989 --- /dev/null +++ b/src/mem/concepts.py @@ -0,0 +1,334 @@ +"""The concept map: what a person *says*, mapped to what they *typed*. + +Shell history is written in one vocabulary and remembered in another. Nobody +types ``openssl x509 -in cert.pem -noout -dates`` and later recalls it as +"openssl x509"; they recall it as *"the command I used to check the +certificate"*. Substring search cannot bridge those two vocabularies, and +measured on ten such questions against a real history it finds nothing at all +— recall@5 of 0/10. + +The bridge is this module: a curated dictionary from a natural-language +concept to the shell vocabulary that expresses it. It is ~200 lines of JSON +that anyone can read, grep, edit, translate and send as a pull request. + +Why a dictionary rather than a model, in one paragraph: the alternatives were +measured. Asking the on-device Apple Foundation Model to expand the query +scored 2/10 at 2086 ms per query and hallucinated ``certutil /rebuild`` — a +*Windows* tool — for the certificate question. Apple's ``NLContextualEmbedding`` +scored 0/5 on top-1, because a natural-language BERT has never seen +``lsof -i :8080`` and shell commands are simply out of its distribution. The +dictionary scores 8/10 in 3.9 ms: four times the accuracy, five hundred times +the speed, and unlike either model it can be *fixed* when it is wrong. See +``docs/decisions/011-concept-map-over-embeddings.md``. + +Everything here is standard library only and free of Pydantic, for the same +reason :mod:`mem.ranking` is: the interactive finder's entire first-frame +budget is smaller than Pydantic's import. +""" + +from __future__ import annotations + +import json +import sys +from dataclasses import dataclass +from importlib import resources +from pathlib import Path + +# The shipped map lives beside this module and is read through +# ``importlib.resources``, exactly like ``mem/hooks/mem.zsh`` — the one +# resolution that works identically for an editable checkout, a wheel and a +# zipimport. A previous version of the hook loader walked ``__file__`` upwards +# instead, and shipped a stale copy to every pip user for four months. +CONCEPTS_FILENAME = "concepts.json" + +# A user map lives here. Not a *replacement* for the shipped file — a layer +# over it, so an upgrade still delivers new concepts to someone who added one. +USER_CONCEPTS_FILENAME = "concepts.json" + +# Keys starting with an underscore are metadata, not concepts. JSON has no +# comment syntax, and a map meant to be read and edited by hand needs one. +_RESERVED_PREFIX = "_" +_STOPWORDS_KEY = "_stopwords" + +# The longest concept key, in words. Multi-word keys ("disk space", "pull +# request") are matched against consecutive query words, longest first, so +# "disk space" never decays into "disk" AND "space". +MAX_CONCEPT_WORDS = 3 + + +@dataclass(frozen=True) +class ConceptData: + """The loaded map: concepts, plus the words that are not concepts. + + Stopwords ship *in the same JSON file* rather than as a Python constant + on purpose. They are the question scaffolding — "how do I", "the command + I used to" — that carries no shell meaning, and which words those are + depends on the language the user thinks in. A Spanish speaker who adds + ``"certificado"`` to their own map needs ``"para"`` dropped just as much + as an English one needs ``"the"``. Both live in a file they can edit. + """ + + concepts: dict[str, tuple[str, ...]] + stopwords: frozenset[str] + + @property + def max_words(self) -> int: + """Longest concept key in words, for the phrase scan. At least 1.""" + return max((len(k.split()) for k in self.concepts), default=1) + + +@dataclass(frozen=True) +class QueryGroup: + """One unit of query meaning: the words typed, plus what they can mean. + + A group is satisfied *literally* when the user's own words appear in the + command, and *by expansion* when one of the concept's synonyms does. The + distinction is the whole point — it is what keeps someone who typed + ``openssl`` from being served everything merely tagged "certificate". + """ + + text: str + words: tuple[str, ...] + expansions: tuple[str, ...] + + def literal_hit(self, lowered_command: str) -> bool: + """True when every word the user typed appears in the command. + + Every word, not the phrase verbatim: a two-word group is exactly the + conjunction ``search()`` already applies to two separate terms, so + folding "disk space" into one group can never match less than the + unfolded query would have. + """ + return all(word in lowered_command for word in self.words) + + def matched_expansions(self, lowered_command: str) -> tuple[str, ...]: + """The synonyms of this concept that appear in the command.""" + return tuple(e for e in self.expansions if e in lowered_command) + + def variants(self) -> tuple[str, ...]: + """Every string that can satisfy this group, for prefiltering. + + The literal words are included: a command matching the query without + any help from the concept map must still survive the prefilter, or + expansion would have *removed* a result instead of adding one. + """ + return self.words + self.expansions + + +# Loading is cached on (path, mtime, size) rather than done once per process: +# `mem` is a short-lived CLI, but the MCP server and the test suite both live +# long enough to edit ~/.mem/concepts.json underneath a running process, and a +# map that needs a restart to take effect is not the editable file this +# feature is selling. +_cache: dict[tuple[object, ...], ConceptData] = {} + + +def clear_cache() -> None: + """Drop the memoised maps. For tests, and for anything that rewrites the map.""" + _cache.clear() + + +def load(user_path: Path | None = None) -> ConceptData: + """Load the shipped concept map, layered with the user's if present. + + Layering rules, chosen so that upgrading mem never silently discards a + user's edits *or* withholds new concepts from them: + + - a concept defined in the user file **replaces** the shipped one of the + same name, so a synonym list can be corrected rather than only added to; + - concepts the user does not mention are kept; + - ``_stopwords`` are **unioned**, because a second language's function + words are additional to English's, not instead of them. + + A malformed user file is a warning and a fallback to the shipped map, never + an exception: the search command must not stop working because a hand-edited + JSON file is missing a comma. + """ + stat = None + if user_path is not None: + try: + info = user_path.stat() + stat = (info.st_mtime_ns, info.st_size) + except OSError: + stat = None # No user file (the common case), or unreadable. + + key = (str(user_path) if user_path else None, stat) + cached = _cache.get(key) + if cached is not None: + return cached + + data = _load_shipped() + if stat is not None and user_path is not None: + data = _layer_user_map(data, user_path) + + _cache[key] = data + return data + + +def _load_shipped() -> ConceptData: + """Read ``mem/concepts.json`` out of the installed package.""" + try: + raw = ( + resources.files("mem") + .joinpath(CONCEPTS_FILENAME) + .read_text(encoding="utf-8") + ) + parsed = _parse(json.loads(raw)) + except Exception as exc: # noqa: BLE001 - a packaging fault, not a user one + # Unreachable through any supported install; a broken shipped map must + # still degrade to plain literal search rather than break `mem `. + _warn(f"built-in concept map could not be read ({exc}); expansion is off") + return ConceptData(concepts={}, stopwords=frozenset()) + if parsed is None: + _warn("built-in concept map is malformed; expansion is off") + return ConceptData(concepts={}, stopwords=frozenset()) + return parsed + + +def _layer_user_map(shipped: ConceptData, path: Path) -> ConceptData: + """Merge ``~/.mem/concepts.json`` over the shipped map, or warn and skip.""" + try: + raw = path.read_text(encoding="utf-8") + except OSError as exc: + _warn(f"could not read {path} ({exc}); using the built-in concept map") + return shipped + + try: + loaded = json.loads(raw) + except json.JSONDecodeError as exc: + _warn( + f"{path} is not valid JSON (line {exc.lineno}: {exc.msg}); " + "using the built-in concept map instead" + ) + return shipped + + user = _parse(loaded) + if user is None: + _warn( + f"{path} is not a concept map " + '(expected {"concept": ["command", ...]}); ' + "using the built-in concept map instead" + ) + return shipped + + concepts = dict(shipped.concepts) + concepts.update(user.concepts) + return ConceptData( + concepts=concepts, + stopwords=shipped.stopwords | user.stopwords, + ) + + +def _parse(loaded: object) -> ConceptData | None: + """Validate and normalise a decoded JSON document, or return None. + + Returning ``None`` rather than raising keeps the caller's fallback path + (warn, use the shipped map) the same for every kind of malformation. + """ + if not isinstance(loaded, dict): + return None + + concepts: dict[str, tuple[str, ...]] = {} + stopwords: set[str] = set() + + for key, value in loaded.items(): + if key.startswith(_RESERVED_PREFIX): + if key == _STOPWORDS_KEY: + words = _string_list(value) + if words is None: + return None + # Stopwords are compared against whitespace-split query terms, + # so unlike a synonym they can never contain a space. + stopwords.update(word.strip() for word in words) + continue # Any other `_key` is a comment. + + entries = _string_list(value) + if entries is None: + return None + concept = " ".join(key.lower().split()) + if not concept or len(concept.split()) > MAX_CONCEPT_WORDS: + continue + # A synonym equal to the concept itself is already covered by the + # literal test, and counting it twice would let a concept vouch for + # itself as if the map had contributed something. + seen = {concept} + kept = [] + for entry in entries: + if entry and entry not in seen: + seen.add(entry) + kept.append(entry) + if kept: + concepts[concept] = tuple(kept) + + return ConceptData(concepts=concepts, stopwords=frozenset(stopwords)) + + +def _string_list(value: object) -> list[str] | None: + """Lowercase a JSON array of strings, or None if it is not one. + + Whitespace is *not* stripped. A trailing space is how the map says "the + word, not the prefix": ``"ps "`` must not match ``https``, ``"rm "`` must + not match ``chrome``, and stripping them would have quietly turned two + dozen precise synonyms into vague ones. + """ + if not isinstance(value, list): + return None + out: list[str] = [] + for item in value: + if not isinstance(item, str): + return None + if item.strip(): + out.append(item.lower()) + return out + + +def expand(terms: list[str], data: ConceptData) -> list[QueryGroup]: + """Group query terms into concepts, each carrying its shell vocabulary. + + Three things happen here, in order: + + 1. **Phrases are folded first, longest first.** "disk space" is one + concept; scanning left to right for the longest key that matches the + next few words keeps it from decaying into "disk" AND "space", which + are two much vaguer concepts. + 2. **Stopwords are dropped** — but only those that are not themselves + concepts, so a map that defines ``"for"`` keeps it. + 3. **Everything else stays as a literal group with no expansions.** A word + the map has never heard of is still the user's word, and still has to + be matched; the map's job is to add meaning, never to withhold it. + + If the query is nothing *but* stopwords, they are kept: "how to" is a + strange thing to search for, but returning results for it beats silently + searching for nothing. + """ + groups: list[QueryGroup] = [] + index = 0 + span = min(MAX_CONCEPT_WORDS, data.max_words) + while index < len(terms): + for width in range(min(span, len(terms) - index), 0, -1): + phrase = " ".join(terms[index : index + width]) + expansions = data.concepts.get(phrase) + if expansions is not None: + groups.append( + QueryGroup( + text=phrase, + words=tuple(terms[index : index + width]), + expansions=expansions, + ) + ) + index += width + break + else: + term = terms[index] + if term not in data.stopwords: + groups.append(QueryGroup(text=term, words=(term,), expansions=())) + index += 1 + + if not groups: + return [QueryGroup(text=t, words=(t,), expansions=()) for t in terms] + return groups + + +def _warn(message: str) -> None: + """Report a broken map on stderr, where it cannot corrupt ``--json`` output.""" + print(f"warning: {message}", file=sys.stderr) diff --git a/src/mem/ranking.py b/src/mem/ranking.py index 7ff1044..f46e15b 100644 --- a/src/mem/ranking.py +++ b/src/mem/ranking.py @@ -17,6 +17,7 @@ from __future__ import annotations import math +from collections.abc import Sequence from mem import picks @@ -48,6 +49,17 @@ # Recency halves every this many days. RECENCY_HALF_LIFE_DAYS = 7 +# Credit a query concept earns when the command contains the user's own word, +# versus a synonym the concept map supplied. Both live below the hard boundary +# that keeps *every* fully literal match above *any* expanded one (see +# ``mem.search.search``), so this is a tie-breaker inside the expanded tier, +# not the mechanism that protects literal matches. It is deliberately mild: +# make it severe and a command matching only a vague literal word ("fix") +# outranks the one that matched a precise concept ("certificate" -> openssl), +# which is the opposite of what the map is for. +LITERAL_CREDIT = 1.0 +EXPANDED_CREDIT = 0.8 + _LN2 = math.log(2) _LOG_CEILING = math.log1p(FREQUENCY_CEILING) @@ -136,3 +148,69 @@ def score( + prefix_score(command, query) * W_PREFIX + context_score(repo, current_repo) * W_CONTEXT ) + + +def idf(document_frequency: int, n_documents: int) -> float: + """How much a term's presence tells you, normalised to [0, 1]. + + The BM25 form, ``log(1 + (N - df + 0.5) / (df + 0.5))``, divided by its own + value at ``df = 1`` so the result reads as a fraction like every other + feature here. A term in one command out of a thousand scores 1.0; a term in + all thousand scores ~0. + + This is what stops query expansion from doing harm. The concept map is + hand-written, so it will eventually contain a synonym that is far too + common — a ``"version control": ["git", ...]`` in a history that is 40% + git. Without idf that entry would drag every git command into the answer + for any question mentioning version control. With it, a term matching half + the candidates scores below 0.2 (and keeps falling as the history grows), + so it cannot move the ranking: the weighting makes a bad entry inert + instead of harmful, which is the property a hand-edited file needs. + + Both counts are measured over the *candidates* for this query, not the + whole history. Ranking only has to separate the results from each other, + and a term present in every candidate separates nothing however rare it is + globally. It is also the cheap answer: the candidate set is already in + memory, while a corpus-wide count is another pass over every file. + """ + if n_documents <= 1: + return 1.0 + df = min(max(document_frequency, 1), n_documents) + raw = math.log(1 + (n_documents - df + 0.5) / (df + 0.5)) + rarest = math.log(1 + (n_documents - 0.5) / 1.5) + return raw / rarest + + +def coverage(credits: Sequence[float], weights: Sequence[float]) -> float: + """How much of the query's *information* a command accounts for, in [0, 1]. + + ``credits[i]`` is how well concept *i* was satisfied — 1.0 by the user's + own words, 0.8 by a synonym, 0.0 not at all — and ``weights[i]`` is that + concept's idf. Weighting by idf rather than counting concepts is what makes + a match on "certificate" worth more than a match on "fix": the first + narrows a history to a handful of commands, the second barely narrows it at + all, and treating them as one-concept-one-vote would rank the vague hit + first. + + When no concept discriminates (every one of them matches every candidate, + which is the ordinary case for a one-word query) all the weights are ~0. + Falling back to the unweighted mean keeps the multiplier meaningful instead + of collapsing every score to zero and leaving the order to chance. + """ + if not credits: + return 0.0 + total = sum(weights) + if total <= 0: + return sum(credits) / len(credits) + return sum(c * w for c, w in zip(credits, weights)) / total + + +def expanded_score(base: float, match_coverage: float) -> float: + """Scale a score by how much of the query the command actually covered. + + Multiplicative, not additive: a command that satisfies one concept out of + three should not be able to buy its way back with frequency and recency. + The result stays in [0, 1], so the ``score`` field in ``--json`` still + reads as a fraction. + """ + return base * match_coverage diff --git a/src/mem/search.py b/src/mem/search.py index 4d901bf..295ae2c 100644 --- a/src/mem/search.py +++ b/src/mem/search.py @@ -3,14 +3,24 @@ Reads JSONL command history, scores each command using a deterministic formula, and returns ranked results. No ML — just math. + +Two passes, in a fixed order. The **literal** pass is substring search: every +word the user typed must appear in the command. When it finds nothing — which +is what happens to every question phrased in English, because "the command I +used to fix the certificate" shares no word with ``openssl x509 -in +cert.pem`` — the **expanded** pass runs the same query through +:mod:`mem.concepts`, a hand-written map from natural-language concepts to +shell vocabulary. See :func:`search` for the exact rule and why it is the one +that was chosen. """ from __future__ import annotations import time from collections import Counter +from collections.abc import Callable, Iterator, Sequence -from mem import picks, ranking, storage +from mem import concepts, picks, ranking, storage from mem.models import CapturedCommand, CommandPattern, WorkSession @@ -91,73 +101,61 @@ def _matches(command: str, terms: list[str]) -> bool: return all(term in lowered for term in terms) -def search( - query: str, - current_repo: str | None = None, - limit: int = 10, -) -> list[tuple[CapturedCommand, float]]: - """Search command history for commands matching a query. - - Returns a list of (command, score) tuples, ranked by score descending. - - Strategy: - 1. Read from current repo JSONL first (if applicable) - 2. Then read from _global.jsonl - 3. Filter by substring match on query - 4. Compute frequency counts per unique command string - 5. Score each unique command (keep highest score per command) - 6. Return top N by score +def _read_history( + current_repo: str | None, + needles: Sequence[str] | None = None, + line_filter: Callable[[str], object] | None = None, +) -> Iterator[CapturedCommand]: + """Yield every captured command, current repo first, each file read once. + + Order matters only for the caller's convenience; ranking is what decides + what the user sees. Reading each file exactly once is what matters: + ``_global`` used to be read twice, which doubled the frequency of every + command that lived there. """ - terms = _terms(query) - if not terms: - return [] - - # Cheap substring test on the raw JSONL line, so the expensive parse only - # runs for lines that could match. The needles are a *necessary* condition, - # never a sufficient one — `_matches` below is still the real filter. - needles = storage.prefilter_needles(terms) - - # Collect all matching commands - all_commands: list[CapturedCommand] = [] - - # Read current repo first for context boost if current_repo: - repo_name = storage.resolve_repo_key(current_repo) - for cmd in storage.read_commands(repo_name, needles): - if _matches(cmd.command, terms): - all_commands.append(cmd) + yield from storage.read_commands( + storage.resolve_repo_key(current_repo), needles, line_filter + ) - # Read global fallback - for cmd in storage.read_commands("_global", needles): - if _matches(cmd.command, terms): - all_commands.append(cmd) + yield from storage.read_commands("_global", needles, line_filter) - # Also read other repo files if current_repo didn't cover everything repos_dir = storage.MEM_DIR / "repos" - if repos_dir.exists(): - current_sanitized = storage.repo_key(current_repo) if current_repo else None - for path in sorted(repos_dir.glob("*.jsonl")): - repo_name = path.stem - if repo_name == current_sanitized or repo_name == "_global": - continue # already read - for cmd in storage.read_commands(repo_name, needles): - if _matches(cmd.command, terms): - all_commands.append(cmd) - - if not all_commands: - return [] + if not repos_dir.exists(): + return + current_sanitized = storage.repo_key(current_repo) if current_repo else None + for path in sorted(repos_dir.glob("*.jsonl")): + repo_name = path.stem + if repo_name == current_sanitized or repo_name == "_global": + continue # already read + yield from storage.read_commands(repo_name, needles, line_filter) + + +def _rank( + matched: list[CapturedCommand], + query: str, + current_repo: str | None, + scale: Callable[[str, float], float] | None = None, +) -> list[tuple[CapturedCommand, float]]: + """Score, deduplicate and sort a set of matching commands. + + A command string appears once, represented by its highest-scoring + occurrence, with ``frequency`` counted across every occurrence — the same + command run in three repos is one result run three times, not three + results. - # Compute frequency per unique command string - freq = Counter(cmd.command for cmd in all_commands) + ``scale`` optionally adjusts a command's score by how well it matched; + the literal pass has nothing to adjust and passes nothing. + """ + freq = Counter(cmd.command for cmd in matched) # What the user has actually chosen before, decayed. Read once for the # whole page rather than per candidate: it is one small file, and reading # it inside the loop would turn a search into thousands of stat() calls. pick_weights = picks.load() - # Score and deduplicate — keep highest score per unique command best: dict[str, tuple[CapturedCommand, float]] = {} - for cmd in all_commands: + for cmd in matched: s = score_command( cmd, query, @@ -165,12 +163,202 @@ def search( freq[cmd.command], pick_weights.get(cmd.command, 0.0), ) + if scale is not None: + s = scale(cmd.command, s) if cmd.command not in best or s > best[cmd.command][1]: best[cmd.command] = (cmd, s) - # Sort by score descending, return top N - ranked = sorted(best.values(), key=lambda x: x[1], reverse=True) - return ranked[:limit] + return sorted(best.values(), key=lambda x: x[1], reverse=True) + + +def _literal_search( + terms: list[str], query: str, current_repo: str | None +) -> list[tuple[CapturedCommand, float]]: + """Rank the commands containing every word the user typed.""" + # Cheap substring test on the raw JSONL line, so the expensive parse only + # runs for lines that could match. The needles are a *necessary* condition, + # never a sufficient one — `_matches` below is still the real filter. + needles = storage.prefilter_needles(terms) + matched = [ + cmd + for cmd in _read_history(current_repo, needles) + if _matches(cmd.command, terms) + ] + return _rank(matched, query, current_repo) + + +def _expanded_search( + terms: list[str], query: str, current_repo: str | None +) -> list[tuple[CapturedCommand, float]]: + """Rank the commands that match the *concepts* behind the words typed. + + Each query concept (see :func:`mem.concepts.expand`) is satisfied by the + user's own words or by one of the concept's synonyms. A candidate must + satisfy **at least one concept through a synonym** — that is the rule, and + both halves of it are load-bearing: + + - *At least one*, not all of them. Requiring every concept was tried and + answers none of the questions this pass exists for: nothing in + ``openssl x509 -in cert.pem`` satisfies the "fix" in "the command I used + to fix the certificate", so a single unsatisfiable concept would veto + the correct answer. What separates a good candidate from a poor one is + *coverage*, scored rather than filtered, weighted by idf so that + satisfying "certificate" counts for far more than satisfying "fix". + - *Through a synonym*. A command that matches only some of the literal + words is not a discovery of the concept map — it is the plain AND search + quietly downgraded to an OR, which is the exact defect fixed in #10: + ``mem docker zzzz-no-such-term`` must return nothing, or the user cannot + tell that a word was ignored. Requiring the map to have contributed + something keeps that promise, and it also drops the noise it would + otherwise let in: for "fix the certificate", a ``git commit -m "fix + flaky test"`` matching nothing but the word "fix" is not an answer. + + A literal *anchor* — requiring at least one of the user's own words to + match — was considered and rejected for the opposite reason: it scores 0 + on these questions, because the words a person uses to describe a command + are usually not in the command. + """ + data = concepts.load(storage.MEM_DIR / concepts.USER_CONCEPTS_FILENAME) + groups = concepts.expand(terms, data) + + admitted = list(_read_history(current_repo, line_filter=_any_variant(groups))) + + # Judged once per distinct command rather than once per occurrence: the + # prefilter admits whole files' worth of repeated commands, and the verdict + # depends on nothing but the text. + credits: dict[str, list[float]] = {} + for command in {cmd.command for cmd in admitted}: + lowered = command.lower() + row = [_credit(lowered, group) for group in groups] + if ranking.EXPANDED_CREDIT in row: + credits[command] = row + + matched = [cmd for cmd in admitted if cmd.command in credits] + if not matched: + return [] + + # Document frequency over the candidates, in distinct commands: three runs + # of the same command are one piece of evidence about how specific a term + # is, not three. + n_documents = len(credits) + weights = [ + ranking.idf(sum(1 for row in credits.values() if row[i] > 0), n_documents) + for i in range(len(groups)) + ] + + coverages = { + command: ranking.coverage(row, weights) for command, row in credits.items() + } + return _rank( + matched, + query, + current_repo, + scale=lambda command, s: ranking.expanded_score(s, coverages[command]), + ) + + +def _credit(lowered_command: str, group: concepts.QueryGroup) -> float: + """How well a command satisfies one query concept: literally, or by synonym.""" + if group.literal_hit(lowered_command): + return ranking.LITERAL_CREDIT + if group.matched_expansions(lowered_command): + return ranking.EXPANDED_CREDIT + return 0.0 + + +def _any_variant( + groups: Sequence[concepts.QueryGroup], +) -> Callable[[str], object] | None: + """A raw-line prefilter for "contains any of these", or None if unsafe. + + The literal pass can drop a needle it considers too short and still be + correct, because its needles are ANDed: a missing one only means more + lines get parsed. Here they are ORed, so dropping one would *exclude* + every line that contains only that alternative — a wrong answer, not a + slow one. If any variant reduces to nothing usable (``ss -``, an accented + word, a bare flag someone added to their own map) the prefilter is + abandoned entirely and every line is parsed. + + A loop of ``in`` tests, not a compiled alternation, and not + ``re.IGNORECASE``. All three were measured over 20k lines on the query + "change file permissions to executable" (15 needles): 17ms for this, + 36ms for ``re.compile("a|b|...").search(line.lower())``, and 117ms for + the same pattern with ``IGNORECASE``. Each ``in`` gets the interpreter's + optimised substring search and the loop stops at the first hit, while an + alternation retries every branch at every position and a case-insensitive + one gives up its literal optimisations entirely. Lowercasing the line once + is cheaper than asking the matcher to ignore case. + """ + variants = [v for group in groups for v in group.variants()] + needles = storage.prefilter_needles(variants, min_length=_EXPANSION_NEEDLE_LEN) + if len(needles) != len(variants): + return None + unique = tuple(dict.fromkeys(needles)) + + def contains_any(line: str) -> bool: + lowered = line.lower() + return any(needle in lowered for needle in unique) + + return contains_any + + +# Two characters, not the three the literal pass uses. Half the shell's most +# useful vocabulary is two letters — df, du, ps, rm, ln, jq, go — and an OR +# prefilter that drops one of those needles drops results with it. +_EXPANSION_NEEDLE_LEN = 2 + + +def search( + query: str, + current_repo: str | None = None, + limit: int = 10, + expand: bool = True, +) -> list[tuple[CapturedCommand, float]]: + """Search command history for commands matching a query. + + Returns a list of (command, score) tuples, ranked by score descending. + + **The matching rule.** A command matches when every word of the query + appears in it. If nothing does, and only then, the query is re-read + through the concept map (:mod:`mem.concepts`) and commands are matched by + what those words *mean*: "certificate" finds ``openssl x509``, "port" + finds ``lsof -i``, "disk space" finds ``du -sh``. + + Expansion is a fallback rather than a blend, and that is the design, not + an implementation shortcut. Three properties fall out of it, all of which + were requirements: + + - **A literal match always outranks an expanded one.** Not by a weight + that could be overcome by frequency and recency — expanded results are + only ever consulted when there are no literal ones at all. Someone who + typed ``openssl`` gets ``openssl``, never everything tagged + "certificate". + - **Expansion can only add.** Every result the substring search would have + returned is still returned, in the same order, with the same score. The + concept map cannot demote, dilute or reorder an answer that already + worked, which is the property that makes a hand-edited file safe to ship + — a bad entry can waste a fallback, never damage a working query. + - **It costs nothing when it is not needed.** The map is not even loaded + for a query that matches something. + + The price is that a query with one poor literal match gets no help. That + is the right trade for a tool whose users type shell fragments far more + often than sentences: it is better to answer ``docker compose`` exactly + than to pad it with guesses. + + ``expand=False`` disables the fallback, leaving pure substring search. It + exists so the recall benchmark in ``tests/test_concepts.py`` can measure + both halves against one history. + """ + terms = _terms(query) + if not terms: + return [] + + literal = _literal_search(terms, query, current_repo) + if literal or not expand: + return literal[:limit] + + return _expanded_search(terms, query, current_repo)[:limit] def search_patterns(tool: str) -> list[CommandPattern]: diff --git a/src/mem/storage.py b/src/mem/storage.py index 0717c8c..b44e22a 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -21,7 +21,7 @@ from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path -from typing import Iterable, Iterator, NamedTuple, Sequence +from typing import Callable, Iterable, Iterator, NamedTuple, Sequence from mem import _fsutil, keychain from mem._fsutil import FILE_MODE, atomic_write @@ -382,7 +382,9 @@ def append_commands(cmds: list[CapturedCommand]) -> int: _MIN_NEEDLE_LEN = 3 -def prefilter_needles(terms: Iterable[str]) -> list[str]: +def prefilter_needles( + terms: Iterable[str], min_length: int = _MIN_NEEDLE_LEN +) -> list[str]: """Reduce search terms to substrings safe to look for in a raw JSON line. Answering a query currently costs ~140ms per 100k commands, and 82% of @@ -406,6 +408,15 @@ def prefilter_needles(terms: Iterable[str]) -> list[str]: them raw: these files are meant to be edited by hand, and an editor that writes ``ensure_ascii`` JSON would turn ``café`` into ``caf\\u00e9``. The ASCII run around them still counts, so ``café`` narrows to ``caf``. + + ``min_length`` exists for the one caller that cannot afford to drop a + needle. Three characters is a *selectivity* floor, not a correctness one: + below it a needle matches so many lines that the scan costs more than the + parse it saves. But an "any of these" prefilter is only sound if every + alternative is represented — drop the needle for ``df`` and lines + containing only ``df`` stop being read at all. Query expansion therefore + asks for ``min_length=2`` and accepts the weaker filter; see + :func:`mem.search.search`. """ needles: list[str] = [] for term in terms: @@ -413,13 +424,15 @@ def prefilter_needles(terms: Iterable[str]) -> list[str]: if not runs: continue longest = max(runs, key=len) - if len(longest) >= _MIN_NEEDLE_LEN: + if len(longest) >= min_length: needles.append(longest.lower()) return needles def read_commands( - repo: str, needles: Sequence[str] | None = None + repo: str, + needles: Sequence[str] | None = None, + line_filter: Callable[[str], object] | None = None, ) -> Iterator[CapturedCommand]: """Lazily read commands from a repo's JSONL file. @@ -429,6 +442,14 @@ def read_commands( ``needles`` is an optional set of lowercase substrings from :func:`prefilter_needles`; a line missing any of them is skipped without being parsed. Callers that want every command leave it unset. + + ``line_filter`` is the same optimisation for a caller whose test is not + "every needle present" — query expansion needs "*any* of these forty", + which no list of needles can express here, because ``needles`` are ANDed. + It receives the raw line and returns something falsy to skip it. Like + ``needles`` it must only ever be a *necessary* condition: whatever it + rejects is never parsed, so a filter that is too strict silently loses + results rather than reporting an error. """ path = repo_file(repo) if not path.exists(): @@ -438,6 +459,8 @@ def read_commands( line = line.strip() if not line: continue + if line_filter is not None and not line_filter(line): + continue if needles: lowered = line.lower() if not all(needle in lowered for needle in needles): diff --git a/tests/test_concepts.py b/tests/test_concepts.py new file mode 100644 index 0000000..d602b60 --- /dev/null +++ b/tests/test_concepts.py @@ -0,0 +1,593 @@ +"""Tests for the concept map and the query expansion built on it. + +The first class is the one that matters. Everything else in this file checks a +mechanism; :class:`TestRecall` checks the *claim* — that a hand-written +dictionary turns questions a person would actually ask into the commands they +actually ran. A feature justified by a measurement needs the measurement in +the suite, or the number is folklore by the second refactor. +""" + +from __future__ import annotations + +import json +import time + +import pytest + +from conftest import make_command +from mem import concepts, ranking, search, storage + +REPO = "/Users/test/projects/myapp" + + +@pytest.fixture(autouse=True) +def _fresh_concept_cache(): + """Drop the memoised map around every test. + + The loader caches on (path, mtime, size), and a test that writes + ``~/.mem/concepts.json`` twice inside one filesystem timestamp tick would + otherwise read the first version back. + """ + concepts.clear_cache() + yield + concepts.clear_cache() + + +# --- The measurement -------------------------------------------------------- + + +# A small but realistic history: the commands a working developer runs, plus +# the noise they run far more often. The noise is the point — recall is easy +# against ten commands and hard against ten commands buried in fifty. +HISTORY = [ + "openssl x509 -in cert.pem -noout -dates", + "lsof -i :8080", + "du -sh * | sort -h", + "docker logs -f api --tail 100", + 'pkill -f "node server.js"', + "git reset --hard HEAD~1", + "tar -czf backup.tar.gz ./data", + "pg_dump -U postgres mydb > dump.sql", + "ssh -L 5432:localhost:5432 user@host -N", + "chmod 755 deploy.sh", + # Noise, including words the questions use ("fix", "check", "show"). + "git status", + "git add -A", + 'git commit -m "fix flaky test"', + 'git commit -m "check the release notes"', + "git push origin main", + "git pull --rebase", + "git log --oneline -20", + "npm run dev", + "npm install", + "npm test", + "ls -la", + "cd ../api", + "make build", + "make test", + "vim README.md", + "cat package.json", + "code .", + "brew update", + "kubectl get pods", + "docker ps", + "curl -s https://api.example.com/health", + "echo $SHELL", + "python3 -m pytest -q", + "ruff check .", + "gh pr create --fill", +] + +# Questions phrased the way they are actually asked, with the one command in +# HISTORY that answers each. None of them share a word with their answer, +# which is exactly why substring search scores zero. +QUESTIONS = [ + ( + "the command I used to fix the certificate", + "openssl x509 -in cert.pem -noout -dates", + ), + ("how do I see what's listening on a port", "lsof -i :8080"), + ("how to check disk space", "du -sh * | sort -h"), + ("show me the docker container logs", "docker logs -f api --tail 100"), + ("how do I kill a process by name", 'pkill -f "node server.js"'), + ("undo my last commit", "git reset --hard HEAD~1"), + ("how do I create an archive of a folder", "tar -czf backup.tar.gz ./data"), + ("dump the postgres database", "pg_dump -U postgres mydb > dump.sql"), + ("how do I set up an ssh tunnel", "ssh -L 5432:localhost:5432 user@host -N"), + ("change file permissions to executable", "chmod 755 deploy.sh"), +] + +RECALL_AT = 5 + + +def _recall(expand: bool) -> tuple[int, list[str]]: + """Answer every question and count how often the right command is top-5.""" + hits = 0 + missed: list[str] = [] + for question, answer in QUESTIONS: + found = [ + cmd.command + for cmd, _ in search.search( + question, current_repo=REPO, limit=RECALL_AT, expand=expand + ) + ] + if answer in found: + hits += 1 + else: + missed.append(question) + return hits, missed + + +@pytest.fixture +def history(tmp_mem_dir): + """Write HISTORY to the current repo, newest command last.""" + now = int(time.time()) + for offset, command in enumerate(HISTORY): + storage.append_command( + make_command( + command=command, ts=now - (len(HISTORY) - offset) * 3600, repo=REPO + ) + ) + + +class TestRecall: + """recall@5 over ten natural-language questions against a real history. + + The numbers this pins are the ones the feature was justified by. Measured + on a developer's own history, the four approaches scored: + + | approach | recall@5 | latency | + |----------------------------------|----------|---------| + | substring search | 0/10 | 9.6 ms | + | Apple Foundation Models expansion| 2/10 | 2086 ms | + | hybrid ranker, no synonyms | 2/10 | 2.4 ms | + | hybrid ranker + concept map | 8/10 | 3.9 ms | + + A dictionary beat the on-device LLM by 4x on accuracy and 500x on latency. + """ + + def test_substring_search_answers_none_of_them(self, history) -> None: + """The baseline, and the reason this feature exists: 0/10.""" + hits, _ = _recall(expand=False) + + assert hits == 0 + + def test_the_concept_map_answers_most_of_them(self, history) -> None: + hits, missed = _recall(expand=True) + + assert hits >= 8, f"recall@5 fell to {hits}/10; missed: {missed}" + + def test_expansion_only_ever_adds(self, history) -> None: + """Every result substring search returns is still returned, in order. + + The property that makes a hand-edited map safe to ship: a bad entry + can waste a fallback, but it cannot damage a query that already works. + """ + for query in ("git commit", "docker", "openssl", "make", "npm run"): + literal = search.search(query, REPO, limit=50, expand=False) + expanded = search.search(query, REPO, limit=50) + + assert [c.command for c, _ in expanded][: len(literal)] == [ + c.command for c, _ in literal + ] + assert [s for _, s in expanded][: len(literal)] == pytest.approx( + [s for _, s in literal], abs=1e-6 + ) + + def test_a_literal_match_outranks_everything_the_map_finds(self, history) -> None: + """Someone who typed `openssl` wants openssl, not everything TLS.""" + results = search.search("openssl", current_repo=REPO) + + assert [cmd.command for cmd, _ in results] == [ + "openssl x509 -in cert.pem -noout -dates" + ] + + +# --- The rule --------------------------------------------------------------- + + +class TestMatchingRule: + def test_a_term_matching_nothing_still_returns_nothing(self, history) -> None: + """The #10 invariant survives expansion. + + Loosening the query's AND into an OR would answer this with every + docker command, and the user could not tell their second word was + ignored. Expansion is allowed to *add* what the concept map found — + never to quietly drop a word. + """ + assert search.search("docker zzzz-no-such-term", current_repo=REPO) == [] + + def test_a_command_needs_more_than_a_shared_english_word(self, history) -> None: + """`git commit -m "fix flaky test"` is not the answer to a question about + fixing a certificate, however literally it matches the word "fix".""" + found = [ + cmd.command + for cmd, _ in search.search( + "the command I used to fix the certificate", REPO, limit=10 + ) + ] + + assert 'git commit -m "fix flaky test"' not in found + assert "openssl x509 -in cert.pem -noout -dates" in found + + def test_expansion_is_not_consulted_when_the_query_matches(self, history) -> None: + """A query with literal hits never pays for the map, or shows its results.""" + found = [cmd.command for cmd, _ in search.search("logs", REPO, limit=50)] + + assert found == ["docker logs -f api --tail 100"] + + def test_an_unknown_single_word_finds_nothing(self, tmp_mem_dir) -> None: + storage.append_command(make_command(command="git status", repo=REPO)) + + assert search.search("zzzznotaword", current_repo=REPO) == [] + + def test_multi_word_concepts_are_matched_as_one(self, tmp_mem_dir) -> None: + """ "disk space" is a concept; "disk" AND "space" are two vague ones.""" + data = concepts.load(None) + + groups = concepts.expand(["how", "much", "disk", "space"], data) + + assert [g.text for g in groups] == ["much", "disk space"] + + def test_question_scaffolding_is_dropped(self, tmp_mem_dir) -> None: + data = concepts.load(None) + + groups = concepts.expand( + ["how", "do", "i", "check", "the", "certificate"], data + ) + + assert [g.text for g in groups] == ["check", "certificate"] + + def test_a_query_of_pure_scaffolding_is_still_searched(self, tmp_mem_dir) -> None: + """`mem how to` is a strange search, but it is not an empty one.""" + data = concepts.load(None) + + groups = concepts.expand(["how", "to"], data) + + assert [g.text for g in groups] == ["how", "to"] + + +# --- idf weighting ---------------------------------------------------------- + + +class TestIdfWeighting: + def test_a_synonym_matching_everything_carries_no_weight(self) -> None: + """The property that makes a hand-written map safe. + + A concept whose synonym appears in every candidate cannot separate + them, so it must not be able to move the ranking. This is what stops a + careless `"version control": ["git"]` from dragging every git command + into every question that mentions version control. + """ + assert ranking.idf(document_frequency=100, n_documents=100) == pytest.approx( + 0.0, abs=0.01 + ) + assert ranking.idf(document_frequency=50, n_documents=100) < 0.2 + assert ranking.idf(document_frequency=1, n_documents=100) == pytest.approx(1.0) + + def test_idf_is_monotonic(self) -> None: + weights = [ranking.idf(df, 1000) for df in (1, 10, 100, 500, 1000)] + + assert weights == sorted(weights, reverse=True) + + def test_a_single_document_is_not_a_division_by_zero(self) -> None: + assert ranking.idf(1, 1) == 1.0 + + def test_coverage_weights_concepts_by_how_much_they_narrow(self) -> None: + """A hit on a rare concept beats a hit on a common one.""" + rare_hit = ranking.coverage(credits=[1.0, 0.0], weights=[0.9, 0.1]) + common_hit = ranking.coverage(credits=[0.0, 1.0], weights=[0.9, 0.1]) + + assert rare_hit > common_hit + + def test_coverage_falls_back_when_nothing_discriminates(self) -> None: + """All weights zero — every concept matched every candidate.""" + assert ranking.coverage(credits=[1.0, 0.0], weights=[0.0, 0.0]) == 0.5 + assert ranking.coverage(credits=[], weights=[]) == 0.0 + + def test_an_expanded_score_can_never_exceed_a_perfect_one(self) -> None: + assert ranking.expanded_score(1.0, 1.0) == 1.0 + assert ranking.expanded_score(1.0, 0.5) == 0.5 + + def test_a_useless_synonym_cannot_outrank_a_useful_one(self, tmp_mem_dir) -> None: + """End to end: a concept satisfied by a term present everywhere loses. + + Every command here contains "git", so a query concept satisfied only + through "git" has learned nothing about which one to return. + """ + now = int(time.time()) + for command in ( + "git commit -m wip", + "git status", + "git push", + "git log", + "git config --global user.name", + ): + for _ in range(5): + storage.append_command(make_command(command=command, ts=now, repo=REPO)) + storage.append_command( + make_command( + command="git config --global user.email a@b.c", ts=now, repo=REPO + ) + ) + + user_map = tmp_mem_dir / "concepts.json" + user_map.write_text( + json.dumps({"vcs": ["git"], "email": ["user.email", "--global user.email"]}) + ) + + results = search.search("vcs email", current_repo=REPO, limit=3) + + assert results[0][0].command == "git config --global user.email a@b.c" + + +# --- The user's own map ----------------------------------------------------- + + +class TestUserMap: + def test_a_user_concept_is_searchable(self, tmp_mem_dir) -> None: + storage.append_command(make_command(command="pnpm run typecheck", repo=REPO)) + (tmp_mem_dir / "concepts.json").write_text( + json.dumps({"types": ["typecheck", "tsc"]}) + ) + + results = search.search("check the types", current_repo=REPO) + + assert [c.command for c, _ in results] == ["pnpm run typecheck"] + + def test_a_user_concept_replaces_the_shipped_one(self, tmp_mem_dir) -> None: + (tmp_mem_dir / "concepts.json").write_text(json.dumps({"port": ["myportcmd"]})) + + data = concepts.load(tmp_mem_dir / "concepts.json") + + assert data.concepts["port"] == ("myportcmd",) + assert "certificate" in data.concepts # everything else survives + + def test_user_stopwords_are_added_not_substituted(self, tmp_mem_dir) -> None: + (tmp_mem_dir / "concepts.json").write_text(json.dumps({"_stopwords": ["cómo"]})) + + data = concepts.load(tmp_mem_dir / "concepts.json") + + assert "cómo" in data.stopwords + assert "how" in data.stopwords + + def test_an_edit_takes_effect_without_a_restart(self, tmp_mem_dir) -> None: + path = tmp_mem_dir / "concepts.json" + path.write_text(json.dumps({"widget": ["first"]})) + assert concepts.load(path).concepts["widget"] == ("first",) + + path.write_text(json.dumps({"widget": ["second"]})) + + assert concepts.load(path).concepts["widget"] == ("second",) + + def test_broken_json_warns_and_falls_back(self, tmp_mem_dir, capsys) -> None: + path = tmp_mem_dir / "concepts.json" + path.write_text('{"port": ["lsof",}') + + data = concepts.load(path) + + assert "certificate" in data.concepts + err = capsys.readouterr().err + assert "not valid JSON" in err + assert "built-in concept map" in err + + @pytest.mark.parametrize( + "content", + [ + '["certificate", "openssl"]', # a list, not a map + '{"certificate": "openssl"}', # a string, not a list + '{"certificate": [1, 2]}', # not strings + '{"_stopwords": {"the": true}}', # reserved key, wrong type + ], + ) + def test_a_map_of_the_wrong_shape_warns_and_falls_back( + self, tmp_mem_dir, capsys, content: str + ) -> None: + path = tmp_mem_dir / "concepts.json" + path.write_text(content) + + data = concepts.load(path) + + assert data.concepts["port"][0] == "lsof" + assert "is not a concept map" in capsys.readouterr().err + + def test_an_unreadable_map_warns_and_falls_back(self, tmp_mem_dir, capsys) -> None: + path = tmp_mem_dir / "concepts.json" + path.write_text("{}") + path.chmod(0o000) + try: + data = concepts.load(path) + finally: + path.chmod(0o600) + + assert "certificate" in data.concepts + assert "could not read" in capsys.readouterr().err + + def test_a_broken_map_never_breaks_search(self, tmp_mem_dir, capsys) -> None: + """The whole point of the fallback: `mem ` still answers.""" + storage.append_command( + make_command(command="openssl x509 -in cert.pem", repo=REPO) + ) + (tmp_mem_dir / "concepts.json").write_text("not json at all") + + results = search.search("check the certificate", current_repo=REPO) + + assert [c.command for c, _ in results] == ["openssl x509 -in cert.pem"] + + def test_no_user_map_is_the_normal_case(self, tmp_mem_dir) -> None: + data = concepts.load(tmp_mem_dir / "concepts.json") + + assert "certificate" in data.concepts + + def test_comments_are_allowed_and_ignored(self, tmp_mem_dir) -> None: + (tmp_mem_dir / "concepts.json").write_text( + json.dumps({"_comment": "mine", "_unknown": ["x"], "thing": ["mycmd"]}) + ) + + data = concepts.load(tmp_mem_dir / "concepts.json") + + assert data.concepts["thing"] == ("mycmd",) + assert "_comment" not in data.concepts + assert "_unknown" not in data.concepts + + def test_a_concept_cannot_vouch_for_itself(self, tmp_mem_dir) -> None: + """A synonym equal to its own key is already covered by the literal test.""" + (tmp_mem_dir / "concepts.json").write_text( + json.dumps({"grep": ["grep", "rg ", "grep"]}) + ) + + data = concepts.load(tmp_mem_dir / "concepts.json") + + assert data.concepts["grep"] == ("rg ",) + + def test_an_overlong_key_is_ignored(self, tmp_mem_dir) -> None: + """Keys are concepts, not sentences; the phrase scan has to be bounded.""" + (tmp_mem_dir / "concepts.json").write_text( + json.dumps({"a b c d e": ["nope"], "ok": ["yes"]}) + ) + + data = concepts.load(tmp_mem_dir / "concepts.json") + + assert "a b c d e" not in data.concepts + assert data.concepts["ok"] == ("yes",) + + def test_an_empty_synonym_list_is_dropped(self, tmp_mem_dir) -> None: + (tmp_mem_dir / "concepts.json").write_text(json.dumps({"empty": ["", " "]})) + + assert "empty" not in concepts.load(tmp_mem_dir / "concepts.json").concepts + + +# --- The shipped map -------------------------------------------------------- + + +class TestShippedMap: + """Curation rules, enforced rather than described. + + A concept map is data, and data rots quietly: a synonym added in a hurry + is invisible until someone notices their search got worse. + """ + + @pytest.fixture + def shipped(self): + return concepts.load(None) + + def test_it_is_big_enough_to_be_useful(self, shipped) -> None: + assert 150 <= len(shipped.concepts) <= 250 + + def test_every_key_is_lowercase_and_normalised(self, shipped) -> None: + for key in shipped.concepts: + assert key == " ".join(key.lower().split()) + + def test_every_synonym_survives_the_prefilter(self, shipped) -> None: + """The OR prefilter is only sound if every alternative has a needle. + + One synonym reducing to nothing usable disables the prefilter for + every query that touches its concept — correct, but it silently parses + the entire history. Failing here instead makes that a review comment. + """ + for concept, expansions in shipped.concepts.items(): + for expansion in expansions: + needles = storage.prefilter_needles([expansion], min_length=2) + assert needles, f"{concept!r}: {expansion!r} reduces to no needle" + + def test_no_synonym_is_a_bare_stopword(self, shipped) -> None: + """A synonym that is also scaffolding would match half the history.""" + for concept, expansions in shipped.concepts.items(): + for expansion in expansions: + assert expansion not in shipped.stopwords, f"{concept}: {expansion}" + + def test_no_concept_is_also_a_stopword(self, shipped) -> None: + """A word cannot be both meaningless and a concept; the map would never + reach the concept, because stopwords are dropped first.""" + assert not set(shipped.concepts) & shipped.stopwords + + def test_synonyms_are_unique_within_a_concept(self, shipped) -> None: + for concept, expansions in shipped.concepts.items(): + assert len(set(expansions)) == len(expansions), concept + + def test_it_ships_inside_the_package(self) -> None: + """Read through importlib.resources, like the shell hooks. + + A path walked up from ``__file__`` works in a checkout and fails in a + wheel, which is how a stale hook reached every pip user for months. + """ + from importlib import resources + + raw = ( + resources.files("mem") + .joinpath(concepts.CONCEPTS_FILENAME) + .read_text(encoding="utf-8") + ) + + assert isinstance(json.loads(raw), dict) + + def test_a_missing_shipped_map_degrades_to_literal_search( + self, tmp_mem_dir, monkeypatch, capsys + ) -> None: + """A packaging fault must not take `mem ` down with it.""" + monkeypatch.setattr(concepts, "CONCEPTS_FILENAME", "no-such-file.json") + storage.append_command(make_command(command="git status", repo=REPO)) + + assert search.search("check the certificate", current_repo=REPO) == [] + assert "expansion is off" in capsys.readouterr().err + + def test_a_malformed_shipped_map_degrades_to_literal_search( + self, tmp_mem_dir, monkeypatch, capsys + ) -> None: + monkeypatch.setattr(concepts, "_parse", lambda raw: None) + + data = concepts.load(None) + + assert data.concepts == {} + assert "expansion is off" in capsys.readouterr().err + + +# --- The prefilter ---------------------------------------------------------- + + +class TestExpansionPrefilter: + def test_it_never_changes_the_answer(self, history, monkeypatch) -> None: + """Differential check: the optimised path and the unfiltered one agree. + + The prefilter skips `json.loads` for lines that cannot match. Unlike + the literal pass it ORs its needles, so dropping one silently loses + results — the failure mode nobody notices. + """ + with_filter = {q: _answers(q) for q, _ in QUESTIONS} + + monkeypatch.setattr(search, "_any_variant", lambda groups: None) + without_filter = {q: _answers(q) for q, _ in QUESTIONS} + + assert with_filter == without_filter + + def test_it_is_abandoned_when_a_synonym_has_no_needle(self, tmp_mem_dir) -> None: + """A user's one-character synonym costs speed, never correctness.""" + storage.append_command(make_command(command="ps aux | grep node", repo=REPO)) + (tmp_mem_dir / "concepts.json").write_text( + json.dumps({"whatsup": ["x", "ps "]}) + ) + + results = search.search("whatsup", current_repo=REPO) + + assert [c.command for c, _ in results] == ["ps aux | grep node"] + + +class TestConceptsCommand: + """``mem concepts > ~/.mem/concepts.json`` is the whole customisation story.""" + + def test_it_prints_a_map_that_can_be_loaded_back(self, tmp_mem_dir) -> None: + from click.testing import CliRunner + + from mem.cli import cli + + result = CliRunner().invoke(cli, ["concepts"]) + + assert result.exit_code == 0 + (tmp_mem_dir / "concepts.json").write_text(result.stdout) + data = concepts.load(tmp_mem_dir / "concepts.json") + assert data.concepts == concepts.load(None).concepts + assert data.stopwords == concepts.load(None).stopwords + + +def _answers(query: str) -> list[str]: + return [cmd.command for cmd, _ in search.search(query, REPO, limit=RECALL_AT)]