diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c820ec..07f8875 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,8 +38,431 @@ the `mimir-mem` crate, and the on-disk schema move together. one opened in the last 30 minutes. The report says plainly that the comparison favours live. `[learn] shadow_ranking = false` to disable. +- **A memory's state has a name, and the surfaces that show one print it.** + A memory is always one of live, superseded, expired, archived or forgotten, + but that was spread over four columns and worked out separately by each + reader. It is now one type (`lifecycle::Lifecycle`) with one derivation. A + memory that is not live says so in one word on the compact line (`[gotcha + 11-18 superseded]`, CLI and MCP) and as `"lifecycle"` in `--json`; `get` + leads with why (`! superseded by m:… — kept as history`), and shows a + pending `expires:` date and the `resolves when:` condition, which was + echoed at capture and never shown again. In link lists (`get`, `graph + node`) a retired memory is marked `[superseded]` or `[expired]`. A live + memory's line is unchanged. +- **`mimir project prune` — projects whose directory is gone.** A project is + registered the first time anything runs in a directory and its code graph + is built on first use; nothing ever removed one, so a deleted worktree or a + scratch clone kept its whole graph for good. `mimir project prune` lists + such projects with what they still hold and changes nothing; `--apply` + removes their symbols, code-file rows and edges. Memories are never + removed, and a symbol or a code file a memory is linked to is kept as a + tombstone so the memory reads `stale` instead of losing its link. Only a + directory the filesystem says is absent counts: one that cannot be checked + (no permission to look, a relative path) is never listed. Rows are removed + in transactions of a quarter of a second with a pause after each, so other + writers to the store are not held up, and a prune that is interrupted is + finished by running it again. It ends by saying how much of the store + file is free and the command that shrinks the file. Rehearsed on a store + of 3.7 million rows: 1.13 million symbols of 127 dead projects removed in + 4 to 11 minutes while a second process wrote throughout (953 writes, none + failed, the slowest 1.2 s); a `VACUUM` afterwards took 39 s and took the + file from 8.1 GB to 3.9 GB. + `mimir doctor` says when there is something to prune, and stops saying so + once it has been done. +- **`mimir sync push --full` and `mimir sync pull --full`.** Send or ask for + everything instead of what changed since the last round. Both are safe to + repeat (the merge keeps the winning version of each memory). They exist for the one-time + repair after a hub upgrade: see "Sync" under Fixed. +- **`mimir graph build --full`** re-extracts every file and rebuilds every + edge, for when an answer looks wrong. +- **Graph answers say how far to trust them.** `callers`, `calls`, `impact`, + `path` and `node` add `note: the code graph is N file(s) behind the working + tree` when it is (CLI: stderr; MCP: last line; checked for projects of up + to 5,000 code files), `peek` says when its one file changed since the + build, and a result reached only through an ambiguous call edge is marked + `(unconfirmed call)`. +- **`mimir doctor` reports more of what can be wrong:** a config value no + mode recognises (with what the setting behaves as meanwhile), installed + hook scripts older than this binary, a daemon that wants a bearer token the + environment does not have, lookup indexes not built yet, and projects left + behind by a deleted directory. +- **`mimir project init --no-sync`** turns project sync off again; `--sync` + could only ever turn it on. +- **`recall --json`** keeps `strength` as the match label and adds the learned + number as `node_strength`. **`remember --json`** prints one JSON object + carrying what was attached (expiry, confidence, link), where it used to + print a JSON line followed by prose. + +### Fixed + +Projects and worktrees: + +- **A git worktree shares its repository's memories.** Project identity was + the checkout's path, so a `git worktree add` checkout was a project of its + own: it saw none of the main checkout's project memories, and what was + remembered in it stayed behind under a dead project when the worktree was + deleted. With a committed `.mimir` id it was the other way round: every + checkout shared one project row, whose path, and with it the code graph, + followed whichever checkout ran last. One id was answering two questions. + Now memories belong to the repository and the code graph to the checkout. + A linked worktree keeps a project of its own for `graph`, `peek`, + `outline`, docs collections and `project prune`, and files and reads + memories under the main checkout's project: `remember`, `list`, the brief, + per-prompt injection, guard anchors, the rules pack, `misses`. `recall` + reads both in one ranked list: the repository's memories and the + worktree's own code and docs. A worktree is recognised from its `.git` + file, with no git subprocess. Memories already filed under a worktree's + own project move to the main checkout's with the first memory command run + there (`remember`, `recall`, `list` and the like, or an MCP server + starting), which says so on one line, including when they will now be + sent at the next sync; one ledger row each (`mimir audit`). Hooks, + `status` and `doctor` never move anything. Only memories written since the + worktree was created move: one left at that path by an earlier, + unrelated checkout stays where it is. `mimir status` and the MCP `status` + tool add `linked worktree of ; memories are filed under project + `; `status --json` gains `checkout`, `worktree_of`, `memory_project`, + `memory_project_path`, `memory_filing` and `worktree_memories`. + Stays a project of its own, as before: a submodule; a worktree of a bare + repository; and a worktree whose committed `.mimir` id is not the one the + main checkout carries (the marker not merged to main yet, or unreadable + there), so a sync identity is never taken from a project. A main checkout + made with `git init --separate-git-dir` is not found from its worktrees + (that layout records no path back to it); they share a project under the + directory that holds the repository. A worktree of a submodule shares the + submodule checkout's memories. A directory counts as a worktree only when + the repository names it back (`/gitdir`, which git writes), so a + hand-written `.git` file cannot make a directory read another + repository's memories. +- **A session handoff stays with the checkout it was written in.** Worktrees + of one repository now share a memory project, and a handoff belonged to a + project: the first session to clear would have been handed whichever + snapshot was written last, by any of them. A handoff records its checkout + (`meta.handoff_checkout`) and is restored, re-armed, listed, recalled and + injected only there (`--all` and `get ` still show it). A handoff an + older build wrote in a worktree is given that worktree's checkout when it + moves home. One written outside any worktree before this records none and + behaves as before. +- **Upgrading a store that already has worktrees.** What you may notice: + memories that were filed under a worktree now carry the main checkout's + project label, and if that project syncs, they sync from now on. If a + worktree and the main checkout each had a rules pack, the one whose text + is newer is in force, and `mimir rules show` names the other. In a + repository with a committed `.mimir` id, a docs collection that was added + from a worktree is filed under the main checkout: run `mimir docs remove + `, then `docs add` and `mimir index` in the worktree, to make + `recall` there find it again; and the main checkout's code graph may have + been built from a worktree's files (`mimir graph build` there repairs it). + Restart long-running `mimir mcp` servers and the daemon after upgrading: a + server on the old build still files and reads by the old rule. +- **`mimir project prune --apply` and worktrees.** A memory linked to a + symbol or file of a pruned worktree is re-linked to the same code in the + main checkout, so it stays grounded instead of reading `stale`. A main + checkout's project is kept while a live worktree still files memories + under it. +- **Several processes opening a new directory at once registered it + several times.** A session start runs three hooks side by side; each could + insert its own project row, and later lookups used only one of them. + Registration now looks again under the write lock, and a directory that + already has several rows resolves to the oldest. Existing duplicates are + left as they are (on the store this was tested on, 9 directories, all + extra rows empty). +- **Every hook event in a project with a sync identity took the store's + write lock.** Resolving such a project re-bound it to its path with an + `UPDATE` whether or not anything had changed. It reads first now. + +Capture, edit, forget: + +- **A rejected capture was stored anyway.** The MCP `remember` tool parsed + `expires_in` and `confidence` after the insert: the memory went in without + its deadline, the caller got `invalid …`, and the corrected retry was + refused as a near-duplicate. `mimir remember --link ` did the same. + Both surfaces now run one pipeline (`capture.rs`): every argument is + validated first, and the memory and everything attached to it are written + in one transaction, so a capture is stored as asked or not at all. An + invalid argument is therefore reported ahead of a duplicate refusal. +- **The secret guard had gaps.** It scanned the body, the tags and the + trigger phrases of a new memory. An `--anchor`, a `--resolves-when` + condition, `edit --title`, `rules set` and `docs note` all stored free text + unscanned, and so did `mimir anchor`. They go through the same guard now. +- **Retired memories were still handed to agents as current.** A guard anchor + kept injecting a superseded memory's text, ahead of the memory that + replaced it; the replacement now speaks for it. An expired guard no longer + fires. The session brief admitted expired gotchas and decisions. The + handoff restore brought back a handoff that had expired or been superseded. +- **A forgotten memory still showed up through its links.** `get` and `graph + node` printed the title of a deliberately deleted memory to anyone who + opened something it had been linked to. +- **Supersede was two writes that could come apart.** It is one atomic + operation everywhere (CLI, MCP, review, consolidation), and refuses what + would strand a memory: a non-memory on either side, a deleted or expired + replacement, and a loop. Repeating a supersede records nothing. +- **`forget` could not reach everything it should.** `forget --hard` now + works on an existing tombstone; forgetting an archived memory makes it a + deliberate forget (its earlier wordings go, `remember` then refuses the + text); hard-deleting a memory others were superseded by names them instead + of failing with `FOREIGN KEY constraint failed`; a project cannot be + forgotten. The refusal for a forgotten memory names who forgot it (a + person, an agent, another machine) and the day it was forgotten. +- **Changes that change nothing left history.** `edit --pin` alone wrote a + revision and an `edit` row; so did an edit with the same text, and a pin + that was already set. A tags-only edit no longer resets the title. A + superseded or deleted memory cannot be pinned. +- **An exact copy of a superseded or expired memory was refused as a + duplicate** of a memory recall no longer shows. It can be remembered again. + (Imports are stricter on purpose: re-running one never re-creates what the + store retired.) +- **Imported notes were archived by the next weekly pass, and never synced.** + The importer backdated both timestamps; it now keeps the date a note was + written and counts the import itself as the change. The decay pass leaves + alone anything that changed inside the idle window. +- **Review queue.** A decision is atomic and refused if the finding was + decided meanwhile; `--supersede` on a finding the store has moved past is + refused with what to do; findings whose subject no longer stands leave the + list and are closed as `resolved` by the scan. +- **Consolidation.** Expired memories take no part (an expired newer memory + could retire a live older one, hiding both); two near-duplicate summaries + no longer produce a new summary on every pass; a dry run reports what a + real run does; the weekly pass runs once across processes; a memory stored + without a type consolidates with the notes. +- **The rules pack** is updated like any memory (previous text in `mimir + history`, an audit row, a fresh content hash) and is found by its exact tag + among current memories. +- **A memory stored without a type** decayed as a note, was labelled + `memory`, and was not found by `list -t note`. It is a note everywhere. + +Sync (upgrade the hub first; then run `mimir sync push --full` and `mimir +sync pull --full` once on each machine): + +- **A memory pushed long after it was written never reached the other + machines.** The hub answered a pull by each row's own timestamp, and a peer + that had pulled in the meantime had a cursor past it. The hub now relays by + when a row reached it. This is fixed on the hub; a hub on 0.17.1 still + loses such rows. +- **Supersession did not replicate.** The wire carried the `supersedes` edge + but not the column that hides a memory, so one superseded on one machine + stayed live on every other. Records carry it now (an optional field an + older peer ignores). Two machines that retired a pair in opposite + directions each keep the one they kept, instead of hiding both everywhere. +- **Decay archival deleted memories on machines that used them.** The weekly + pass archives by local usage, and the tombstone replicated. Archival stays + on the machine that decayed. Memories already removed everywhere by past + archival are not restored. +- **A forget could lose to housekeeping.** A row archived locally by the + decay pass was shielded from a forget or an edit another machine had made + earlier, which was then never relayed, so the memory stayed live on every + third machine. Decay is not a write: an archived row is compared as the + live row it was. +- **A pin could bring a forgotten memory back, and undo a rewrite.** Sync + ordered two versions of a memory by the row's last write of any kind, so a + pin, a tag or an anchor made on a machine that had not heard of a forget + outranked it and the memory came back everywhere; made on the old wording, + it replaced a rewrite made elsewhere. A memory now records when its *text* + was last decided (`meta.text_clock`, kept by every write that only + annotates), and versions are ordered by that first: the later decision + about what the memory says wins, and annotations only compete with each + other. A rewrite after a forget still wins, as it always did. +- **Two machines changing one memory in the same second each kept their own + version for good.** One version wins now, the same one on every machine. +- The whole ordering is one type (`replicate::Standing`), a total order, with + a test that runs two hundred random histories on three stores and requires + them to end in agreement. Stores on an older build order by the last write + alone; they agree with upgraded ones except where an annotation followed + an unseen forget or rewrite, so upgrade the hub and every machine. +- **Pins, anchors and expiry replicate.** They mark the memory changed, like + a retag. A pin does not hold off a supersession made on another machine. +- **A forget arriving over sync kept the memory's earlier wordings.** A local + `forget` purges them; the same deletion applied from a peer did not. +- **`sync status` showed changes pending forever** after the first push; it + counts from what was pushed. File mode shows its directory and no cursors; + the token line says where the token comes from. An unknown `[sync] mode` is + one error from every sync command. The MCP server's background sync follows + `config.toml` without a restart and is quiet when sync is off. The hub + answers 400 to an unparseable `since` instead of sending everything; file + mode skips an unreadable peer file instead of stopping half-way. + +Recall, injection, embeddings: + +- **Per-prompt injection could inject the wrong memory.** With a session id, + which the hook always sends, a lower-ranked hit was injected when the top + hit failed the relevance floor: the case the floor exists to refuse, and + one the eval could not see because it scored the path without a session. + Both paths decide the same way now. +- **A loaded model with no usable vectors silenced injection and made every + hit `weak`** (after a model switch, or before anything was embedded). An + empty vector leg is treated as not run, as with no model at all. +- **Nodes stored without a content hash were re-embedded on every pass** + (docs notes, memories synced without one), which also kept the model + loading on every capture. +- **A failed model load was final until restart.** It is retried, at first + after five minutes and at most once an hour while it keeps failing. +- **`recall --as-of` showed today's wording.** A hit is shown as it read + then; it is still found by its current wording, and the banner says so. +- **`recall --include-superseded` could close a miss** on the strength of a + retired memory. Views into the past or into retired memories no longer feed + the miss ledger. +- **`recall --rerank` with no reranker** returned the fused order without a + word; CLI and MCP now say so. + +Hooks, init, daemon, MCP (re-run `mimir init --hooks` to get the new hook +script): + +- **Warm auto-recall took 13 to 99 s per prompt on a store with large code + graphs**, so the hook gave up and fell back to the cold path. The daemon + kept every embedding in one in-memory matrix and reread all of it after + any other process's commit: on the store this was found on, 2.9 GB of + code-symbol vectors to search 1,814 memories. The cache now holds one + matrix per kind and loads a kind the first time a search asks for it, so + a memory recall reads only memory vectors (tens of ms again). A search + that includes code still reloads the symbols after a commit elsewhere. + +- **Warm auto-recall searched the wrong project.** The daemon scoped every + prompt to the directory it was started in; started by systemd, that is no + project, so it searched all of them. The hook script (v5) sends the + session's directory, and the bearer token when the daemon requires one. +- **A hook command could fail a session start.** `brief show`, `rules show` + and the context-guard hooks exit 0 on any error and say why on stderr. + `rules show` follows the session's directory when run as a hook + (`--hook`, which the installer writes). +- **A session handoff was restored on every later clear,** however old. It is + restored once; saving the same handoff again makes it pending again. The + pause-mode nudge tells you how to get a handoff back, since pause mode does + not restore one. +- **A misspelled mode half-enabled a feature.** `[sync] mode = "sever"` + counted as enabled and then failed; a misspelled `[hooks] context_guard` + installed hooks and wrote state but never printed. Mode settings are parsed + in one place; an unknown value behaves as the documented safe value and + `doctor` names it. +- **`mimir init --hooks`:** parses `settings.json` before writing anything; + backs it up only when it changes; treats an empty file as empty; exits + non-zero when the hook install it was asked for failed; upgrades its own + older entries in place and leaves alone any entry that also holds a hook of + yours; `--context-guard off` alone installs nothing; the SessionStart + commands do nothing when `mimir` is not on PATH; the line about the session + brief reflects the config. +- **A server left running across an upgrade** kept answering from a store it + no longer understood. Every MCP tool now answers `error: this Mimir server + is older than its store … restart it`, and the daemon's `/inject` answers + 503 so the hook falls back to the cold path, which runs the new binary. +- **MCP tool failures were not all marked.** Every failure starts with + `error: `; `status` reports the project the tools actually use; `outline` + resolves a relative path against the server's project directory. +- **The daemon** address is derived in one place (`MIMIR_INJECT_URL` now + moves the daemon, the delegation client and `doctor` as well as the hook); + `/inference` answers while the engine is busy; `doctor` probes the daemon + with the bearer the hook would send. + +Code graph: + +- **`graph impact` answered from other projects' files.** Paths were matched + across every project in the store, capped at three, and only then filtered + to the current one, so a checkout past the third was told `none of those + paths are in the code graph`; the MCP tool skipped the filter and answered + `no impact`. Both share one lookup and one outcome type now. +- **`graph impact` missed files that depend on a change only by import.** + They are listed, marked `(reached by import only)`. +- **An incremental build did not leave what a full build leaves.** Callers in + unchanged files kept a missing or stale edge when a symbol they call, or a + file they import, appeared or disappeared elsewhere, and `graph check` + still said current. Unchanged files are re-resolved when that happens. +- **Imports resolve by language.** C and C++ includes, Java and Kotlin + imports and PHP requires fell into the Python rule and produced no edge; + the Rust rule matched `util.rs` against `db_util.rs` and never tried + `x/mod.rs`. An edge is written only when one file matches, and not at all + where the match would be a guess (a platform package, a bare header name, + a `` include). A graph built before this was resolved by the old + rules: a project of up to 1,500 code files and 15,000 symbols is rebuilt + in full by its next ordinary build (`mimir graph build`, or the MCP + server's start-up build); a larger one says so on every answer until + `mimir graph build --full`. +- **A symbol a memory is linked to** is kept as a tombstone when it leaves + its file, so the memory reads `stale` and the link survives the symbol's + return. A later ambiguous call no longer downgrades a resolved edge. +- **A file that cannot be read or parsed** is skipped and reported instead of + aborting the build or erasing its symbols. +- **MCP `graph` and `peek`** use the CLI's wording, and say when the project + has no graph yet instead of `no callers found`. +- **Removing any row scanned the whole store, twice.** Two of the four + foreign keys into the node table had no index, so every deleted symbol, + chunk or memory cost time in proportion to the store (measured: 46 ms a row + at 500,000 rows, 0.04 ms with the indexes). The indexes are added without + a schema version; a large store gets them from `mimir init`. + +Proxy: + +- **A cache breakpoint could land where the API rejects one** (an empty text + block, a thinking block, a turn-scoped system message); it goes on the + nearest earlier block that can take one. A client that caches through a + tool definition, the top-level field or a nested block is recognised and + left alone; cache savings are claimed only where the proxy added a + breakpoint. +- **Requests keep the client's bytes.** Every request used to be + re-serialised with its keys sorted. An unchanged request is forwarded as + sent, and a changed one keeps everything outside the changed values. +- **Savings were booked for requests that were never accepted** (a 413 from + the size breaker, a failed send). They are recorded after upstream accepts. +- **Cache-read measurement** no longer truncates a count split across chunks + and works on large non-streaming responses. De-duplication covers a + repeated plain-string message, and leaves alone a per-turn system reminder + (the API has already cleared the earlier copy, so eliding the new one hid + it from the model) and a tool result the client put a cache breakpoint + inside. `--prune` advances in steps so the request prefix, and with it the + prompt cache, survives between them. An oversized body gets 413 + `request_too_large` instead of 502. A panicked ledger write no longer + switches recording off. +- **Every request was tokenized for the size breaker, even with the breaker + off** (the default). It is counted only when a limit is set, which takes + about 38% off request preparation on a 4 MB conversation. + +CLI: + +- **Flags that were silently ignored are refused.** `mimir link A B + --dry-run` wrote the link it was asked to preview. Also: a review decision + without a finding, `misses --dismiss` with listing flags, and `--all` + together with `--global` on `recall` and `list`. +- **`mimir link`** refuses relations Mimir derives for itself (`calls`, + `imports`, …): the next build would delete a hand-made one. Its help lists + what it accepts, built from the same list. `mimir report`'s "links created" + counted every call and import edge; it counts links somebody made. +- **Docs commands with two collections under one name** acted on whichever + row came first. They prefer the docs collection, say which one they acted + on and which remain, and `mimir index ` indexes every match. +- **The output-filter hook wrapped commands that never exit.** `mimir run` + prints when its child exits, so `kubectl logs -f`, `docker compose up` or + `npm run dev` showed an agent nothing, in the foreground until the timeout + and in the background for as long as the server lived. Followers, watchers + and dev servers are left unwrapped, also behind a global option + (`kubectl -n prod logs -f`, `pnpm --filter web dev`). The table is a list + of known commands: a server started some other way is still wrapped. +- **`mimir run`** reports a child killed by a signal as 128 + the signal. + **`mimir project init`** refuses to overwrite a `.mimir` it cannot parse, + and leaves no marker behind when the store cannot be opened. + ### Changed +- **Things an existing script may notice.** `mimir doctor` exits 1 for an + invalid config value (the unattended `--check` only when the value has no + fallback). `mimir sync status` exits 1 on an unknown mode. `mimir forget` + on an already forgotten memory says so instead of `not found`. `mimir init + --hooks` exits non-zero when the install failed. A memory stored without a + type is labelled `note`, not `memory`. Pinning or anchoring a memory marks + it changed: it syncs and `get` shows `updated`. The session brief's age + tag follows the text, so it no longer restarts when a guard is anchored or + given a trigger (and does not when it is pinned). Memories that arrive + over sync get an audit row saying so. An + annotated memory carries `meta.text_clock` (when its text was last + decided), visible in `--json` and in exports. The dashboard's "superseded" + and "archived" tiles are the same counts `mimir status` prints; a memory + superseded and later forgotten used to be in both. +- **For contributors: the one-definition rule is now a test.** + `crates/mimir-cli/tests/one_definition.rs` reads the workspace's + production source and fails when code outside a state's owners spells + that state by hand (a `meta` flag by its key, a lifecycle column written + directly, a mode compared as a string), naming the function to call + instead. A tripwire, not a proof; `docs/design/state-machines.md` is the + map it guards. +- **None of the fixes above changes the schema.** They work on the v14 + schema described next, and the two lookup indexes are not a schema + version, so a binary built before them still opens the store. - **Schema v13** adds the `recall_miss` table, **v14** the `shadow_rank` table. As with every schema bump, a store opened by this binary is refused by older ones (`SchemaTooNew`): diff --git a/README.md b/README.md index 9779ec1..f77aa9d 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,7 @@ mimir recall tricky semantic question --rerank # cross-encoder rescoring (~1 s # code graph (the MCP server runs build + docs indexing automatically # on session start — these are for manual/CLI use) mimir graph build # tree-sitter extraction, incremental +mimir graph build --full # re-extract everything (when an answer looks wrong) mimir graph check # exit 1 if the graph lags the tree (CI/hooks) mimir graph callers resolve_ref # who calls this? mimir graph callers resolve_ref --all-projects # …in every repo with a graph @@ -476,7 +477,12 @@ default 200,000): `session-handoff`-tagged memory before you clear. The next `SessionStart` after a clear or compact restores the latest handoff memory automatically, so the new session picks up where the old one - left off instead of starting cold. + left off instead of starting cold. A handoff is restored once: a later + clear without a new handoff restores nothing, where it used to replay + the old one. (In `pause` mode nothing is restored; get a saved handoff + back with `mimir list --tag session-handoff -n 1`.) A handoff belongs to + the project, not to one session: with two sessions in one project, the + first to clear takes it. Tune the estimate in `config.toml`: @@ -568,6 +574,25 @@ the server returns. > commit the `.mimir` file. If something still lands in the wrong place, > move it with `mimir reproject --project ` (or `--global`). +Because identity is the path, a project outlives its directory: a deleted +worktree or a scratch clone stays registered, with its whole code graph. +`mimir project prune` lists projects whose directory is gone and what they +still hold, and `mimir project prune --apply` removes those code graphs +(never memories; a symbol or code file a memory is linked to is kept, so +the memory reads `stale` instead of losing its link). `mimir doctor` tells you when +there is something to prune. + +A git linked worktree (`git worktree add`) is a checkout of its own with its +repository's memories. It has its own code graph and docs collections, so +`graph`, `peek` and `outline` read the files in that directory; `remember`, +the session brief, guard anchors and the rules pack use the project of the +repository's main checkout; and `recall` answers with both, the repository's +memories beside the worktree's own code and docs. `mimir status` says which +is which. What is remembered in a worktree therefore outlives it: once its +directory is gone, `mimir project prune --apply` removes its code graph and +its project. A submodule and a worktree of a bare repository are projects of +their own (global memories are visible everywhere). + `mimir init` also installs a set of `/m-*` slash commands for the agent CLIs it finds on the machine — Claude Code, Codex, OpenCode, Gemini CLI and Cursor (the `m-` prefix keeps them clear of your own commands): diff --git a/crates/mimir-cli/src/brief_cmd.rs b/crates/mimir-cli/src/brief_cmd.rs index 5c9e453..b16d1b5 100644 --- a/crates/mimir-cli/src/brief_cmd.rs +++ b/crates/mimir-cli/src/brief_cmd.rs @@ -7,51 +7,27 @@ //! //! Two entry points: //! - `show()` — the SessionStart hook (stdin JSON: session_id, source, -//! cwd). Silent unless `[brief] enabled = true` (the kill-switch; the +//! cwd, read through `context_guard_cmd::HookEvent` like every other +//! hook). Silent unless `[brief] enabled = true` (the kill-switch; the //! hook entry itself is always installed, same rollback pattern as the -//! context guard). +//! context guard). Fails open: an error is a line on stderr and exit 0. //! - `dry_run()` — human-facing `mimir brief`: prints exactly what a //! startup fire would inject, then the ranked candidates with scores, //! so "why did this appear?" always has an answer. Records nothing. use std::collections::HashSet; -use std::io::Read; use anyhow::Result; +use mimir_core::config::ContextGuardMode; +use mimir_core::context_guard::SessionSource; use mimir_core::model::{now_unix, short_uid, Scope}; use mimir_core::savings::{self, source}; -use mimir_core::{brief, memory, store, tokens, Mimir}; +use mimir_core::{brief, store, tokens, Mimir}; + +use crate::context_guard_cmd::{fail_open, HookEvent}; const FIRE_COUNT_KEY: &str = "brief_fire_count"; const SHOWN_PREFIX: &str = "brief_shown:"; -/// Wall-clock fallback: any node briefed in ANY session inside this -/// window is excluded, covering the unverified case where a resume (or a -/// client's compact) mints a fresh session_id — without it, a fresh id -/// would re-show the identical brief minutes later. -const RECENT_SHOWN_SECS: i64 = 6 * 3600; - -fn read_stdin_json() -> serde_json::Value { - let mut buf = String::new(); - if std::io::stdin().read_to_string(&mut buf).is_err() { - return serde_json::Value::Null; - } - serde_json::from_str(&buf).unwrap_or(serde_json::Value::Null) -} - -/// Same cwd→scope resolution as the context guard's hook entry. -fn scope_for_cwd(mimir: &Mimir, input: &serde_json::Value) -> Scope { - input - .get("cwd") - .and_then(|v| v.as_str()) - .and_then(|c| { - mimir - .project_for_cwd(std::path::Path::new(c)) - .ok() - .flatten() - }) - .map(|p| Scope::Project(p.id)) - .unwrap_or(Scope::Global) -} /// Node ids to suppress for this fire. Semantics differ by fire kind: /// @@ -77,7 +53,7 @@ fn suppressed(mimir: &Mimir, session_id: &str, now: i64, recap: bool) -> Result< rusqlite::params![ format!("{SHOWN_PREFIX}%"), session_id, - now - RECENT_SHOWN_SECS + now - brief::RECENT_SHOWN_SECS ], |r| r.get::<_, String>(0), )?; @@ -103,29 +79,38 @@ fn rules_body(mimir: &Mimir, scope: Scope) -> Option { } } -/// SessionStart hook entry. +/// SessionStart hook entry. Never fails the event: see [`fail_open`]. pub fn show() -> Result<()> { - let input = read_stdin_json(); - let mimir = Mimir::open()?; + fail_open("brief show", || { + let event = HookEvent::from_stdin(); + let mimir = Mimir::open()?; + fire(&mimir, &event) + }) +} + +/// Print the brief this event calls for, if any, and record that it fired. +fn fire(mimir: &Mimir, event: &HookEvent) -> Result<()> { if !mimir.config.brief.enabled { return Ok(()); } - let Some(session_id) = input.get("session_id").and_then(|v| v.as_str()) else { + let Some(session_id) = event.session_id() else { return Ok(()); }; - let event_source = input.get("source").and_then(|v| v.as_str()).unwrap_or(""); + let event_source = event.source(); // resume and fork (v2.1.214+; older clients report forks as "resume"): // the transcript already contains prior context including any earlier // brief. Unknown values: fail closed (never fire), matching the - // context guard's inert-default arm. session_id stability across - // clear/compact is undocumented upstream — the wall-clock fallback in - // suppressed() covers a minted id, so nothing here depends on it. + // context guard's leave-alone arm; a *missing* source is a start-up + // (`SessionSource::parse`), for the guard and for the brief alike. + // session_id stability across clear/compact is undocumented upstream — + // the wall-clock fallback in suppressed() covers a minted id, so + // nothing here depends on it. let budget = match event_source { - "startup" => mimir.config.brief.max_tokens, - "clear" | "compact" => mimir.config.brief.recap_tokens, - _ => return Ok(()), + SessionSource::Startup => mimir.config.brief.max_tokens, + SessionSource::Clear | SessionSource::Compact => mimir.config.brief.recap_tokens, + SessionSource::Resume | SessionSource::Other => return Ok(()), }; - let recap = matches!(event_source, "clear" | "compact"); + let recap = event_source.is_context_reset(); let now = now_unix(); // Fire-cap check before any selection work — a capped session pays // zero query cost. Only RENDERED fires increment it (below): a @@ -137,21 +122,26 @@ pub fn show() -> Result<()> { return Ok(()); } - let scope = scope_for_cwd(&mimir, &input); - let mut exclude = suppressed(&mimir, session_id, now, recap)?; - // Compact-boundary overlap: in handoff mode the context guard is about - // to restore the handoff memory on this same event — don't brief it too. - if matches!(event_source, "clear" | "compact") && mimir.config.hooks.context_guard == "handoff" - { - if let Some(n) = memory::list(&mimir.conn, scope, None, Some("session-handoff"), 1)? - .into_iter() - .next() - { + let place = event.place(mimir); + let scope = place.scope; + let mut exclude = suppressed(mimir, session_id, now, recap)?; + // Compact-boundary overlap: in handoff mode the context guard restores + // the handoff memory on this same event — don't brief it too. The two + // hooks run side by side, so "restores" has to cover "has just + // restored": see `handoff_being_restored_in`. The guard restores the + // handoff of this checkout, so that is the one excluded. + if recap && mimir.config.hooks.context_guard() == ContextGuardMode::Handoff { + if let Some(n) = mimir_core::context_guard::handoff_being_restored_in( + &mimir.conn, + scope, + place.checkout.as_deref(), + now, + )? { exclude.insert(n.id); } } - let rules = rules_body(&mimir, scope); + let rules = rules_body(mimir, scope); let ranked = brief::select( &mimir.conn, scope, @@ -192,7 +182,7 @@ pub fn show() -> Result<()> { source::BRIEF, 0, tokens::count(&composed.text), - serde_json::json!({ "items": composed.shown.len(), "source": event_source }), + serde_json::json!({ "items": composed.shown.len(), "source": event_source.as_str() }), ); Ok(()) } @@ -202,10 +192,8 @@ pub fn show() -> Result<()> { /// or written, nothing is recorded — pure preview/explainability. pub fn dry_run() -> Result<()> { let mimir = Mimir::open()?; - let scope = mimir - .project_for_cwd(&std::env::current_dir()?)? - .map(|p| Scope::Project(p.id)) - .unwrap_or(Scope::Global); + let project = mimir.memory_project_for_cwd(&std::env::current_dir()?)?; + let scope = mimir_core::scope::push_scope(project.map(|p| p.id)); let now = now_unix(); let rules = rules_body(&mimir, scope); let ranked = brief::select( @@ -255,7 +243,7 @@ pub fn dry_run() -> Result<()> { "{mark} {:>6.3} {} {} [{flags}]", r.score, short_uid(r.node.kind, &r.node.uid), - r.node.subkind.as_deref().unwrap_or("memory"), + r.node.type_label(), ); } } diff --git a/crates/mimir-cli/src/capture.rs b/crates/mimir-cli/src/capture.rs new file mode 100644 index 0000000..76974ff --- /dev/null +++ b/crates/mimir-cli/src/capture.rs @@ -0,0 +1,964 @@ +//! One capture pipeline behind `mimir remember` and the MCP `remember` tool. +//! +//! A capture has three endings and no others: **stored** exactly as asked, +//! **refused** (it duplicates a live memory, or one somebody forgot on +//! purpose), or **rejected** with nothing written. Each surface used to walk +//! the same nine steps itself, in its own order, and every difference between +//! them was an accident: one validated a duration after the insert, one +//! resolved a link target after it, each scanned a different set of fields for +//! secrets. The order is fixed here, once: +//! +//! 1. validate every argument — nothing is written yet +//! 2. scan every free-text field for secrets — a refusal is recorded, nothing +//! is stored +//! 3. resolve the link target — see [`MissingLink`] +//! 4. `memory::remember` — the duplicate and forgotten refusals +//! 5. attach what was asked for: link, triggers, anchors, expiry, confidence, +//! validity +//! 6. embed (best effort) +//! +//! Steps 4 and 5 are one transaction, so a failure part-way through cannot +//! leave a memory stored without the deadline or the certainty its author +//! asked to record — an omission nothing afterwards would reveal, and one the +//! corrected retry could not repair because it would be refused as a +//! duplicate. +//! +//! What legitimately differs between the two surfaces is a field of +//! [`Capture`], never a branch in a handler: who is acting, whether `--force` +//! exists, and what a missing link target does. + +use anyhow::anyhow; +use mimir_core::error::Error; +use mimir_core::memory::{self, Remember, RememberOutcome}; +use mimir_core::model::{ + now_unix, short_uid, Actor, Kind, MemoryConfidence, MemoryType, MutationOp, Node, Rel, +}; +use mimir_core::secrets::{self, Surface}; +use mimir_core::{anchors, context_guard, format, store, Mimir}; + +/// Everything a caller can ask of a capture. +pub struct Capture { + pub text: String, + pub mtype: MemoryType, + pub tags: Vec, + /// The project the memory belongs to; `None` stores it globally. + pub project_id: Option, + /// The project the caller is working in, whose code graph resolves a + /// symbol *name* given as the link target. Deliberately separate from + /// `project_id`: a global memory about `retry_with_backoff` is still + /// about the `retry_with_backoff` in the checkout it was written from. + pub working_project: Option, + /// Store past a duplicate or a deliberate tombstone. Only a person gets + /// this; an agent that was refused is told who can override it. + pub force: bool, + pub actor: Actor, + /// Where the request came from, for the refusal ledger and for wording + /// an argument error in that surface's vocabulary. + pub surface: Surface, + pub link: Option, + pub missing_link: MissingLink, + pub fires_when: Vec, + pub anchors: Vec, + pub expires_in: Option, + pub resolves_when: Option, + pub confidence: Option, + pub valid_from: Option, + pub valid_to: Option, +} + +/// What a link target that does not exist does to the capture. +/// +/// The two surfaces differ on purpose. A person at a terminal re-runs the +/// command with the name fixed, so the capture is rejected whole. An agent +/// pays for a retry by re-sending the entire memory, and an unlinked memory +/// is still worth having, so it is stored and the reply says the link was +/// not made. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MissingLink { + Reject, + StoreUnlinked, +} + +/// How a capture ended when nothing was rejected. +#[derive(Debug)] +pub enum Captured { + Stored(Box), + /// An exact or near duplicate of this live memory already exists. + /// `rearmed_handoff`: the duplicate is a session handoff that had already + /// been restored once, and offering it again made it restorable again + /// (see [`REARMED_HANDOFF`]). + Duplicate { + node: Node, + rearmed_handoff: bool, + }, + /// This text was deliberately forgotten; `by` is who did it and `on` + /// is when, as far as the ledger still knows. + Forgotten { + node: Node, + by: Option, + on: i64, + }, +} + +/// A stored memory and everything that was attached to it. +#[derive(Debug)] +pub struct Stored { + /// Read back after every attachment, so `meta` is what the store holds. + pub node: Node, + pub link: Linked, + /// The duration as the caller wrote it, and the instant it resolved to. + pub expires: Option<(String, i64)>, + pub resolves_when: Option, + pub confidence: Option, + pub valid: Option<(Option, Option)>, +} + +/// What became of the requested link. +#[derive(Debug)] +pub enum Linked { + NotRequested, + To { + target: Box, + rel: Rel, + }, + /// The target did not resolve and [`MissingLink::StoreUnlinked`] applied. + Missing(String), +} + +/// An argument a capture can be rejected for. One list, so the CLI flag and +/// the MCP field for the same thing share one rule and one description of +/// what was expected. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Arg { + ExpiresIn, + Confidence, + ValidFrom, + ValidTo, +} + +impl Arg { + fn name(self, surface: Surface) -> &'static str { + let flag = !matches!(surface, Surface::McpRemember); + match (self, flag) { + (Arg::ExpiresIn, true) => "--expires-in", + (Arg::ExpiresIn, false) => "expires_in", + (Arg::Confidence, true) => "--confidence", + (Arg::Confidence, false) => "confidence", + (Arg::ValidFrom, true) => "--valid-from", + (Arg::ValidFrom, false) => "valid_from", + (Arg::ValidTo, true) => "--valid-to", + (Arg::ValidTo, false) => "valid_to", + } + } + + fn expected(self) -> &'static str { + match self { + Arg::ExpiresIn => { + "a positive duration like 90d, 2w or 12h (units: h/d/w — use 365d for a year)" + } + Arg::Confidence => "certain, likely or unsure", + Arg::ValidFrom | Arg::ValidTo => "a date like 2024-06-30", + } + } +} + +/// Why a capture wrote nothing. +#[derive(Debug)] +pub enum Rejected { + /// An argument that cannot be honoured as given. + Invalid { arg: Arg, value: String }, + /// A validity interval that ends on or before the day it starts. + ValidityOrder, + /// The link target does not exist and the surface rejects on that. + Link(anyhow::Error), + /// The store refused (a secret) or failed (a database error). + Store(Error), +} + +impl Rejected { + fn invalid(arg: Arg, value: &str) -> Self { + Rejected::Invalid { + arg, + value: value.to_string(), + } + } + + /// The rejection in the vocabulary of `surface`: flags for the CLI, + /// field names for the MCP tool. + pub fn message(&self, surface: Surface) -> String { + match self { + Rejected::Invalid { arg, value } => format!( + "invalid {} {value:?}: expected {}", + arg.name(surface), + arg.expected() + ), + Rejected::ValidityOrder => format!( + "{} must be after {}", + Arg::ValidTo.name(surface), + Arg::ValidFrom.name(surface) + ), + Rejected::Link(err) => err.to_string(), + Rejected::Store(err) => err.to_string(), + } + } + + /// For the CLI: store errors keep their type (so `main` reports them as + /// it reports any other), argument errors carry the flag names. + pub fn into_anyhow(self) -> anyhow::Error { + match self { + Rejected::Store(err) => err.into(), + Rejected::Link(err) => err, + other => anyhow!(other.message(Surface::CliRemember)), + } + } +} + +impl From for Rejected { + fn from(err: Error) -> Self { + Rejected::Store(err) + } +} + +impl From for Rejected { + fn from(err: rusqlite::Error) -> Self { + Rejected::Store(err.into()) + } +} + +/// The relation a capture-time link gets. A memory pointing at something +/// Mimir indexes from disk is *about* it (that is the link grounding reads); +/// a memory pointing at another memory merely relates to it. +fn link_rel(target: &Node) -> Rel { + if target.kind == Kind::Memory { + Rel::Relates + } else { + Rel::About + } +} + +fn parse_day(arg: Arg, value: Option<&str>) -> Result, Rejected> { + value + .map(|s| format::parse_date(s).ok_or_else(|| Rejected::invalid(arg, s))) + .transpose() +} + +/// Who recorded the deliberate forget of `gone`, and when. Read from the +/// ledger because the row cannot say: a refusal that names the wrong party +/// ("a human forgot this", about a tombstone an agent or a sync peer wrote) +/// sends the reader to the wrong place to ask why, and `deleted_at` is the +/// day the memory decayed when it was archived first and forgotten later. +/// Without a ledger row the row's own tombstone date is the best there is. +fn forgotten_by(conn: &rusqlite::Connection, gone: &Node) -> (Option, i64) { + let recorded = mimir_core::audit::history(conn, gone.id) + .ok() + .and_then(|rows| rows.into_iter().rev().find(|m| m.op == MutationOp::Forget)); + match recorded { + Some(row) => (Some(row.actor), row.at), + None => (None, gone.deleted_at.unwrap_or(gone.updated_at)), + } +} + +/// The secret guard, for every surface that stores free text a person or an +/// agent typed: capture, `edit`, the rules pack, a docs note. `declared` is +/// whatever else rides along (trigger phrases, anchors, a title). A refusal +/// is recorded in the ledger by fingerprint, never by value, and nothing is +/// stored. +/// +/// One function because the guard is only as good as its narrowest caller: +/// it used to be called from capture and from `edit`'s body, so a credential +/// pasted as an `--anchor`, a `--title`, a rules pack or a docs note went +/// into the store (and over sync) unchecked. +pub(crate) fn refuse_secrets( + conn: &rusqlite::Connection, + text: &str, + tags: &[String], + declared: &[String], + surface: Surface, +) -> Result<(), Error> { + let Some(kind) = secrets::scan_capture(text, tags, declared) else { + return Ok(()); + }; + secrets::record_refusal( + conn, + &secrets::capture_hash(text, tags, declared), + kind, + surface, + now_unix(), + ); + Err(Error::Secret(kind)) +} + +/// What a duplicate refusal adds when the duplicate is a session handoff +/// that was made restorable again: the capture was refused, and the thing +/// the caller wanted from it will still happen. +pub const REARMED_HANDOFF: &str = "it is the session handoff already stored; it had been \ + restored once and is pending again, so the next clear restores it"; + +/// How a refusal names whoever forgot a memory. Only a person can override +/// the refusal, so the wording has to send the reader to the right party: +/// a tombstone an agent or a sync peer wrote was not "forgotten by a human". +pub fn forgotten_phrase(by: Option) -> &'static str { + match by { + Some(Actor::Human) => "a human forgot this", + Some(Actor::Agent) => "an agent forgot this", + Some(Actor::Sync) => "this was forgotten on another machine", + Some(Actor::System) | None => "this was forgotten", + } +} + +/// Run one capture. See the module documentation for the order and why it +/// is fixed. +pub fn capture(mimir: &mut Mimir, req: Capture) -> Result { + let now = now_unix(); + + // 1. Arguments. Parsed before anything is written: a bad duration costs + // the caller an error message, not a memory that silently never + // expires. + let expires = match req.expires_in.as_deref() { + Some(spec) => Some(( + spec.to_string(), + memory::parse_expires_in(spec, now) + .ok_or_else(|| Rejected::invalid(Arg::ExpiresIn, spec))?, + )), + None => None, + }; + let confidence = req + .confidence + .as_deref() + .map(|level| { + level + .parse::() + .map_err(|_| Rejected::invalid(Arg::Confidence, level)) + }) + .transpose()?; + let valid_from = parse_day(Arg::ValidFrom, req.valid_from.as_deref())?; + let valid_to = parse_day(Arg::ValidTo, req.valid_to.as_deref())?; + if let (Some(from), Some(to)) = (valid_from, valid_to) { + if to <= from { + return Err(Rejected::ValidityOrder); + } + } + + // 2. Secrets, across every free-text field this capture would store. + // The trigger phrases, the anchor patterns and the falsifying + // condition all land in `meta` and replicate with the memory, so a + // credential pasted into any of them leaks exactly as far as one in + // the body would. + let mut declared = req.fires_when.clone(); + declared.extend(req.anchors.iter().cloned()); + declared.extend(req.resolves_when.iter().cloned()); + refuse_secrets(&mimir.conn, &req.text, &req.tags, &declared, req.surface)?; + + // 3. The link target, while rejecting is still free. + let link = match req.link.as_deref() { + None => Linked::NotRequested, + Some(target) => { + match crate::commands::resolve_link_target(&mimir.conn, target, req.working_project) { + Ok(node) => Linked::To { + rel: link_rel(&node), + target: Box::new(node), + }, + Err(err) => match req.missing_link { + MissingLink::Reject => return Err(Rejected::Link(err)), + MissingLink::StoreUnlinked => Linked::Missing(target.to_string()), + }, + } + } + }; + + // 4 and 5. The memory and everything asked of it, or nothing. + let tx = rusqlite::Transaction::new_unchecked( + &mimir.conn, + rusqlite::TransactionBehavior::Immediate, + )?; + // What was offered, kept for the duplicate case below: `remember` takes + // the text and the tags. + let offered_as_handoff = req.tags.iter().any(|t| t == context_guard::HANDOFF_TAG); + let offered_hash = memory::content_hash(&req.text); + // The checkout a handoff is written in, which is the one it will be + // restored in: `working_project` is the checkout's own project even + // when the memory is filed under another (a linked worktree's goes to + // the main checkout's), and its path is the checkout's root. + let handoff_checkout = match req.working_project { + Some(id) if offered_as_handoff => store::get_node(&tx, id).ok().and_then(|p| p.path), + _ => None, + }; + let outcome = memory::remember( + &tx, + Remember { + text: req.text, + mtype: req.mtype, + tags: req.tags, + project_id: req.project_id, + force: req.force, + actor: req.actor, + }, + )?; + let node = match outcome { + RememberOutcome::Created(node) => node, + // Committed, not rolled back: a refusal can leave a note in the + // review queue ("offered again after being forgotten"), and that + // note is the point of noticing. + RememberOutcome::Duplicate(existing) => { + // Saving the same handoff twice is refused like any duplicate, + // but it means "this is where I am, again": the stored copy was + // already consumed by a restore, and without this the next + // clear would deliver nothing at all. + // + // Only the same handoff, offered as one. The duplicate check + // also refuses text that is merely close, and a new handoff + // that resembles an old one must not bring the old one's + // contents back as the state to resume from; nor must a plain + // note that happens to repeat a handoff's words. + // + // And only from the checkout it belongs to: the same words + // saved in another worktree of the repository are that + // session's state, and must not make this one pending again + // for a session that already resumed from it. + let rearmed_handoff = offered_as_handoff + && existing.tags().contains(&context_guard::HANDOFF_TAG) + && existing.content_hash.as_deref() == Some(offered_hash.as_slice()) + && context_guard::restored_at(&existing).is_some() + && context_guard::handoff_is_for(&existing, handoff_checkout.as_deref()); + if rearmed_handoff { + context_guard::rearm_handoff(&tx, existing.id)?; + } + tx.commit()?; + return Ok(Captured::Duplicate { + node: existing, + rearmed_handoff, + }); + } + RememberOutcome::Forgotten(gone) => { + tx.commit()?; + let (by, on) = forgotten_by(&mimir.conn, &gone); + return Ok(Captured::Forgotten { node: gone, by, on }); + } + }; + if let Linked::To { target, rel } = &link { + store::link(&tx, node.id, target.id, *rel, 1.0)?; + } + // A handoff is restored in the checkout it was written in and nowhere + // else (`context_guard::handoff_is_for`), so it records which. Asked of + // the stored node: the tag is what the restore looks for. + if let Some(checkout) = handoff_checkout + .as_deref() + .filter(|_| node.tags().contains(&context_guard::HANDOFF_TAG)) + { + context_guard::set_handoff_checkout(&tx, node.id, checkout)?; + } + let phrases = memory::sanitize_fires_when(req.fires_when); + if !phrases.is_empty() { + store::set_fires_when(&tx, node.id, &phrases)?; + } + let patterns = anchors::sanitize_anchors(req.anchors); + if !patterns.is_empty() { + anchors::set_anchors(&tx, node.id, &patterns)?; + } + if expires.is_some() || req.resolves_when.is_some() { + store::set_expiry( + &tx, + node.id, + expires.as_ref().map(|(_, at)| *at), + req.resolves_when.as_deref(), + )?; + } + if let Some(level) = confidence { + store::set_confidence(&tx, node.id, level)?; + } + let valid = (valid_from.is_some() || valid_to.is_some()).then_some((valid_from, valid_to)); + if valid.is_some() { + store::set_valid_interval(&tx, node.id, valid_from, valid_to)?; + } + let node = store::get_node(&tx, node.id)?; + tx.commit()?; + + // 6. Keep semantic recall fresh; a harmless no-op without a model, and + // never a reason to report a stored memory as failed. + if let Err(err) = mimir.embed_pending() { + tracing::warn!(%err, "embedding new memory failed"); + } + + Ok(Captured::Stored(Box::new(Stored { + node, + link, + expires, + resolves_when: req.resolves_when, + confidence, + valid, + }))) +} + +impl Stored { + /// The lines the CLI prints under the stored memory, one per thing that + /// was attached, in the order a reader checks them. + pub fn detail_lines(&self, describe: impl Fn(&Node) -> String) -> Vec { + let mut lines = Vec::new(); + if let Linked::To { target, .. } = &self.link { + lines.push(format!("linked → {}", describe(target))); + } + if let Some((spec, at)) = &self.expires { + lines.push(format!("expires in {spec} (at {at})")); + } + if let Some(condition) = &self.resolves_when { + lines.push(format!("resolves when: {condition}")); + } + if let Some(level) = self.confidence { + lines.push(format!("confidence: {level}")); + } + if let Some((from, to)) = self.valid { + lines.push(format!( + "valid {} → {}", + from.map(format::full_date).unwrap_or_else(|| "?".into()), + to.map(format::full_date).unwrap_or_else(|| "now".into()) + )); + } + lines + } + + /// The same attachments as fields of the memory's JSON object, so + /// `--json` output is one object a caller can parse whole rather than a + /// JSON line followed by prose. + pub fn extend_json(&self, value: &mut serde_json::Value) { + if let Linked::To { target, rel } = &self.link { + value["linked"] = serde_json::json!({ + "id": short_uid(target.kind, &target.uid), + "rel": rel.as_str(), + }); + } + if let Some((_, at)) = &self.expires { + value["expires_at"] = serde_json::json!(at); + } + if let Some(condition) = &self.resolves_when { + value["resolves_when"] = serde_json::json!(condition); + } + if let Some(level) = self.confidence { + value["confidence"] = serde_json::json!(level.to_string()); + } + if let Some((from, to)) = self.valid { + value["valid_from"] = serde_json::json!(from); + value["valid_to"] = serde_json::json!(to); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use mimir_core::model::NewNode; + + fn engine() -> Mimir { + Mimir::open_in_memory().unwrap() + } + + /// A plain global capture typed by a person; each test changes the one + /// field it is about. + fn request(text: &str) -> Capture { + Capture { + text: text.into(), + mtype: MemoryType::Note, + tags: Vec::new(), + project_id: None, + working_project: None, + force: false, + actor: Actor::Human, + surface: Surface::CliRemember, + link: None, + missing_link: MissingLink::Reject, + fires_when: Vec::new(), + anchors: Vec::new(), + expires_in: None, + resolves_when: None, + confidence: None, + valid_from: None, + valid_to: None, + } + } + + fn memories(m: &Mimir) -> i64 { + m.conn + .query_row("SELECT count(*) FROM node WHERE kind = 'memory'", [], |r| { + r.get(0) + }) + .unwrap() + } + + fn stored(m: &mut Mimir, req: Capture) -> Stored { + match capture(m, req) { + Ok(Captured::Stored(stored)) => *stored, + other => panic!("expected a stored memory, got {other:?}"), + } + } + + fn rejected(m: &mut Mimir, req: Capture) -> Rejected { + match capture(m, req) { + Err(rejected) => rejected, + Ok(other) => panic!("expected a rejection, got {other:?}"), + } + } + + /// "Rejected" has to mean nothing was written, for every argument a + /// capture can be rejected on — otherwise the corrected retry is refused + /// as a duplicate of the half-made memory. And the message has to name + /// the argument the way the caller typed it. + #[test] + fn a_rejected_argument_stores_nothing_and_is_named_in_the_callers_words() { + let mut m = engine(); + let text = "the deploy key rotates every quarter"; + + let mut bad = request(text); + bad.expires_in = Some("soon".into()); + let why = rejected(&mut m, bad); + assert_eq!( + why.message(Surface::CliRemember), + "invalid --expires-in \"soon\": expected a positive duration like 90d, 2w or 12h \ + (units: h/d/w — use 365d for a year)" + ); + assert!(why + .message(Surface::McpRemember) + .starts_with("invalid expires_in \"soon\": expected a positive duration")); + + let mut bad = request(text); + bad.confidence = Some("maybe".into()); + assert_eq!( + rejected(&mut m, bad).message(Surface::McpRemember), + "invalid confidence \"maybe\": expected certain, likely or unsure" + ); + + let mut bad = request(text); + bad.valid_from = Some("last spring".into()); + assert_eq!( + rejected(&mut m, bad).message(Surface::CliRemember), + "invalid --valid-from \"last spring\": expected a date like 2024-06-30" + ); + + let mut bad = request(text); + bad.valid_from = Some("2024-06-30".into()); + bad.valid_to = Some("2024-06-01".into()); + assert_eq!( + rejected(&mut m, bad).message(Surface::CliRemember), + "--valid-to must be after --valid-from" + ); + + assert_eq!(memories(&m), 0, "a rejected capture wrote a memory"); + let mut retry = request(text); + retry.expires_in = Some("90d".into()); + stored(&mut m, retry); + } + + /// Trigger phrases, anchor patterns and the falsifying condition are + /// stored in `meta` and replicate with the memory, so a credential in + /// any of them leaks as far as one in the body. Only the body, the tags + /// and the trigger phrases used to be scanned. + #[test] + fn a_secret_in_any_field_the_capture_would_store_is_refused() { + let secret = format!("AKIA{}", "IOSFODNN7EXAMPLE"); + let mut m = engine(); + for field in ["fires_when", "anchors", "resolves_when"] { + let mut req = request("rotate the uploader credentials after the migration"); + match field { + "fires_when" => req.fires_when = vec![secret.clone()], + "anchors" => req.anchors = vec![secret.clone()], + _ => req.resolves_when = Some(format!("when {secret} is revoked")), + } + let why = rejected(&mut m, req); + assert!( + matches!(why, Rejected::Store(Error::Secret(_))), + "a secret in {field} was not refused: {why:?}" + ); + } + assert_eq!(memories(&m), 0); + } + + /// The one deliberate difference in what a missing link target does: + /// a person's capture is rejected whole, an agent's is stored and the + /// outcome says the link was not made. + #[test] + fn a_missing_link_target_rejects_for_a_person_and_stores_unlinked_for_an_agent() { + let mut m = engine(); + let mut person = request("the retry budget is three attempts"); + person.link = Some("no_such_symbol".into()); + assert!(matches!(rejected(&mut m, person), Rejected::Link(_))); + assert_eq!(memories(&m), 0); + + let mut agent = request("the retry budget is three attempts"); + agent.link = Some("no_such_symbol".into()); + agent.actor = Actor::Agent; + agent.surface = Surface::McpRemember; + agent.missing_link = MissingLink::StoreUnlinked; + let kept = stored(&mut m, agent); + assert!(matches!(&kept.link, Linked::Missing(t) if t == "no_such_symbol")); + } + + /// A symbol name resolves in the project the caller is working in even + /// when the memory itself is stored globally, and the relation says what + /// the link is: *about* something indexed from disk, *relates* to + /// another memory. + #[test] + fn a_link_is_about_an_artifact_and_relates_to_a_memory() { + let mut m = engine(); + let mut proj = NewNode::new(Kind::Project); + proj.title = Some("probe".into()); + let project = store::insert_node(&m.conn, proj).unwrap(); + let mut sym = NewNode::new(Kind::Symbol); + sym.title = Some("retry_with_backoff".into()); + sym.project_id = Some(project.id); + let symbol = store::insert_node(&m.conn, sym).unwrap(); + + let mut global = request("retries back off exponentially with full jitter"); + global.working_project = Some(project.id); + global.link = Some("retry_with_backoff".into()); + let first = stored(&mut m, global); + assert!(first.node.project_id.is_none(), "the memory is global"); + assert!( + matches!(&first.link, Linked::To { target, rel: Rel::About } if target.id == symbol.id) + ); + + let mut second = request("billing webhooks are verified before they are queued"); + second.link = Some(first.node.uid.clone()); + let second = stored(&mut m, second); + assert!(matches!( + &second.link, + Linked::To { + rel: Rel::Relates, + .. + } + )); + } + + /// The node handed back is read after every attachment, so what a + /// surface prints is what the store holds — not the bare memory as it + /// was the instant after the insert. + #[test] + fn the_stored_node_carries_everything_that_was_attached() { + let mut m = engine(); + let mut req = request("the staging certificate is pinned to the old intermediate"); + req.expires_in = Some("30d".into()); + req.resolves_when = Some("when the new intermediate is deployed".into()); + req.confidence = Some("unsure".into()); + req.anchors = vec!["deploy.sh".into()]; + req.fires_when = vec!["release checklist".into()]; + req.valid_from = Some("2024-01-01".into()); + req.valid_to = Some("2024-06-30".into()); + let kept = stored(&mut m, req); + + let (_, at) = kept.expires.clone().expect("an expiry was asked for"); + assert_eq!(kept.node.expires_at(), Some(at)); + assert_eq!( + kept.node.meta["resolves_when"], + "when the new intermediate is deployed" + ); + assert_eq!(kept.node.meta["confidence"], "unsure"); + assert_eq!(kept.node.meta["anchors"][0], "deploy.sh"); + assert_eq!(kept.node.meta["fires_when"][0], "release checklist"); + + let lines = kept.detail_lines(|n| n.uid.clone()); + assert_eq!( + lines, + vec![ + format!("expires in 30d (at {at})"), + "resolves when: when the new intermediate is deployed".to_string(), + "confidence: unsure".to_string(), + "valid 2024-01-01 → 2024-06-30".to_string(), + ] + ); + + let mut json = serde_json::json!({}); + kept.extend_json(&mut json); + assert_eq!(json["expires_at"], at); + assert_eq!(json["confidence"], "unsure"); + assert!(json["valid_from"].is_i64() && json["valid_to"].is_i64()); + } + + /// A handoff is restored once. Saving the very same handoff again is + /// refused as a duplicate, and used to leave the stored copy consumed, + /// so the next clear delivered nothing. Offering it again makes it + /// pending again, and the refusal says so. + #[test] + fn saving_the_same_handoff_again_makes_it_pending_again() { + use mimir_core::model::Scope; + let mut m = engine(); + let handoff = || { + let mut req = request("handoff: migration half applied, run step 4 next"); + req.tags = vec![context_guard::HANDOFF_TAG.into()]; + req + }; + stored(&mut m, handoff()); + assert!(context_guard::restore_handoff_text(&m.conn, Scope::Global) + .unwrap() + .is_some()); + assert!(context_guard::current_handoff(&m.conn, Scope::Global) + .unwrap() + .is_none()); + + match capture(&mut m, handoff()) { + Ok(Captured::Duplicate { + rearmed_handoff, .. + }) => assert!(rearmed_handoff), + other => panic!("expected the duplicate refusal, got {other:?}"), + } + assert!( + context_guard::current_handoff(&m.conn, Scope::Global) + .unwrap() + .is_some(), + "the next clear has a handoff to restore" + ); + + // The same words offered as a plain note are a duplicate and nothing + // more: nobody asked for a handoff. + context_guard::restore_handoff_text(&m.conn, Scope::Global).unwrap(); + match capture( + &mut m, + request("handoff: migration half applied, run step 4 next"), + ) { + Ok(Captured::Duplicate { + rearmed_handoff, .. + }) => assert!(!rearmed_handoff), + other => panic!("expected the duplicate refusal, got {other:?}"), + } + // Nor is a handoff that only resembles the stored one. It is refused + // as a near-duplicate, and the old text must not become the state + // to resume from on the strength of that. + let mut near = request("handoff: migration half applied, run step 4 next today"); + near.tags = vec![context_guard::HANDOFF_TAG.into()]; + match capture(&mut m, near) { + Ok(Captured::Duplicate { + rearmed_handoff, .. + }) => assert!(!rearmed_handoff), + other => panic!("expected the near-duplicate refusal, got {other:?}"), + } + assert!(context_guard::current_handoff(&m.conn, Scope::Global) + .unwrap() + .is_none()); + + // An ordinary duplicate is only a duplicate. + stored(&mut m, request("the retry budget is three attempts")); + match capture(&mut m, request("the retry budget is three attempts")) { + Ok(Captured::Duplicate { + rearmed_handoff, .. + }) => assert!(!rearmed_handoff), + other => panic!("expected the duplicate refusal, got {other:?}"), + } + } + + /// The refusal for a deliberately forgotten memory says who forgot it, + /// read from the ledger. It used to say "a human forgot this" for a + /// tombstone an agent had written through the MCP `forget` tool. + #[test] + fn a_forgotten_refusal_names_who_forgot() { + let mut m = engine(); + let text = "the legacy importer needs python 2"; + let kept = stored(&mut m, request(text)); + store::soft_delete(&m.conn, kept.node.id, Actor::Agent, None).unwrap(); + + match capture(&mut m, request(text)) { + Ok(Captured::Forgotten { node, by, on }) => { + assert_eq!(node.id, kept.node.id); + assert_eq!(by, Some(Actor::Agent)); + assert_eq!(Some(on), node.deleted_at); + assert_eq!(forgotten_phrase(by), "an agent forgot this"); + } + other => panic!("expected the forgotten refusal, got {other:?}"), + } + assert_eq!(forgotten_phrase(Some(Actor::Human)), "a human forgot this"); + assert_eq!(forgotten_phrase(None), "this was forgotten"); + } + + /// A repository's main checkout and two linked worktrees of it, as + /// project rows: the worktrees' memories are filed under the first. + fn checkouts(m: &Mimir) -> (Node, Node, Node) { + let project = |path: &str, name: &str| store::ensure_project(&m.conn, path, name).unwrap(); + ( + project("/repo/main", "main"), + project("/repo/wt-a", "wt-a"), + project("/repo/wt-b", "wt-b"), + ) + } + + /// A handoff offered from `checkout`, filed under the repository's + /// memory project `home`. + fn handoff_from(home: &Node, checkout: &Node, text: &str) -> Capture { + let mut req = request(text); + req.tags = vec![context_guard::HANDOFF_TAG.into()]; + req.project_id = Some(home.id); + req.working_project = Some(checkout.id); + req + } + + /// A stored handoff says which checkout wrote it: the working project's + /// root, not the project the memory is filed under. Nothing else does. + #[test] + fn a_handoff_records_the_checkout_it_was_written_in() { + let mut m = engine(); + let (home, wt_a, _) = checkouts(&m); + let kept = stored( + &mut m, + handoff_from(&home, &wt_a, "handoff: A is mid-rebase onto main"), + ); + assert_eq!(kept.node.project_id, Some(home.id)); + assert_eq!( + context_guard::handoff_checkout(&kept.node), + Some("/repo/wt-a"), + "the node handed back already carries it" + ); + + // A plain memory written in the same checkout records none. + let mut note = request("the importer batches by five hundred rows"); + note.project_id = Some(home.id); + note.working_project = Some(wt_a.id); + assert_eq!( + context_guard::handoff_checkout(&stored(&mut m, note).node), + None + ); + // Nor does a handoff written outside any project. + let mut nowhere = request("handoff: nothing in flight, start on the changelog"); + nowhere.tags = vec![context_guard::HANDOFF_TAG.into()]; + assert_eq!( + context_guard::handoff_checkout(&stored(&mut m, nowhere).node), + None + ); + } + + /// Re-arming follows the rule restoring does. The same words saved from + /// another worktree are refused as the duplicate they are, and do not + /// make this checkout's consumed handoff pending again; saved again + /// from its own checkout, they do. + #[test] + fn the_same_handoff_saved_from_another_checkout_does_not_rearm_it() { + use mimir_core::model::Scope; + let mut m = engine(); + let (home, wt_a, wt_b) = checkouts(&m); + let scope = Scope::Project(home.id); + let text = "handoff: migration half applied, run step 4 next"; + stored(&mut m, handoff_from(&home, &wt_a, text)); + assert!( + context_guard::restore_handoff_text_in(&m.conn, scope, wt_a.path.as_deref()) + .unwrap() + .is_some() + ); + let pending_in = |m: &Mimir, checkout: &Node| { + context_guard::current_handoff_in(&m.conn, scope, checkout.path.as_deref()) + .unwrap() + .is_some() + }; + assert!(!pending_in(&m, &wt_a), "consumed"); + + match capture(&mut m, handoff_from(&home, &wt_b, text)) { + Ok(Captured::Duplicate { + rearmed_handoff, .. + }) => assert!(!rearmed_handoff, "another checkout's save"), + other => panic!("expected the duplicate refusal, got {other:?}"), + } + assert!(!pending_in(&m, &wt_a), "A already resumed from it"); + assert!(!pending_in(&m, &wt_b), "and it never was B's"); + + match capture(&mut m, handoff_from(&home, &wt_a, text)) { + Ok(Captured::Duplicate { + rearmed_handoff, .. + }) => assert!(rearmed_handoff, "its own checkout's save"), + other => panic!("expected the duplicate refusal, got {other:?}"), + } + assert!(pending_in(&m, &wt_a)); + assert!(!pending_in(&m, &wt_b)); + } +} diff --git a/crates/mimir-cli/src/cli_tests.rs b/crates/mimir-cli/src/cli_tests.rs new file mode 100644 index 0000000..9020a8e --- /dev/null +++ b/crates/mimir-cli/src/cli_tests.rs @@ -0,0 +1,64 @@ +//! Parser-level tests: which flag combinations `mimir` accepts. +//! +//! A flag that is silently ignored is worse than one that is refused. The +//! sharpest case was `mimir link A B --dry-run`: `--dry-run` only applies to +//! `--scan`, so the command parsed, ignored the flag, and wrote the link the +//! user had asked to preview. These combinations are declared on the parser +//! instead of being checked (or not) by hand in each command. + +use clap::Parser; + +use crate::Cli; + +fn parses(args: &[&str]) -> bool { + Cli::try_parse_from(std::iter::once("mimir").chain(args.iter().copied())).is_ok() +} + +#[test] +fn link_dry_run_only_exists_for_a_scan() { + assert!(!parses(&["link", "m:AAAAAA", "m:BBBBBB", "--dry-run"])); + assert!(!parses(&["link", "m:AAAAAA", "m:BBBBBB", "--all-projects"])); + assert!(parses(&["link", "--scan", "--dry-run"])); + assert!(parses(&["link", "--scan", "--all-projects", "--dry-run"])); +} + +#[test] +fn link_scan_takes_no_endpoints_and_no_relation() { + assert!(!parses(&["link", "--scan", "m:AAAAAA", "m:BBBBBB"])); + assert!(!parses(&["link", "--scan", "--rel", "about"])); + // The relation's default must not count as "given". + assert!(parses(&["link", "--scan"])); + assert!(parses(&["link", "m:AAAAAA", "m:BBBBBB"])); + assert!(parses(&["link", "m:AAAAAA", "m:BBBBBB", "--rel", "about"])); +} + +#[test] +fn a_review_decision_needs_the_finding_it_decides() { + assert!(!parses(&["review", "--keep"])); + assert!(!parses(&["review", "--dismiss", "--reason", "noise"])); + assert!(!parses(&["review", "--reason", "noise"])); + assert!(!parses(&["review", "3", "--keep", "--dismiss"])); + assert!(parses(&["review"])); + assert!(parses(&["review", "--limit", "5"])); + assert!(parses(&["review", "3", "--keep", "--reason", "both hold"])); +} + +#[test] +fn dismissing_a_miss_is_not_a_listing() { + assert!(!parses(&["misses", "--dismiss", "12", "--all"])); + assert!(!parses(&["misses", "--dismiss", "12", "--resolved"])); + assert!(parses(&["misses", "--dismiss", "12"])); + assert!(parses(&["misses", "--all", "--resolved"])); +} + +/// `--all` used to win over `--global` without a word, so a caller who asked +/// for global-only results got every project's. +#[test] +fn a_read_has_one_scope() { + assert!(!parses(&["recall", "query", "--all", "--global"])); + assert!(!parses(&["list", "--all", "-g"])); + assert!(parses(&["recall", "query", "--all"])); + assert!(parses(&["recall", "query", "-g"])); + assert!(parses(&["list", "--all"])); + assert!(parses(&["list", "-g"])); +} diff --git a/crates/mimir-cli/src/commands.rs b/crates/mimir-cli/src/commands.rs index f16faae..5dca613 100644 --- a/crates/mimir-cli/src/commands.rs +++ b/crates/mimir-cli/src/commands.rs @@ -1,12 +1,16 @@ use std::collections::HashMap; use anyhow::{anyhow, bail, Context, Result}; -use mimir_core::config::{Config, Paths}; -use mimir_core::memory::{self, Remember, RememberOutcome}; -use mimir_core::model::{now_unix, short_uid, Kind, MemoryType, Node, Rel, Scope}; -use mimir_core::search::SearchQuery; +use mimir_core::config::{ColdMode, Config, ContextGuardMode, Paths}; +use mimir_core::index::CollectionKind; +use mimir_core::lifecycle::Lifecycle; +use mimir_core::memory; +use mimir_core::model::{now_unix, short_uid, Kind, MemoryType, Node, Rel, RelOrigin, Scope}; +use mimir_core::search::{Reach, SearchQuery}; use mimir_core::{db, store, Mimir}; +use crate::capture::{self, Capture, Captured, MissingLink}; + pub fn init( no_model: bool, hooks: bool, @@ -15,17 +19,38 @@ pub fn init( ) -> Result<()> { let paths = Paths::resolve()?; let mut config = Config::load(&paths.config_file)?; + let mut hooks = hooks; if let Some(mode) = context_guard { - if !matches!(mode, "off" | "pause" | "handoff") { - bail!("--context-guard must be one of: off, pause, handoff (got {mode:?})"); - } - config.hooks.context_guard = mode.to_string(); + let Some(mode) = ContextGuardMode::parse(mode) else { + bail!( + "--context-guard must be one of: {} (got {mode:?})", + ContextGuardMode::ACCEPTED.join(", ") + ); + }; + config.hooks.context_guard = mode.as_str().to_string(); + // A guard that is on needs its hook entries, so asking for one asks + // for hooks. `off` needs none: on its own it records the mode and + // installs nothing. + hooks |= mode != ContextGuardMode::Off; } config.save(&paths.config_file)?; // Opening creates + migrates the database. - let _conn = db::open(&paths.db_file)?; + let conn = db::open(&paths.db_file)?; println!("config {}", paths.config_file.display()); println!("db {}", paths.db_file.display()); + // A store too large to index on open gets its lookup indexes here, where + // someone is watching and nothing has a deadline. + let missing = db::missing_indexes(&conn)?; + if !missing.is_empty() { + println!( + "index adding {} lookup index(es); this reads the whole store once and can \ + take a minute on a large one…", + missing.len() + ); + db::ensure_indexes(&conn)?; + println!("index added — removing a row no longer scans every other row"); + } + drop(conn); if no_model { println!( "model skipped (BM25-only; run `mimir embed --fetch` to enable semantic search)" @@ -34,7 +59,7 @@ pub fn init( match mimir_core::embed::Embedder::load( &paths, &config.embedding.model, - &config.embedding.device, + config.embedding.device().as_str(), true, ) { Ok(e) => println!("model {} ready ({}-dim)", e.name, e.dim), @@ -44,9 +69,14 @@ pub fn init( } } install_agent_commands(&config); + // A failed model download above leaves a supported state (BM25-only). + // A failed hook install leaves the thing this run was asked for undone, + // so it is remembered and becomes the exit code once the rest is said. + let mut hooks_failed = false; if hooks { if let Err(err) = install_hooks(&config, auto_recall) { eprintln!("hooks install failed: {err}"); + hooks_failed = true; } } println!(); @@ -61,11 +91,17 @@ pub fn init( println!("Per-prompt auto-recall (inject a relevant memory into every prompt) is opt-in:"); println!(" mimir init --hooks --auto-recall"); } - if hooks && config.hooks.context_guard == "off" { + if hooks && config.hooks.context_guard() == ContextGuardMode::Off { println!(); println!("Context-window guard (nudge before an auto-compact takes control) is opt-in:"); println!(" mimir init --hooks --context-guard pause # or: handoff"); } + if hooks_failed { + bail!( + "the hooks were not installed (see `hooks install failed` above); \ + config and database are in place" + ); + } Ok(()) } @@ -97,8 +133,13 @@ jq -n --argjson updated "$UPDATED" '{ /// endpoint first (only live while `mimir mcp --http` is running — see /// `mcp.rs::inject_router`), falling back to the cold `mimir recall-inject` /// CLI path when that's unreachable. Both paths run the exact same -/// relevance-floor/formatting/budget logic (`mimir_core::inject::compute`), -/// so which one answers is purely a latency concern, never a behavior one. +/// relevance-floor/formatting/budget logic (`mimir_core::inject::compute`) +/// over the same project: the script sends the event's `cwd` to the warm +/// endpoint, which resolves the project from it, and runs the cold command +/// from that same directory. Which one answers therefore decides latency +/// and what the search can see — the warm endpoint always has the vector +/// leg, the cold path only under `[hooks] cold_mode = "full"` — never which +/// project is searched or how a hit is judged. /// Unlike `MIMIR_REWRITE_SH`, plain stdout (not a `hookSpecificOutput` JSON /// envelope) is how Claude Code injects UserPromptSubmit context — same /// mechanism as the SessionStart rules hook. @@ -108,9 +149,17 @@ jq -n --argjson updated "$UPDATED" '{ /// documented in README.md's remote-MCP example) — baked into the script at /// install time by `render_recall_script`. `MIMIR_INJECT_URL` still /// overrides it at hook-invocation time, for a one-off run against a -/// different bind without touching config.toml. If no daemon answers there, -/// curl fails fast (2s timeout) and behavior is identical to before this -/// endpoint existed — just slower. +/// different bind without touching config.toml (the same override +/// `infer::DaemonAddr` applies for the daemon, the delegation client and +/// `doctor`). If no daemon answers there, curl fails fast (2s timeout) and +/// behavior is identical to before this endpoint existed — just slower. +/// +/// A daemon started with `MIMIR_HTTP_TOKEN` requires the bearer on every +/// route, `/inject` included, so the script sends it whenever the variable +/// is set in the hook's environment — on curl's stdin (`-H @-`), which +/// keeps it out of the process list. A curl older than 7.55 does not read +/// headers that way; there the request is rejected and the hook goes cold, +/// as it does without a token. /// /// Also extracts a cheap enrichment signal from the caller's working tree: /// the stems (basename, extension stripped) of up to 8 files changed since @@ -122,7 +171,7 @@ jq -n --argjson updated "$UPDATED" '{ /// Silent if `git` isn't on PATH or the cwd isn't a repo — enrichment is a /// nice-to-have, not a requirement. const MIMIR_RECALL_SH: &str = r#"#!/usr/bin/env bash -# mimir-hook-version: 4 +# mimir-hook-version: 5 # Mimir UserPromptSubmit hook — prints at most one relevant memory (or # nothing) as extra context for this turn. Tries the warm HTTP endpoint # (fast; requires `mimir mcp --http` to be running) first, falls back to @@ -160,11 +209,27 @@ if command -v curl >/dev/null 2>&1; then ENC_SESSION=$(printf '%s' "$SESSION" | jq -sRr @uri) URL="${URL}&session=${ENC_SESSION}" fi - if WARM=$(curl -sf --max-time 2 "$URL" 2>/dev/null); then + # One daemon serves every project, so it is told which directory this + # prompt came from and scopes the search to that directory's project — + # the same directory the cold path below runs from. + ENC_CWD=$(printf '%s' "$PROJECT_DIR" | jq -sRr @uri) + URL="${URL}&cwd=${ENC_CWD}" + # A daemon started with MIMIR_HTTP_TOKEN rejects a request without the + # bearer. Sent on stdin (curl 7.55+) so it never shows in a process list. + WARM_OK="" + if [ -n "${MIMIR_HTTP_TOKEN:-}" ]; then + WARM=$(printf 'Authorization: Bearer %s\n' "$MIMIR_HTTP_TOKEN" \ + | curl -sf --max-time 2 -H @- "$URL" 2>/dev/null) && WARM_OK=1 + else + WARM=$(curl -sf --max-time 2 "$URL" 2>/dev/null) && WARM_OK=1 + fi + if [ -n "$WARM_OK" ]; then [ -n "$WARM" ] && printf '%s\n' "$WARM" exit 0 fi fi +# The cold path scopes by its working directory: make that the event's. +cd "$PROJECT_DIR" 2>/dev/null COLD=(mimir recall-inject) [ -n "$ENRICH" ] && COLD+=(--enrich "$ENRICH") [ -n "$SESSION" ] && COLD+=(--session "$SESSION") @@ -172,7 +237,8 @@ COLD=(mimir recall-inject) exit 0 "#; -/// The PreToolUse(Bash|Edit|Write) guard-anchors hook script: unconditional +/// The PreToolUse guard-anchors hook script (installed for the tools in +/// `context_guard_cmd::ANCHOR_TOOLS`): unconditional /// under `--hooks` (no separate opt-in flag) — a memory with no /// `meta.anchors` makes every invocation a silent no-op, so there is /// nothing to gate. All matching logic lives in `mimir_core::anchors` / @@ -223,25 +289,134 @@ fn render_recall_script(inject_url: &str) -> String { MIMIR_RECALL_SH.replace("__MIMIR_INJECT_URL_DEFAULT__", inject_url) } +/// Which opt-in a hook script belongs to. +#[derive(Clone, Copy, PartialEq, Eq)] +enum HookGroup { + /// Installed by `--hooks` itself. + Base, + /// Installed by `--auto-recall`. + AutoRecall, + /// Installed while `[hooks] context_guard` is not off. + ContextGuard, +} + +const REWRITE_SCRIPT: &str = "mimir-rewrite.sh"; +const RECALL_SCRIPT: &str = "mimir-recall.sh"; +const ANCHORS_SCRIPT: &str = "mimir-anchors.sh"; +const GUARD_PROMPT_SCRIPT: &str = "mimir-context-guard-prompt.sh"; +const GUARD_PRECOMPACT_SCRIPT: &str = "mimir-context-guard-precompact.sh"; +const GUARD_SESSION_SCRIPT: &str = "mimir-context-guard-session.sh"; + +/// Every hook script `mimir init --hooks` can install: file name, the text +/// this binary ships, and the opt-in it belongs to. Each text carries a +/// `# mimir-hook-version: N` line, which `doctor` compares against the +/// installed copy. +const HOOK_SCRIPTS: &[(&str, &str, HookGroup)] = &[ + (REWRITE_SCRIPT, MIMIR_REWRITE_SH, HookGroup::Base), + (RECALL_SCRIPT, MIMIR_RECALL_SH, HookGroup::AutoRecall), + (ANCHORS_SCRIPT, MIMIR_ANCHORS_SH, HookGroup::Base), + ( + GUARD_PROMPT_SCRIPT, + MIMIR_CONTEXT_GUARD_PROMPT_SH, + HookGroup::ContextGuard, + ), + ( + GUARD_PRECOMPACT_SCRIPT, + MIMIR_CONTEXT_GUARD_PRECOMPACT_SH, + HookGroup::ContextGuard, + ), + ( + GUARD_SESSION_SCRIPT, + MIMIR_CONTEXT_GUARD_SESSION_SH, + HookGroup::ContextGuard, + ), +]; + +/// The `# mimir-hook-version: N` a hook script carries, if it has one. +fn hook_version(script: &str) -> Option { + script.lines().find_map(|line| { + line.strip_prefix("# mimir-hook-version:")? + .trim() + .parse() + .ok() + }) +} + +/// Installed hook scripts that are older than the ones this binary ships, +/// as `(name, installed version, shipped version)`. A script with no +/// version line predates versioning and counts as 0. Scripts that are not +/// installed are not listed: every hook is opt-in. +fn outdated_hook_scripts(hooks_dir: &std::path::Path) -> Vec<(&'static str, u32, u32)> { + HOOK_SCRIPTS + .iter() + .filter_map(|(name, shipped, _)| { + let installed = std::fs::read_to_string(hooks_dir.join(name)).ok()?; + let installed = hook_version(&installed).unwrap_or(0); + let shipped = hook_version(shipped).unwrap_or(0); + (installed < shipped).then_some((*name, installed, shipped)) + }) + .collect() +} + +/// The command a `SessionStart` entry runs for a `mimir` subcommand that +/// needs no wrapper script: the subcommand, guarded so a machine where +/// `mimir` is gone from PATH (uninstalled, or a session with another +/// environment) starts its sessions without a hook error. The subcommands +/// fail open by themselves; this covers the one failure they cannot. +/// +/// The guard is POSIX shell, which is what Claude Code runs a hook command +/// in everywhere except Windows without Git Bash, where it is PowerShell. +/// The installer cannot know which of the two a Windows machine will use, +/// so there the command stays bare — valid in both, unguarded as before. +fn guarded_hook_command(subcommand: &str) -> String { + if cfg!(windows) { + format!("mimir {subcommand}") + } else { + format!("command -v mimir >/dev/null 2>&1 || exit 0; mimir {subcommand}") + } +} + +/// The anchors matcher earlier versions installed. An entry still carrying +/// it is brought up to [`crate::context_guard_cmd::anchor_matcher`] on the +/// next `mimir init --hooks`; any other matcher is somebody's own edit and +/// is left alone. +const SUPERSEDED_ANCHOR_MATCHERS: &[&str] = &["Bash|Edit|Write"]; + /// Install the opt-in Claude Code hooks: a PreToolUse(Bash) rewrite hook, a -/// PreToolUse(Bash|Edit|Write) guard-anchors hook, and a SessionStart hook -/// that injects the project rules pack — all unconditional under `--hooks` -/// — plus (when `auto_recall`) a UserPromptSubmit hook that injects at -/// most one relevant memory per prompt, and (when `config.hooks. -/// context_guard != "off"`) the UserPromptSubmit/PreCompact/SessionStart -/// context-guard hooks. Idempotent, backs up settings.json, and never -/// clobbers existing hooks. `auto_recall=false` leaves -/// `hooks.UserPromptSubmit`'s auto-recall entry untouched, and -/// `context_guard == "off"` (the default) adds none of the context-guard -/// entries at all — behavior is otherwise identical to before either flag -/// existed (see `merge_hook_settings`'s unit tests). Re-running after -/// editing `config.hooks.inject_url` rewrites `mimir-recall.sh` -/// unconditionally (step 2 below is a plain `fs::write`, no existence -/// check), so the new URL always lands on the next `mimir init --hooks -/// --auto-recall`. +/// PreToolUse guard-anchors hook, and the two SessionStart hooks that +/// inject the project rules pack and the session brief — all unconditional +/// under `--hooks` — plus (when `auto_recall`) a UserPromptSubmit hook that +/// injects at most one relevant memory per prompt, and (when the context +/// guard is on) the UserPromptSubmit/PreCompact/SessionStart context-guard +/// hooks. Idempotent, and never clobbers existing hooks: an entry Mimir +/// installed in an older shape is brought up to date in place, everything +/// else is left as found. `auto_recall=false` leaves +/// `hooks.UserPromptSubmit`'s auto-recall entry untouched, and a guard that +/// is off (the default) adds none of the context-guard entries at all +/// (see `merge_hook_settings`'s unit tests). +/// +/// Order matters, and is: read and merge `settings.json`, then write the +/// scripts, then write `settings.json`. A settings file that cannot be +/// parsed or merged stops the install before anything is on disk. The +/// scripts go first so no entry ever points at a script that is not there; +/// the price is that a settings file that parses but cannot be *written* +/// leaves the scripts behind, unreferenced, and the error names the file. The +/// backup is taken only when there is a file to back up and it is about to +/// change — a re-run that changes nothing rewrites nothing. +/// +/// A script is written when its hook is being installed now, and also when +/// a copy is already installed: `mimir-recall.sh` carries +/// `config.hooks.inject_url`, and every script carries a version, so a +/// plain `mimir init --hooks` after a config change or an upgrade always +/// brings what is installed up to date. fn install_hooks(config: &Config, auto_recall: bool) -> Result<()> { if std::env::var_os("MIMIR_HOME").is_some() { - return Ok(()); // isolated instances never touch the user's agent config + // Isolated instances never touch the user's agent config. + println!( + "hooks skipped — MIMIR_HOME is set, and an isolated instance never touches \ + ~/.claude (unset MIMIR_HOME to install hooks)" + ); + return Ok(()); } let base = directories::BaseDirs::new().context("cannot resolve home directory")?; let claude = base.home_dir().join(".claude"); @@ -251,85 +426,111 @@ fn install_hooks(config: &Config, auto_recall: bool) -> Result<()> { } let hooks_dir = claude.join("hooks"); - std::fs::create_dir_all(&hooks_dir)?; + let script_path = |name: &str| hooks_dir.join(name).to_string_lossy().into_owned(); + let installed = |name: &str| hooks_dir.join(name).is_file(); + let guard_on = config.hooks.context_guard() != ContextGuardMode::Off; - let write_script = |name: &str, content: &str| -> Result { + // 1. Read settings.json and merge into it, in memory. + let settings_path = claude.join("settings.json"); + let existing = match std::fs::read_to_string(&settings_path) { + Ok(text) => Some(text), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(e.into()), + }; + // An empty file is a settings file nobody has put anything in yet (a + // `touch`, or a tool that created it and has not written). It says the + // same as no file, and is not a reason to refuse. + let before: serde_json::Value = match &existing { + Some(text) if text.trim().is_empty() => serde_json::json!({}), + Some(text) => serde_json::from_str(text) + .with_context(|| format!("{} is not valid JSON", settings_path.display()))?, + None => serde_json::json!({}), + }; + let rewrite_script = script_path(REWRITE_SCRIPT); + let anchors_script = script_path(ANCHORS_SCRIPT); + let recall_script = auto_recall.then(|| script_path(RECALL_SCRIPT)); + let context_guard_scripts = guard_on.then(|| { + ( + script_path(GUARD_PROMPT_SCRIPT), + script_path(GUARD_PRECOMPACT_SCRIPT), + script_path(GUARD_SESSION_SCRIPT), + ) + }); + let (after, messages) = merge_hooks( + before.clone(), + &HookPlan { + rewrite_script: &rewrite_script, + recall_script: recall_script.as_deref(), + anchors_script: &anchors_script, + context_guard_scripts: context_guard_scripts + .as_ref() + .map(|(p, c, s)| (p.as_str(), c.as_str(), s.as_str())), + brief_enabled: config.brief.enabled, + }, + )?; + + // 2. Write the delegate scripts (executable). + std::fs::create_dir_all(&hooks_dir)?; + let write_script = |name: &str, content: &str| -> Result<()> { let path = hooks_dir.join(name); - std::fs::write(&path, content)?; + std::fs::write(&path, content).with_context(|| format!("write {}", path.display()))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)) + .with_context(|| format!("make {} executable", path.display()))?; } - Ok(path.to_string_lossy().into_owned()) - }; - - // 1. Write the PreToolUse delegate scripts (executable). - let script_str = write_script("mimir-rewrite.sh", MIMIR_REWRITE_SH)?; - let anchors_script_str = write_script("mimir-anchors.sh", MIMIR_ANCHORS_SH)?; - - // 2. Auto-recall delegate script — only written when opted in. Always - // rewritten (not skipped if already present), so changing - // config.hooks.inject_url and re-running takes effect immediately. - let recall_script_str = if auto_recall { - Some(write_script( - "mimir-recall.sh", - &render_recall_script(&config.hooks.inject_url), - )?) - } else { - None + Ok(()) }; - - // 3. Context-guard delegate scripts — only written when opted in. - let context_guard_scripts = if config.hooks.context_guard != "off" { - Some(( - write_script( - "mimir-context-guard-prompt.sh", - MIMIR_CONTEXT_GUARD_PROMPT_SH, - )?, - write_script( - "mimir-context-guard-precompact.sh", - MIMIR_CONTEXT_GUARD_PRECOMPACT_SH, - )?, - write_script( - "mimir-context-guard-session.sh", - MIMIR_CONTEXT_GUARD_SESSION_SH, - )?, - )) - } else { - None - }; - let context_guard_scripts_ref = context_guard_scripts - .as_ref() - .map(|(p, c, s)| (p.as_str(), c.as_str(), s.as_str())); - - // 4. Merge into settings.json (back it up first). - let settings_path = claude.join("settings.json"); - let root: serde_json::Value = match std::fs::read_to_string(&settings_path) { - Ok(text) => { - std::fs::write(claude.join("settings.json.mimir-bak"), &text)?; - serde_json::from_str(&text).context("settings.json is not valid JSON")? + let recall = render_recall_script(crate::infer::DaemonAddr::configured(config)); + for (name, shipped, group) in HOOK_SCRIPTS { + let wanted = match group { + HookGroup::Base => true, + HookGroup::AutoRecall => auto_recall, + HookGroup::ContextGuard => guard_on, + }; + if wanted || installed(name) { + let content = if *name == RECALL_SCRIPT { + recall.as_str() + } else { + shipped + }; + write_script(name, content)?; } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}), - Err(e) => return Err(e.into()), - }; - let (root, messages) = merge_hook_settings( - root, - &script_str, - recall_script_str.as_deref(), - &anchors_script_str, - context_guard_scripts_ref, - )?; + } - std::fs::write(&settings_path, serde_json::to_string_pretty(&root)?)?; + // 3. Write settings.json, backing up what was there, if it changes. + let changed = after != before; + let backup = claude.join("settings.json.mimir-bak"); + if changed { + if let Some(text) = &existing { + std::fs::write(&backup, text) + .with_context(|| format!("write the backup {}", backup.display()))?; + } + std::fs::write(&settings_path, serde_json::to_string_pretty(&after)?) + .with_context(|| format!("write {}", settings_path.display()))?; + } println!("hooks {}", messages.join("; ")); - println!( - "hooks backup at {}", - claude.join("settings.json.mimir-bak").display() - ); + if changed && existing.is_some() { + println!("hooks backup at {}", backup.display()); + } Ok(()) } +/// What one `mimir init --hooks` run wants in `settings.json`. +struct HookPlan<'a> { + rewrite_script: &'a str, + /// `None` leaves the auto-recall entry untouched. + recall_script: Option<&'a str>, + anchors_script: &'a str, + /// Prompt, precompact and session-start script paths, in that order; + /// `None` adds none of the context-guard entries. + context_guard_scripts: Option<(&'a str, &'a str, &'a str)>, + /// `[brief] enabled`, so the line about the brief entry says whether + /// the entry does anything. + brief_enabled: bool, +} + /// Pure settings.json merge, split out of `install_hooks` so the merge /// logic (idempotency, which keys get touched) is unit-testable without a /// real `~/.claude` — `install_hooks` early-returns under `MIMIR_HOME`, so @@ -341,12 +542,39 @@ fn install_hooks(config: &Config, auto_recall: bool) -> Result<()> { /// add none of the UserPromptSubmit/PreCompact/SessionStart context-guard /// entries — what makes `context_guard == "off"` byte-identical to /// pre-context-guard behavior. +/// +/// [`merge_hooks`] with the brief in its default state. +#[cfg(test)] fn merge_hook_settings( - mut root: serde_json::Value, + root: serde_json::Value, rewrite_script: &str, recall_script: Option<&str>, anchors_script: &str, context_guard_scripts: Option<(&str, &str, &str)>, +) -> Result<(serde_json::Value, Vec)> { + merge_hooks( + root, + &HookPlan { + rewrite_script, + recall_script, + anchors_script, + context_guard_scripts, + brief_enabled: mimir_core::config::BriefConfig::default().enabled, + }, + ) +} + +/// Merge `plan` into a parsed `settings.json`, returning the result and one +/// message per hook saying what happened to it. +/// +/// Each of Mimir's entries is in one of three states — absent, installed +/// in the current shape, or installed in a shape an older version wrote — +/// and the merge moves it to "current" from either of the others without +/// ever adding a second copy. Entries Mimir did not write, and Mimir +/// entries somebody edited by hand, are left exactly as found. +fn merge_hooks( + mut root: serde_json::Value, + plan: &HookPlan, ) -> Result<(serde_json::Value, Vec)> { if !root.is_object() { bail!("settings.json is not a JSON object"); @@ -369,27 +597,49 @@ fn merge_hook_settings( let session_arr = session .as_array_mut() .context("hooks.SessionStart is not an array")?; - if entries_mention(session_arr, "mimir rules show") { + // `--hook` is what tells the command to read the event Claude Code + // puts on its stdin; an entry written before the flag existed is the + // bare command, which reads nothing and scopes by the process cwd. + let rules_command = guarded_hook_command("rules show --hook"); + if upgrade_command(session_arr, "mimir rules show", &rules_command) { + messages.push( + "SessionStart (project rules) upgraded — now follows the session's directory and \ + skips when `mimir` is not on PATH" + .into(), + ); + } else if entries_mention(session_arr, "mimir rules show") { messages.push("SessionStart already installed".into()); } else { session_arr.push(serde_json::json!({ - "hooks": [{ "type": "command", "command": "mimir rules show" }] + "hooks": [{ "type": "command", "command": rules_command }] })); messages.push("SessionStart (project rules) added".into()); } // SessionStart: the session brief (own entry — stdouts concatenate). - // Installed unconditionally but inert until `[brief] enabled = true` - // (the command's own first check), so installing costs nothing. - if entries_mention(session_arr, "mimir brief show") { - messages.push("SessionStart (brief) already installed".into()); + // Installed unconditionally; `[brief] enabled` is the command's own + // first check, so an entry for a disabled brief costs nothing. + let brief_state = if plan.brief_enabled { + "on: `[brief] enabled = true`" + } else { + "inert while `[brief] enabled = false`" + }; + let brief_command = guarded_hook_command("brief show"); + if upgrade_command(session_arr, "mimir brief show", &brief_command) { + messages.push(format!( + "SessionStart (brief) upgraded — now skips when `mimir` is not on PATH ({brief_state})" + )); + } else if entries_mention(session_arr, "mimir brief show") { + messages.push(format!( + "SessionStart (brief) already installed ({brief_state})" + )); } else { session_arr.push(serde_json::json!({ - "hooks": [{ "type": "command", "command": "mimir brief show" }] + "hooks": [{ "type": "command", "command": brief_command }] })); - messages.push( - "SessionStart (session brief) added — inert until `[brief] enabled = true`".into(), - ); + messages.push(format!( + "SessionStart (session brief) added ({brief_state})" + )); } // PreToolUse(Bash): the rewrite hook. Skip if another rewrite hook (e.g. @@ -411,26 +661,56 @@ fn merge_hook_settings( } else { pre_arr.push(serde_json::json!({ "matcher": "Bash", - "hooks": [{ "type": "command", "command": rewrite_script }] + "hooks": [{ "type": "command", "command": plan.rewrite_script }] })); messages.push("PreToolUse (command filter) added".into()); } - // PreToolUse(Bash|Edit|Write): guard anchors. Unconditional under - // `--hooks` — see `MIMIR_ANCHORS_SH`'s doc comment for why there's no - // separate opt-in. - if entries_mention(pre_arr, "mimir-anchors") { + // PreToolUse: guard anchors, for every tool the handler reads a target + // from. Unconditional under `--hooks` — see `MIMIR_ANCHORS_SH`'s doc + // comment for why there's no separate opt-in. + let anchor_matcher = crate::context_guard_cmd::anchor_matcher(); + // An entry is Mimir's to rewrite only when it is exactly what Mimir + // wrote: one hook, running this install's anchors script, under a + // matcher an earlier version installed. A matcher is per entry, so an + // entry that also carries somebody's own hook, or whose command merely + // contains the script's name, is theirs: widening it would start + // running their hook on tools they never asked for. + let wrote_it = |entry: &serde_json::Value| { + let one_hook_ours = entry + .get("hooks") + .and_then(|h| h.as_array()) + .is_some_and(|hooks| { + hooks.len() == 1 + && hooks[0].get("command").and_then(|c| c.as_str()) == Some(plan.anchors_script) + }); + let old_matcher = entry + .get("matcher") + .and_then(|m| m.as_str()) + .is_some_and(|m| SUPERSEDED_ANCHOR_MATCHERS.contains(&m)); + one_hook_ours && old_matcher + }; + let mut upgraded = false; + for entry in pre_arr.iter_mut().filter(|entry| wrote_it(entry)) { + entry["matcher"] = serde_json::json!(anchor_matcher); + upgraded = true; + } + if upgraded { + messages.push(format!( + "PreToolUse anchors upgraded — matcher is now {anchor_matcher}" + )); + } else if entries_mention(pre_arr, "mimir-anchors") { messages.push("PreToolUse anchors already installed".into()); } else { pre_arr.push(serde_json::json!({ - "matcher": "Bash|Edit|Write", - "hooks": [{ "type": "command", "command": anchors_script }] + "matcher": anchor_matcher, + "hooks": [{ "type": "command", "command": plan.anchors_script }] })); messages.push("PreToolUse (guard anchors) added".into()); } // UserPromptSubmit: opt-in auto-recall. Only touched when asked for. - if let Some(recall_script) = recall_script { + if let Some(recall_script) = plan.recall_script { let prompt = hooks .entry("UserPromptSubmit") .or_insert_with(|| serde_json::json!([])); @@ -448,10 +728,10 @@ fn merge_hook_settings( } // Context guard: UserPromptSubmit + PreCompact + SessionStart entries, - // only when `[hooks] context_guard != "off"` — this is what keeps a - // default (`"off"`) install byte-identical to pre-context-guard - // settings.json output (see this fn's unit tests). - if let Some((prompt_script, precompact_script, session_script)) = context_guard_scripts { + // only when the guard is on — this is what keeps a default (`"off"`) + // install byte-identical to pre-context-guard settings.json output (see + // `merge_hook_settings`'s unit tests). + if let Some((prompt_script, precompact_script, session_script)) = plan.context_guard_scripts { let cg_prompt = hooks .entry("UserPromptSubmit") .or_insert_with(|| serde_json::json!([])); @@ -501,6 +781,28 @@ fn merge_hook_settings( Ok((root, messages)) } +/// Rewrite every hook whose command is *exactly* `from` to run `to`; true +/// when at least one was. Exact on purpose: a command somebody extended by +/// hand is theirs. Nothing to do, and `false`, when the two are the same. +fn upgrade_command(entries: &mut [serde_json::Value], from: &str, to: &str) -> bool { + if from == to { + return false; + } + let mut replaced = false; + for entry in entries { + let Some(hooks) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) else { + continue; + }; + for hook in hooks { + if hook.get("command").and_then(|c| c.as_str()) == Some(from) { + hook["command"] = serde_json::json!(to); + replaced = true; + } + } + } + replaced +} + /// True if any hook entry (or its nested hooks) has a command containing `needle`. fn entries_mention(entries: &[serde_json::Value], needle: &str) -> bool { entries.iter().any(|e| { @@ -747,8 +1049,16 @@ pub fn status(json: bool) -> Result<()> { let db_size = std::fs::metadata(&mimir.paths.db_file) .with_context(|| format!("stat {}", mimir.paths.db_file.display()))? .len(); - let (project, detection) = mimir.detect_project(&std::env::current_dir()?)?; - let via = match &detection { + // `project` is the checkout's own; where its memories go is a second + // answer in a linked worktree, and status says both. Status reads: it + // reports memories a linked worktree's own row still holds, and leaves + // moving them to the next memory command. + let here = mimir.projects_for_cwd(&std::env::current_dir()?)?; + let (project, detection) = (&here.checkout, &here.detection); + let leftovers = mimir + .worktree_leftovers(&here)? + .filter(|left| !left.is_empty()); + let via = match detection { mimir_core::scope::Detection::Found { via, .. } => Some(mimir_core::scope::via_label(via)), mimir_core::scope::Detection::NotFound { .. } => None, }; @@ -766,26 +1076,68 @@ pub fn status(json: bool) -> Result<()> { "project": project.as_ref().and_then(|p| p.title.clone()), "project_path": project.as_ref().and_then(|p| p.path.clone()), "scope": if project.is_some() { "project" } else { "global" }, + // `scope` is where a new memory goes. Where a read looks is + // a different answer outside a project, so it has its own key. + "recall_scope": match mimir_core::scope::query_scope(here.memory_id()) { + Scope::Project(_) => "project", + Scope::Global => "global", + Scope::All => "all", + }, "detected_via": via, + // `project` above is the checkout's own (its code graph). + // Its memories are filed under `memory_project`: the same + // project, except in a git linked worktree. + "checkout": project.as_ref().map(|_| here.checkout_kind.as_str()), + "worktree_of": here.checkout_kind.home(), + "memory_project": here.memory.as_ref().and_then(|p| p.title.clone()), + "memory_project_path": here.memory.as_ref().and_then(|p| p.path.clone()), + // `home`: a linked worktree's memories go to the main + // checkout's project; `own_key`: it keeps its own, by the + // `.mimir` id only it carries; `own`: everything else. + "memory_filing": project.as_ref().map(|_| here.filing.as_str()), + // What a linked worktree's own row still holds: `to_move` + // goes home with the next memory command, `kept` is older + // than the worktree and stays. `null` when there is none. + "worktree_memories": leftovers.map(|left| serde_json::json!({ + "to_move": left.to_move, + "kept": left.kept, + "worktree_created_at": left.worktree_created_at, + })), "counts": counts_json, }) ); return Ok(()); } - match (&project, &detection) { - (Some(p), _) => println!( - "project {} ({}) [via: {}]", - p.title.as_deref().unwrap_or("?"), - p.path.as_deref().unwrap_or("?"), - via.unwrap_or("?") - ), + match (project, detection) { + (Some(p), _) => { + println!( + "project {} ({}) [via: {}]", + p.title.as_deref().unwrap_or("?"), + p.path.as_deref().unwrap_or("?"), + via.unwrap_or("?") + ); + if let Some(note) = here.worktree_note() { + println!(" {note}"); + } + if let (Some(left), Some(home)) = (leftovers, &here.memory) { + for line in left.lines(home) { + println!(" {line}"); + } + } + } + // Outside a project the two directions differ, so both are said: + // what is written is global, what is asked searches everything + // (`scope::query_scope`). (None, mimir_core::scope::Detection::NotFound { from }) => println!( - "project (none) — no git root or project marker found above {}; \ - using global scope (touch .mimir here to make it a project)", + "project (none — global scope) — no git root or project marker found above {}; \ + new memories are global, recall searches every project \ + (touch .mimir here to make it a project)", from.display() ), - (None, _) => println!("project (none — global scope)"), + (None, _) => println!( + "project (none — global scope; new memories are global, recall searches every project)" + ), } if counts.is_empty() { println!("store empty"); @@ -798,22 +1150,7 @@ pub fn status(json: bool) -> Result<()> { mimir.paths.db_file.display(), db_size / 1024 ); - let sc = &mimir.config.sync; - if sc.enabled() { - let push = mimir_core::replicate::get_watermark(&mimir.conn, "last_push").unwrap_or(0); - let pull = mimir_core::replicate::get_watermark(&mimir.conn, "last_pull").unwrap_or(0); - let cadence = if sc.auto { - format!("auto every {} min", sc.interval_mins) - } else { - "manual".into() - }; - println!( - "sync {} {} ({cadence}); local watermarks push={push} pull={pull}", - sc.mode, sc.endpoint - ); - } else { - println!("sync off (local store only)"); - } + println!("sync {}", crate::sync::status_line(&mimir)); Ok(()) } @@ -886,7 +1223,11 @@ pub fn doctor(check_only: bool) -> Result<()> { // Informational, and never a failure: a refusal is the guard // working. What's worth seeing is a *retry* — one value offered // repeatedly means something upstream keeps trying to store it - // and doesn't know it's being turned away. + // and doesn't know it's being turned away. The two numbers cover + // different spans, and the line says so: the values are the ones + // refused in the last 30 days, the attempts are every offer of + // those values since each was first seen (the ledger keeps one + // running count per value, not one row per offer). let month_ago = mimir_core::model::now_unix() - 30 * 86_400; if let Ok((distinct, offers)) = mimir_core::secrets::refusal_counts(&conn, month_ago) { if distinct > 0 { @@ -894,9 +1235,9 @@ pub fn doctor(check_only: bool) -> Result<()> { "secret guard", true, format!( - "{distinct} value(s) refused in the last 30d over {offers} attempt(s)\ - {} (fingerprints only — the values were never stored; \ - `mimir refusals` for detail)", + "{distinct} value(s) refused in the last 30d, offered {offers} \ + time(s) in all since first seen{} (fingerprints only — the \ + values were never stored; `mimir refusals` for detail)", if offers > distinct { " — something is retrying" } else { @@ -935,18 +1276,86 @@ pub fn doctor(check_only: bool) -> Result<()> { if let Some(detail) = link_scan_hint(&conn) { check("link scan", true, detail, &mut failures); } + // Two more things a store can be in that nothing else reports. + // Both are hints, not failures: the store is sound, only slower + // and larger than it needs to be. Watchdog mode prints no hint, + // so it does not pay for them either: the second one stats every + // project directory and counts the rows of the missing ones. + if !check_only { + if let Ok(missing) = db::missing_indexes(&conn) { + if !missing.is_empty() { + check( + "indexes", + true, + format!( + "{} lookup index(es) not built yet ({}), so removing any \ + row scans the whole store — run `mimir init` once to build \ + them", + missing.len(), + missing.join(", ") + ), + &mut failures, + ); + } + } + if let Some(detail) = missing_projects_hint(&conn) { + check("projects", true, detail, &mut failures); + } + } // Same argument for the review queue: findings nobody is told // about are findings nobody acts on, which is the state - // `consolidate`'s contradiction report was already in. - if let Ok(m) = Mimir::open() { - if let Some(detail) = crate::review_cmd::summary(&m) { - check("review", true, detail, &mut failures); + // `consolidate`'s contradiction report was already in. `mimir + // review` runs its detectors before it lists, so the count here + // does too — otherwise this line says "nothing waiting" (by + // saying nothing) about a queue the command it points at would + // fill. Watchdog mode prints no such line and skips the scan. + if !check_only { + if let Ok(m) = Mimir::open() { + let _ = mimir_core::review::scan(&m.conn); + if let Some(detail) = crate::review_cmd::summary(&m) { + check("review", true, detail, &mut failures); + } } } } Err(e) => check("db", false, e.to_string(), &mut failures), } + // The config every command loads. A file that does not parse stops all + // of them; a mode nobody recognizes is quieter — the setting falls back + // (see `Config::issues`) and this is the surface that says so, one line + // per value, with what it is behaving as meanwhile. + let config = match Config::load(&paths.config_file) { + Ok(config) => { + let issues = config.issues(); + if issues.is_empty() { + check( + "config", + true, + paths.config_file.display().to_string(), + &mut failures, + ); + } + for issue in issues { + // A value with a fallback is a misspelling of a setting that + // still behaves as something documented: worth a FAIL line + // to whoever runs `doctor`, not worth the watchdog raising + // an alarm every time it runs on a store that is sound. + // Only a value with no fallback (the proxy will not start) + // fails the unattended check. + if check_only && issue.behaves_as.is_some() { + continue; + } + check("config", false, issue.to_string(), &mut failures); + } + config + } + Err(e) => { + check("config", false, e.to_string(), &mut failures); + Config::default() + } + }; + // Everything below is informational (can never fail the exit code), so // watchdog mode skips it — including the daemon probe's network wait. if !check_only { @@ -956,17 +1365,20 @@ pub fn doctor(check_only: bool) -> Result<()> { .unwrap_or("not compiled in (CPU; rebuild with --features gpu-webgpu or gpu-cuda)") ); - let model_present = paths.models_dir.exists() - && std::fs::read_dir(&paths.models_dir) - .map(|mut d| d.next().is_some()) - .unwrap_or(false); + // The engine's own predicate: the ready marker of the *configured* + // model. A models directory that merely has something in it — a + // reranker, another embedder, half a download — is not a model + // search can load. + let model = &config.embedding.model; check( "model", true, // informational until embeddings land; BM25-only is a valid state - if model_present { - format!("present at {}", paths.models_dir.display()) + if mimir_core::embed::model_ready(&paths, model) { + format!("{model} present at {}", paths.models_dir.display()) } else { - "not downloaded (search is BM25-only until `mimir init` fetches it)".into() + format!( + "{model} not downloaded (search is BM25-only until `mimir init` fetches it)" + ) }, &mut failures, ); @@ -975,35 +1387,84 @@ pub fn doctor(check_only: bool) -> Result<()> { // `mimir mcp --http` is actually up. Absence is a normal, supported // state — the hooks fall back to the cold `mimir recall-inject` path — // so this must never fail `doctor`'s exit code, same precedent as the - // "model" check above. - let (inject_url, delegation) = Config::load(&paths.config_file) - .map(|c| (c.hooks.inject_url, c.daemon.inference)) - .unwrap_or_else(|_| { - ( - mimir_core::config::HooksConfig::default().inject_url, - mimir_core::config::DaemonConfig::default().inference, - ) - }); - let warm = ureq::get(&inject_url) - .timeout(std::time::Duration::from_secs(1)) - .call() - .is_ok(); + // "model" check above. Probed the way the hook script probes it: the + // same address (`DaemonAddr`), and the same bearer when + // MIMIR_HTTP_TOKEN is set, so "warm" here means warm for the hook. + let addr = crate::infer::DaemonAddr::resolve(&config); + let inject_url = addr.inject_url(); + let delegation = config.daemon.inference(); + let token = crate::mcp::http_token_from_env(); + let mut probe = ureq::get(inject_url).timeout(std::time::Duration::from_secs(1)); + if let Some(token) = &token { + probe = probe.set("Authorization", &format!("Bearer {token}")); + } check( "daemon", true, - if warm { - format!( + match probe.call() { + Ok(_) => format!( "warm ({inject_url} reachable — hooks use the fast HTTP path; \ inference delegation: {delegation})" - ) - } else { - format!( + ), + Err(ureq::Error::Status(401, _)) => format!( + "cold ({inject_url} answers 401 — the daemon requires a bearer token and \ + MIMIR_HTTP_TOKEN {}; hooks fall back to `mimir recall-inject`; \ + inference delegation: {delegation})", + if token.is_some() { + "in this environment is not the one it was started with" + } else { + "is not set in this environment" + } + ), + Err(ureq::Error::Status(code, _)) => format!( + "cold ({inject_url} answers HTTP {code}, which a Mimir daemon does not — \ + hooks fall back to `mimir recall-inject`; inference delegation: \ + {delegation})" + ), + Err(_) => format!( "cold ({inject_url} not reachable — hooks fall back to `mimir recall-inject`; \ run `mimir daemon` for the warm path; inference delegation: {delegation})" - ) + ), }, &mut failures, ); + + // Installed hook scripts against the ones this binary ships. A + // script is a copy made at `init` time, so an upgraded binary keeps + // running the old copy until someone re-installs — and nothing else + // would ever say so. + if let Some(base) = directories::BaseDirs::new() { + let hooks_dir = base.home_dir().join(".claude").join("hooks"); + let installed = HOOK_SCRIPTS + .iter() + .filter(|(name, ..)| hooks_dir.join(name).is_file()) + .count(); + let outdated = outdated_hook_scripts(&hooks_dir); + if !outdated.is_empty() { + let list: Vec = outdated + .iter() + .map(|(name, found, shipped)| format!("{name} v{found}, shipped v{shipped}")) + .collect(); + check( + "hooks", + true, + format!( + "{} of {installed} installed script(s) older than this binary ({}) — \ + re-run `mimir init --hooks`", + outdated.len(), + list.join("; ") + ), + &mut failures, + ); + } else if installed > 0 { + check( + "hooks", + true, + format!("{installed} installed script(s) match this binary"), + &mut failures, + ); + } + } } if failures > 0 { @@ -1033,139 +1494,77 @@ pub fn remember( ) -> Result<()> { let mut mimir = Mimir::open()?; let mtype: MemoryType = mtype.parse()?; - // Parse BEFORE writing anything: a bad duration should cost the user an - // error message, not a stored memory that silently never expires. - let expires_at = match expires_in.as_deref() { - Some(spec) => Some(memory::parse_expires_in(spec, now_unix()).ok_or_else(|| { - anyhow!( - "invalid --expires-in {spec:?}: expected a positive duration \ - like 90d, 2w or 12h (units: h/d/w — use 365d for a year)" - ) - })?), - None => None, - }; - // Same rule: reject before writing. A memory stored without the - // certainty its author asked to record is worse than an error, because - // nothing afterwards reveals the omission. - let confidence = confidence - .as_deref() - .map(|c| { - c.parse::() - .map_err(|_| { - anyhow!("invalid --confidence {c:?}: expected certain, likely or unsure") - }) - }) - .transpose()?; - // Same rule again for the validity interval. - let parse_day = |label: &str, v: &Option| -> Result> { - v.as_deref() - .map(|s| { - mimir_core::format::parse_date(s).ok_or_else(|| { - anyhow!("invalid --{label} {s:?}: expected a date like 2024-06-30") - }) - }) - .transpose() - }; - let valid_from = parse_day("valid-from", &valid_from)?; - let valid_to = parse_day("valid-to", &valid_to)?; - if let (Some(f), Some(t)) = (valid_from, valid_to) { - if t <= f { - bail!("--valid-to must be after --valid-from"); - } - } - let project = if global { - None + // The checkout this was run from resolves a symbol name given to + // `--link`, global memory or not; `--global` only decides where the + // memory itself lives. A global capture therefore must not fail because + // the directory it was typed in could not be resolved to a project. + // + // Two projects, then: the checkout's own for the symbol lookup, and the + // memory project for the memory, which in a linked worktree is the + // main checkout's. + let detected = mimir.projects_for_cwd(&std::env::current_dir()?); + let (working_project, memory_project) = if global { + detected + .ok() + .map_or((None, None), |p| (p.checkout_id(), p.memory_id())) } else { - mimir.project_for_cwd(&std::env::current_dir()?)? + let here = detected?; + (here.checkout_id(), here.memory_id()) }; - if let Some(kind) = mimir_core::secrets::scan_capture(&text, &tags, &fires_when) { - mimir_core::secrets::record_refusal( - &mimir.conn, - &mimir_core::secrets::capture_hash(&text, &tags, &fires_when), - kind, - mimir_core::secrets::Surface::CliRemember, - mimir_core::model::now_unix(), - ); - bail!(mimir_core::error::Error::Secret(kind)); - } - let outcome = memory::remember( - &mimir.conn, - Remember { + let outcome = capture::capture( + &mut mimir, + Capture { text, mtype, tags, - project_id: project.as_ref().map(|p| p.id), + project_id: if global { None } else { memory_project }, + working_project, force, actor: mimir_core::model::Actor::Human, + surface: mimir_core::secrets::Surface::CliRemember, + link: link_ref, + missing_link: MissingLink::Reject, + fires_when, + anchors, + expires_in, + resolves_when, + confidence, + valid_from, + valid_to, }, - )?; + ) + .map_err(capture::Rejected::into_anyhow)?; let projects = store::project_titles(&mimir.conn)?; let snippet = mimir.config.output.snippet_chars; match outcome { - RememberOutcome::Created(node) => { + Captured::Stored(stored) => { if json { - println!("{}", node_json(&node, &projects)); + let mut value = node_json(&stored.node, &projects); + stored.extend_json(&mut value); + println!("{value}"); } else { - println!("{}", line(&node, &projects, snippet)); - } - if let Some(r) = link_ref { - let target = resolve_link_target(&mimir.conn, &r, project.as_ref().map(|p| p.id))?; - store::link(&mimir.conn, node.id, target.id, Rel::Relates, 1.0)?; - println!("linked → {}", line(&target, &projects, 0)); - } - if !fires_when.is_empty() { - let phrases = memory::sanitize_fires_when(fires_when); - if !phrases.is_empty() { - store::set_fires_when(&mimir.conn, node.id, &phrases)?; - } - } - if !anchors.is_empty() { - let patterns = mimir_core::anchors::sanitize_anchors(anchors); - if !patterns.is_empty() { - mimir_core::anchors::set_anchors(&mimir.conn, node.id, &patterns)?; + println!("{}", line(&stored.node, &projects, snippet)); + for detail in stored.detail_lines(|n| line(n, &projects, 0)) { + println!("{detail}"); } } - if expires_at.is_some() || resolves_when.is_some() { - store::set_expiry(&mimir.conn, node.id, expires_at, resolves_when.as_deref())?; - if let Some(ts) = expires_at { - println!( - "expires in {} (at {ts})", - expires_in.as_deref().unwrap_or("") - ); - } - if let Some(c) = resolves_when.as_deref() { - println!("resolves when: {c}"); - } - } - if let Some(c) = confidence { - store::set_confidence(&mimir.conn, node.id, c)?; - println!("confidence: {c}"); - } - if valid_from.is_some() || valid_to.is_some() { - store::set_valid_interval(&mimir.conn, node.id, valid_from, valid_to)?; - println!( - "valid {} → {}", - valid_from - .map(mimir_core::format::full_date) - .unwrap_or_else(|| "?".into()), - valid_to - .map(mimir_core::format::full_date) - .unwrap_or_else(|| "now".into()) - ); - } - // Keep semantic recall fresh; harmless no-op without a model. - if let Err(err) = mimir.embed_pending() { - tracing::warn!(%err, "embedding new memory failed"); - } Ok(()) } - RememberOutcome::Duplicate(existing) => bail!( - "refused: near-duplicate of\n {}\nuse --force to store anyway", - line(&existing, &projects, snippet) + Captured::Duplicate { + node: existing, + rearmed_handoff, + } => bail!( + "refused: near-duplicate of\n {}\n{}", + line(&existing, &projects, snippet), + if rearmed_handoff { + capture::REARMED_HANDOFF + } else { + "use --force to store anyway" + } ), - RememberOutcome::Forgotten(gone) => bail!( + Captured::Forgotten { node: gone, on, .. } => bail!( "refused: this was forgotten on {}\n {}\nuse --force to bring it back deliberately", - mimir_core::format::full_date(gone.deleted_at.unwrap_or(gone.updated_at)), + mimir_core::format::full_date(on), line(&gone, &projects, snippet) ), } @@ -1188,8 +1587,13 @@ pub fn recall( as_of: Option, ) -> Result<()> { let mut mimir = Mimir::open()?; + // Memories and code and docs are read in two scopes that differ in a + // linked worktree. The query's own scope is the memories', which is + // what the miss ledger files this question under. + let place = read_reach(&mimir, global, all)?; + let reach = place.reach; let query = SearchQuery { - scope: read_scope(&mimir, global, all)?, + scope: reach.memories, kinds: parse_kind_filter(kind)?, since: since.map(|s| parse_since(&s)).transpose()?, limit: limit.unwrap_or(mimir.config.output.default_limit), @@ -1201,13 +1605,26 @@ pub fn recall( as_of, text, }; - let (mut hits, legs) = mimir.search_with_evidence(&query, rerank)?; + let mimir_core::SearchOutcome { + mut hits, + legs, + rerank: reranked, + } = mimir.search_with_outcome_within(&query, reach, rerank)?; + // Another checkout's session handoff is not this session's to find; it + // does not count as an answer either. + hits.retain(|hit| place.shows(&hit.node)); + // `--rerank` was asked for by name, so falling back to the fused order + // is said out loud — on stderr, where it cannot end up in a pipe that + // parses the hits. + if let Some(note) = reranked.note().filter(|_| rerank) { + eprintln!("--rerank: {note}"); + } let mut strengths = mimir_core::strength::classify_page(&hits, &query.text, &legs); // Judged on the page as retrieved, before `--min-score` trims it: a // threshold the caller chose is not evidence the store lacks an answer. - // A time-sliced view (`--since`, `--as-of`) is not a question to the - // store as it stands, so it never feeds the ledger either. - if mimir.config.learn.log_misses && query.since.is_none() && as_of.is_none() { + // Which recalls count at all is `misses::should_observe`'s call, shared + // with the MCP tool. + if mimir_core::misses::should_observe(mimir.config.learn.log_misses, &query) { mimir_core::misses::observe( &mimir.conn, &query.text, @@ -1257,8 +1674,9 @@ pub fn recall( if !json { println!( "as of {} — what the store held then, not what was true then. \ - Ranking is more lexical than usual: the semantic index only \ - covers memories that are still live.", + A hit is shown in the wording it had then, but it is found by \ + the wording it has now. Ranking is more lexical than usual: \ + the semantic index only covers memories that are still live.", mimir_core::format::full_date(at) ); } @@ -1277,6 +1695,12 @@ pub fn recall( if json { let mut value = node_json(&hit.node, &projects); value["score"] = serde_json::json!(hit.score); + // On a recall hit `strength` is the match label ("strong" / + // "weak"), where every other JSON surface puts the node's + // learned strength under that key. Scripts read the label + // there, so it stays; the number keeps a key of its own + // instead of being overwritten out of the output. + value["node_strength"] = serde_json::json!(hit.node.strength); value["strength"] = serde_json::json!(strength.as_str()); println!("{value}"); } else if full { @@ -1344,8 +1768,9 @@ pub fn recall( /// - `"fast"` (default): BM25-only, via `compute_with_mode(.., bm25_only /// = true)` — never calls `ensure_embedder`, so no ONNX load and no /// matrix build. This is the mode actually measured for hook latency -/// (see CHANGELOG); an unrecognized value logs a warning and falls back -/// to `"full"`, the safe default, same precedent as `[rerank] auto`. +/// (see CHANGELOG); an unrecognized value behaves as `"full"` +/// (`ColdMode::UNKNOWN`) and is reported by `mimir doctor`, not by +/// every prompt's hook. /// - `"full"`: restores the pre-`cold_mode` behavior — hybrid search with /// the embedder loaded cold, same as the warm endpoint. /// @@ -1356,49 +1781,68 @@ pub fn recall( /// `MIMIR_RECALL_SH`'s `git diff`), passed straight through to /// `inject::compute_with_mode` — see that function's doc comment for how /// it's used. +/// +/// `session`: the per-session dedup key. An empty one is no key, as on the +/// warm path — an empty key would be one ledger shared by every session +/// that sent none. +/// +/// A hook entry point, so it never fails the prompt it runs on: an error +/// is a line on stderr and exit 0 (`context_guard_cmd::fail_open`). pub fn recall_inject( prompt: String, enrich: Option, session: Option, ) -> Result<()> { - let mut mimir = Mimir::open()?; - let scope = read_scope(&mimir, false, false)?; - let enrich = enrich.unwrap_or_default(); - let bm25_only = match mimir.config.hooks.cold_mode.as_str() { - "fast" => true, - "full" => false, - other => { - tracing::warn!( - cold_mode = other, - "unknown [hooks] cold_mode value; treating as full" - ); - false + crate::context_guard_cmd::fail_open("recall-inject", || { + let mut mimir = Mimir::open()?; + let place = read_reach(&mimir, false, false)?; + let checkout = place.handoffs_of.flatten(); + let enrich = enrich.unwrap_or_default(); + let bm25_only = mimir.config.hooks.cold_mode() == ColdMode::Fast; + if let Some(text) = mimir_core::inject::compute_in_checkout( + &mut mimir, + &prompt, + &enrich, + place.reach.memories, + bm25_only, + session.as_deref().filter(|s| !s.is_empty()), + checkout.as_deref(), + )? { + println!("{text}"); } - }; - if let Some(text) = mimir_core::inject::compute_with_session( - &mut mimir, - &prompt, - &enrich, - scope, - bm25_only, - session.as_deref(), - )? { - println!("{text}"); - } - Ok(()) + Ok(()) + }) } /// `mimir daemon` — a thin, discoverable alias for `mimir mcp --http `. -/// The bind address is derived from `config.hooks.inject_url` (the exact -/// same key `MIMIR_RECALL_SH` already reads — see `render_recall_script`), -/// so there is one setting for "where does the warm path live" instead of -/// two independent ones that could drift apart. No auto-spawn, no process -/// supervision: this is purely a memorable name for a command the hooks -/// already know how to fall back from — see `contrib/mimir-daemon.service` -/// for running it unattended. +/// The bind address is `infer::DaemonAddr`: `config.hooks.inject_url` (the +/// exact same key `MIMIR_RECALL_SH` already reads — see +/// `render_recall_script`) unless `MIMIR_INJECT_URL` overrides it, as it +/// does for the hook script, the delegation client and `doctor`. So there +/// is one answer to "where does the warm path live" instead of several +/// that could drift apart. No auto-spawn, no process supervision: this is +/// purely a memorable name for a command the hooks already know how to +/// fall back from — see `contrib/mimir-daemon.service` for running it +/// unattended. +/// +/// Loopback only. `daemon` takes no flags, so an address that is not +/// loopback is refused here, with the command that can serve it, rather +/// than by the transport's own refusal, which recommends a flag this +/// command does not have. pub fn daemon() -> Result<()> { let mimir = Mimir::open()?; - let addr = inject_addr(&mimir.config.hooks.inject_url)?; + let daemon_addr = crate::infer::DaemonAddr::resolve(&mimir.config); + let addr = daemon_addr.bind()?; + if !crate::mcp::bind_is_loopback(&addr) { + bail!( + "refusing to run the daemon on non-loopback address `{addr}` (from {}): its HTTP \ + surface gives anyone who can reach the port full read/write access to the store. \ + Point it at 127.0.0.1 — or, if the exposure is deliberate (e.g. a container port \ + published to 127.0.0.1 only), serve the same endpoints with \ + `mimir mcp --http {addr} --http-allow-remote`.", + daemon_addr.origin() + ); + } println!( "mimir daemon: warm path at http://{addr}/inject — the auto-recall hook will use \ this instead of the cold `mimir recall-inject` fallback; /embed and /rerank serve \ @@ -1410,19 +1854,11 @@ pub fn daemon() -> Result<()> { } /// Strip `config.hooks.inject_url` (e.g. `"http://127.0.0.1:8077/inject"`) -/// down to the bare `host:port` that `mimir mcp --http` binds to. Split out -/// as a pure function so the parsing is unit-testable without a real config -/// file — mirrors `render_recall_script`'s split for the same reason. +/// down to the bare `host:port` that `mimir mcp --http` binds to: the +/// configured layer of `infer::DaemonAddr::bind`, where the parsing lives. +#[cfg(test)] fn inject_addr(inject_url: &str) -> Result { - let without_scheme = inject_url - .split_once("://") - .map(|(_, rest)| rest) - .unwrap_or(inject_url); - let host_port = without_scheme.split('/').next().unwrap_or(""); - if host_port.is_empty() { - bail!("config.hooks.inject_url `{inject_url}` has no host:port to bind to"); - } - Ok(host_port.to_string()) + crate::infer::DaemonAddr::from_parts(inject_url, None).bind() } pub fn get(json: bool, refs: Vec) -> Result<()> { @@ -1456,9 +1892,20 @@ pub fn list( limit: usize, ) -> Result<()> { let mimir = Mimir::open()?; - let scope = read_scope(&mimir, global, all)?; + let place = read_reach(&mimir, global, all)?; + let scope = place.reach.memories; let mtype = mtype.map(|t| t.parse::()).transpose()?; - let nodes = memory::list(&mimir.conn, scope, mtype, tag.as_deref(), limit)?; + let nodes = match &place.handoffs_of { + None => memory::list(&mimir.conn, scope, mtype, tag.as_deref(), limit)?, + Some(checkout) => mimir_core::context_guard::list_in_checkout( + &mimir.conn, + scope, + mtype, + tag.as_deref(), + limit, + checkout.as_deref(), + )?, + }; let projects = store::project_titles(&mimir.conn)?; if nodes.is_empty() && !json { println!("no memories"); @@ -1500,7 +1947,7 @@ pub fn mark(reference: &str, useful: bool) -> Result<()> { /// would have shipped a grounding feature that nearly nothing could reach — /// the same shape as the anchors that sat at zero adoption because the only /// way to set one was at capture time. -fn resolve_link_target( +pub(crate) fn resolve_link_target( conn: &rusqlite::Connection, reference: &str, project_id: Option, @@ -1729,7 +2176,10 @@ pub fn audit(reference: Option<&str>, limit: usize, json: bool) -> Result<()> { } None => mimir_core::audit::recent(&mimir.conn, limit)?, }; - if rows.is_empty() { + // `--json` prints one object per row and nothing else, so an empty + // ledger is empty output, as it is for `list` and `recall`; the sentence + // is for a person reading a terminal. + if rows.is_empty() && !json { println!("nothing recorded"); return Ok(()); } @@ -1821,8 +2271,18 @@ pub fn history(reference: &str) -> Result<()> { // Say what this does NOT cover, rather than letting an empty list read as // "nothing happened": a deliberate forget purges prior wordings on // purpose, so their absence here is the deletion working. - if node.deleted_at.is_some() { - println!("\nforgotten — prior wordings were purged with it, by design."); + // + // Only a deliberate forget, though. Decay archival also tombstones, and + // it keeps prior wordings on purpose — telling that reader they were + // purged was simply false. + match node.lifecycle(now_unix()) { + Lifecycle::Forgotten => { + println!("\nforgotten — prior wordings were purged with it, by design.") + } + Lifecycle::Archived => println!( + "\narchived — it decayed while idle and nobody deleted it, so prior wordings are kept." + ), + Lifecycle::Live | Lifecycle::Expired | Lifecycle::Superseded => {} } Ok(()) } @@ -1858,15 +2318,19 @@ fn print_consolidate_report(report: &mimir_core::consolidate::Report, dry_run: b } } +/// Forget a memory. Which references resolve, and what may be forgotten, +/// is decided in `store::forget` — the same function the MCP tool calls — +/// so `--hard` reaches an existing tombstone and a plain forget turns an +/// archived memory into a forgotten one. pub fn forget(reference: &str, hard: bool, reason: Option<&str>) -> Result<()> { let mimir = Mimir::open()?; - let node = store::resolve_ref(&mimir.conn, reference)?; - let actor = mimir_core::model::Actor::Human; - if hard { - store::hard_delete(&mimir.conn, node.id, actor, reason)?; - } else { - store::soft_delete(&mimir.conn, node.id, actor, reason)?; - } + let node = store::forget( + &mimir.conn, + reference, + hard, + mimir_core::model::Actor::Human, + reason, + )?; println!( "forgot {} {}{}", short_uid(node.kind, &node.uid), @@ -1889,20 +2353,16 @@ pub fn edit( let mimir = Mimir::open()?; let node = store::resolve_ref(&mimir.conn, reference)?; let mtype = mtype.map(|t| t.parse::()).transpose()?; - // Same guard as `remember`: an edited body/tags is a capture too - // (memory::Edit has no fires_when field, hence the empty slice). - if let Some(kind) = - mimir_core::secrets::scan_capture(&text, tags.as_deref().unwrap_or(&[]), &[]) - { - mimir_core::secrets::record_refusal( - &mimir.conn, - &mimir_core::secrets::capture_hash(&text, tags.as_deref().unwrap_or(&[]), &[]), - kind, - mimir_core::secrets::Surface::CliEdit, - mimir_core::model::now_unix(), - ); - bail!(mimir_core::error::Error::Secret(kind)); - } + // Same guard as `remember`: an edited body, title or tag set is a + // capture too. + let declared: Vec = title.iter().cloned().collect(); + capture::refuse_secrets( + &mimir.conn, + &text, + tags.as_deref().unwrap_or(&[]), + &declared, + mimir_core::secrets::Surface::CliEdit, + )?; let edit = memory::Edit { text: if text.is_empty() { None } else { Some(text) }, title, @@ -1953,9 +2413,20 @@ pub fn reproject(json: bool, reference: &str, project: Option, global: b let node = store::resolve_ref(&mimir.conn, reference)?; let target: Option = match project { Some(name) => { - let proj = store::find_project_by_title(&mimir.conn, &name)?.ok_or_else(|| { + let named = store::find_project_by_title(&mimir.conn, &name)?.ok_or_else(|| { anyhow::anyhow!("no project named '{name}' (titles match exactly)") })?; + // A linked worktree's name stands for the project its memories + // are filed under. Left on the worktree's own row, the memory + // would be out of every reader's scope until the next time + // something ran there and moved it. + let proj = mimir.memory_project_of(&named)?; + if proj.id != named.id { + eprintln!( + "note: '{name}' is a {}", + mimir_core::linked_worktree_note(&proj) + ); + } // A memory only rides sync while global or in a sync-enabled // project; moving it into a plain local project silently takes it // out of that set, so say so instead of letting peers diverge @@ -1990,6 +2461,18 @@ pub fn reproject(json: bool, reference: &str, project: Option, global: b Ok(()) } +/// Help text for `mimir link --rel`, built from the relation list so the +/// vocabulary a user reads is the one the guard below enforces. +pub fn rel_help() -> String { + let accepted: Vec<&str> = Rel::authorable().map(Rel::as_str).collect(); + format!( + "{}. Not accepted: `supersedes` (use `mimir supersede`), `co_recalled` (the \ + store writes those for itself from what you actually recall), and the \ + relations Mimir derives from the code graph", + accepted.join("|") + ) +} + /// The relations `mimir link` will not author, and why. Lives apart from /// `link` because `link` opens the store before it ever looks at the /// relation, and a refusal that needs a database on disk to exercise is a @@ -1999,19 +2482,32 @@ fn reject_unauthorable_rel(rel: Rel) -> Result<()> { // `superseded_by` column are independent, and only the column hides a node // from recall. Allowing it here would silently record a retirement that // retires nothing. - if rel == Rel::Supersedes { + if rel.origin() == RelOrigin::Retirement { bail!( "`--rel supersedes` records an edge but does NOT retire the old node — \ it would look like a supersede and change nothing. Use `mimir supersede \ ` instead (it sets both)." ); } + // What Mimir derives from the things it indexes is rebuilt from them: the + // extractor deletes a file's `calls` and `imports` edges before it writes + // the fresh ones, so a hand-made edge of those relations disappears on + // the next `graph build` — and until then it is indistinguishable from + // one the extractor resolved. + if rel.origin() == RelOrigin::Extracted { + bail!( + "`--rel {rel}` is not a link you can make by hand: Mimir derives `{rel}` \ + edges from what it indexes (the code graph, communities, tags) and \ + replaces them when it re-reads the source. Use `link --rel relates` or \ + `--rel about` for a link you actually mean." + ); + } // `co_recalled` is not a claim anybody makes: the store writes it for // itself when it observes two memories opened together. Hand-authoring one // forges a usage record for a co-recall that never happened — and because // the observer skips any pair that already has an authored edge, it would // also suppress the real edge if that pair ever does get recalled together. - if rel == Rel::CoRecalled { + if rel.origin() == RelOrigin::Observed { bail!( "`--rel co_recalled` is the store's own observation of memories recalled \ together — writing one by hand forges usage that never happened, and it \ @@ -2044,10 +2540,28 @@ pub fn link(a: &str, b: &str, rel: &str) -> Result<()> { pub fn anchor(reference: &str, patterns: Vec) -> Result<()> { let mimir = Mimir::open()?; let node = resolve_any(&mimir, reference)?; + // The PreToolUse reader only looks at memories, so an anchor on anything + // else would be accepted here and then never fire. + if node.kind != Kind::Memory { + bail!( + "{} is a {}, not a memory; guard anchors only fire for memories", + short_uid(node.kind, &node.uid), + node.kind + ); + } let clean = mimir_core::anchors::sanitize_anchors(patterns); if clean.is_empty() { bail!("no usable anchor patterns after sanitizing (empty or oversized are dropped)"); } + // An anchor is stored, shown and synced like the memory it sits on, so + // it passes the same guard as `remember --anchor`. + capture::refuse_secrets( + &mimir.conn, + "", + &[], + &clean, + mimir_core::secrets::Surface::CliEdit, + )?; mimir_core::anchors::set_anchors(&mimir.conn, node.id, &clean)?; println!( "{} anchored to {}", @@ -2058,19 +2572,19 @@ pub fn anchor(reference: &str, patterns: Vec) -> Result<()> { } /// Mark OLD as superseded by NEW: OLD stops surfacing in recall (kept as -/// history) and a `supersedes` edge is recorded. +/// history) and a `supersedes` edge is recorded. One operation +/// (`store::supersede`), which also says what it refuses and why. pub fn supersede(old: &str, by: &str, reason: Option<&str>) -> Result<()> { let mimir = Mimir::open()?; let old = resolve_any(&mimir, old)?; let new = resolve_any(&mimir, by)?; - store::set_superseded( + store::supersede( &mimir.conn, old.id, new.id, mimir_core::model::Actor::Human, reason, )?; - store::link(&mimir.conn, new.id, old.id, Rel::Supersedes, 1.0)?; println!( "{} superseded by {}", short_uid(old.kind, &old.uid), @@ -2079,6 +2593,27 @@ pub fn supersede(old: &str, by: &str, reason: Option<&str>) -> Result<()> { Ok(()) } +/// `doctor`'s line about projects whose directory is gone, or `None` when +/// there is nothing left behind for any. A deleted worktree or a scratch +/// clone keeps its whole code graph until someone prunes it, and nothing +/// else ever says so. +fn missing_projects_hint(conn: &rusqlite::Connection) -> Option { + let missing: Vec<_> = mimir_graph::missing_projects(conn) + .ok()? + .into_iter() + .filter(|m| m.has_graph_rows()) + .collect(); + if missing.is_empty() { + return None; + } + let symbols: i64 = missing.iter().map(|m| m.symbols).sum(); + Some(format!( + "{} project(s) point at a directory that no longer exists and still hold {symbols} \ + symbols — `mimir project prune` lists them", + missing.len() + )) +} + /// `doctor`'s line about auto-linking, or `None` when there is nothing /// useful to say (no code graphs, or a recent scan). /// @@ -2086,14 +2621,8 @@ pub fn supersede(old: &str, by: &str, reason: Option<&str>) -> Result<()> { /// advice you already took is one people learn to skim, and then it cannot /// tell them anything. fn link_scan_hint(conn: &rusqlite::Connection) -> Option { - let graphed: i64 = conn - .query_row( - "SELECT COUNT(DISTINCT project_id) FROM node - WHERE kind='symbol' AND deleted_at IS NULL AND project_id IS NOT NULL", - [], - |r| r.get(0), - ) - .ok()?; + // The same projects `link --scan --all-projects` would range over. + let graphed = mimir_graph::graphed_projects(conn).ok()?.len(); if graphed == 0 { return None; } @@ -2135,18 +2664,13 @@ fn link_scan_hint(conn: &rusqlite::Connection) -> Option { pub fn link_scan(dry_run: bool, all_projects: bool) -> Result<()> { let mimir = Mimir::open()?; + // Each target is a checkout project: the scan reads its symbols. The + // memories compared against them are its memory project's (see + // `scan_one_project`). let targets: Vec = if all_projects { // Only projects that actually have a graph; the rest cost a query // and can match nothing. - let mut stmt = mimir.conn.prepare(&format!( - "SELECT {} FROM node p WHERE p.kind='project' AND p.deleted_at IS NULL - AND EXISTS (SELECT 1 FROM node s WHERE s.kind='symbol' - AND s.project_id=p.id AND s.deleted_at IS NULL) - ORDER BY p.title", - store::NODE_COLS - ))?; - let rows = stmt.query_map([], mimir_core::store::row_to_node)?; - rows.collect::>()? + mimir_graph::graphed_projects(&mimir.conn)? } else { vec![mimir.project_for_cwd(&std::env::current_dir()?)?.context( "not inside a project (the scan links memories to this project's symbols) \ @@ -2184,7 +2708,8 @@ pub fn link_scan(dry_run: bool, all_projects: bool) -> Result<()> { let mut total = 0usize; for proj in &targets { - let created = scan_one_project(&mimir, proj, dry_run, &mut existing)?; + let memories_of = mimir.memory_project_of(proj)?; + let created = scan_one_project(&mimir, proj, memories_of.id, dry_run, &mut existing)?; total += created; if all_projects { println!( @@ -2211,11 +2736,15 @@ pub fn link_scan(dry_run: bool, all_projects: bool) -> Result<()> { Ok(()) } -/// One project's pass. Returns links created (or, in a dry run, the number -/// that would be). +/// One project's pass: the symbols of the checkout project `proj` against +/// the memories of `memory_project` and the global ones. The two are one +/// project except for a linked worktree, whose memories are its main +/// checkout's while the symbols they name are in its own graph. Returns +/// links created (or, in a dry run, the number that would be). fn scan_one_project( mimir: &Mimir, proj: &Node, + memory_project: i64, dry_run: bool, existing: &mut std::collections::HashSet<(i64, i64)>, ) -> Result { @@ -2244,7 +2773,7 @@ fn scan_one_project( WHERE kind='memory' AND deleted_at IS NULL AND superseded_by IS NULL AND (project_id=?1 OR project_id IS NULL)", )?; - let rows = stmt.query_map([proj.id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?; + let rows = stmt.query_map([memory_project], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?; rows.collect::>()? }; @@ -2314,7 +2843,7 @@ fn mentions_symbol(text: &str, name: &str) -> bool { // ---------- docs & index ---------- pub fn docs_add(path: &str, name: Option, global: bool) -> Result<()> { - add_collection_cmd(path, name, global, "docs") + add_collection_cmd(path, name, global, CollectionKind::Docs) } /// Register + index a source-code collection: chunks function/method bodies @@ -2322,10 +2851,15 @@ pub fn docs_add(path: &str, name: Option, global: bool) -> Result<()> { /// mirrors `docs add`, indexing source instead of markdown. Idea credit: /// nworks3d's THOR fork of Mimir (see CHANGELOG.md). pub fn code_add(path: &str, name: Option, global: bool) -> Result<()> { - add_collection_cmd(path, name, global, "code") + add_collection_cmd(path, name, global, CollectionKind::Code) } -fn add_collection_cmd(path: &str, name: Option, global: bool, kind: &str) -> Result<()> { +fn add_collection_cmd( + path: &str, + name: Option, + global: bool, + kind: CollectionKind, +) -> Result<()> { let mimir = Mimir::open()?; let root = std::path::Path::new(path); let canonical = std::fs::canonicalize(root).with_context(|| format!("no such dir: {path}"))?; @@ -2340,7 +2874,7 @@ fn add_collection_cmd(path: &str, name: Option, global: bool, kind: &str } else { mimir.project_for_cwd(&canonical)? }; - let coll = mimir_core::index::add_collection( + let coll = mimir_core::index::add_collection_of_kind( &mimir.conn, &canonical, &name, @@ -2357,6 +2891,81 @@ fn add_collection_cmd(path: &str, name: Option, global: bool, kind: &str Ok(()) } +/// The error `index::find_collection` gives for a reference nothing answers +/// to, for the commands that look collections up by kind instead. +fn no_such_collection(reference: &str) -> anyhow::Error { + mimir_core::error::Error::NotFound(format!("collection '{reference}'")).into() +} + +/// What a `docs` subcommand found for a reference: the collection it acts +/// on, and every other collection that answers to the same name or path. +struct DocsCmdTarget { + acted_on: Node, + others: Vec, +} + +/// The collection a `docs` subcommand means by `reference`, and the ones it +/// does not. +/// +/// A docs and a code collection can share a root and the name derived from +/// it (`mimir code add .` beside the auto-registered docs collection), and +/// then `reference` names both. A `docs` command means the docs one. Only +/// when no docs collection answers does it reach a code collection, because +/// `docs remove` and `docs note` are also the only commands there are for +/// those — so a second `docs remove ` on such a root removes the code +/// collection. A collection named `reference` always comes before one that +/// only lives at that path, whatever their kinds. +/// +/// Within one kind the oldest match is acted on (two projects can each +/// register a `docs` folder under that name). Whatever else matched comes +/// back as `others`, and the command says so: acting on one of several +/// without naming it, or without saying the rest are still there, is the +/// silent "first row wins" this replaces. +fn collection_for_docs_cmd( + conn: &rusqlite::Connection, + reference: &str, +) -> Result> { + use mimir_core::index::find_collections; + // One lookup across both kinds, so a name is tried before a path for + // the whole set: `find_collections` returns the name matches when there + // are any and only then falls back to the path. Asking per kind let a + // docs collection that merely *sits at* `reference` win over a code + // collection that is *named* `reference`, and `docs remove proj` + // removed a collection called something else. Within what matched, docs + // come first (the sort is stable, so each kind stays oldest first). + let mut matches = find_collections(conn, reference, None)?; + matches.sort_by_key(|node| CollectionKind::of(node) != CollectionKind::Docs); + let mut matches = matches.into_iter(); + Ok(matches.next().map(|acted_on| DocsCmdTarget { + acted_on, + others: matches.collect(), + })) +} + +/// `docs collection l:ABC123`: a collection named by what tells it apart +/// from another with the same name. +fn kind_and_id(collection: &Node) -> String { + format!( + "{} collection {}", + CollectionKind::of(collection), + short_uid(collection.kind, &collection.uid) + ) +} + +/// The clause naming the collections a `docs` command left alone, for a +/// sentence the caller finishes: `a code collection l:ABC123 also answers to +/// 'proj'`, or the count and the list when there are several. +fn also_answering(others: &[Node], reference: &str) -> String { + match others { + [one] => format!("a {} also answers to '{reference}'", kind_and_id(one)), + many => format!( + "{} other collections also answer to '{reference}' ({})", + many.len(), + many.iter().map(kind_and_id).collect::>().join(", ") + ), + } +} + pub fn docs_list(json: bool) -> Result<()> { let mimir = Mimir::open()?; let collections = mimir_core::index::list_collections(&mimir.conn)?; @@ -2373,11 +2982,7 @@ pub fn docs_list(json: bool) -> Result<()> { v["chunks"] = serde_json::json!(chunks); println!("{v}"); } else { - let kind = coll - .meta - .get("kind") - .and_then(|v| v.as_str()) - .unwrap_or("docs"); + let kind = CollectionKind::of(&coll); println!( "{} [{kind}] {} {} ({files} files, {chunks} chunks)", short_uid(coll.kind, &coll.uid), @@ -2391,16 +2996,50 @@ pub fn docs_list(json: bool) -> Result<()> { pub fn docs_remove(name: &str) -> Result<()> { let mimir = Mimir::open()?; - let coll = mimir_core::index::find_collection(&mimir.conn, name)?; + let Some(DocsCmdTarget { + acted_on: coll, + others, + }) = collection_for_docs_cmd(&mimir.conn, name)? + else { + return Err(no_such_collection(name)); + }; mimir_core::index::remove_collection(&mimir.conn, coll.id)?; - println!("removed {}", coll.title.as_deref().unwrap_or(name)); + let title = coll.title.as_deref().unwrap_or(name); + if others.is_empty() { + println!("removed {title}"); + } else { + // More than one collection answered to `name`: say which one went, + // and that the rest are still registered and how to reach them. + let (verb, next) = if others.len() == 1 { + ("is", "it") + } else { + ("are", "the next one") + }; + println!( + "removed {} collection {title} ({}); {} and {verb} still registered, \ + run the command again to remove {next}", + CollectionKind::of(&coll), + short_uid(coll.kind, &coll.uid), + also_answering(&others, name), + ); + } Ok(()) } pub fn docs_note(target: &str, text: String) -> Result<()> { let mimir = Mimir::open()?; - let target_node = mimir_core::index::find_collection(&mimir.conn, target) - .or_else(|_| store::resolve_ref(&mimir.conn, target))?; + let (target_node, others) = match collection_for_docs_cmd(&mimir.conn, target)? { + Some(found) => (found.acted_on, found.others), + None => (store::resolve_ref(&mimir.conn, target)?, Vec::new()), + }; + // A note is free text stored and embedded like any memory. + capture::refuse_secrets( + &mimir.conn, + &text, + &[], + &[], + mimir_core::secrets::Surface::CliRemember, + )?; let note = mimir_core::index::annotate(&mimir.conn, &target_node, &text)?; println!( "{} describes {} {}", @@ -2408,16 +3047,41 @@ pub fn docs_note(target: &str, text: String) -> Result<()> { short_uid(target_node.kind, &target_node.uid), target_node.title.as_deref().unwrap_or("") ); + if !others.is_empty() { + // The line above carries an id, not a kind; with several + // collections under one name that is not enough to tell which got + // the note. An id as the target reaches any of the others. + let (verb, how) = if others.len() == 1 { + ("was", "pass its id as the target to annotate it") + } else { + ("were", "pass an id as the target to annotate one of them") + }; + println!( + "the note is on the {} collection; {} and {verb} not annotated, {how}", + CollectionKind::of(&target_node), + also_answering(&others, target), + ); + } Ok(()) } pub fn index(name: Option) -> Result<()> { let mut mimir = Mimir::open()?; let results = match name { + // Every collection the name or path answers to, not the first: a + // root registered for both docs and code is one name for two + // collections, and "index this root" means both of them. Some(n) => { - let coll = mimir_core::index::find_collection(&mimir.conn, &n)?; - let stats = mimir_core::index::index_collection(&mut mimir.conn, &coll)?; - vec![(coll.title.unwrap_or(n), stats)] + let collections = mimir_core::index::find_collections(&mimir.conn, &n, None)?; + if collections.is_empty() { + return Err(no_such_collection(&n)); + } + let mut results = Vec::with_capacity(collections.len()); + for coll in collections { + let stats = mimir_core::index::index_collection(&mut mimir.conn, &coll)?; + results.push((coll.title.unwrap_or_else(|| n.clone()), stats)); + } + results } None => mimir_core::index::index_all(&mut mimir.conn)?, }; @@ -2537,21 +3201,98 @@ fn resolve_any(mimir: &Mimir, reference: &str) -> Result { } } -/// Scope for read operations. Inside a project: that project + global. -/// Outside: everything (reads want breadth; -g narrows to global-only). -fn read_scope(mimir: &Mimir, global: bool, all: bool) -> Result { +/// Before a CLI command that reads or writes memories: move what a linked +/// worktree's own project row still holds to the project its memories are +/// filed under (`Mimir::projects_for_cwd_moving_memories_home`), and say so +/// in one line on stderr when anything moved. The commands that do this +/// are listed in one place, `main.rs`'s `moves_worktree_memories`; hooks, +/// `status` and `doctor` never do. +/// +/// Best-effort: the command runs either way. A store that cannot be opened +/// is left for the command to report; a move that fails is a warning line +/// from the engine, and the next memory command tries again. +pub fn move_worktree_memories_here() { + let Ok(cwd) = std::env::current_dir() else { + return; + }; + let Ok(mimir) = Mimir::open() else { + return; + }; + match mimir.projects_for_cwd_moving_memories_home(&cwd) { + Ok((_, Some(moved))) => eprintln!("{}", moved.line()), + Ok((_, None)) => {} + Err(err) => tracing::debug!(%err, "could not resolve the projects to move memories home"), + } +} + +/// What a read from the working directory reaches: `--all` and `-g` say it +/// outright, for every kind; otherwise it is +/// [`mimir_core::scope::query_reach`] of the directory's two projects — the +/// project + global inside one, everything outside (reads want breadth). +/// The two are one except in a linked worktree, which reads the memories of +/// its repository's main checkout and its own code and docs. +/// +/// It also says whose session handoffs the read may show: a scoped read +/// leaves out the handoffs written in other checkouts +/// ([`mimir_core::context_guard::shown_in_checkout`]), `--all` shows them. +fn read_reach(mimir: &Mimir, global: bool, all: bool) -> Result { if all { - return Ok(Scope::All); + return Ok(ReadPlace { + reach: Reach::uniform(Scope::All), + handoffs_of: None, + }); } + let cwd = std::env::current_dir()?; if global { - return Ok(Scope::Global); + // The checkout a handoff records is its project row's path, which + // is the detected root's canonical form: no project row is needed + // to know it, and `-g` registers none. + let checkout = match mimir_core::scope::detect(&cwd) { + mimir_core::scope::Detection::Found { root, .. } => { + Some(mimir_core::scope::canonical_root(&root)) + } + mimir_core::scope::Detection::NotFound { .. } => None, + }; + return Ok(ReadPlace { + reach: Reach::uniform(Scope::Global), + handoffs_of: Some(checkout), + }); } - Ok(match mimir.project_for_cwd(&std::env::current_dir()?)? { - Some(p) => Scope::Project(p.id), - None => Scope::All, + let here = mimir.projects_for_cwd(&cwd)?; + Ok(ReadPlace { + reach: here.query_reach(), + handoffs_of: Some(here.checkout_path().map(str::to_owned)), }) } +/// What [`read_reach`] found: the scopes a read reaches, and whose session +/// handoffs it may show. +struct ReadPlace { + reach: Reach, + /// `Some(checkout)` for a scoped read: only the handoffs that + /// [`mimir_core::context_guard::handoff_is_for`] that checkout (`None` + /// outside any project). `None` for `--all`: every handoff. + handoffs_of: Option>, +} + +impl ReadPlace { + /// Whether this read may show `node`. + fn shows(&self, node: &Node) -> bool { + match &self.handoffs_of { + None => true, + Some(checkout) => { + mimir_core::context_guard::shown_in_checkout(node, checkout.as_deref()) + } + } + } +} + +/// Scope for reading memories and nothing else (`misses`): the memories +/// half of [`read_reach`]. +fn read_scope(mimir: &Mimir, global: bool, all: bool) -> Result { + Ok(read_reach(mimir, global, all)?.reach.memories) +} + fn parse_kind_filter(kind: &str) -> Result> { Ok(match kind { // No kind filter — deliberately includes CodeChunk. The point of @@ -2638,11 +3379,17 @@ fn print_full(node: &Node, mimir: &Mimir, projects: &HashMap) -> Re } fn node_json(node: &Node, projects: &HashMap) -> serde_json::Value { - serde_json::json!({ + let mut value = serde_json::json!({ "id": short_uid(node.kind, &node.uid), "uid": node.uid, "kind": node.kind.as_str(), - "type": node.subkind, + // A memory's type as every other surface reads it: one stored + // without a type is a note, not null. + "type": if node.kind == Kind::Memory { + Some(node.type_label()) + } else { + node.subkind.as_deref() + }, "project": node.project_id.and_then(|id| projects.get(&id)), "title": node.title, "body": node.body, @@ -2652,7 +3399,14 @@ fn node_json(node: &Node, projects: &HashMap) -> serde_json::Value "updated_at": node.updated_at, "access_count": node.access_count, "strength": node.strength, - }) + }); + // The state a text line spells as one word, for a caller parsing JSON. + // Always present on a memory — "live" included, so a script can match on + // the field instead of on its absence. Memories only, like the label. + if node.kind == Kind::Memory { + value["lifecycle"] = serde_json::json!(node.lifecycle(now_unix()).as_str()); + } + value } #[cfg(test)] @@ -3081,4 +3835,284 @@ mod link_rel_guard_tests { assert!(reject_unauthorable_rel(rel).is_ok(), "{rel} was refused"); } } + + /// A `calls` or `imports` edge drawn by hand is deleted the next time + /// the extractor re-reads the file, and until then nothing tells it + /// apart from one the extractor resolved. The refusal names the + /// relation that was asked for and the ones to use instead. + #[test] + fn relations_mimir_derives_are_refused() { + for rel in [ + Rel::Calls, + Rel::Imports, + Rel::Defines, + Rel::MemberOf, + Rel::Tagged, + ] { + let err = reject_unauthorable_rel(rel) + .expect_err("a derived relation must not be authorable") + .to_string(); + assert!(err.contains(&format!("--rel {rel}")), "{err}"); + assert!(err.contains("relates") && err.contains("about"), "{err}"); + } + } + + /// The guard and the list agree on every relation, so a new relation + /// cannot be accepted by one and refused by the other. + #[test] + fn the_guard_accepts_exactly_the_authorable_relations() { + let authorable: Vec = Rel::authorable().collect(); + for rel in Rel::ALL.iter().copied() { + assert_eq!( + reject_unauthorable_rel(rel).is_ok(), + authorable.contains(&rel), + "{rel}" + ); + } + } + + /// `mimir link --help` used to offer `supersedes` (always refused) and + /// leave out nothing else the guard refuses. The help is now built from + /// the same list the guard reads. + #[test] + fn the_help_offers_what_the_guard_accepts() { + let help = super::rel_help(); + let offered = help.split('.').next().unwrap(); + for rel in Rel::ALL.iter().copied() { + let listed = offered.split('|').any(|word| word == rel.as_str()); + assert_eq!( + listed, + reject_unauthorable_rel(rel).is_ok(), + "{rel} in {offered:?}" + ); + } + } +} + +#[cfg(test)] +mod hook_upgrade_tests { + use super::*; + + fn plan<'a>(brief_enabled: bool) -> HookPlan<'a> { + HookPlan { + rewrite_script: "/h/mimir-rewrite.sh", + recall_script: None, + anchors_script: "/h/mimir-anchors.sh", + context_guard_scripts: None, + brief_enabled, + } + } + + /// What `mimir init --hooks` wrote before the matcher covered every + /// tool the handler reads and before the SessionStart commands were + /// guarded. + fn older_install() -> serde_json::Value { + serde_json::json!({ + "hooks": { + "SessionStart": [ + { "hooks": [{ "type": "command", "command": "mimir rules show" }] }, + { "hooks": [{ "type": "command", "command": "mimir brief show" }] }, + ], + "PreToolUse": [ + { "matcher": "Bash", "hooks": [ + { "type": "command", "command": "/h/mimir-rewrite.sh" } + ] }, + { "matcher": "Bash|Edit|Write", "hooks": [ + { "type": "command", "command": "/h/mimir-anchors.sh" } + ] }, + ], + } + }) + } + + #[test] + fn every_shipped_script_carries_a_version() { + for (name, text, _) in HOOK_SCRIPTS { + assert!(hook_version(text).is_some(), "{name} has no version line"); + } + assert_eq!(hook_version(MIMIR_RECALL_SH), Some(5)); + assert_eq!(hook_version("#!/usr/bin/env bash\necho hi\n"), None); + assert_eq!(hook_version("# mimir-hook-version: seven\n"), None); + } + + /// The script is the one reader of the daemon's address outside this + /// process: it must apply the same override, by the same name, and tell + /// the daemon which directory the prompt came from. + #[test] + fn the_recall_script_spells_the_daemon_address_rule_and_sends_the_cwd() { + let script = render_recall_script("http://127.0.0.1:8077/inject"); + assert!(script.contains(&format!( + "INJECT_URL=\"${{{}:-http://127.0.0.1:8077/inject}}\"", + crate::infer::INJECT_URL_ENV + ))); + assert!(script.contains("URL=\"${URL}&cwd=${ENC_CWD}\""), "{script}"); + assert!(script.contains("cd \"$PROJECT_DIR\""), "{script}"); + assert!(script.contains("Authorization: Bearer %s"), "{script}"); + } + + #[test] + fn outdated_scripts_are_the_installed_ones_older_than_shipped() { + let dir = tempfile::tempdir().unwrap(); + assert!( + outdated_hook_scripts(dir.path()).is_empty(), + "none installed" + ); + + std::fs::write(dir.path().join(ANCHORS_SCRIPT), MIMIR_ANCHORS_SH).unwrap(); + assert!(outdated_hook_scripts(dir.path()).is_empty(), "current"); + + std::fs::write( + dir.path().join(RECALL_SCRIPT), + "#!/usr/bin/env bash\n# mimir-hook-version: 4\n", + ) + .unwrap(); + // A copy from before scripts were versioned at all. + std::fs::write(dir.path().join(REWRITE_SCRIPT), "#!/usr/bin/env bash\n").unwrap(); + let mut outdated = outdated_hook_scripts(dir.path()); + outdated.sort(); + assert_eq!( + outdated, + vec![(RECALL_SCRIPT, 4, 5), (REWRITE_SCRIPT, 0, 1)] + ); + } + + /// An older install is brought to the current shape in place: same + /// number of entries, the anchors matcher widened to every tool the + /// handler reads, and nothing left to do on the next run. + #[test] + fn an_older_install_is_upgraded_in_place_and_then_stable() { + let (root, messages) = merge_hooks(older_install(), &plan(true)).unwrap(); + let pre = root["hooks"]["PreToolUse"].as_array().unwrap(); + assert_eq!(pre.len(), 2); + assert_eq!(pre[1]["matcher"], "Bash|Edit|Write|MultiEdit|NotebookEdit"); + assert_eq!( + pre[0]["matcher"], "Bash", + "the rewrite hook stays Bash-only" + ); + assert!( + messages + .iter() + .any(|m| m.starts_with("PreToolUse anchors upgraded")), + "{messages:?}" + ); + let session = root["hooks"]["SessionStart"].as_array().unwrap(); + assert_eq!(session.len(), 2); + assert_eq!( + session[0]["hooks"][0]["command"], + guarded_hook_command("rules show --hook") + ); + assert_eq!( + session[1]["hooks"][0]["command"], + guarded_hook_command("brief show") + ); + + let (again, messages) = merge_hooks(root.clone(), &plan(true)).unwrap(); + assert_eq!(again, root, "a second run has nothing to change"); + assert!(!messages.iter().any(|m| m.contains("upgraded"))); + assert!(!messages.iter().any(|m| m.contains("added"))); + } + + /// Only what Mimir itself wrote is upgraded: a matcher or a command + /// somebody changed by hand is kept exactly. + #[test] + fn hand_edited_entries_are_left_alone() { + let mut edited = older_install(); + edited["hooks"]["PreToolUse"][1]["matcher"] = "Edit".into(); + edited["hooks"]["SessionStart"][0]["hooks"][0]["command"] = + "mimir rules show | head -50".into(); + let (root, messages) = merge_hooks(edited, &plan(true)).unwrap(); + assert_eq!(root["hooks"]["PreToolUse"][1]["matcher"], "Edit"); + assert_eq!( + root["hooks"]["SessionStart"][0]["hooks"][0]["command"], + "mimir rules show | head -50" + ); + assert!(messages.contains(&"SessionStart already installed".to_string())); + assert!(messages.contains(&"PreToolUse anchors already installed".to_string())); + assert_eq!(root["hooks"]["SessionStart"].as_array().unwrap().len(), 2); + } + + /// A matcher belongs to the whole entry. Mimir widens it only on an + /// entry that is exactly its own: one hook, running the anchors script + /// of this install. An entry that shares the matcher with somebody's + /// hook, or whose command only contains the script's name, is left + /// alone, and a stock entry behind it is still upgraded. + #[test] + fn an_entry_that_is_not_only_mimirs_keeps_its_matcher() { + let mut shared = older_install(); + shared["hooks"]["PreToolUse"][1]["hooks"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ "type": "command", "command": "~/bin/my-own-lint.sh" })); + let (root, messages) = merge_hooks(shared, &plan(true)).unwrap(); + assert_eq!( + root["hooks"]["PreToolUse"][1]["matcher"], "Bash|Edit|Write", + "the user's own hook would start running on tools they never asked for" + ); + assert!(messages.contains(&"PreToolUse anchors already installed".to_string())); + + let mut lookalike = older_install(); + lookalike["hooks"]["PreToolUse"] + .as_array_mut() + .unwrap() + .insert( + 1, + serde_json::json!({ "matcher": "Bash|Edit|Write", "hooks": [ + { "type": "command", "command": "~/bin/not-mimir-anchors-but-mine.sh" } + ] }), + ); + let (root, messages) = merge_hooks(lookalike, &plan(true)).unwrap(); + let pre = root["hooks"]["PreToolUse"].as_array().unwrap(); + assert_eq!(pre[1]["matcher"], "Bash|Edit|Write", "not Mimir's entry"); + assert_eq!( + pre[2]["matcher"], + crate::context_guard_cmd::anchor_matcher(), + "the stock entry behind it is still upgraded" + ); + assert!(messages + .iter() + .any(|m| m.starts_with("PreToolUse anchors upgraded"))); + } + + #[cfg(not(windows))] + #[test] + fn session_start_commands_are_guarded_against_a_missing_binary() { + assert_eq!( + guarded_hook_command("rules show"), + "command -v mimir >/dev/null 2>&1 || exit 0; mimir rules show" + ); + // The guarded form still carries the text the installer recognizes + // its own entry by, so it is found — not added again — next run. + let entry = serde_json::json!({ + "hooks": [{ "type": "command", "command": guarded_hook_command("brief show") }] + }); + assert!(entries_mention(&[entry], "mimir brief show")); + } + + /// The line about the brief entry describes the entry: on when the + /// brief is enabled (the default), inert when it is not. + #[test] + fn the_brief_message_says_whether_the_brief_is_enabled() { + let brief_line = |enabled: bool, root: serde_json::Value| { + merge_hooks(root, &plan(enabled)) + .unwrap() + .1 + .into_iter() + .find(|m| m.contains("brief")) + .unwrap() + }; + let fresh = || serde_json::json!({}); + assert_eq!( + brief_line(true, fresh()), + "SessionStart (session brief) added (on: `[brief] enabled = true`)" + ); + assert_eq!( + brief_line(false, fresh()), + "SessionStart (session brief) added (inert while `[brief] enabled = false`)" + ); + let installed = merge_hooks(fresh(), &plan(true)).unwrap().0; + assert_eq!( + brief_line(false, installed), + "SessionStart (brief) already installed (inert while `[brief] enabled = false`)" + ); + } } diff --git a/crates/mimir-cli/src/context_cmd.rs b/crates/mimir-cli/src/context_cmd.rs index a4e8ded..47ce9e1 100644 --- a/crates/mimir-cli/src/context_cmd.rs +++ b/crates/mimir-cli/src/context_cmd.rs @@ -32,6 +32,10 @@ pub struct Peeked { /// Node id of the resolved symbol, so callers can record the access /// without resolving it a second time. pub symbol_id: i64, + /// One line to show after the body when the file was edited since the + /// graph stored this symbol's line numbers, so the lines above may not + /// be the symbol. `None` when the file is as indexed. + pub stale_note: Option, } /// Build a signature map for `target` (a file or directory, relative to @@ -302,6 +306,17 @@ pub fn peek_symbol( std::fs::read_to_string(&file).with_context(|| format!("reading {}", file.display()))?; let before = tokens::count(&src); + // The slice below trusts line numbers stored at the last build. If the + // file has been edited since, they may point at other lines; the body is + // still returned (it is usually close), with a line saying so. Read-only, + // and a failed comparison is no reason to fail the peek. + let stale_note = match mimir_graph::file_is_current(conn, project_id, root, &rel) { + Ok(Some(false)) => Some(format!( + "note: {rel} changed since the code graph was built — these lines may be off; \ + run `mimir graph build`" + )), + _ => None, + }; // 1-based inclusive lines → slice. Clamp defensively if the file shifted. let lines: Vec<&str> = src.lines().collect(); let lo = start.saturating_sub(1).min(lines.len()); @@ -316,6 +331,7 @@ pub fn peek_symbol( tokens_after: after, path: rel, symbol_id: sym.id, + stale_note, }) } @@ -383,6 +399,10 @@ pub fn peek(reference: &str, json: bool) -> Result<()> { // Reading one symbol is a genuine access — feed the learning signal // (peek_symbol already resolved it; no second lookup). let _ = mimir_core::learn::record_opened(&mimir.conn, p.symbol_id); + // On stderr in both output modes, so stdout stays the body (or the JSON). + if let Some(note) = &p.stale_note { + eprintln!("{note}"); + } if json { println!( diff --git a/crates/mimir-cli/src/context_guard_cmd.rs b/crates/mimir-cli/src/context_guard_cmd.rs index e9e0e1a..9931e42 100644 --- a/crates/mimir-cli/src/context_guard_cmd.rs +++ b/crates/mimir-cli/src/context_guard_cmd.rs @@ -3,6 +3,11 @@ //! [`mimir_core::anchors`] (guard anchors). Each subcommand reads one hook //! event's JSON from stdin. //! +//! This module also owns [`HookEvent`], the one reader of that JSON, and +//! [`fail_open`], the one wrapper every hook entry point returns through — +//! the session brief (`brief_cmd`) and the rules hook (`rules_cmd`) use +//! both, so no hook reads the event or handles an error its own way. +//! //! Field names and the "how does this reach the model" mechanics below were //! verified against the live Claude Code hooks docs while implementing //! this (not assumed): @@ -17,79 +22,273 @@ //! two does nothing useful, so these subcommands always exit 0. //! //! Fail-open throughout: a parse error, missing field, or DB error is -//! swallowed (treated as "say nothing"), never a nonzero exit — a hook that -//! can break a prompt/tool-call/compact by erroring is worse than one that -//! occasionally stays quiet. +//! treated as "say nothing", never a nonzero exit — a hook that can break a +//! prompt/tool-call/compact by erroring is worse than one that occasionally +//! stays quiet. An error that stopped a hook is written to stderr, which +//! the wrapper scripts discard and which, on exit 0, is never fed to the +//! model — so it is there for whoever goes looking, and nowhere else. use std::io::Read as _; +use std::path::Path; +use std::time::Duration; use anyhow::Result; -use mimir_core::context_guard; -use mimir_core::model::Scope; -use mimir_core::Mimir; - -fn read_stdin_json() -> serde_json::Value { - let mut buf = String::new(); - if std::io::stdin().read_to_string(&mut buf).is_err() { - return serde_json::Value::Null; - } - serde_json::from_str(&buf).unwrap_or(serde_json::Value::Null) -} - -fn transcript_bytes(input: &serde_json::Value) -> u64 { - input - .get("transcript_path") - .and_then(|v| v.as_str()) - .and_then(|p| std::fs::metadata(p).ok()) - .map(|m| m.len()) - .unwrap_or(0) -} - -/// Scope inferred from a hook event's `cwd` field: the project it maps to, -/// or `Scope::Global` if there isn't one (no project marker at/above cwd, -/// or `cwd` missing). Mirrors `commands::read_scope`'s project-detection -/// fallback, but hooks never pass `--global`/`--all`, so there is nothing -/// to thread through beyond the one lookup. -fn scope_for_cwd(mimir: &Mimir, input: &serde_json::Value) -> Scope { - input - .get("cwd") - .and_then(|v| v.as_str()) - .and_then(|c| { - mimir - .project_for_cwd(std::path::Path::new(c)) - .ok() - .flatten() - }) - .map(|p| Scope::Project(p.id)) - .unwrap_or(Scope::Global) +use mimir_core::config::ContextGuardMode; +use mimir_core::context_guard::{self, SessionSource}; +use mimir_core::model::{Node, Scope}; +use mimir_core::{Mimir, ProjectContext}; + +/// One Claude Code hook event, as far as any Mimir hook reads it. +/// +/// Parsing never fails: input that is not a JSON object is an event with +/// nothing in it, and every accessor answers "absent". What a hook does +/// with an absent field is its own rule; how the field is read is not. +pub(crate) struct HookEvent { + raw: serde_json::Value, +} + +impl HookEvent { + /// Read an event from its JSON text. + pub(crate) fn parse(text: &str) -> HookEvent { + HookEvent { + raw: serde_json::from_str(text).unwrap_or(serde_json::Value::Null), + } + } + + /// Read the event Claude Code pipes to a hook: all of stdin, to EOF. + /// For the commands that are only ever run as hooks. + pub(crate) fn from_stdin() -> HookEvent { + let mut buf = String::new(); + if std::io::stdin().read_to_string(&mut buf).is_err() { + buf.clear(); + } + HookEvent::parse(&buf) + } + + /// The event on stdin, if there is one — for a command that is both a + /// hook and something a person types (`mimir rules show`). + /// + /// `None` when stdin is a terminal, when it carries no JSON object, or + /// when nothing closes it within `wait`. The bound is what makes this + /// safe to call from a hand-typed command: a hook's event arrives the + /// moment the process starts, but a stdin inherited from a wrapper that + /// never closes it would otherwise hold the command forever. + pub(crate) fn from_piped_stdin(wait: Duration) -> Option { + use std::io::IsTerminal as _; + if std::io::stdin().is_terminal() { + return None; + } + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut buf = String::new(); + let _ = std::io::stdin().read_to_string(&mut buf); + let _ = tx.send(buf); + }); + let event = HookEvent::parse(&rx.recv_timeout(wait).ok()?); + event.raw.is_object().then_some(event) + } + + fn str_field(&self, pointer: &str) -> Option<&str> { + self.raw.pointer(pointer).and_then(|v| v.as_str()) + } + + /// The session the event belongs to. An empty id is no id: keyed state + /// under `""` would be shared by every session that sent none. + pub(crate) fn session_id(&self) -> Option<&str> { + self.str_field("/session_id").filter(|s| !s.is_empty()) + } + + /// What a `SessionStart` event says started the session; see + /// [`SessionSource::parse`] for the missing and the unknown case. + pub(crate) fn source(&self) -> SessionSource { + SessionSource::parse(self.str_field("/source")) + } + + /// The directory the session is working in. + pub(crate) fn cwd(&self) -> Option<&Path> { + self.str_field("/cwd") + .filter(|c| !c.is_empty()) + .map(Path::new) + } + + /// `PreCompact`'s trigger: `"auto"` or `"manual"`. + pub(crate) fn trigger(&self) -> Option<&str> { + self.str_field("/trigger") + } + + /// Current size of the session's transcript file; 0 when the event + /// names none or it cannot be read. + pub(crate) fn transcript_bytes(&self) -> u64 { + self.str_field("/transcript_path") + .and_then(|p| std::fs::metadata(p).ok()) + .map(|m| m.len()) + .unwrap_or(0) + } + + /// The projects the event's `cwd` resolves to + /// (`Mimir::projects_for_cwd`), or `None` when the event carries no + /// `cwd`. A detection error is logged and reads as no project: every + /// caller is a hook, and a hook narrows its scope rather than failing. + fn projects(&self, mimir: &Mimir) -> Option { + let cwd = self.cwd()?; + match mimir.projects_for_cwd(cwd) { + Ok(projects) => Some(projects), + Err(err) => { + tracing::warn!(%err, cwd = %cwd.display(), "hook: project detection failed"); + None + } + } + } + + /// The project whose memories the event's session works with: the + /// memory project of its `cwd`, which in a git linked worktree is the + /// main checkout's. `None` outside any project and when the event + /// carries no `cwd`. Everything a hook volunteers is a memory, so this + /// is the project every hook scopes by. + pub(crate) fn project(&self, mimir: &Mimir) -> Option { + self.projects(mimir)?.memory + } + + /// The scope for what a hook volunteers into this session: + /// [`mimir_core::scope::push_scope`] of the event's project. + pub(crate) fn push_scope(&self, mimir: &Mimir) -> Scope { + mimir_core::scope::push_scope(self.project(mimir).map(|p| p.id)) + } + + /// Where the event's session is, from one resolution: the scope a hook + /// volunteers into ([`HookEvent::push_scope`]), and the checkout a + /// session handoff is tied to. + pub(crate) fn place(&self, mimir: &Mimir) -> Place { + let projects = self.projects(mimir); + Place { + scope: mimir_core::scope::push_scope(projects.as_ref().and_then(|p| p.memory_id())), + checkout: projects + .and_then(|p| p.checkout) + .and_then(|checkout| checkout.path), + } + } + + /// What a `PreToolUse` event is about to act on, for the guard anchors: + /// the target text and whether it is a shell command rather than a + /// path. `None` for a tool [`ANCHOR_TOOLS`] does not list. + pub(crate) fn anchor_target(&self) -> Option<(&str, bool)> { + let tool = self.str_field("/tool_name")?; + let (_, pointer, is_command) = ANCHOR_TOOLS.iter().find(|(name, ..)| *name == tool)?; + Some((self.str_field(pointer)?, *is_command)) + } +} + +/// Where a hook event's session is working; see [`HookEvent::place`]. +pub(crate) struct Place { + /// [`mimir_core::scope::push_scope`] of the session's memory project. + pub(crate) scope: Scope, + /// The canonical root of the session's checkout, the identity a handoff + /// records (`context_guard::handoff_is_for`). `None` outside any + /// project. + pub(crate) checkout: Option, +} + +/// Every tool the guard-anchors hook reads a target from: its name, where +/// in the event the target is, and whether that target is a shell command. +/// The `PreToolUse` matcher `mimir init --hooks` installs is built from +/// this table ([`anchor_matcher`]), so the hook is never registered for a +/// tool it ignores, nor blind to one it handles. +pub(crate) const ANCHOR_TOOLS: &[(&str, &str, bool)] = &[ + ("Bash", "/tool_input/command", true), + ("Edit", "/tool_input/file_path", false), + ("Write", "/tool_input/file_path", false), + ("MultiEdit", "/tool_input/file_path", false), + ("NotebookEdit", "/tool_input/notebook_path", false), +]; + +/// The `PreToolUse` matcher covering exactly [`ANCHOR_TOOLS`]. +pub(crate) fn anchor_matcher() -> String { + ANCHOR_TOOLS + .iter() + .map(|(name, ..)| *name) + .collect::>() + .join("|") +} + +/// Run a hook entry point so that it cannot fail the event it is attached +/// to: an error becomes one line on stderr and the command still exits 0 +/// with whatever it had already printed. +/// +/// Every hook-facing command returns through here, including the ones +/// installed behind a wrapper script that masks the exit code anyway — the +/// guarantee belongs to the command, not to how it happened to be +/// installed. +pub(crate) fn fail_open(what: &str, run: impl FnOnce() -> Result<()>) -> Result<()> { + if let Err(err) = run() { + eprintln!("mimir {what}: {err:#} (hook failed open; nothing more was injected)"); + } + Ok(()) +} + +/// A nudge that is due, and the percent it should be recorded at once it +/// has been printed. +struct Nudge { + text: String, + pct: u8, +} + +/// The session's estimated context use, in percent of the window. +fn context_pct(mimir: &Mimir, session_id: &str, event: &HookEvent) -> u8 { + let marker = context_guard::transcript_marker(&mimir.conn, session_id).unwrap_or(0); + context_guard::estimate_pct(event.transcript_bytes(), marker, &mimir.config.hooks) +} + +/// The `UserPromptSubmit` nudge for this event, if one is due. Reads state +/// and writes none: [`prompt`] records the nag after printing. +fn prompt_nudge(mimir: &Mimir, event: &HookEvent) -> Option { + let mode = mimir.config.hooks.context_guard(); + if mode == ContextGuardMode::Off { + return None; + } + let session_id = event.session_id()?; + let pct = context_pct(mimir, session_id, event); + let threshold = mimir.config.hooks.context_guard_threshold_pct; + if !context_guard::nag_due(&mimir.conn, session_id, pct, threshold).unwrap_or(false) { + return None; + } + let text = context_guard::guard_message_for(pct, threshold, mode)?; + Some(Nudge { text, pct }) } /// `UserPromptSubmit`: nudge toward a deliberate `/clear`/`/compact` (or a /// handoff-then-clear) once the transcript crosses the configured /// threshold. Plain stdout, no JSON — see the module doc comment. Silent -/// whenever `[hooks] context_guard = "off"` (the default), below -/// threshold, or already nagged at this +10% band this session -/// (`context_guard::should_emit`). +/// whenever the guard is off (the default, and what a misspelled mode is), +/// below threshold, or already nagged at this +10% band this session +/// (`context_guard::nag_due`). The nag is recorded after the nudge is +/// printed, so a nudge that was never emitted cannot silence the next one. pub fn prompt() -> Result<()> { - let input = read_stdin_json(); - let mimir = Mimir::open()?; - let mode = &mimir.config.hooks.context_guard; - if mode == "off" { - return Ok(()); - } - let Some(session_id) = input.get("session_id").and_then(|v| v.as_str()) else { - return Ok(()); - }; - let bytes = transcript_bytes(&input); - let marker = context_guard::transcript_marker(&mimir.conn, session_id).unwrap_or(0); - let pct = context_guard::estimate_pct(bytes, marker, &mimir.config.hooks); - let threshold = mimir.config.hooks.context_guard_threshold_pct; - if context_guard::should_emit(&mimir.conn, session_id, pct, threshold).unwrap_or(false) { - if let Some(msg) = context_guard::guard_message(pct, threshold, mode) { - println!("{msg}"); + fail_open("context-guard prompt", || { + let event = HookEvent::from_stdin(); + let mimir = Mimir::open()?; + if let Some(nudge) = prompt_nudge(&mimir, &event) { + println!("{}", nudge.text); + if let Some(session_id) = event.session_id() { + let _ = context_guard::record_nag(&mimir.conn, session_id, nudge.pct); + } } + Ok(()) + }) +} + +/// The `PreCompact` block reason for this event, if the compaction should +/// be blocked. +fn precompact_block(mimir: &Mimir, event: &HookEvent) -> Option { + let mode = mimir.config.hooks.context_guard(); + if mode == ContextGuardMode::Off { + return None; } - Ok(()) + if event.trigger() != Some("auto") { + return None; // never block a user's explicit /compact + } + let session_id = event.session_id()?; + let pct = context_pct(mimir, session_id, event); + context_guard::guard_message_for(pct, mimir.config.hooks.context_guard_threshold_pct, mode) } /// `PreCompact`: on an AUTO-triggered compaction only — never a user's @@ -100,111 +299,471 @@ pub fn prompt() -> Result<()> { /// silently would hand control of *when* a compact happens back to Claude /// Code, defeating the point of `"pause"`/`"handoff"` mode. pub fn precompact() -> Result<()> { - let input = read_stdin_json(); - let mimir = Mimir::open()?; - let mode = &mimir.config.hooks.context_guard; - if mode == "off" { - return Ok(()); - } - if input.get("trigger").and_then(|v| v.as_str()) != Some("auto") { - return Ok(()); // never block a user's explicit /compact - } - let Some(session_id) = input.get("session_id").and_then(|v| v.as_str()) else { - return Ok(()); - }; - let bytes = transcript_bytes(&input); - let marker = context_guard::transcript_marker(&mimir.conn, session_id).unwrap_or(0); - let pct = context_guard::estimate_pct(bytes, marker, &mimir.config.hooks); - let threshold = mimir.config.hooks.context_guard_threshold_pct; - if let Some(reason) = context_guard::guard_message(pct, threshold, mode) { - println!( - "{}", - serde_json::json!({ "decision": "block", "reason": reason }) - ); + fail_open("context-guard precompact", || { + let event = HookEvent::from_stdin(); + let mimir = Mimir::open()?; + if let Some(reason) = precompact_block(&mimir, &event) { + println!( + "{}", + serde_json::json!({ "decision": "block", "reason": reason }) + ); + } + Ok(()) + }) +} + +/// Apply a `SessionStart` event: move the marker/nag state, and return the +/// handoff text to restore, if this event restores one. +fn session_start_restore(mimir: &Mimir, event: &HookEvent) -> Option<(i64, String)> { + let mode = mimir.config.hooks.context_guard(); + if mode == ContextGuardMode::Off { + return None; } - Ok(()) + let session_id = event.session_id()?; + let source = event.source(); + let _ = + context_guard::on_session_start(&mimir.conn, session_id, source, event.transcript_bytes()); + if mode != ContextGuardMode::Handoff || !source.is_context_reset() { + return None; + } + // The handoff written in this checkout: the scope is the memory + // project, which a session in another worktree of the repository + // shares, and its handoff is not this session's to resume from. + let place = event.place(mimir); + context_guard::pending_handoff_in(&mimir.conn, place.scope, place.checkout.as_deref()) + .ok() + .flatten() + .map(|(node, text)| (node.id, text)) } /// `SessionStart`: updates the transcript-marker/nag bookkeeping -/// (`context_guard::handle_session_start`) for every `source`, and in -/// `"handoff"` mode, restores the most recent `session-handoff`-tagged -/// memory as plain-stdout context right after a `/clear` or a `compact`. -/// Entirely skipped — no DB writes either — when `context_guard = "off"`, -/// so an off install leaves zero new `session_state` rows behind. +/// (`context_guard::on_session_start`) for every `source`, and in +/// `"handoff"` mode restores the pending `session-handoff` memory as +/// plain-stdout context right after a `/clear` or a compaction — once: the +/// restore consumes it (`context_guard::restore_handoff_text`). +/// Entirely skipped — no DB writes either — when the guard is off, so an +/// off install leaves zero new `session_state` rows behind. pub fn session_start() -> Result<()> { - let input = read_stdin_json(); - let mimir = Mimir::open()?; - let mode = &mimir.config.hooks.context_guard; - if mode == "off" { - return Ok(()); - } - let Some(session_id) = input.get("session_id").and_then(|v| v.as_str()) else { - return Ok(()); - }; - let source = input - .get("source") - .and_then(|v| v.as_str()) - .unwrap_or("startup"); - let bytes = transcript_bytes(&input); - let _ = context_guard::handle_session_start(&mimir.conn, session_id, source, bytes); - - if mode == "handoff" && matches!(source, "clear" | "compact") { - let scope = scope_for_cwd(&mimir, &input); - if let Ok(Some(text)) = context_guard::restore_handoff_text(&mimir.conn, scope) { - println!("{text}"); - } + fail_open("context-guard session-start", || { + let event = HookEvent::from_stdin(); + let mimir = Mimir::open()?; + deliver_handoff(&mimir, &event, &mut std::io::stdout().lock()) + }) +} + +/// Write the handoff this event restores, if any, to `out`, and only then +/// mark it restored. +/// +/// Delivered first, consumed second: if the reader is gone the write fails +/// (or kills the process) before the handoff is marked, and the next clear +/// still has it. The other order loses a handoff for good whenever the hook +/// is cut off between the two. +fn deliver_handoff(mimir: &Mimir, event: &HookEvent, out: &mut impl std::io::Write) -> Result<()> { + if let Some((handoff, text)) = session_start_restore(mimir, event) { + writeln!(out, "{text}")?; + out.flush()?; + context_guard::mark_handoff_restored(&mimir.conn, handoff); } Ok(()) } -/// `PreToolUse` (Bash/Edit/Write matcher): guard anchors — see +/// `PreToolUse` (the [`anchor_matcher`] tools): guard anchors — see /// `mimir_core::anchors`. Independent of `[hooks] context_guard`: dormant /// until a memory declares `meta.anchors` via `mimir remember --anchor`. pub fn pretool() -> Result<()> { - let input = read_stdin_json(); - let mimir = Mimir::open()?; - let Some(session_id) = input.get("session_id").and_then(|v| v.as_str()) else { - return Ok(()); - }; - let tool_name = input - .get("tool_name") - .and_then(|v| v.as_str()) - .unwrap_or(""); - let (target, is_command) = match tool_name { - "Bash" => ( - input - .pointer("/tool_input/command") - .and_then(|v| v.as_str()), - true, - ), - "Edit" | "Write" | "MultiEdit" => ( - input - .pointer("/tool_input/file_path") - .and_then(|v| v.as_str()), - false, - ), - "NotebookEdit" => ( - input - .pointer("/tool_input/notebook_path") - .and_then(|v| v.as_str()), - false, - ), - _ => (None, false), - }; - let Some(target) = target else { return Ok(()) }; - let scope = scope_for_cwd(&mimir, &input); - if let Ok(Some(text)) = - mimir_core::anchors::find_and_record(&mimir.conn, session_id, scope, target, is_command) - { - println!( - "{}", - serde_json::json!({ - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "additionalContext": text - } - }) + fail_open("context-guard pretool", || { + let event = HookEvent::from_stdin(); + let mimir = Mimir::open()?; + let Some(session_id) = event.session_id() else { + return Ok(()); + }; + let Some((target, is_command)) = event.anchor_target() else { + return Ok(()); + }; + let scope = event.push_scope(&mimir); + if let Ok(Some(text)) = + mimir_core::anchors::find_and_record(&mimir.conn, session_id, scope, target, is_command) + { + println!( + "{}", + serde_json::json!({ + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "additionalContext": text + } + }) + ); + } + Ok(()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use mimir_core::config::Paths; + use mimir_core::store; + + /// A store in a temp dir with the guard in `mode`, and a transcript + /// file big enough to read as 50% of a 1000-token window. + fn guarded(mode: &str) -> (tempfile::TempDir, Mimir, String) { + let dir = tempfile::tempdir().unwrap(); + let mut mimir = Mimir::open_at(Paths::under_root(dir.path())).unwrap(); + mimir.config.hooks.context_guard = mode.into(); + mimir.config.hooks.context_guard_threshold_pct = 45; + mimir.config.hooks.context_window_tokens = 1000; + mimir.config.hooks.transcript_bytes_per_token = 8.0; + let transcript = dir.path().join("transcript.jsonl"); + std::fs::write(&transcript, vec![b'x'; 4000]).unwrap(); + let transcript = transcript.to_string_lossy().into_owned(); + (dir, mimir, transcript) + } + + fn event(fields: serde_json::Value) -> HookEvent { + HookEvent::parse(&fields.to_string()) + } + + fn session_rows(mimir: &Mimir) -> i64 { + mimir + .conn + .query_row("SELECT count(*) FROM session_state", [], |r| r.get(0)) + .unwrap() + } + + #[test] + fn an_event_that_is_not_json_has_nothing_in_it() { + for text in ["", "not json", "[1, 2]", "null"] { + let e = HookEvent::parse(text); + assert_eq!(e.session_id(), None, "{text:?}"); + assert_eq!(e.cwd(), None); + assert_eq!(e.trigger(), None); + assert_eq!(e.transcript_bytes(), 0); + assert_eq!(e.anchor_target(), None); + // No `source` at all is a start-up, by the one rule. + assert_eq!(e.source(), SessionSource::Startup); + } + } + + #[test] + fn an_empty_session_id_or_cwd_is_absent() { + let e = event(serde_json::json!({ "session_id": "", "cwd": "" })); + assert_eq!(e.session_id(), None); + assert_eq!(e.cwd(), None); + let e = + event(serde_json::json!({ "session_id": "s1", "cwd": "/tmp/x", "source": "compact" })); + assert_eq!(e.session_id(), Some("s1")); + assert_eq!(e.cwd(), Some(Path::new("/tmp/x"))); + assert_eq!(e.source(), SessionSource::Compact); + } + + /// Outside a project a hook pushes global memories only; inside one, + /// that project plus global. Neither ever widens to every project. + #[test] + fn hooks_push_into_the_events_project_or_global_only() { + let (dir, mimir, _) = guarded("off"); + let repo = dir.path().join("repo"); + std::fs::create_dir_all(repo.join(".git")).unwrap(); + let nested = repo.join("src"); + std::fs::create_dir_all(&nested).unwrap(); + let bare = dir.path().join("scratch"); + std::fs::create_dir_all(&bare).unwrap(); + + let inside = event(serde_json::json!({ "cwd": nested })); + let project = inside.project(&mimir).expect("the repo is a project"); + assert_eq!(inside.push_scope(&mimir), Scope::Project(project.id)); + + let outside = event(serde_json::json!({ "cwd": bare })); + assert_eq!(outside.push_scope(&mimir), Scope::Global); + assert_eq!( + event(serde_json::json!({})).push_scope(&mimir), + Scope::Global ); } - Ok(()) + + #[test] + fn the_matcher_names_every_tool_the_handler_reads_and_no_other() { + assert_eq!(anchor_matcher(), "Bash|Edit|Write|MultiEdit|NotebookEdit"); + for (tool, pointer, is_command) in ANCHOR_TOOLS { + // Build the event the table says this tool sends. + let key = pointer.rsplit('/').next().unwrap(); + let e = event(serde_json::json!({ + "tool_name": tool, + "tool_input": { key: "the-target" } + })); + assert_eq!( + e.anchor_target(), + Some(("the-target", *is_command)), + "{tool}" + ); + } + let other = event(serde_json::json!({ + "tool_name": "Read", + "tool_input": { "file_path": "src/lib.rs" } + })); + assert_eq!(other.anchor_target(), None); + } + + /// The nudge is decided without writing anything; only `prompt`, after + /// printing, records the nag. + #[test] + fn deciding_a_nudge_is_due_records_nothing() { + let (_dir, mimir, transcript) = guarded("pause"); + let e = event(serde_json::json!({ "session_id": "s1", "transcript_path": transcript })); + let nudge = prompt_nudge(&mimir, &e).expect("50% is over the 45% threshold"); + assert_eq!(nudge.pct, 50); + assert!(nudge.text.contains("~50% full"), "{}", nudge.text); + assert_eq!(session_rows(&mimir), 0, "asking must not record"); + assert!(prompt_nudge(&mimir, &e).is_some(), "still due"); + + context_guard::record_nag(&mimir.conn, "s1", nudge.pct).unwrap(); + assert!(prompt_nudge(&mimir, &e).is_none(), "nagged at this band"); + } + + /// A mode config.toml misspells used to pass every `== "off"` gate, + /// write the nag and marker rows, and then print nothing. It is off. + #[test] + fn a_misspelled_mode_is_off_at_every_gate() { + let (_dir, mimir, transcript) = guarded("handof"); + let e = event(serde_json::json!({ + "session_id": "s1", + "transcript_path": transcript, + "trigger": "auto", + "source": "clear", + })); + assert!(prompt_nudge(&mimir, &e).is_none()); + assert!(precompact_block(&mimir, &e).is_none()); + assert!(session_start_restore(&mimir, &e).is_none()); + assert_eq!( + session_rows(&mimir), + 0, + "an off guard writes no session state" + ); + } + + #[test] + fn precompact_blocks_only_an_automatic_compaction_over_threshold() { + let (_dir, mimir, transcript) = guarded("pause"); + let auto = event(serde_json::json!({ + "session_id": "s1", "transcript_path": transcript, "trigger": "auto" + })); + assert!(precompact_block(&mimir, &auto) + .unwrap() + .contains("~50% full")); + // No nag cadence here: the second attempt is blocked like the first. + assert!(precompact_block(&mimir, &auto).is_some()); + let manual = event(serde_json::json!({ + "session_id": "s1", "transcript_path": transcript, "trigger": "manual" + })); + assert!(precompact_block(&mimir, &manual).is_none()); + } + + /// Handoff mode restores on a reset, once, and a start-up or a resume + /// restores nothing. A missing `source` is a start-up for the marker. + #[test] + fn session_start_restores_a_handoff_once_and_only_after_a_reset() { + let (_dir, mimir, transcript) = guarded("handoff"); + mimir_core::memory::remember( + &mimir.conn, + mimir_core::memory::Remember { + text: "handoff: the migration is half applied; run step 4 next".into(), + mtype: mimir_core::model::MemoryType::Note, + tags: vec![context_guard::HANDOFF_TAG.into()], + project_id: None, + force: false, + actor: mimir_core::model::Actor::Agent, + }, + ) + .unwrap(); + let at = |source: Option<&str>| { + let mut fields = serde_json::json!({ + "session_id": "s1", "transcript_path": transcript + }); + if let Some(source) = source { + fields["source"] = source.into(); + } + session_start_restore(&mimir, &event(fields)) + }; + + assert_eq!(at(Some("startup")), None); + assert_eq!(at(Some("resume")), None); + store::set_session_state(&mimir.conn, "s1", "guard_last_pct", "70").unwrap(); + assert_eq!( + at(None), + None, + "no source: a start-up, which restores nothing" + ); + assert_eq!( + store::get_session_state(&mimir.conn, "s1", "guard_last_pct").unwrap(), + None, + "and, as a start-up, it reset the nag state" + ); + + let (handoff, restored) = at(Some("clear")).expect("a reset restores the handoff"); + assert!( + restored.starts_with("Restored session handoff:"), + "{restored}" + ); + assert!(restored.contains("run step 4 next")); + assert_eq!( + context_guard::transcript_marker(&mimir.conn, "s1").unwrap(), + 4000 + ); + // Producing the text consumes nothing: a hook that dies before it + // has printed leaves the handoff for the next reset. + assert_eq!( + at(Some("compact")).map(|(id, _)| id), + Some(handoff), + "not delivered yet, so still pending" + ); + + // Delivery to a reader that is gone fails, and marks nothing. + struct Gone; + impl std::io::Write for Gone { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + } + let reset = event(serde_json::json!({ + "session_id": "s1", "transcript_path": transcript, "source": "clear" + })); + assert!(deliver_handoff(&mimir, &reset, &mut Gone).is_err()); + assert_eq!( + at(Some("compact")).map(|(id, _)| id), + Some(handoff), + "the write failed, so the handoff is still pending" + ); + // A reader that takes the bytes but cannot be flushed got nothing + // it can be relied on to have seen, either. + struct Unflushed(Vec); + impl std::io::Write for Unflushed { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + } + assert!(deliver_handoff(&mimir, &reset, &mut Unflushed(Vec::new())).is_err()); + assert!(at(Some("compact")).is_some(), "not flushed: still pending"); + + // Delivered: the text is out, and only then is the handoff spent. + let mut out = Vec::new(); + deliver_handoff(&mimir, &reset, &mut out).unwrap(); + let printed = String::from_utf8(out).unwrap(); + assert!( + printed.starts_with("Restored session handoff:"), + "{printed}" + ); + assert!(printed.contains("run step 4 next") && printed.ends_with('\n')); + assert_eq!(at(Some("compact")), None, "already restored: not replayed"); + let mut again = Vec::new(); + deliver_handoff(&mimir, &reset, &mut again).unwrap(); + assert!(again.is_empty(), "nothing is delivered twice"); + } + + /// A repository's main checkout and two linked worktrees of it, as the + /// files `git worktree add` leaves. + fn repo_with_two_worktrees(dir: &Path) -> [std::path::PathBuf; 3] { + let main = dir.join("main"); + let worktree = |name: &str| { + let root = dir.join(name); + let gitdir = main.join(".git/worktrees").join(name); + std::fs::create_dir_all(&gitdir).unwrap(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(gitdir.join("commondir"), "../..\n").unwrap(); + std::fs::write(root.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap(); + std::fs::write( + gitdir.join("gitdir"), + format!("{}\n", root.join(".git").display()), + ) + .unwrap(); + root + }; + let (wt_a, wt_b) = (worktree("wt-a"), worktree("wt-b")); + [main, wt_a, wt_b] + } + + /// Worktrees of one repository share a memory project, and sessions run + /// in several at once. A handoff saved by the session in one of them is + /// restored by a reset there, and by a reset in no other checkout. + #[test] + fn a_handoff_saved_in_one_worktree_is_restored_there_and_nowhere_else() { + use crate::capture::{capture, Capture, Captured, MissingLink}; + let (dir, mut mimir, transcript) = guarded("handoff"); + let [main, wt_a, wt_b] = repo_with_two_worktrees(dir.path()); + + // Saved from worktree A, the way `mimir remember` run there does. + let here = mimir.projects_for_cwd(&wt_a).unwrap(); + assert_ne!(here.checkout_id(), here.memory_id()); + let saved = capture( + &mut mimir, + Capture { + text: "handoff: A is mid-rebase; resolve src/lib.rs next".into(), + mtype: mimir_core::model::MemoryType::Note, + tags: vec![context_guard::HANDOFF_TAG.into()], + project_id: here.memory_id(), + working_project: here.checkout_id(), + force: false, + actor: mimir_core::model::Actor::Agent, + surface: mimir_core::secrets::Surface::CliRemember, + link: None, + missing_link: MissingLink::Reject, + fires_when: Vec::new(), + anchors: Vec::new(), + expires_in: None, + resolves_when: None, + confidence: None, + valid_from: None, + valid_to: None, + }, + ); + assert!(matches!(saved, Ok(Captured::Stored(_))), "{saved:?}"); + + let reset_in = |cwd: &Path, session: &str| { + event(serde_json::json!({ + "session_id": session, + "transcript_path": transcript, + "source": "clear", + "cwd": cwd, + })) + }; + // All three checkouts push into one scope, the repository's: the + // scope alone cannot say whose handoff this is. + let scope = reset_in(&wt_a, "a").push_scope(&mimir); + assert_eq!(scope, Scope::Project(here.memory_id().unwrap())); + assert_eq!(reset_in(&wt_b, "b").push_scope(&mimir), scope); + assert_eq!(reset_in(&main, "m").push_scope(&mimir), scope); + + assert_eq!( + session_start_restore(&mimir, &reset_in(&wt_b, "b")), + None, + "a session in worktree B must not resume from A's state" + ); + assert_eq!( + session_start_restore(&mimir, &reset_in(&main, "m")), + None, + "nor one in the main checkout" + ); + // A session anywhere inside worktree A is in that checkout. + let mut out = Vec::new(); + deliver_handoff(&mimir, &reset_in(&wt_a.join("src"), "a"), &mut out).unwrap(); + let printed = String::from_utf8(out).unwrap(); + assert!(printed.contains("A is mid-rebase"), "{printed}"); + assert_eq!( + session_start_restore(&mimir, &reset_in(&wt_a, "a")), + None, + "restored once" + ); + } + + #[test] + fn a_failing_hook_reports_on_stderr_and_still_succeeds() { + let ran = fail_open("test hook", || anyhow::bail!("the store is on fire")); + assert!(ran.is_ok(), "a hook error must never become an exit code"); + assert!(fail_open("test hook", || Ok(())).is_ok()); + } } diff --git a/crates/mimir-cli/src/dashboard.rs b/crates/mimir-cli/src/dashboard.rs index 20bd748..4aa3f2a 100644 --- a/crates/mimir-cli/src/dashboard.rs +++ b/crates/mimir-cli/src/dashboard.rs @@ -4,7 +4,7 @@ //! one file you can open offline. Charts are hand-rolled inline SVG. use anyhow::{Context, Result}; -use mimir_core::model::now_unix; +use mimir_core::model::{now_unix, RecallEvent}; use mimir_core::{learn, store, Mimir}; pub fn dashboard(out: Option, open: bool) -> Result<()> { @@ -79,7 +79,15 @@ fn render(mimir: &Mimir) -> Result { let projects = q1("SELECT count(*) FROM node WHERE kind='project' AND deleted_at IS NULL")?; let collections = q1("SELECT count(*) FROM node WHERE kind='collection' AND deleted_at IS NULL")?; - let files = q1("SELECT count(*) FROM node WHERE kind='file' AND deleted_at IS NULL")?; + // Two writers share `kind='file'`: the code graph (no collection) and the + // docs indexer (a collection). One total would add source files to + // markdown files under a single unlabelled number. + let code_files = q1( + "SELECT count(*) FROM node WHERE kind='file' AND deleted_at IS NULL AND collection_id IS NULL", + )?; + let doc_files = q1( + "SELECT count(*) FROM node WHERE kind='file' AND deleted_at IS NULL AND collection_id IS NOT NULL", + )?; // ---- memory types ---- let mut stmt = conn.prepare( @@ -98,8 +106,12 @@ fn render(mimir: &Mimir) -> Result { "SELECT at/86400, event, count(*) FROM recall_event WHERE at >= ?1 GROUP BY 1, 2", )?; + // Two series, as the chart's key names them: "shown in results" and + // "opened / marked useful". The second is engagement — either event — + // and is not the count of opens that `mimir report` prints on its own + // row; `RecallEvent::is_engagement` is the one definition of it. let mut shown = [0i64; 14]; - let mut opened = [0i64; 14]; + let mut engaged = [0i64; 14]; for row in stmt.query_map([day0 * 86_400], |r| { Ok(( r.get::<_, i64>(0)?, @@ -109,10 +121,11 @@ fn render(mimir: &Mimir) -> Result { })? { let (day, event, n) = row?; let idx = (day - day0).clamp(0, 13) as usize; - match event.as_str() { - "shown" => shown[idx] += n, - "opened" | "useful" => opened[idx] += n, - _ => {} + match event.parse::() { + Ok(RecallEvent::Shown) => shown[idx] += n, + Ok(event) if event.is_engagement() => engaged[idx] += n, + // A mark of "noise", or an event a newer build wrote. + Ok(_) | Err(_) => {} } } drop(stmt); @@ -167,10 +180,22 @@ fn render(mimir: &Mimir) -> Result { drop(stmt); // ---- graph + hygiene + storage ---- - let calls_resolved = - q1("SELECT count(*) FROM edge WHERE rel='calls' AND json_extract(meta,'$.resolved')=1")?; - let calls_heuristic = - q1("SELECT count(*) FROM edge WHERE rel='calls' AND json_extract(meta,'$.resolved')=0")?; + // Call edges a query can actually walk: both ends live symbols. An edge + // row outlives a tombstoned end (a deleted file's symbols keep theirs), + // and counting those reported calls no `graph callers` would show. + let live_calls = |resolved: i64| -> Result { + Ok(conn.query_row( + "SELECT count(*) FROM edge e + JOIN node s ON s.id = e.src JOIN node d ON d.id = e.dst + WHERE e.rel='calls' AND json_extract(e.meta,'$.resolved')=?1 + AND s.kind='symbol' AND s.deleted_at IS NULL + AND d.kind='symbol' AND d.deleted_at IS NULL", + [resolved], + |r| r.get(0), + )?) + }; + let calls_resolved = live_calls(1)?; + let calls_heuristic = live_calls(0)?; let imports = q1("SELECT count(*) FROM edge WHERE rel='imports'")?; let links = q1("SELECT count(*) FROM edge WHERE rel IN ('about','relates','links','mentions')")?; @@ -180,19 +205,17 @@ fn render(mimir: &Mimir) -> Result { // row into machine activity. Hiding them entirely was the other option and // is worse — the rows exist and take space, so they should be legible. let co_recalled = q1("SELECT count(*) FROM edge WHERE rel='co_recalled'")?; - let embedded = q1("SELECT count(*) FROM embedding")?; - // Kind list mirrors `embed::embed_pending`'s eligibility filter exactly — - // drawing from the shared constant means a kind added there (e.g. the - // `codechunk` fallback content in index::mod) shows up here too, instead - // of silently under-counting against a second, hand-copied list. - let embeddable = q1(&format!( - "SELECT count(*) FROM node WHERE deleted_at IS NULL AND body IS NOT NULL - AND kind IN ({})", - mimir_core::embed::EMBEDDABLE_KINDS - ))?; - let superseded = q1("SELECT count(*) FROM node WHERE superseded_by IS NOT NULL")?; - let archived = - q1("SELECT count(*) FROM node WHERE deleted_at IS NOT NULL AND json_extract(meta,'$.archived')=1")?; + // Both numbers come from the predicate `embed::embed_pending` selects + // with, for the configured model: "embedded" is a live node whose vector + // matches its current content, not a row in the `embedding` table (those + // also exist for deleted nodes, retired models and edited content, which + // is how the percentage used to pass 100). + let (embedded, embeddable) = mimir_core::embed::coverage(conn, &mimir.config.embedding.model)?; + // The same counts `mimir status` prints, from the one derivation of a + // memory's state. Counted here by hand, a memory superseded and later + // forgotten was in both numbers. + let states = mimir_core::lifecycle::counts(conn)?; + let (superseded, archived) = (states.superseded, states.archived); let pinned = q1("SELECT count(*) FROM node WHERE pinned=1 AND deleted_at IS NULL")?; let events_total = q1("SELECT count(*) FROM recall_event")?; let db_bytes = std::fs::metadata(&mimir.paths.db_file)?.len(); @@ -238,10 +261,10 @@ fn render(mimir: &Mimir) -> Result { )); } - // Activity bars (overlaid shown/opened) + // Activity bars (overlaid shown/engaged) let max_act = shown .iter() - .chain(opened.iter()) + .chain(engaged.iter()) .copied() .max() .unwrap_or(1) @@ -250,7 +273,7 @@ fn render(mimir: &Mimir) -> Result { for i in 0..14 { let x = i as f64 * 22.0; let hs = 72.0 * shown[i] as f64 / max_act as f64; - let ho = 72.0 * opened[i] as f64 / max_act as f64; + let ho = 72.0 * engaged[i] as f64 / max_act as f64; act_bars.push_str(&format!( r#""#, i * 40, x, 76.0 - hs, hs.max(1.0), @@ -440,7 +463,10 @@ fn render(mimir: &Mimir) -> Result { .replace("{{PROJECT_ROWS}}", &project_rows) .replace("{{PROJECTS}}", &fmt_n(projects)) .replace("{{COLLECTIONS}}", &fmt_n(collections)) - .replace("{{FILES}}", &fmt_n(files)) + .replace( + "{{FILES}}", + &format!("{} code · {} docs", fmt_n(code_files), fmt_n(doc_files)), + ) .replace("{{CALLS_R}}", &fmt_n(calls_resolved)) .replace("{{CALLS_H}}", &fmt_n(calls_heuristic)) .replace("{{IMPORTS}}", &fmt_n(imports)) @@ -710,3 +736,75 @@ footer span{margin-left:auto}
ᛗᛁᛗᛁᚱ — what is remembered, remainslocal · private · yours
"##; + +#[cfg(test)] +mod tests { + use super::*; + + fn write(dir: &std::path::Path, rel: &str, content: &str) { + let path = dir.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, content).unwrap(); + } + + /// The graph numbers on the dashboard are the graph a query walks: code + /// files apart from indexed docs files, and call edges only where both + /// ends still exist. A deleted file's symbols keep their outgoing edge + /// rows, and those used to be counted as calls. + #[test] + fn graph_tiles_count_code_files_and_live_call_edges() { + let dir = tempfile::tempdir().unwrap(); + write( + dir.path(), + "src/main.rs", + "fn main() { run(); }\n\nfn run() { slugify(); }\n\npub fn helper() {}\n", + ); + write( + dir.path(), + "src/util.rs", + "pub fn slugify() { helper(); }\n", + ); + write(dir.path(), "README.md", "# Probe\n\nSome words.\n"); + // A store on disk: the page also reports the database file's size. + let home = tempfile::tempdir().unwrap(); + let mut mimir = Mimir::open_at(mimir_core::config::Paths::under_root(home.path())).unwrap(); + let proj = + mimir_core::store::ensure_project(&mimir.conn, &dir.path().to_string_lossy(), "probe") + .unwrap(); + mimir_graph::update(&mut mimir.conn, &proj, dir.path()).unwrap(); + let docs = mimir_core::index::add_collection( + &mimir.conn, + dir.path(), + "probe", + Some(proj.id), + "docs", + ) + .unwrap(); + mimir_core::index::index_collection(&mut mimir.conn, &docs).unwrap(); + + let html = render(&mimir).unwrap(); + assert!(html.contains("files 2 code · 1 docs"), "file legend"); + assert!( + html.contains("calls resolved3"), + "main → run → slugify → helper" + ); + + // util.rs goes. `slugify → helper` is still a row in the edge table. + std::fs::remove_file(dir.path().join("src/util.rs")).unwrap(); + mimir_graph::update(&mut mimir.conn, &proj, dir.path()).unwrap(); + let rows: i64 = mimir + .conn + .query_row("SELECT count(*) FROM edge WHERE rel='calls'", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(rows, 2, "main → run, and the dead slugify → helper"); + + let html = render(&mimir).unwrap(); + assert!(html.contains("files 1 code · 1 docs"), "file legend"); + assert!( + html.contains("calls resolved1"), + "only main → run is a call any query would show" + ); + } +} diff --git a/crates/mimir-cli/src/filters/mod.rs b/crates/mimir-cli/src/filters/mod.rs index 5df6010..8eb1890 100644 --- a/crates/mimir-cli/src/filters/mod.rs +++ b/crates/mimir-cli/src/filters/mod.rs @@ -9,28 +9,28 @@ mod rules; -pub(crate) use rules::{is_content, is_filterable}; -use rules::{is_signal, verdict, Verdict}; +pub(crate) use rules::{classify, Filter, Hook}; +use rules::{is_signal, Verdict}; /// Above this many kept lines, the generic volume cap kicks in. const VOLUME_CAP: usize = 400; /// Lines kept verbatim at the head and tail when the cap triggers. const VOLUME_EDGE: usize = 60; -/// Filter `raw` output from `program` (the command's argv[0]): strip ANSI, drop -/// the lines the program's [`rules`] mark as noise, collapse blank runs, and — -/// if the result is still huge — keep only head + tail + signal lines. -pub fn filter_output(program: &str, raw: &str) -> String { +/// Filter `raw` output with the [`Filter`] of the program that printed it: +/// strip ANSI, drop the lines the program's [`rules`] mark as noise, collapse +/// blank runs, and — if the result is still huge — keep only head + tail + +/// signal lines. +pub fn filter_with(filter: &Filter, raw: &str) -> String { if raw.is_empty() { return String::new(); } let cleaned = strip_ansi(raw); - let base = base_program(program); // Content commands (coreutils/search/listings/kubectl): their output *is* // the signal you asked for, so we never drop individual lines — only bound // runaway volume. Non-lossy by construction (head + tail + signal kept). - if is_content(base) { + if matches!(filter, Filter::Content) { let lines: Vec<&str> = cleaned.lines().collect(); return volume_cap(&lines); } @@ -39,7 +39,7 @@ pub fn filter_output(program: &str, raw: &str) -> String { let mut kept: Vec<&str> = Vec::new(); let mut prev_blank = false; for line in cleaned.lines() { - if matches!(verdict(base, line), Verdict::Drop) { + if matches!(filter.verdict(line), Verdict::Drop) { continue; } let blank = line.trim().is_empty(); @@ -54,6 +54,12 @@ pub fn filter_output(program: &str, raw: &str) -> String { volume_cap(&kept) } +/// [`filter_with`] the filter of `program` (the command's argv[0]). +#[cfg(test)] +pub fn filter_output(program: &str, raw: &str) -> String { + filter_with(&classify(base_program(program), &[]).filter, raw) +} + /// Bound runaway output: under [`VOLUME_CAP`] lines, return them unchanged; /// otherwise keep the head, the tail, and every signal line in between, eliding /// the rest with a visible count so nothing important vanishes silently. diff --git a/crates/mimir-cli/src/filters/rules.rs b/crates/mimir-cli/src/filters/rules.rs index 42c014b..8623dfc 100644 --- a/crates/mimir-cli/src/filters/rules.rs +++ b/crates/mimir-cli/src/filters/rules.rs @@ -4,7 +4,12 @@ //! suffixes to drop, plus an optional custom predicate for the few shapes that //! aren't a simple match). The `is_signal` safety net — anything that looks //! like an error/warning/failure is always kept — is applied centrally in -//! [`verdict`], so a new program's rules physically *cannot* forget it. +//! [`Filter::verdict`], so a new program's rules physically *cannot* forget it. +//! +//! What a command *is* gets decided in one function, [`classify`]. `mimir +//! run` reads how to filter its output from the answer, the PreToolUse hook +//! (`mimir rewrite`) reads whether to wrap it, and neither keeps a table of +//! its own. #[derive(Debug, PartialEq, Eq)] pub enum Verdict { @@ -15,7 +20,7 @@ pub enum Verdict { /// A line (after left-trim for prefix/suffix tests) is dropped if it starts /// with any `prefixes`, ends with any `ends_with`, contains any `contains`, or /// `custom` returns true. -struct Noise { +pub struct Noise { prefixes: &'static [&'static str], contains: &'static [&'static str], ends_with: &'static [&'static str], @@ -82,35 +87,341 @@ const CONTENT_CMDS: &[&str] = &[ ]; /// True for a [`CONTENT_CMDS`] command — cap-only handling, never line-dropped. -pub fn is_content(program: &str) -> bool { +fn is_content(program: &str) -> bool { CONTENT_CMDS.contains(&program) } -/// True if Mimir should auto-wrap `program` in `mimir run`: either it has a -/// dedicated noise handler, or it's a high-volume content command we volume-cap. -/// The single source of truth the PreToolUse rewrite shares, so adding a handler -/// (or content command) makes it rewrite-eligible too. -pub fn is_filterable(program: &str) -> bool { - rules_for(program).is_some() || is_content(program) +/// git subcommands noisy enough for the hook to wrap unasked (clone/fetch +/// progress + status boilerplate). +const GIT_NOISY_SUBCMDS: &[&str] = &["clone", "pull", "fetch", "push", "status"]; + +/// How `mimir run` filters a program's output. +pub enum Filter { + /// Output is the signal (see [`CONTENT_CMDS`]): no line is dropped, only + /// runaway volume is capped. + Content, + /// A tool with noise rules of its own, applied to whatever it prints. + /// The rules go by program alone: `mimir run -- git log` gets the git + /// rules although the hook would not have wrapped it (see + /// [`Hook::LeaveQuietSubcommand`]). + Noisy(&'static Noise), + /// A program nothing is known about: the gentle generic rules. + Generic, } -/// Decide one line. `is_signal` wins first; then the program's rules (or the -/// gentle generic fallback for unknown programs). -pub fn verdict(program: &str, line: &str) -> Verdict { - if is_signal(line) { - return Verdict::Keep; - } - let rules = rules_for(program).unwrap_or(&GENERIC); - let t = line.trim_start(); - let drop = rules.prefixes.iter().any(|p| t.starts_with(p)) - || rules.ends_with.iter().any(|s| t.ends_with(s)) - || rules.contains.iter().any(|c| line.contains(c)) - || rules.custom.is_some_and(|f| f(line)); - if drop { - Verdict::Drop +/// What the PreToolUse hook (`mimir rewrite`) does with a command. +/// +/// `mimir run` filters anything it is handed, by [`Filter`]. The hook wraps +/// commands nobody asked it to, so it is choosier; each `Leave…` names one +/// way the two differ. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Hook { + /// Wrap it in `mimir run`: its output is noisy or large, and it ends on + /// its own. + Wrap, + /// Leave it: it follows a stream until killed (`tail -f`), and `mimir + /// run` waits for the child to exit before it prints anything — wrapped, + /// it would hang the agent forever. + LeaveFollowing, + /// Leave it: the program has noise rules, but this subcommand is not one + /// of its noisy ones (git outside [`GIT_NOISY_SUBCMDS`]). + LeaveQuietSubcommand, + /// Leave it: the program has no filter of its own, and the generic rules + /// are not worth a wrapper nobody asked for. + LeaveUnknown, +} + +/// What Mimir knows about one command. +pub struct Class { + /// How `mimir run` filters its output. + pub filter: Filter, + /// Whether the hook wraps it. + pub hook: Hook, +} + +/// Classify a command: `program` is argv[0]'s base name, `args` the rest. +/// +/// The one place that reads the registries above. A program gets a filter +/// from its name alone; whether the hook wraps it also depends on how it is +/// being run. +pub fn classify(program: &str, args: &[&str]) -> Class { + let filter = if is_content(program) { + Filter::Content + } else if let Some(rules) = rules_for(program) { + Filter::Noisy(rules) } else { - Verdict::Keep + Filter::Generic + }; + let hook = match filter { + Filter::Generic => Hook::LeaveUnknown, + Filter::Content | Filter::Noisy(_) if follows(program, args) => Hook::LeaveFollowing, + Filter::Noisy(_) if !is_noisy_subcommand(program, args) => Hook::LeaveQuietSubcommand, + Filter::Content | Filter::Noisy(_) => Hook::Wrap, + }; + Class { filter, hook } +} + +/// True when this invocation streams until something kills it: a log +/// follower, a watcher, a dev server. +/// +/// `mimir run` prints once the child has exited, so a wrapped command that +/// never exits shows the agent nothing at all — not on a foreground call, +/// which sits until its timeout, and not on a background one, whose output +/// the agent polls and finds empty for as long as the server lives. Leaving +/// such a command unwrapped costs only the filtering. +/// +/// Decided per program, because the same flag means different things: +/// `kubectl logs -f` follows, `kubectl apply -f x.yaml` names a file, and +/// `docker compose -f x.yml logs` names one before a subcommand that ends. +/// So each rule first finds the subcommand ([`subcommand`], which steps over +/// the global options in front of it) and reads only the flags after it. +/// Only programs the hook would otherwise wrap have a rule here (a test +/// holds the table to that), and a rule that is too eager is the safe +/// mistake. +fn follows(program: &str, args: &[&str]) -> bool { + let has = |flags: &[&str]| args.iter().any(|a| flags.contains(a)); + match program { + "tail" => args.iter().any(|a| *a == "--retry" || is_follow_flag(a)), + "kubectl" => { + has(&["-w", "--watch", "--watch-only"]) + || match subcommand(args, KUBECTL_VALUE_FLAGS) { + Some(("logs", rest)) => rest.iter().any(|a| is_follow_flag(a)), + Some(("port-forward" | "proxy" | "attach", _)) => true, + _ => false, + } + } + "docker" | "podman" => subcommand(args, DOCKER_VALUE_FLAGS) + .is_some_and(|(sub, rest)| container_follows(sub, rest)), + "docker-compose" => compose_follows(args), + "npm" | "pnpm" | "yarn" | "bun" => { + (program == "bun" && has(&["--watch", "--hot"])) || script_follows(program, args) + } + "next" => matches!(subcommand(args, &[]), Some(("dev" | "start", _))), + // `jest -w` is `--maxWorkers`; only the long forms watch. + "jest" => args + .iter() + .any(|a| is_on(a, "--watch") || is_on(a, "--watchAll")), + "vitest" => { + args.iter().any(|a| *a == "-w" || is_on(a, "--watch")) + || matches!(subcommand(args, &[]), Some(("watch" | "dev", _))) + } + "tsc" => args.iter().any(|a| *a == "-w" || is_on(a, "--watch")), + "cargo" => { + // `cargo +nightly watch`: the toolchain comes before everything. + let args = match args.first() { + Some(first) if first.starts_with('+') => &args[1..], + _ => args, + }; + matches!(subcommand(args, CARGO_VALUE_FLAGS), Some(("watch", _))) + } + _ => false, + } +} + +/// Global options that take their value as the next argument, per program: +/// what [`subcommand`] has to step over to find the subcommand in +/// `kubectl -n prod logs -f` or `npm --prefix web run dev`. The +/// `--flag=value` spelling needs no entry. +const KUBECTL_VALUE_FLAGS: &[&str] = &[ + "-n", + "--namespace", + "--context", + "--cluster", + "--user", + "--kubeconfig", + "-s", + "--server", + "--as", + "--as-group", + "--token", + "--request-timeout", + "--cache-dir", + "--certificate-authority", + "--client-certificate", + "--client-key", + "--tls-server-name", + "-v", +]; +const DOCKER_VALUE_FLAGS: &[&str] = &[ + "--context", + "-c", + "--config", + "-H", + "--host", + "-l", + "--log-level", + "--tlscacert", + "--tlscert", + "--tlskey", + "--connection", + "--url", + "--root", + "--runroot", +]; +const COMPOSE_VALUE_FLAGS: &[&str] = &[ + "-f", + "--file", + "-p", + "--project-name", + "--profile", + "--env-file", + "--project-directory", + "--ansi", + "--parallel", + "--progress", +]; +const CARGO_VALUE_FLAGS: &[&str] = &["--config", "-Z", "--color", "-C", "--manifest-path"]; + +/// Value-taking options of the script runners. Per program on purpose: +/// `-w` names a workspace to npm and is a plain switch to pnpm, and treating +/// pnpm's as taking a value would swallow the script name after it. +fn script_runner_value_flags(program: &str) -> &'static [&'static str] { + match program { + "npm" => &[ + "--prefix", + "-C", + "-w", + "--workspace", + "--userconfig", + "--registry", + "--cache", + ], + "pnpm" => &["--filter", "-F", "--dir", "-C", "--workspace-dir"], + "yarn" => &["--cwd"], + "bun" => &["--cwd", "--filter", "-F", "--config", "-c", "--env-file"], + _ => &[], + } +} + +/// The subcommand of an invocation and the arguments after it: the first +/// argument that is neither an option nor the value of one of `value_flags`. +fn subcommand<'a>(args: &'a [&'a str], value_flags: &[&str]) -> Option<(&'a str, &'a [&'a str])> { + let mut i = 0; + while i < args.len() { + let arg = args[i]; + if value_flags.contains(&arg) { + i += 2; + } else if arg.starts_with('-') { + i += 1; + } else { + return Some((arg, &args[i + 1..])); + } } + None +} + +/// `--flag` or `--flag=`. +fn is_on(arg: &str, flag: &str) -> bool { + match arg.strip_prefix(flag) { + Some("") => true, + Some(value) => value.starts_with('=') && value != "=false", + None => false, + } +} + +/// A "keep following" flag: `--follow` in any spelling, or a short-flag +/// bundle containing `f` or `F` (`-f`, `-F`, `-ft`, `-fn`). +fn is_follow_flag(arg: &str) -> bool { + if arg.starts_with("--") { + return is_on(arg, "--follow"); + } + arg.starts_with('-') && arg.contains(['f', 'F']) +} + +/// `docker …` / `podman …`, global options already stepped over. +fn container_follows(sub: &str, rest: &[&str]) -> bool { + match sub { + "compose" => compose_follows(rest), + "logs" => rest.iter().any(|a| is_follow_flag(a)), + "stats" => !rest.contains(&"--no-stream"), + "events" | "attach" => true, + // `docker container logs -f`, `docker service logs -f`. + "container" | "service" => { + subcommand(rest, &[]).is_some_and(|(sub, rest)| container_follows(sub, rest)) + } + _ => false, + } +} + +/// The arguments of `docker compose` (or of `docker-compose`). `-f` before +/// the subcommand names a compose file; only after `logs` does it follow. +fn compose_follows(args: &[&str]) -> bool { + match subcommand(args, COMPOSE_VALUE_FLAGS) { + Some(("up", rest)) => !rest + .iter() + .any(|a| matches!(*a, "-d" | "--detach" | "--wait")), + Some(("logs", rest)) => rest.iter().any(|a| is_follow_flag(a)), + Some(("watch" | "events" | "attach" | "stats", _)) => true, + _ => false, + } +} + +/// `npm run dev`, `pnpm --filter web dev`, `yarn workspace app start`: the +/// script is the word after `run`, or the subcommand itself. +fn script_follows(program: &str, args: &[&str]) -> bool { + const SERVES: &[&str] = &["dev", "start", "serve", "watch", "preview", "storybook"]; + let value_flags = script_runner_value_flags(program); + let script = match subcommand(args, value_flags) { + Some(("run" | "run-script", rest)) => subcommand(rest, value_flags).map(|(s, _)| s), + // `yarn workspace