hippo-memory 3.5.1 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +27 -24
  2. package/dist/api/context/context.d.ts +1 -1
  3. package/dist/api/context/context.js +13 -9
  4. package/dist/api/ledger-db.d.ts +4 -2
  5. package/dist/api/ledger-db.js +11 -1
  6. package/dist/api/pilot-arm.js +4 -1
  7. package/dist/api/recall/finish.js +3 -2
  8. package/dist/api/recall/recall.js +3 -1
  9. package/dist/api/recall/request.d.ts +1 -1
  10. package/dist/api/recall/request.js +3 -1
  11. package/dist/api/tokens.d.ts +1 -1
  12. package/dist/api/tokens.js +3 -0
  13. package/dist/api/types.d.ts +2 -0
  14. package/dist/api/types.js +4 -0
  15. package/dist/base/config/config.d.ts +2 -0
  16. package/dist/base/errors/read-only.d.ts +3 -0
  17. package/dist/base/errors/read-only.js +4 -0
  18. package/dist/base/util/env.d.ts +1 -0
  19. package/dist/base/util/env.js +3 -0
  20. package/dist/base/util/version.d.ts +1 -1
  21. package/dist/base/util/version.js +1 -1
  22. package/dist/cli.js +14 -1
  23. package/dist/db/connect.d.ts +4 -0
  24. package/dist/db/connect.js +79 -1
  25. package/dist/db/grant.js +1 -1
  26. package/dist/db/migrate.d.ts +3 -0
  27. package/dist/db/migrate.js +1 -1
  28. package/dist/db/store-runtime.d.ts +7 -0
  29. package/dist/db/store-runtime.js +4 -0
  30. package/dist/store/sqlite/index.d.ts +1 -1
  31. package/dist/store/sqlite/learning/prediction-baserate.js +4 -2
  32. package/dist/store/sqlite/recall/search-rows.js +5 -2
  33. package/dist/store/sqlite/runtime/handles.js +3 -0
  34. package/dist/surface/cli/api-context.js +1 -0
  35. package/dist/surface/cli/cli-runtime.js +2 -1
  36. package/dist/surface/cli/serve.js +4 -1
  37. package/dist/surface/cli/verb-row.d.ts +2 -0
  38. package/dist/surface/cli/verbs/health.js +3 -0
  39. package/dist/surface/cli/verbs/memory.js +5 -0
  40. package/dist/surface/cli/verbs/objects.js +2 -0
  41. package/dist/surface/cli/verbs/sessions.js +11 -0
  42. package/dist/surface/mcp/request.js +6 -2
  43. package/dist/surface/mcp/tools.d.ts +2 -0
  44. package/dist/surface/mcp/tools.js +8 -0
  45. package/dist/surface/open-store.d.ts +2 -2
  46. package/dist/surface/open-store.js +2 -2
  47. package/extensions/openclaw-plugin/openclaw.plugin.json +1 -1
  48. package/extensions/openclaw-plugin/package.json +1 -1
  49. package/openclaw.plugin.json +1 -1
  50. package/package.json +1 -1
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # 🦛 Hippo
2
2
 
3
- **Stop re-teaching your agent.**
3
+ **Your corrections, remembered by Claude Code, Codex and Cursor.**
4
4
 
5
- Make your agent's memory work like a brain. Hippo is long-term memory for coding agents. It's a critical layer for your AI harness that connects across your different tools (Cursor, Claude Code, Codex). It keeps your proprietary data completely local, and it actually learns over time. By strengthening memories each time they are recalled, Hippo preserves what works, lets mistakes decay, and continuously compounds your agents' intelligence.
5
+ Hippo is open-source memory that runs on your machine and gives the rules it captured back to the agent when a new session starts. In our Claude Code test on 29 repositories, adding it to built-in memory cut repeat mistakes from 21 in 100 to 11, at the same cost.
6
6
 
7
7
  [![npm](https://img.shields.io/npm/v/hippo-memory)](https://npmjs.com/package/hippo-memory)
8
8
  [![npm downloads](https://img.shields.io/npm/dm/hippo-memory)](https://npmjs.com/package/hippo-memory)
@@ -24,7 +24,7 @@ npm install -g hippo-memory && hippo init
24
24
 
25
25
  Setting up every git repo under a folder in one go is a second step. The [Quick start](#quick-start) says what it changes, then gives the command.
26
26
 
27
- Package installation alone does not enable automatic preservation on every agent. Complete the documented setup and required host trust; capture and compaction coverage depend on the integration.
27
+ Installing the package alone captures nothing, and what runs after init depends on the agent.
28
28
 
29
29
  Having an AI agent install it? Point it at [llms-install.md](llms-install.md): it installs, wires hippo into the agents it finds, and verifies with `hippo doctor`.
30
30
 
@@ -88,7 +88,7 @@ npm install -g hippo-memory
88
88
  hippo init
89
89
  ```
90
90
 
91
- **Optional: many repos at once.** Read what it changes first. `hippo init --scan <folder>` looks for git repos in the folder and up to three levels below it, skipping dot-folders and `node_modules`. Each repo gets a `.hippo/` store, seeded with lessons from the last 365 days of its commits and with its [agent memories](#agent-memories), and is added to the daily run's list. For the agents it finds, it installs the same user-level hooks as `hippo init`: 7 Claude Code hook entries in `~/.claude/settings.json` and the OpenCode plugin. It also sets up the daily 6:15am run, a crontab line on Linux and macOS or a scheduled task on Windows. It adds no block to any repo's `CLAUDE.md` or `AGENTS.md`. `--no-hooks`, `--no-schedule` and `--no-learn` leave out the hooks, the daily run and the history import.
91
+ **Optional: many repos at once.** Read what it changes first. `hippo init --scan <folder>` looks for git repos in the folder and up to three levels below it, skipping dot-folders and `node_modules`. Each repo gets a `.hippo/` store, seeded with lessons from the last 365 days of its commits and with its [agent memories](#agent-memories), and is added to the daily run's list. For the agents it finds, it installs the same user-level hooks as `hippo init`: 8 Claude Code hook entries in `~/.claude/settings.json` and the OpenCode plugin. It also sets up the daily 6:15am run, a crontab line on Linux and macOS or a scheduled task on Windows. It adds no block to any repo's `CLAUDE.md` or `AGENTS.md`. `--no-hooks`, `--no-schedule` and `--no-learn` leave out the hooks, the daily run and the history import.
92
92
 
93
93
  ```bash
94
94
  hippo init --scan ~
@@ -119,7 +119,7 @@ Run `hippo init` inside one project. This is everything it writes, in the projec
119
119
 
120
120
  - **The project's store.** A `.hippo/` folder: SQLite plus markdown mirrors. On the first run in a git repo it learns lessons from the last 30 days of commits.
121
121
  - **Instruction files.** A block between `<!-- hippo:start -->` and `<!-- hippo:end -->` in the project's `CLAUDE.md` or `AGENTS.md`, only if that file already exists. Codex, Cursor, OpenClaw, OpenCode and Pi read `AGENTS.md`.
122
- - **Claude Code,** when the project has `CLAUDE.md` or `.claude/settings.json`: 7 hook entries in `~/.claude/settings.json`, one each on SessionEnd, UserPromptSubmit, PreCompact, PostCompact and PostToolUseFailure and two on SessionStart. [Framework Integrations](#framework-integrations) says what each one runs.
122
+ - **Claude Code,** when the project has `CLAUDE.md` or `.claude/settings.json`: 8 hook entries in `~/.claude/settings.json`, one each on SessionEnd, UserPromptSubmit, PreCompact, PostCompact and PostToolUseFailure and three on SessionStart. [Framework Integrations](#framework-integrations) says what each one runs.
123
123
  - **OpenCode,** when the project has `.opencode/` or `opencode.json`: a plugin at `~/.config/opencode/plugins/hippo.ts`.
124
124
  - **Codex,** when the project has `AGENTS.md` or `.codex` and Codex is installed (`$CODEX_HOME`, else `~/.codex`, exists): 2 hook entries in Codex's `hooks.json`, one on UserPromptSubmit that sends your pinned memories plus up to 5 that match the prompt with every prompt and one on SessionStart after a compaction. **Codex runs them only after you trust them once in `/hooks`.** Init also prints `hippo hook install codex`, the opt-in that wraps the Codex launcher to capture sessions; `hippo hook uninstall codex` removes hippo's hooks and the wrapper.
125
125
  - **A daily run at 6:15am,** one per machine: a crontab line on Linux and macOS, a scheduled task named `hippo-daily-runner` on Windows. It runs `hippo learn --git --days 1` and then `hippo sleep` in every project listed in `~/.hippo/workspaces.json`, and init adds this project to that list.
@@ -773,7 +773,7 @@ The command runs with no shell, so each argument reaches the program as written.
773
773
  | `hippo decide "<decision>" --context "<why>"` | Include reasoning |
774
774
  | `hippo decide "<decision>" --supersedes <id>` | Supersede a previous decision |
775
775
  | `hippo hook list` | Show available framework hooks |
776
- | `hippo hook install <target>` | Install hook (claude-code also adds its 7 settings.json hook entries: session start and end, each prompt, compaction, failed tool calls) |
776
+ | `hippo hook install <target>` | Install hook (claude-code also adds its 8 settings.json hook entries: session start and end, each prompt, compaction, failed tool calls) |
777
777
  | `hippo hook uninstall <target>` | Remove hook |
778
778
  | `hippo handoff create --summary "..."` | Create a session handoff |
779
779
  | `hippo handoff latest` | Show the most recent handoff |
@@ -803,6 +803,8 @@ The command runs with no shell, so each argument reaches the program as written.
803
803
 
804
804
  On `heartbeat`, `block`, `review` and `complete`, a given `--run` is checked against the card's live run and the command is refused, unchanged, if the two do not match.
805
805
 
806
+ `HIPPO_READ_ONLY=1` uses a store without changing it, for example in the test phase of a benchmark. `hippo recall`, `hippo context`, the prompt hook and the MCP read tools give the same answers and write nothing: no recall counts, token-ledger rows, audit rows or mirror files, and a store with a WAL keeps its WAL. `remember`, `supersede`, `refine`, `outcome`, `resolve`, `decide`, `invalidate`, `forget`, `learn`, `promote`, `share` and `import`, and the MCP tools `hippo_remember`, `hippo_outcome`, `hippo_learn`, `hippo_resolve` and `hippo_share`, answer `read-only: not saved (HIPPO_READ_ONLY=1)` and save nothing (the CLI exits 1). `capture`, `capture-error`, `sleep`, `pre-compact`, `post-compact` and `session-end` log one line and do nothing, `hippo serve` does not start, and any other command that writes to the store fails with the store's own read-only error.
807
+
806
808
  ---
807
809
 
808
810
  ## Framework Integrations
@@ -813,7 +815,7 @@ On `heartbeat`, `block`, `review` and `complete`, a given `--run` is checked aga
813
815
 
814
816
  | Framework | Detected by | Patches |
815
817
  |-----------|------------|---------|
816
- | Claude Code | `CLAUDE.md` or `.claude/settings.json` | `CLAUDE.md` + 7 hook entries in `~/.claude/settings.json` (listed below) |
818
+ | Claude Code | `CLAUDE.md` or `.claude/settings.json` | `CLAUDE.md` + 8 hook entries in `~/.claude/settings.json` (listed below) |
817
819
  | Codex | `AGENTS.md` or `.codex` | `AGENTS.md` + `UserPromptSubmit`/`SessionStart(compact)` hooks in Codex's `hooks.json` when Codex is installed (trust them once in `/hooks`); session capture is opt-in with `hippo hook install codex`, which wraps the Codex launcher |
818
820
  | Cursor | `AGENTS.md` | `AGENTS.md`, which Cursor reads from the project root |
819
821
  | OpenClaw | `.openclaw` or `AGENTS.md` | `AGENTS.md`; the native plugin is a separate install: `openclaw plugins install hippo-memory` |
@@ -829,7 +831,7 @@ Setup guides on the website: [Claude Code](https://hippo-memory.com/claude-code/
829
831
  If you prefer explicit control:
830
832
 
831
833
  ```bash
832
- hippo hook install claude-code # patches CLAUDE.md + adds the 7 settings.json hook entries listed below
834
+ hippo hook install claude-code # patches CLAUDE.md + adds the 8 settings.json hook entries listed below
833
835
  hippo hook install codex # patches AGENTS.md + adds hooks to Codex's hooks.json + wraps the detected Codex launcher
834
836
  hippo hook install cursor # patches AGENTS.md
835
837
  hippo hook install openclaw # patches AGENTS.md
@@ -844,9 +846,10 @@ This adds a `<!-- hippo:start -->` ... `<!-- hippo:end -->` block that tells the
844
846
 
845
847
  The block asks for nothing a hook already does, because each extra tool call re-reads the whole context. Re-running `hippo init` swaps a block an older hippo wrote for the current one, as long as nobody edited it. It leaves an edited block alone and says so, and never touches text outside the markers.
846
848
 
847
- For Claude Code, it also adds 7 hook entries to `~/.claude/settings.json`:
849
+ For Claude Code, it also adds 8 hook entries to `~/.claude/settings.json`:
848
850
  - a `SessionEnd` hook that runs `hippo sleep` and then `hippo capture` when the session exits. Capture matches the last 20 user and 10 assistant messages of the transcript against word patterns for decisions, rules, errors and preferences. It uses no model unless you turn on `capture.followUpRules` (see Conversation Capture) and does not read earlier turns, so a correction older than that window needs a `hippo remember` by hand.
849
851
  - a `SessionStart` hook that prints the previous session's consolidation log on stderr, where `claude --debug` shows it. When the last sleep failed or a compaction summary was set aside, it shows you one line that points to `hippo doctor`.
852
+ - a second `SessionStart` hook that runs `hippo session-rules`, which prints the rules you taught under `## Rules from the user` and nothing else. It has no matcher, so a resumed or cleared session and a compaction get the rules again.
850
853
  - a `UserPromptSubmit` hook that runs `hippo context --pinned-only --include-recent 5 --format additional-context` every turn. It re-injects pinned memories (`hippo remember <text> --pin`) plus up to 5 memories that share words with your prompt. When nothing matches, it adds only the pinned ones. Since 1.55.0 this replaces the 5 newest memories, which cut the median block from 847 to 533 tokens in our eval. `{"pinnedInject":{"promptRecall":false}}` brings back the 5 newest, so fresh same-session lessons appear on the next prompt whatever you ask. The block is rendered without live strength percentages, so it stays byte-identical while its memories do not change, and it is sent only when it changed since the session's last prompt: an unchanged block is skipped, resent every 10 skips (`pinnedInject.refreshTurns`, `0` never resends) and resent after compaction. The prompt-matched memories go in a separate block that is never skipped, so they are sent on every prompt they match. `{"pinnedInject":{"skipUnchanged":false}}` sends the pinned block every turn as before. `{"pinnedInject":{"excludeTags":["session-digest"]}}` leaves out every memory that carries a listed tag, whether it is pinned, recent or matched to the prompt; the list is empty by default. Opt out entirely with `{"pinnedInject":{"enabled":false}}` in `.hippo/config.json`.
851
854
  - a `PreCompact` hook that runs `hippo pre-compact` before the transcript gets summarized. It records the compaction in the store, saves a working-state snapshot (task/summary/next step) so mid-session compaction can't drop it, and asks the summariser to end its summary with a "Memories for hippo" list: the lessons, decisions and corrections from the session that should outlive it. The `SessionEnd` hook still owns extracting durable memories from the transcript.
852
855
  - a second `SessionStart` hook (matcher `compact`) that runs `hippo compact-resume`, printing that snapshot back into context right after compaction, if it is under 15 minutes old.
@@ -934,7 +937,7 @@ Plugin docs: [extensions/openclaw-plugin/](extensions/openclaw-plugin/). Integra
934
937
 
935
938
  ### Claude Code Plugin
936
939
 
937
- Plugin with session, prompt and compaction hooks plus error auto-capture. See [extensions/claude-code-plugin/](extensions/claude-code-plugin/).
940
+ Plugin with session, prompt and compaction hooks, error auto-capture, and the `hippo-memory` MCP server (`hippo mcp`). See [extensions/claude-code-plugin/](extensions/claude-code-plugin/).
938
941
 
939
942
  Full integration details: [integrations/](integrations/)
940
943
 
@@ -1107,59 +1110,59 @@ node run.mjs --adapter all
1107
1110
 
1108
1111
  ### How do I give Claude Code memory between sessions?
1109
1112
 
1110
- Run `npm install -g hippo-memory`, then `hippo init` in the project. If the project has a `CLAUDE.md`, init adds a short block saying the prompt hook injects pinned rules and matching memories, and asking Claude to run `hippo context --auto` at the start of a task only if no hippo memory block has appeared. It also adds hooks to Claude Code's settings that keep your pinned memories in context, save a task snapshot before compaction, and run `hippo sleep` when the session ends. `hippo init --scan ~` gives every git repo under your home folder a store and installs the same hooks, but adds no block to any `CLAUDE.md`. The [Claude Code plugin](https://github.com/kitfunso/hippo-memory/tree/master/extensions/claude-code-plugin) is the alternative to these hooks; use one, not both.
1113
+ Run `npm install -g hippo-memory`, then `hippo init` in the project. Init adds a short block to an existing `CLAUDE.md` and installs hooks that keep pinned memories in context, save your task before compaction, store failed tool calls and run `hippo sleep` when the session ends.
1111
1114
 
1112
1115
  ### How do I give Cursor memory between sessions?
1113
1116
 
1114
- `hippo init` adds its instructions to `AGENTS.md` if the project has one, and Cursor reads that file from the project root. The [MCP server](#mcp-server) gives Cursor's agent tools to recall and store memories once you add `hippo mcp` to `.cursor/mcp.json`. Older hippo versions wrote the block to `.cursorrules`; `hippo hook uninstall cursor` removes it from there, and from `AGENTS.md` only when the block there is Cursor's own and unedited (`hippo hook install cursor` puts it back). A block written for Codex or another agent stays, since Cursor reads it too, and so does an edited block, since hippo cannot tell whose it is. `hippo import --cursor .cursor/rules` turns your existing rules into memories; it reads an older single `.cursorrules` file too.
1117
+ `hippo init` adds its instructions to `AGENTS.md` if the project has one, which Cursor reads. Add `hippo mcp` to `.cursor/mcp.json` and Cursor's agent gets tools to recall and store memories. `hippo import --cursor .cursor/rules` turns your existing rules into memories.
1115
1118
 
1116
1119
  ### How do I give Codex memory across sessions?
1117
1120
 
1118
- `hippo init` adds its instructions to your `AGENTS.md`, which Codex reads before it starts work. Capturing Codex sessions is opt-in: `hippo hook install codex` wraps the Codex launcher, and `hippo hook uninstall codex` removes the wrapper.
1121
+ `hippo init` adds its instructions to your `AGENTS.md`, which Codex reads before it starts work. Capturing Codex sessions is opt-in, with `hippo hook install codex`.
1119
1122
 
1120
1123
  ### Which agents does hippo work with?
1121
1124
 
1122
- `hippo init` detects Claude Code, Codex, Cursor, OpenClaw, OpenCode and Pi, and wires itself into each one's instruction file, hooks or plugin. It only patches instruction files that already exist. Any MCP client can use the [MCP server](#mcp-server), and other tools can call the CLI or the HTTP API that `hippo serve` starts.
1125
+ `hippo init` detects Claude Code, Codex, Cursor, OpenClaw, OpenCode and Pi, and wires itself into each one's instruction file, hooks or plugin. What runs automatically differs by agent. Any MCP client can use the [MCP server](#mcp-server), and anything else can call the CLI.
1123
1126
 
1124
1127
  ### Can I use hippo as an MCP memory server?
1125
1128
 
1126
- Yes. `hippo mcp` runs the server over stdio, and `npx -y hippo-memory mcp` runs it without a global install. Add it to the MCP config of Claude Desktop, Cursor, Windsurf (now Devin Desktop), Cline or any other client (example [above](#mcp-server)); in Claude Code, run `claude mcp add hippo-memory -- hippo mcp`. The agent gets tools such as `hippo_recall`, `hippo_remember` and `hippo_outcome`.
1129
+ Yes. `hippo mcp` runs the server over stdio. Add it to the MCP config of Cursor, Claude Desktop, Windsurf (now Devin Desktop), Cline or any other client, or in Claude Code run `claude mcp add hippo-memory -- hippo mcp`.
1127
1130
 
1128
1131
  ### How is hippo different from mem0?
1129
1132
 
1130
- mem0 uses a language model to extract memories, OpenAI by default in its open-source library, and memories stored through its hosted MCP server live in your Mem0 account ([mem0 docs](https://docs.mem0.ai/platform/mem0-mcp), checked 2026-09-28). Hippo stores memories in SQLite on your machine, needs no account and no model, and `hippo init` wires it into the coding agents it finds. mem0's platform and hippo both mark an older fact superseded when a newer one replaces it. Hippo also lets you mark a recalled memory wrong with `hippo outcome --bad`, and it drops out of the top results.
1133
+ mem0 uses a language model to extract memories, and its hosted MCP server keeps them in your Mem0 account ([mem0 docs](https://docs.mem0.ai/platform/mem0-mcp), checked 2026-09-28). Hippo stores memories in SQLite on your machine and needs no account and no model. On LoCoMo, a public test of questions about long conversations, Mem0 scored 94.9 and hippo 89.4 when we ran both.
1131
1134
 
1132
1135
  ### Is this just RAG?
1133
1136
 
1134
- No. RAG searches a fixed corpus. Hippo's store changes as your agent works: a memory marked wrong drops out of the top results, a newer fact supersedes the old one, and memories that keep getting recalled last longer while unused ones fade on a half-life. Recall itself is search: BM25, plus embeddings if you install them.
1137
+ Partly. Recall is search, BM25 plus embeddings if you install them. The difference is that the store changes as your agent works. A memory you mark wrong drops down the results, a newer fact replaces an old one, and unused memories fade.
1135
1138
 
1136
1139
  ### Does it need embeddings?
1137
1140
 
1138
- No. Recall runs on BM25 out of the box, with no model and no network call, and a default install has no embedder. Embeddings are an optional install for hybrid search. On LongMemEval-S, where each question gets its own haystack, the benchmark scripts (not `hippo recall`) fuse BM25 with the free local MiniLM embedder and reach 98.0% recall@5, counting a hit when any answer session is in the top five. On LongMemEval's oracle split with one pooled store, BM25 alone scored 74.0% recall@5 in v0.11. The two runs use different setups, so they are not a before and after.
1141
+ No. Recall runs on BM25 out of the box, with no model and no network call. With the optional free local embedder on, hippo scored higher than without it on two of five public answer tests, by 3.4 and 11.9 points, with no clear difference on the other three.
1139
1142
 
1140
1143
  ### Do I still need CLAUDE.md?
1141
1144
 
1142
- Yes, for short standing rules such as build commands, code style and things never to do. Claude Code loads `CLAUDE.md` and its auto memory into every session, and its [memory docs](https://code.claude.com/docs/en/memory) say that when two rules contradict each other, Claude may pick one arbitrarily. Hippo holds the lessons that pile up, recalls the ones that match the task, and retires the ones marked wrong or replaced. `hippo init` adds its block to `CLAUDE.md`, and `hippo import --claude CLAUDE.md` turns existing notes into memories.
1145
+ Yes, for short standing rules such as build commands and code style. Claude Code's [memory docs](https://code.claude.com/docs/en/memory) say that when two rules contradict each other, Claude may pick one arbitrarily. Hippo holds the lessons that pile up and recalls the ones that match the task.
1143
1146
 
1144
1147
  ### What happens when a memory turns out to be wrong?
1145
1148
 
1146
- Mark it, and it drops out of the top results. `hippo outcome --bad` weakens the memories from the last recall, `hippo supersede <id> "<new fact>"` replaces one with a newer version, and `hippo reject <id> --reason "<why>"` stops that value from returning at all. On the synthetic E1 test, where every mark is correct, plain BM25 plus the outcome mark cut how often a marked-bad memory stayed in the top five from 71.9% to 0.0%. Real marks are noisier, because `--bad` marks the whole recall batch.
1149
+ `hippo outcome --bad` weakens the memories from the last recall, and `hippo supersede <id> "<new fact>"` replaces one. On a synthetic test where every mark was correct, a bad mark cut how often a wrong memory stayed in the top five from 71.9% to 0.0%. Real marks are noisier.
1147
1150
 
1148
1151
  ### Where does hippo keep my data?
1149
1152
 
1150
- On your machine, in SQLite: `.hippo/hippo.db` in each project, plus a global store in `~/.hippo/` for lessons shared across projects, with markdown mirrors you can read and commit. Recall makes no network call by default. Text goes to an outside provider only through features that use one: an API embedder, the Jev or LLM reranker, `hippo refine`, and the fact extraction `hippo sleep` runs through Anthropic's API whenever `ANTHROPIC_API_KEY` is set in its environment. To turn that last one off, set `{"extraction":{"enabled":false}}` in `.hippo/config.json`.
1153
+ On your machine, in SQLite, as `.hippo/hippo.db` in each project and a global store in `~/.hippo/`, with markdown mirrors you can read and commit. Recall makes no network call by default. Text leaves your machine only through an API embedder, a reranker, model-read rule capture (`capture.followUpRules`), `hippo refine`, or `hippo sleep` when `ANTHROPIC_API_KEY` is set. `{"extraction":{"enabled":false}}` in `.hippo/config.json` turns that last one off.
1151
1154
 
1152
1155
  ### What does hippo cost?
1153
1156
 
1154
- Nothing. Hippo is MIT-licensed and needs no account or API key. Optional features that call an outside provider bill through it: the Jev reranker costs about 0.0004 USD a recall, and API embedders and sleep's fact extraction bill your own keys. Memory text handed to your agent uses context tokens, and `hippo tokens` shows how many.
1157
+ Nothing. Hippo is MIT-licensed and needs no account or API key. Optional features that call an outside provider bill through it. The Jev reranker costs about 0.0004 USD a recall, and API embedders and sleep's fact extraction use your own keys.
1155
1158
 
1156
1159
  ### Is it production-ready?
1157
1160
 
1158
- Judge it by what is tested. 3,500+ tests run against a real database, with no module mocks and no mocked store, and a negative test checks that one tenant cannot read another's memories. It is MIT-licensed and has zero runtime dependencies. For what it does to an agent's work, see the next question.
1161
+ Judge it by what is tested. 3,500+ tests run against a real database, with no module mocks and no mocked store. It has zero runtime dependencies. The next question covers what it does to an agent's work.
1159
1162
 
1160
1163
  ### Has hippo been shown to make agents better at their work?
1161
1164
 
1162
- On repeat mistakes, yes. Z0 round 3 ran real Claude Code sessions on 29 repositories, with hippo and with Claude Code's built-in memory alone. An agent corrected once repeated that mistake about half as often with hippo installed: 11 times in 100 against 21, 2 to 4 tasks after the correction, at the same cost. Over every first chance to repeat, the pre-registered read is 14.9 points fewer [5.5, 24.3] ([result](https://github.com/kitfunso/hippo-memory/blob/master/docs/evals/2026-11-08-z0-round3-result.md)). On tasks with no lesson to apply, hippo changed neither the cost nor the share solved. The gain was the same with lesson capture switched off, so round 4 tests how much of it the stored lessons carry. The other published numbers measure retrieval. Every measurement, including failed runs and one retracted claim, is indexed in [docs/evals](https://github.com/kitfunso/hippo-memory/blob/master/docs/evals/README.md).
1165
+ On repeat mistakes, yes, in [one test of our own](https://github.com/kitfunso/hippo-memory/blob/master/docs/evals/2026-11-08-z0-round3-result.md). We corrected Claude Code once on 29 repositories and counted repeats 2 to 4 tasks later, finding 11 in 100 with hippo added, against 21 with built-in memory alone, at the same cost. We can't yet say why, because the gain was the same with lesson capture switched off. Failed runs are in [docs/evals](https://github.com/kitfunso/hippo-memory/blob/master/docs/evals/README.md) too.
1163
1166
 
1164
1167
  ---
1165
1168
 
@@ -1,5 +1,5 @@
1
1
  import type { ContextOptions, ContextResult } from './context-types.js';
2
- import type { Context } from '../types.js';
2
+ import { type Context } from '../types.js';
3
3
  /** Tokens a context block may use when the caller sets no budget; the hook command and the CLI
4
4
  * default match it. */
5
5
  export declare const DEFAULT_CONTEXT_BUDGET = 1500;
@@ -9,6 +9,7 @@ import { selectPinned, selectStrongest } from './context-select.js';
9
9
  import { selectBySearch } from './context-search.js';
10
10
  import { strengthenOf } from '../recall/finish.js';
11
11
  import { keepShownIds } from '../recall/last-recalled.js';
12
+ import { readOnlyOf } from '../types.js';
12
13
  import { NO_QUERY, sourceOf, globalSource, planContext, promptRecallRequest, openBlockBudget, } from './context-plan.js';
13
14
  import { ambientAdmission, loadPools, userRuleReserve } from './context-pools.js';
14
15
  import { loadTaskSections, pointerModes } from './context-task-state.js';
@@ -51,7 +52,7 @@ export async function assembleContext(ctx, opts) {
51
52
  if (items.length === 0 && noSections) {
52
53
  // A query that found nothing is the coverage-gap signal, so it still gets a trace; pinned-only
53
54
  // stays read-only.
54
- if (!plan.pinnedOnly)
55
+ if (!plan.pinnedOnly && !readOnlyOf(ctx))
55
56
  await traceEmptyContext(ctx, opts, plan);
56
57
  return { entries: [], tokens: 0 };
57
58
  }
@@ -156,14 +157,17 @@ async function recordRetrieval(ctx, { opts, plan, selected, activeSnapshot }) {
156
157
  })),
157
158
  };
158
159
  const writes = { goalLog: [], audit: [], trace, strengthen: strengthenOf(ctx, retrievedIds) };
159
- // The last recall feeds only outcomeForLastRecall, so a store that keeps none still finishes the
160
- // recall without one.
161
- const store = ctx.store;
162
- const traceId = store.lastRecall
163
- ? await store.lastRecall.finishRecall(writes, plan.hasGlobal ? plan.globalRoot : undefined)
164
- : await store.finishRecall(writes).then(() => null);
165
- plan.obs?.traced(traceId);
166
- await store.bumpRecallStats(selected.length);
160
+ // A read-only store keeps its rows; the reply still shows them as this retrieval left them.
161
+ if (!readOnlyOf(ctx)) {
162
+ // The last recall feeds only outcomeForLastRecall, so a store that keeps none still finishes the
163
+ // recall without one.
164
+ const store = ctx.store;
165
+ const traceId = store.lastRecall
166
+ ? await store.lastRecall.finishRecall(writes, plan.hasGlobal ? plan.globalRoot : undefined)
167
+ : await store.finishRecall(writes).then(() => null);
168
+ plan.obs?.traced(traceId);
169
+ await store.bumpRecallStats(selected.length);
170
+ }
167
171
  // Replace selectedItems entries with markRetrieved-updated copies so the returned ContextResult
168
172
  // reflects post-recall state.
169
173
  const items = selected.map((s) => ({
@@ -1,7 +1,7 @@
1
1
  import type { LedgerTurn } from '../base/ports/store.js';
2
2
  import type { TokenSurface, TokenUse } from '../base/ports/store/ledger.js';
3
3
  import type { LastSent } from '../base/session/skip-unchanged.js';
4
- import type { Context, GlobalInReach, LedgerHome } from './types.js';
4
+ import { type Context, type GlobalInReach, type LedgerHome } from './types.js';
5
5
  import { type DeliveryFault, type DeliveryRecorder } from './delivery/delivery-recorder.js';
6
6
  import type { DeliveryEventInput, DeliveryEventType } from '../base/session/delivery.js';
7
7
  import type { HookRuntime } from '../base/session/capture-contract.js';
@@ -10,10 +10,12 @@ import type { HookRuntime } from '../base/session/capture-contract.js';
10
10
  export interface LedgerReach {
11
11
  readonly local?: LedgerHome;
12
12
  readonly global?: GlobalInReach;
13
+ /** Under HIPPO_READ_ONLY=1 the rows are still read, so a skip decision holds, and never booked. */
14
+ readonly readOnly?: true;
13
15
  }
14
16
  /** Only a store that keeps a ledger has one, and a local one needs a reach that says the caller
15
17
  * has a store. */
16
- export declare function ledgerReachOf(ctx: Pick<Context, 'reach'>, shared?: boolean): LedgerReach;
18
+ export declare function ledgerReachOf(ctx: Pick<Context, 'reach' | 'config'>, shared?: boolean): LedgerReach;
17
19
  /** The call's own store, else the global store (the prompt hook fires where none is); null with
18
20
  * neither. */
19
21
  export declare function ledgerHome(reach: LedgerReach): LedgerHome | null;
@@ -1,3 +1,4 @@
1
+ import { readOnlyOf } from './types.js';
1
2
  import { createDeliveryRecorder, } from './delivery/delivery-recorder.js';
2
3
  import { errorMessage, log, errorFields } from '../base/util/log.js';
3
4
  function homeOf(global) {
@@ -11,7 +12,8 @@ function homeOf(global) {
11
12
  * has a store. */
12
13
  export function ledgerReachOf(ctx, shared) {
13
14
  const local = ctx.reach?.hasLocal === true ? ctx.reach.ledger : undefined;
14
- return shared === true ? { local } : { local, global: ctx.reach?.global };
15
+ const reach = shared === true ? { local } : { local, global: ctx.reach?.global };
16
+ return readOnlyOf(ctx) ? { ...reach, readOnly: true } : reach;
15
17
  }
16
18
  /** The call's own store, else the global store (the prompt hook fires where none is); null with
17
19
  * neither. */
@@ -23,16 +25,22 @@ export function ledgerHome(reach) {
23
25
  }
24
26
  /** Books one row in ledgerHome's store, best-effort. */
25
27
  export async function bookTokenUse(use, reach) {
28
+ if (reach.readOnly === true)
29
+ return;
26
30
  await ledgerHome(reach)?.ledger.recordTurn({ uses: [use] });
27
31
  }
28
32
  /** Books a turn's rows and then its delivery event on one connection of ledgerHome's store,
29
33
  * best-effort. */
30
34
  export async function bookLedgerTurn(turn, reach) {
35
+ if (reach.readOnly === true)
36
+ return;
31
37
  await ledgerHome(reach)?.ledger.recordTurn(turn);
32
38
  }
33
39
  /** bookLedgerTurn where each row is its own attempt: a row that fails is noted and the rest
34
40
  * still land. */
35
41
  export async function bookLedgerTurnPerRow(turn, reach) {
42
+ if (reach.readOnly === true)
43
+ return;
36
44
  await ledgerHome(reach)?.ledger.recordTurn({ ...turn, perRow: true });
37
45
  }
38
46
  /** What the session last sent on `surface` in ledgerHome's store; null with no ledger, no row or
@@ -43,6 +51,8 @@ export async function ledgerLastSent(tenantId, sessionId, surface, reach) {
43
51
  /** A delivery recorder for a hook on `ctx`'s store when the ledger store enables one, else null;
44
52
  * never throws. */
45
53
  export async function startDeliveryRecorder(ctx, start) {
54
+ if (readOnlyOf(ctx))
55
+ return null;
46
56
  try {
47
57
  // The same store the token ledger writes to, so its config governs both.
48
58
  const reach = ledgerReachOf(ctx);
@@ -13,6 +13,9 @@ export async function sessionPilotArm(tenantId, sessionId, write, opts) {
13
13
  if (rate <= 0)
14
14
  return null;
15
15
  const { ownTenantOnly } = opts;
16
- return home.ledger.pilotArm(tenantId, sessionId, rate, { write, ownTenantOnly });
16
+ return home.ledger.pilotArm(tenantId, sessionId, rate, {
17
+ write: write && opts.reach.readOnly !== true,
18
+ ownTenantOnly,
19
+ });
17
20
  }
18
21
  //# sourceMappingURL=pilot-arm.js.map
@@ -2,7 +2,7 @@
2
2
  // counter, token ledger row and the client's shown list).
3
3
  import { auditQueryFields } from '../../base/records/audit-report.js';
4
4
  import { recordTokens } from '../tokens.js';
5
- import { strengthOf } from '../types.js';
5
+ import { readOnlyOf, strengthOf } from '../types.js';
6
6
  import { keepShownIds } from './last-recalled.js';
7
7
  import { biasHintEnabled, } from './anchoring.js';
8
8
  import { sessionRing, peekSessionRing, noteRecall } from './session-rings.js';
@@ -116,7 +116,8 @@ export async function recordShownRecall(ctx, store, how, shown) {
116
116
  }
117
117
  const items = how.counts === 'none' ? 0 : shown.ids.length;
118
118
  // A recall with no audit row counts nothing, as it strengthens and traces nothing.
119
- if (shown.written && (how.counts === 'every' || items > 0))
119
+ const counted = shown.written && !readOnlyOf(ctx) && (how.counts === 'every' || items > 0);
120
+ if (counted)
120
121
  await store.bumpRecallStats(items);
121
122
  // The ledger books text that was sent, so its row does not wait on the audit write.
122
123
  await recordTokens(ctx, how.ledger, {
@@ -3,7 +3,7 @@
3
3
  // request.ts.
4
4
  import { DEFAULT_SEARCH_CANDIDATE_LIMIT } from '../../base/rank/search-types.js';
5
5
  import { assertScopeRequestAllowed, personalScopeOf } from '../../base/scope/recall-scope.js';
6
- import { ownerOrSubject, RecallContractError, sharedStoreOf } from '../types.js';
6
+ import { ownerOrSubject, readOnlyOf, RecallContractError, sharedStoreOf, } from '../types.js';
7
7
  import { callerOf, recallAuditMetadata, recallAuditRow, recallLead, recordShownRecall, shownRecallRows, strengthenOf, } from './finish.js';
8
8
  import { composeRecall, planRecall, recallOrigin, } from './compose.js';
9
9
  import { rankCtxOf, rankRecall, } from './pipeline.js';
@@ -125,6 +125,8 @@ function rankRequestOf(ctx, opts, windowSize, personalScope) {
125
125
  /** The one recall write: the caller's leading audit rows go first, and the ids shown are the
126
126
  * ones strengthened. */
127
127
  async function finishRecall(ctx, opts, writes, shownIds) {
128
+ if (readOnlyOf(ctx))
129
+ return;
128
130
  await ctx.store.finishRecall({
129
131
  ...writes,
130
132
  audit: [...(opts.trace?.leadingAudit ?? []), ...writes.audit],
@@ -1,7 +1,7 @@
1
1
  import { BadRequestError } from '../../base/errors/api-errors.js';
2
2
  import { type JsonValue } from '../../base/util/json.js';
3
3
  import type { ContextOptions } from '../context/context-types.js';
4
- import type { Context } from '../types.js';
4
+ import { type Context } from '../types.js';
5
5
  import type { CliCoreRanker, RecallBoostOptions, RecallFilterOptions, CliCoreQuery, RecallOptions, RecallResult, RecallWindowOptions } from './types.js';
6
6
  /** A recall or context input the caller must fix; MCP answers it with an isError result, HTTP
7
7
  * with a 400. */
@@ -7,6 +7,7 @@ import { reportAuditWriteFailure } from '../../base/records/audit-report.js';
7
7
  import { isJsonString } from '../../base/util/json.js';
8
8
  import { MAX_ID_LEN } from '../../base/util/limits.js';
9
9
  import { estimateTokens } from '../../base/util/token-text.js';
10
+ import { readOnlyOf } from '../types.js';
10
11
  import { rankCtxOf, rankRecall } from './pipeline.js';
11
12
  import { BUDGET_RANKED } from './profiles.js';
12
13
  import { callerOf, heldIds, RECALL_RECORDING, recallAuditMetadata, recallAuditRow, recordShownRecall, shownRecallRows, strengthenOf, } from './finish.js';
@@ -210,7 +211,8 @@ async function recordShown(ctx, { store, opts, core, done }) {
210
211
  strengthen: strengthenOf(ctx, ids),
211
212
  trace: traceOf(ctx, opts, core, shown.results),
212
213
  };
213
- const audited = await finishOrReport(() => finishShown(store, core.lastRecall, writes, ids.length > 0));
214
+ const audited = !readOnlyOf(ctx) &&
215
+ (await finishOrReport(() => finishShown(store, core.lastRecall, writes, ids.length > 0)));
214
216
  if (audited && second !== undefined)
215
217
  await finishSecond(ctx, second, recallRow, heldElsewhere);
216
218
  // The caller prints whether or not the record was written, so the ring and the ledger still take
@@ -1,6 +1,6 @@
1
1
  import type { TokenSummary, TokenSurface } from '../base/ports/store/ledger.js';
2
2
  import type { FailureSummary } from '../base/ports/store/rejections.js';
3
- import type { Context, ContextWith } from './types.js';
3
+ import { type Context, type ContextWith } from './types.js';
4
4
  /** Records memory text handed to an agent in the token ledger. Best-effort: never throws, since
5
5
  * a ledger failure must not fail the recall or context call. */
6
6
  export declare function recordTokens(ctx: Context, surface: TokenSurface, use: {
@@ -1,10 +1,13 @@
1
1
  // Token-use and failure reports.
2
2
  import { rethrowIfStoreBlocked } from '../base/util/store-blocked.js';
3
3
  import { errorMessage, log, errorFields } from '../base/util/log.js';
4
+ import { readOnlyOf } from './types.js';
4
5
  import { DAY_MS } from '../base/util/time.js';
5
6
  /** Records memory text handed to an agent in the token ledger. Best-effort: never throws, since
6
7
  * a ledger failure must not fail the recall or context call. */
7
8
  export async function recordTokens(ctx, surface, use) {
9
+ if (readOnlyOf(ctx))
10
+ return;
8
11
  try {
9
12
  await ctx.store.recordTokens({
10
13
  tenantId: ctx.tenantId,
@@ -94,6 +94,8 @@ export type EntryInfraPorts = Omit<InfraPorts, 'failureNotices'> & {
94
94
  /** A root's reach with the global store's config loaded beside it; `configAt` is the root's own
95
95
  * loader, and a promote embeds its copy with `embedderFor`. */
96
96
  export declare function contextReach(reach: StoreReach, configAt: (root: string) => HippoConfig, embedderFor: EmbedderFor, ledger?: LedgerHome): ContextReach;
97
+ /** Whether the root runs under HIPPO_READ_ONLY=1, where a read skips the writes it would make. */
98
+ export declare function readOnlyOf(ctx: Pick<Context, 'config'>): boolean;
97
99
  /** Whether the store serves many people: the root's reach says, else the store's config for an
98
100
  * integrator's store. */
99
101
  export declare function sharedStoreOf(ctx: Pick<Context, 'reach' | 'config'>): boolean;
package/dist/api/types.js CHANGED
@@ -30,6 +30,10 @@ export function contextReach(reach, configAt, embedderFor, ledger) {
30
30
  }
31
31
  return withConfig;
32
32
  }
33
+ /** Whether the root runs under HIPPO_READ_ONLY=1, where a read skips the writes it would make. */
34
+ export function readOnlyOf(ctx) {
35
+ return ctx.config.runtime?.readOnly === true;
36
+ }
33
37
  /** Whether the store serves many people: the root's reach says, else the store's config for an
34
38
  * integrator's store. */
35
39
  export function sharedStoreOf(ctx) {
@@ -183,6 +183,8 @@ export interface RuntimeSettings {
183
183
  /** HIPPO_LOSS_AVERSION_RATIO, which scales an error memory's strength; strength scoring
184
184
  * applies its floor. */
185
185
  readonly lossAversionRatio?: number;
186
+ /** HIPPO_READ_ONLY=1: the store refuses every write, so a read skips its own bookkeeping. */
187
+ readonly readOnly?: boolean;
186
188
  /** Where the CLEF rerankers send a request; without it they keep the native order. */
187
189
  readonly clef?: ClefSettings;
188
190
  }
@@ -0,0 +1,3 @@
1
+ /** The refusal a write verb prints and a write MCP tool returns, word for word. */
2
+ export declare const READ_ONLY_REFUSAL = "read-only: not saved (HIPPO_READ_ONLY=1)";
3
+ //# sourceMappingURL=read-only.d.ts.map
@@ -0,0 +1,4 @@
1
+ // What every surface answers a write with under HIPPO_READ_ONLY=1, so a caller matches one text.
2
+ /** The refusal a write verb prints and a write MCP tool returns, word for word. */
3
+ export const READ_ONLY_REFUSAL = 'read-only: not saved (HIPPO_READ_ONLY=1)';
4
+ //# sourceMappingURL=read-only.js.map
@@ -47,6 +47,7 @@ export declare const envSkipAutoIntegrations: () => boolean;
47
47
  export declare const envSkipSchedule: () => boolean;
48
48
  export declare const envMcpStdio: () => boolean;
49
49
  export declare const envRequireServer: () => boolean;
50
+ export declare const envReadOnly: () => boolean;
50
51
  export declare const envStdinWaitMs: () => number | undefined;
51
52
  export declare function envLogLevel(): string;
52
53
  /** `HIPPO_LOG_FORMAT=json` writes each log line as one JSON object; anything else keeps the text
@@ -20,6 +20,7 @@ const FLAGS = {
20
20
  HIPPO_REQUIRE_SERVER: false,
21
21
  HIPPO_REQUIRE_SESSION_SCOPED_FRESH_TAIL: false,
22
22
  HIPPO_ALLOW_CLEARTEXT: false,
23
+ HIPPO_READ_ONLY: true,
23
24
  SLACK_ALLOW_UNKNOWN_TEAM_FALLBACK: false,
24
25
  GITHUB_ALLOW_UNKNOWN_INSTALLATION_FALLBACK: false,
25
26
  };
@@ -152,6 +153,7 @@ export function envRuntimeSettings() {
152
153
  dagRebuildCap: envDagRebuildCap(),
153
154
  activeScope: envActiveScope() ?? undefined,
154
155
  lossAversionRatio: envLossAversionRatio(),
156
+ readOnly: envReadOnly(),
155
157
  clef: envClefSettings(),
156
158
  };
157
159
  }
@@ -200,6 +202,7 @@ export const envSkipAutoIntegrations = bool('HIPPO_SKIP_AUTO_INTEGRATIONS');
200
202
  export const envSkipSchedule = bool('HIPPO_SKIP_SCHEDULE');
201
203
  export const envMcpStdio = bool('HIPPO_MCP_STDIO');
202
204
  export const envRequireServer = bool('HIPPO_REQUIRE_SERVER');
205
+ export const envReadOnly = bool('HIPPO_READ_ONLY');
203
206
  const envRequireSessionScopedFreshTail = bool('HIPPO_REQUIRE_SESSION_SCOPED_FRESH_TAIL');
204
207
  export const envStdinWaitMs = posInt('HIPPO_STDIN_WAIT_MS');
205
208
  export function envLogLevel() {
@@ -2,7 +2,7 @@
2
2
  * Single source of truth for the package version, written by scripts/sync-version.mjs; never
3
3
  * edit by hand. Read by the db rollback guard, /health, MCP. A constant, not a runtime
4
4
  * package.json read: the published bundle may lack package.json on a path ESM can resolve. */
5
- export declare const PACKAGE_VERSION = "3.5.1";
5
+ export declare const PACKAGE_VERSION = "3.6.0";
6
6
  /** The floor a store takes on its first expiring key: the first release with schema v53, set by
7
7
  * hand in that release; scripts/checks/check-expiring-keys-floor.mjs gates it. */
8
8
  export declare const EXPIRING_KEYS_MIN_BINARY = "1.64.0";
@@ -2,7 +2,7 @@
2
2
  * Single source of truth for the package version, written by scripts/sync-version.mjs; never
3
3
  * edit by hand. Read by the db rollback guard, /health, MCP. A constant, not a runtime
4
4
  * package.json read: the published bundle may lack package.json on a path ESM can resolve. */
5
- export const PACKAGE_VERSION = '3.5.1';
5
+ export const PACKAGE_VERSION = '3.6.0';
6
6
  /** The floor a store takes on its first expiring key: the first release with schema v53, set by
7
7
  * hand in that release; scripts/checks/check-expiring-keys-floor.mjs gates it. */
8
8
  export const EXPIRING_KEYS_MIN_BINARY = '1.64.0';
package/dist/cli.js CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // Hippo CLI entry point: parses argv and dispatches each verb through the table in
3
3
  // surface/cli/verbs.ts. `hippo help` prints the verb list from that table, so no list is kept here.
4
- import { envSkipAutoIntegrations, envTenant, validateFlags } from './base/util/env.js';
4
+ import { envReadOnly, envSkipAutoIntegrations, envTenant, validateFlags } from './base/util/env.js';
5
+ import { READ_ONLY_REFUSAL } from './base/errors/read-only.js';
5
6
  import * as fs from 'node:fs';
6
7
  import { fileURLToPath } from 'node:url';
7
8
  import { repairCodexWrapperIfInstalled } from './surface/hooks-install/codex-wrapper.js';
@@ -214,6 +215,14 @@ function checkUnknownFlags(command, flags, spec) {
214
215
  printError(`hippo: ignoring unknown flag ${flagNames(ignored)}. A later release will reject it.`);
215
216
  }
216
217
  }
218
+ // Before the verb reads stdin or opens a store, so a hook leaves no row, mirror file or worker.
219
+ function stopReadOnly(command, mode) {
220
+ if (mode === 'skip') {
221
+ log.warn(`hippo ${command}: skipped under HIPPO_READ_ONLY=1`);
222
+ return;
223
+ }
224
+ fail(READ_ONLY_REFUSAL);
225
+ }
217
226
  async function main(command, args, flags, hippoRoot) {
218
227
  if (command === '--version' || command === '-v' || boolFlag(flags, 'version'))
219
228
  printVersion();
@@ -245,6 +254,10 @@ async function main(command, args, flags, hippoRoot) {
245
254
  throw new CliExit(1);
246
255
  }
247
256
  assertVerbPorted(spec, CLI_STORE);
257
+ if (spec.readOnly !== undefined && envReadOnly()) {
258
+ stopReadOnly(command, spec.readOnly);
259
+ return;
260
+ }
248
261
  const run = () => spec.run({ hippoRoot, tenantId: envTenant(), args, flags });
249
262
  await (spec.scoped ? (await import('./surface/cli/api-context.js')).cliRequest(run) : run());
250
263
  }
@@ -11,6 +11,10 @@ export interface StoreAt {
11
11
  /** Runs `step` on the store unless it already ran to the end under the store's runtime; a throw
12
12
  * leaves it due, and with no runtime it always runs. */
13
13
  export declare function oncePerStore({ hippoRoot, runtime }: StoreAt, name: string, step: () => void): void;
14
+ /** Whether `db` was opened under a read-only runtime, so it refuses every write. */
15
+ export declare function isReadOnlyHandle(db: DatabaseSyncLike): boolean;
16
+ /** Runs `fn` with the gate open on `db`: a temp table lives in no store file. */
17
+ export declare function withTempTables<T>(db: DatabaseSyncLike, fn: () => T): T;
14
18
  /** Makes the next connection under `runtime` prove this store's schema again; `hippo init` calls
15
19
  * it because it is the explicit ask to set a store up. */
16
20
  export declare function reproveStoreSchema({ hippoRoot, runtime }: StoreAt): void;
@@ -4,7 +4,7 @@ import { cleanupArchivedMirrors } from './raw-archive-mirror-cleanup.js';
4
4
  import { errorCode, errorFields, errorMessage, log } from '../base/util/log.js';
5
5
  import { DatabaseSync } from './sqlite.js';
6
6
  import { DEFAULT_BUSY_WAIT_MS, execWithBusyRetry } from './busy.js';
7
- import { importLegacyVectors, runMigrations, settledStoreFacts, } from './migrate.js';
7
+ import { currentStoreFacts, importLegacyVectors, runMigrations, settledStoreFacts, } from './migrate.js';
8
8
  import { autoCheckpointPages } from './wal-checkpointer.js';
9
9
  import { storeKey } from './store-runtime.js';
10
10
  import { PRIVATE_DIR } from '../host/private-dir.js';
@@ -61,6 +61,24 @@ function sweepArchivedMirrorsIfDue(hippoRoot, db, pending) {
61
61
  cleanupArchivedMirrors(hippoRoot, db);
62
62
  }
63
63
  const SCHEMA_STEP = 'schema';
64
+ // Connections behind the read-only gate, so a read can still make the temp tables it needs.
65
+ const gated = new WeakSet();
66
+ /** Whether `db` was opened under a read-only runtime, so it refuses every write. */
67
+ export function isReadOnlyHandle(db) {
68
+ return gated.has(db);
69
+ }
70
+ /** Runs `fn` with the gate open on `db`: a temp table lives in no store file. */
71
+ export function withTempTables(db, fn) {
72
+ if (!gated.has(db))
73
+ return fn();
74
+ db.exec('PRAGMA query_only = OFF');
75
+ try {
76
+ return fn();
77
+ }
78
+ finally {
79
+ db.exec('PRAGMA query_only = ON');
80
+ }
81
+ }
64
82
  /** Makes the next connection under `runtime` prove this store's schema again; `hippo init` calls
65
83
  * it because it is the explicit ask to set a store up. */
66
84
  export function reproveStoreSchema({ hippoRoot, runtime }) {
@@ -83,6 +101,59 @@ function settleSchema(db, at, busyWaitMs) {
83
101
  oncePerStore(at, SCHEMA_STEP, () => undefined);
84
102
  return facts;
85
103
  }
104
+ // Shut after the schema step; only withTempTables opens it again, and only for a temp table.
105
+ function closeGate(db, facts) {
106
+ db.exec('PRAGMA query_only = ON');
107
+ gated.add(db);
108
+ return { db, facts };
109
+ }
110
+ // A read-only open never makes a store, so a missing one reads as an empty one held in memory.
111
+ function emptyReadOnlyStore(busyWaitMs) {
112
+ const db = new DatabaseSync(':memory:');
113
+ try {
114
+ return closeGate(db, runMigrations(db, undefined, busyWaitMs));
115
+ }
116
+ catch (error) {
117
+ db.close();
118
+ throw error;
119
+ }
120
+ }
121
+ // A store with a WAL opens read-only, whose close folds no frame into hippo.db; null sends a store
122
+ // with no WAL, or one behind the schema, down the read-write path.
123
+ function walReadOnlyStore(hippoRoot, busyWaitMs) {
124
+ const file = getHippoDbPath(hippoRoot);
125
+ if (!fs.existsSync(`${file}-wal`))
126
+ return null;
127
+ const db = new DatabaseSync(file, { readOnly: true });
128
+ let facts;
129
+ try {
130
+ db.exec(`PRAGMA busy_timeout = ${busyWaitMs}`);
131
+ db.exec('PRAGMA foreign_keys = ON');
132
+ facts = currentStoreFacts(db);
133
+ if (facts !== null)
134
+ return closeGate(db, facts);
135
+ }
136
+ catch (error) {
137
+ db.close();
138
+ throw error;
139
+ }
140
+ db.close();
141
+ return null;
142
+ }
143
+ const READ_WRITE_GATE = 'read-only-via-read-write';
144
+ // A missing store reads as empty and one mid-WAL without a checkpoint at close. The first open picks
145
+ // for the runtime, since its read-write connection makes the WAL a later open would find.
146
+ function readOnlyStore(at, busyWaitMs) {
147
+ const { hippoRoot, runtime } = at;
148
+ if (!fs.existsSync(getHippoDbPath(hippoRoot)))
149
+ return emptyReadOnlyStore(busyWaitMs);
150
+ if (runtime?.hasRun(storeKey(hippoRoot), READ_WRITE_GATE))
151
+ return null;
152
+ const opened = walReadOnlyStore(hippoRoot, busyWaitMs);
153
+ if (opened === null)
154
+ runtime?.markRun(storeKey(hippoRoot), READ_WRITE_GATE);
155
+ return opened;
156
+ }
86
157
  /**
87
158
  * A new connection with the store's pragmas and migrations applied and the mirror cleanup run when
88
159
  * it is due; the caller owns and closes it. `busyWaitMs` is the default lock wait when unset. An
@@ -90,6 +161,10 @@ function settleSchema(db, at, busyWaitMs) {
90
161
  */
91
162
  export function connectWithFacts(at, busyWaitMs = DEFAULT_BUSY_WAIT_MS) {
92
163
  const { hippoRoot } = at;
164
+ const readOnly = at.runtime?.readOnly === true;
165
+ const settled = readOnly ? readOnlyStore(at, busyWaitMs) : null;
166
+ if (settled !== null)
167
+ return settled;
93
168
  createStoreFilesOwnerOnly(at);
94
169
  const db = new DatabaseSync(getHippoDbPath(hippoRoot));
95
170
  try {
@@ -99,6 +174,9 @@ export function connectWithFacts(at, busyWaitMs = DEFAULT_BUSY_WAIT_MS) {
99
174
  db.exec(`PRAGMA wal_autocheckpoint = ${autoCheckpointPages(getHippoDbPath(hippoRoot), at.runtime)}`);
100
175
  db.exec('PRAGMA foreign_keys = ON');
101
176
  const facts = settleSchema(db, at, busyWaitMs);
177
+ // After the schema step, so an older store still migrates; the mirror sweep below writes too.
178
+ if (readOnly)
179
+ return closeGate(db, facts);
102
180
  // Orphan mirrors of archived raw rows go here; a filesystem failure must not block the open.
103
181
  try {
104
182
  sweepArchivedMirrorsIfDue(hippoRoot, db, facts?.archivePending);
package/dist/db/grant.js CHANGED
@@ -52,7 +52,7 @@ export class DbGrant {
52
52
  const file = getHippoDbPath(hippoRoot);
53
53
  if (!existsSync(file))
54
54
  throw new Error(`No existing Hippo database at ${file}`);
55
- const db = new DatabaseSync(file, { readOnly });
55
+ const db = new DatabaseSync(file, { readOnly: readOnly || this.#runtime?.readOnly === true });
56
56
  try {
57
57
  db.exec(`PRAGMA busy_timeout = ${DEFAULT_BUSY_WAIT_MS}`);
58
58
  return fn(db);
@@ -17,6 +17,9 @@ export interface OpenFacts {
17
17
  /** Whether any markdown mirror is marked due for a rewrite. */
18
18
  readonly mirrorsDue: boolean;
19
19
  }
20
+ /** The probe's facts when the store is current and whole, so the open can skip every DDL
21
+ * statement; else null. Runs the binary check either way. */
22
+ export declare function currentStoreFacts(db: DatabaseSyncLike): OpenFacts | null;
20
23
  /** For a store this process has proven: one cheap statement returns the open's facts when both
21
24
  * schema stamps still name the current schema, else null; it refuses when another binary has
22
25
  * since raised the minimum. */
@@ -62,7 +62,7 @@ export const SCHEMA_PROBE_SQL = `SELECT
62
62
  ${MIRRORS_DUE}`;
63
63
  /** The probe's facts when the store is current and whole, so the open can skip every DDL
64
64
  * statement; else null. Runs the binary check either way. */
65
- function currentStoreFacts(db) {
65
+ export function currentStoreFacts(db) {
66
66
  let probe;
67
67
  try {
68
68
  probe = db.prepare(SCHEMA_PROBE_SQL).get();
@@ -12,10 +12,17 @@ interface OpenSession {
12
12
  }
13
13
  /** The resolved path of a store's hippo.db, the key every per-store record here uses. */
14
14
  export declare function storeKey(hippoRoot: string): string;
15
+ /** What a root states when it makes its runtime. */
16
+ export interface StoreRuntimeOptions {
17
+ /** Every connection opened under the runtime refuses writes once its schema is settled. */
18
+ readonly readOnly?: boolean;
19
+ }
15
20
  export declare class StoreRuntime {
16
21
  #private;
17
22
  /** Mirror and stats writes held back to at most one per interval per root. */
18
23
  readonly held: HeldWrites;
24
+ readonly readOnly: boolean;
25
+ constructor(opts?: StoreRuntimeOptions);
19
26
  /** Whether `step` has run to its end on the store at `key`. */
20
27
  hasRun(key: string, step: string): boolean;
21
28
  markRun(key: string, step: string): void;
@@ -16,12 +16,16 @@ export function storeKey(hippoRoot) {
16
16
  export class StoreRuntime {
17
17
  /** Mirror and stats writes held back to at most one per interval per root. */
18
18
  held = new HeldWrites();
19
+ readOnly;
19
20
  #settled = new Map();
20
21
  #open = new Set();
21
22
  #idle = new Map();
22
23
  #background = new Set();
23
24
  #stats = new Map();
24
25
  #detached = new DetachedSet();
26
+ constructor(opts = {}) {
27
+ this.readOnly = opts.readOnly === true;
28
+ }
25
29
  /** Whether `step` has run to its end on the store at `key`. */
26
30
  hasRun(key, step) {
27
31
  return this.#settled.get(key)?.has(step) ?? false;
@@ -5,7 +5,7 @@ export { sqliteImportStores } from './maintenance/agent-import-stores.js';
5
5
  export { openSqliteSession, runSqliteBatch, runSqliteHookRequest, runSqliteRequest, type RequestPreset, } from './runtime/request-scope.js';
6
6
  export { sqliteServerRuntime, type ServerRuntimeOptions, type SqliteServerRuntime, } from './runtime/server-runtime.js';
7
7
  export type { SqliteStoreOptions } from './runtime/grant.js';
8
- export { StoreRuntime } from '../../db/store-runtime.js';
8
+ export { StoreRuntime, type StoreRuntimeOptions } from '../../db/store-runtime.js';
9
9
  export type { RequestStores } from '../../db/index.js';
10
10
  export { tenantOfApiKey, type ResolveOptions } from './runtime/tenant.js';
11
11
  export { askingNearestFirst } from './vectors/vector-reads.js';
@@ -5,6 +5,7 @@ import { assertTenantId } from '../../../base/scope/tenant-id.js';
5
5
  import { appendAuditEvents } from '../audit/audit.js';
6
6
  import { CLI_ACTOR } from '../../../base/scope/actor.js';
7
7
  import { cachedStatement } from '../../../db/statement-cache.js';
8
+ import { isReadOnlyHandle } from '../../../db/connect.js';
8
9
  import { plural } from '../../../base/util/format.js';
9
10
  function emptyBaserate(classTag) {
10
11
  const nulls = {
@@ -65,9 +66,10 @@ emitAudit = true) {
65
66
  `).all(tenantId, classTag);
66
67
  const baserate = predictionBaserateOf(classTag, rows.map((r) => ({ estimate: r.estimate_value, actual: r.actual_value })));
67
68
  // An empty class is audited too, since an agent probing one is a signal; the recall path passes
68
- // false and audits its own hint.
69
- if (emitAudit)
69
+ // false and audits its own hint, and a read-only store keeps no row of the read.
70
+ if (emitAudit && !isReadOnlyHandle(db)) {
70
71
  auditBaserateRead(db, { tenantId, actor, classTag, nClosed: baserate.nClosed });
72
+ }
71
73
  return baserate;
72
74
  }
73
75
  function auditBaserateRead(db, { tenantId, actor, classTag, nClosed }) {
@@ -8,6 +8,7 @@ import { topVectorMatches } from '../../../db/vector-match.js';
8
8
  import { MEMORY_SELECT_COLUMNS, MEMORY_SEARCH_COLUMNS, rowToEntry, } from '../runtime/rows.js';
9
9
  import { DEFAULT_SEARCH_CANDIDATE_LIMIT } from '../../../base/rank/search-types.js';
10
10
  import { cachedStatement } from '../../../db/statement-cache.js';
11
+ import { withTempTables } from '../../../db/connect.js';
11
12
  import { escapeLike } from '../../../base/util/escape.js';
12
13
  import { ftsAnyPhrase } from './fts-phrase.js';
13
14
  import { placeholders } from '../../../db/sql.js';
@@ -273,8 +274,10 @@ const vocabReady = new WeakSet();
273
274
  function ensureRarestVocab(db) {
274
275
  if (vocabReady.has(db))
275
276
  return;
276
- db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS temp.z1_rarest_vocab USING fts5vocab(main, 'memories_fts', 'row')`);
277
- db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS temp.z1_trigram_vocab USING fts5vocab(main, 'memories_trigram', 'row')`);
277
+ withTempTables(db, () => {
278
+ db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS temp.z1_rarest_vocab USING fts5vocab(main, 'memories_fts', 'row')`);
279
+ db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS temp.z1_trigram_vocab USING fts5vocab(main, 'memories_trigram', 'row')`);
280
+ });
278
281
  vocabReady.add(db);
279
282
  }
280
283
  /** Rarest-K prompt terms for this connection's FTS indexes, as a space-joined query string: words
@@ -28,6 +28,9 @@ export function openStore(hippoRoot, { grant, busyWaitMs }) {
28
28
  // this connection cannot write them.
29
29
  if (session?.setupDoneFor === hippoRoot)
30
30
  return db;
31
+ // A read-only store keeps its folder as it is: no mirror folder, due mirror or first-open row.
32
+ if (grant.runtime?.readOnly === true)
33
+ return db;
31
34
  const at = { hippoRoot, runtime: grant.runtime };
32
35
  try {
33
36
  ensureMirrorDirectories(at);
@@ -157,6 +157,7 @@ export function cliSecondStore(root) {
157
157
  export function cliLedgerReach(hippoRoot) {
158
158
  return ledgerReachOf({
159
159
  reach: cliReach(hippoRoot, cliStore(hippoRoot), cliInfra().embedderFor),
160
+ config: cliConfig(hippoRoot),
160
161
  });
161
162
  }
162
163
  /** `root`'s auto-sleep on a session of its own: the sleep outlives the frame whose write started
@@ -1,6 +1,7 @@
1
1
  // The CLI command's store runtime, apart from api-context.ts so cli.ts can end a command without
2
2
  // loading the verbs' store wiring.
3
3
  import { withStoreRuntime } from '../open-store.js';
4
+ import { envReadOnly } from '../../base/util/env.js';
4
5
  // One command per process, so its runtime is root state as its session is; between commands a store
5
6
  // pools nothing.
6
7
  let commandRuntime;
@@ -22,6 +23,6 @@ export async function runCliCommand(fn) {
22
23
  finally {
23
24
  commandRuntime = undefined;
24
25
  }
25
- });
26
+ }, { readOnly: envReadOnly() });
26
27
  }
27
28
  //# sourceMappingURL=cli-runtime.js.map
@@ -2,7 +2,7 @@
2
2
  import { randomBytes } from 'node:crypto';
3
3
  import { installCrashHandlers } from '../../base/util/crash-handlers.js';
4
4
  import { printDashboardBanner, reportListenFailure } from './dashboard-banner.js';
5
- import { envBodyTimeoutMs, envPort, envTlsCert, envTlsKey } from '../../base/util/env.js';
5
+ import { envBodyTimeoutMs, envPort, envReadOnly, envTlsCert, envTlsKey, } from '../../base/util/env.js';
6
6
  import * as fs from 'node:fs';
7
7
  import * as path from 'node:path';
8
8
  import { boolFlag, numberFlag, stringFlag, stringFlagOrExit, } from './flag-values.js';
@@ -81,6 +81,9 @@ function keyRuleLine(hippoRoot) {
81
81
  `${localKeyPath(hippoRoot)} (readable by this user only); mint others with \`hippo auth create\``);
82
82
  }
83
83
  export async function handleServe({ hippoRoot, flags }) {
84
+ // The server's own runtime and worker threads write, so the switch stops it rather than leak.
85
+ if (envReadOnly())
86
+ fail('hippo serve does not run under HIPPO_READ_ONLY=1; read with hippo mcp');
84
87
  requireInit(hippoRoot);
85
88
  const portRaw = stringFlag(flags, 'port') ?? envPort() ?? DEFAULT_SERVER_PORT;
86
89
  const port = Number(portRaw);
@@ -35,6 +35,8 @@ export interface VerbRow {
35
35
  readonly destructive?: true;
36
36
  /** Unset: --dry-run is honoured exactly when the verb declares it; `false` refuses it even so. */
37
37
  readonly dryRun?: false | DryRunForm;
38
+ /** Under HIPPO_READ_ONLY=1, 'refuse' exits 1 and 'skip' exits 0 before the verb opens anything. */
39
+ readonly readOnly?: 'refuse' | 'skip';
38
40
  }
39
41
  export interface VerbSpec extends VerbRow {
40
42
  readonly run: (ctx: CommandContext) => Promise<void>;
@@ -133,6 +133,7 @@ export const HEALTH_VERBS = {
133
133
  ],
134
134
  }),
135
135
  outcome: verb(() => import('../curate.js'), 'handleOutcome', {
136
+ readOnly: 'refuse',
136
137
  repairsCodexWrapper: true,
137
138
  scoped: true,
138
139
  flags: { switches: ['bad', 'good'], values: ['id'] },
@@ -155,6 +156,7 @@ export const HEALTH_VERBS = {
155
156
  ],
156
157
  }),
157
158
  resolve: verb(() => import('../conflicts.js'), 'handleResolve', {
159
+ readOnly: 'refuse',
158
160
  needs: ['conflicts'],
159
161
  destructive: true,
160
162
  flags: { switches: ['forget', 'reject-loser'], values: ['keep', 'reason'] },
@@ -246,6 +248,7 @@ export const HEALTH_VERBS = {
246
248
  ],
247
249
  }),
248
250
  'capture-error': verb(() => import('../hooks/capture-error.js'), 'handleCaptureError', {
251
+ readOnly: 'skip',
249
252
  needs: ['failureLog', 'lessonWrites'],
250
253
  flags: { values: ['format', 'runtime'] },
251
254
  usage: [
@@ -33,6 +33,7 @@ export const MEMORY_VERBS = {
33
33
  ],
34
34
  }),
35
35
  remember: verb(() => import('../remember.js'), 'handleRemember', {
36
+ readOnly: 'refuse',
36
37
  repairsCodexWrapper: true,
37
38
  flags: {
38
39
  switches: ['error', 'extract', 'force', 'global', 'inferred', 'observed', 'pin', 'verified'],
@@ -52,6 +53,7 @@ export const MEMORY_VERBS = {
52
53
  ],
53
54
  }),
54
55
  supersede: verb(() => import('../remember.js'), 'handleSupersede', {
56
+ readOnly: 'refuse',
55
57
  destructive: true,
56
58
  flags: { switches: ['pin'], values: ['layer'], lists: ['tag'] },
57
59
  usage: [
@@ -211,6 +213,7 @@ export const MEMORY_VERBS = {
211
213
  ],
212
214
  }),
213
215
  refine: verb(() => import('../maintenance.js'), 'handleRefine', {
216
+ readOnly: 'refuse',
214
217
  flags: { switches: ['all', 'dry-run', 'json'], values: ['model'], numbers: ['limit'] },
215
218
  usage: [
216
219
  `
@@ -275,6 +278,7 @@ export const MEMORY_VERBS = {
275
278
  ],
276
279
  }),
277
280
  sleep: verb(() => import('../sleep.js'), 'handleSleep', {
281
+ readOnly: 'skip',
278
282
  needs: ['graphReads', 'vectors'],
279
283
  repairsCodexWrapper: true,
280
284
  destructive: true,
@@ -293,6 +297,7 @@ export const MEMORY_VERBS = {
293
297
  ],
294
298
  }),
295
299
  'daily-runner': verb(() => import('../daily-runner.js'), 'handleDailyRunner', {
300
+ readOnly: 'skip',
296
301
  needs: ['reports'],
297
302
  flags: {},
298
303
  usage: [
@@ -31,6 +31,7 @@ export const OBJECT_VERBS = {
31
31
  ],
32
32
  }),
33
33
  decide: verb(() => import('../decisions.js'), 'handleDecide', {
34
+ readOnly: 'refuse',
34
35
  needs: ['objects'],
35
36
  flags: { values: ['context', 'status', 'supersedes'], numbers: ['limit'] },
36
37
  usage: [
@@ -170,6 +171,7 @@ export const OBJECT_VERBS = {
170
171
  ],
171
172
  }),
172
173
  invalidate: verb(() => import('../curate.js'), 'handleInvalidate', {
174
+ readOnly: 'refuse',
173
175
  destructive: true,
174
176
  flags: { switches: ['churn', 'dry-run'], values: ['id', 'reason'] },
175
177
  usage: [
@@ -155,6 +155,7 @@ export const SESSION_VERBS = {
155
155
  ],
156
156
  }),
157
157
  forget: verb(() => import('../curate.js'), 'handleForget', {
158
+ readOnly: 'refuse',
158
159
  destructive: true,
159
160
  scoped: true,
160
161
  flags: { switches: ['archive', 'dry-run'], values: ['reason'] },
@@ -192,6 +193,7 @@ export const SESSION_VERBS = {
192
193
  ],
193
194
  }),
194
195
  learn: verb(() => import('../learn.js'), 'handleLearn', {
196
+ readOnly: 'refuse',
195
197
  needs: ['lessonWrites', 'vectors', 'vectorWrites'],
196
198
  scoped: true,
197
199
  flags: { switches: ['git'], values: ['repos'], numbers: ['days'] },
@@ -204,6 +206,7 @@ export const SESSION_VERBS = {
204
206
  ],
205
207
  }),
206
208
  promote: verb(() => import('../transfer.js'), 'handlePromote', {
209
+ readOnly: 'refuse',
207
210
  scoped: true,
208
211
  flags: {},
209
212
  usage: [
@@ -212,6 +215,7 @@ export const SESSION_VERBS = {
212
215
  ],
213
216
  }),
214
217
  share: verb(() => import('../transfer.js'), 'handleShare', {
218
+ readOnly: 'refuse',
215
219
  needs: ['vectors', 'vectorWrites'],
216
220
  dryRun: {
217
221
  form: '--auto',
@@ -243,6 +247,7 @@ export const SESSION_VERBS = {
243
247
  ],
244
248
  }),
245
249
  import: verb(() => import('../memory-import.js'), 'handleImport', {
250
+ readOnly: 'refuse',
246
251
  flags: {
247
252
  switches: ['agents', 'dry-run', 'global'],
248
253
  values: ['chatgpt', 'claude', 'cursor', 'file', 'markdown', 'name', 'scope', 'vault'],
@@ -278,6 +283,7 @@ export const SESSION_VERBS = {
278
283
  ],
279
284
  }),
280
285
  capture: verb(() => import('../hooks/capture.js'), 'handleCapture', {
286
+ readOnly: 'skip',
281
287
  repairsCodexWrapper: true,
282
288
  flags: {
283
289
  switches: ['dry-run', 'global', 'last-session', 'stdin'],
@@ -332,6 +338,7 @@ export const SESSION_VERBS = {
332
338
  ],
333
339
  }),
334
340
  'session-end': verb(() => import('../hooks/session-end.js'), 'handleSessionEnd', {
341
+ readOnly: 'skip',
335
342
  // Its sleep step reads --dry-run, but the capture after it writes for real.
336
343
  dryRun: false,
337
344
  flags: {
@@ -355,6 +362,7 @@ export const SESSION_VERBS = {
355
362
  ],
356
363
  }),
357
364
  '__session-end-worker': verb(() => import('../hooks/session-end-worker.js'), 'handleSessionEndWorker', {
365
+ readOnly: 'skip',
358
366
  needs: ['sessions', 'reports'],
359
367
  dryRun: false,
360
368
  flags: {
@@ -363,6 +371,7 @@ export const SESSION_VERBS = {
363
371
  },
364
372
  }),
365
373
  'pre-compact': verb(() => import('../hooks/pre-compact.js'), 'handlePreCompact', {
374
+ readOnly: 'skip',
366
375
  flags: { values: ['format', 'log-file', 'runtime'] },
367
376
  usage: [
368
377
  `
@@ -382,6 +391,7 @@ export const SESSION_VERBS = {
382
391
  ],
383
392
  }),
384
393
  'post-compact': verb(() => import('../hooks/post-compact.js'), 'handlePostCompact', {
394
+ readOnly: 'skip',
385
395
  flags: { values: ['log-file'] },
386
396
  usage: [
387
397
  `
@@ -398,6 +408,7 @@ export const SESSION_VERBS = {
398
408
  ],
399
409
  }),
400
410
  '__codex-session-end-worker': verb(() => import('../hooks/codex-session-end-worker.js'), 'handleCodexSessionEndWorker', {
411
+ readOnly: 'skip',
401
412
  flags: { values: ['codex-home', 'history-path', 'log-file', 'start-offset', 'started-at'] },
402
413
  }),
403
414
  hook: verb(() => import('../hook.js'), 'handleHook', {
@@ -9,7 +9,9 @@ import { RecallRequestError } from '../../api/recall/request.js';
9
9
  import { globalTargetOf } from '../../api/infra.js';
10
10
  import { recordTokens } from '../../api/tokens.js';
11
11
  import { mcpApiContext, } from './protocol.js';
12
- import { TOOLS, TOOLS_BY_NAME, ARGS_CHECKED_BY_API } from './tools.js';
12
+ import { TOOLS, TOOLS_BY_NAME, ARGS_CHECKED_BY_API, WRITE_TOOLS } from './tools.js';
13
+ import { READ_ONLY_REFUSAL } from '../../base/errors/read-only.js';
14
+ import { readOnlyOf } from '../../api/types.js';
13
15
  import { runRecallTool, runAssembleTool, runDrillTool, runContextTool } from './recall-tools.js';
14
16
  import { runRememberTool, runOutcomeTool, runLearnTool } from './memory-tools.js';
15
17
  import { runPredictBaserateTool, runStatusTool, runConflictsTool, runResolveTool, runShareTool, runPeersTool, } from './admin-tools.js';
@@ -130,7 +132,9 @@ async function callTool(id, params, ctx) {
130
132
  const run = toolRun(toolName, ctx);
131
133
  if (run === undefined)
132
134
  return errorReply(id, INTERNAL_ERROR, STORE_NOT_PORTED_MESSAGE);
133
- const refusal = sharedStoreRefusal(toolName, ctx);
135
+ const refusal = WRITE_TOOLS.has(toolName) && readOnlyOf(ctx)
136
+ ? READ_ONLY_REFUSAL
137
+ : sharedStoreRefusal(toolName, ctx);
134
138
  if (refusal !== undefined) {
135
139
  return resultReply(id, { content: [{ type: 'text', text: refusal }], isError: true });
136
140
  }
@@ -6,6 +6,8 @@ interface McpToolDefinition {
6
6
  }
7
7
  export declare const TOOLS: readonly McpToolDefinition[];
8
8
  export declare const TOOLS_BY_NAME: Map<string, McpToolDefinition>;
9
+ /** The tools that save, which answer the read-only refusal under HIPPO_READ_ONLY=1. */
10
+ export declare const WRITE_TOOLS: ReadonlySet<string>;
9
11
  export declare const ARGS_CHECKED_BY_API: Map<string, ReadonlySet<string>>;
10
12
  export {};
11
13
  //# sourceMappingURL=tools.d.ts.map
@@ -298,6 +298,14 @@ export const TOOLS = [
298
298
  },
299
299
  ];
300
300
  export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
301
+ /** The tools that save, which answer the read-only refusal under HIPPO_READ_ONLY=1. */
302
+ export const WRITE_TOOLS = new Set([
303
+ 'hippo_remember',
304
+ 'hippo_outcome',
305
+ 'hippo_learn',
306
+ 'hippo_resolve',
307
+ 'hippo_share',
308
+ ]);
301
309
  // api.retrieve rejects these itself, so MCP and HTTP callers get the same typed error code for the
302
310
  // same bad value.
303
311
  export const ARGS_CHECKED_BY_API = new Map([
@@ -1,6 +1,6 @@
1
1
  import type { StoreRules } from '../base/ports/infra.js';
2
2
  import type { HippoStore, StoreGroups } from '../base/ports/store-index.js';
3
- import { StoreRuntime, type ServerRuntimeOptions, type SqliteServerRuntime } from '../store/sqlite/index.js';
3
+ import { StoreRuntime, type ServerRuntimeOptions, type SqliteServerRuntime, type StoreRuntimeOptions } from '../store/sqlite/index.js';
4
4
  export { askingNearestFirst, inSqliteSession as inStoreSession, runSqliteBatch as runStoreBatch, runSqliteHookRequest as runStoreHookRequest, runSqliteRequest as runStoreRequest, saveVectorGraphFile, sqliteDashboardReads as defaultDashboardReads, sqliteDiagnosticsStore as defaultDiagnostics, sqliteImportFiles as defaultImportFiles, sqliteImportStores as defaultImportStores, sqliteReach as defaultReach, sqliteStore as defaultStore, tenantOfApiKey, withSharedStoreHandles, type RequestStores as StoreSession, type ResolveOptions, type ServerRuntimeOptions, type SqliteServerRuntime as ServerRuntime, type SqliteStoreOptions as StoreOptions, type StoreRuntime, } from '../store/sqlite/index.js';
5
5
  export { decodeVector, EMBEDDING_MODEL_META_KEY, encodeVector, OTHER_STORE_MARKER, rankVectorRows, type VectorMatch, type VectorRow, } from '../store/sqlite/index.js';
6
6
  /** The default store as ./store-kit publishes it, with only the rules an add-on picks: a runtime
@@ -8,7 +8,7 @@ export { decodeVector, EMBEDDING_MODEL_META_KEY, encodeVector, OTHER_STORE_MARKE
8
8
  export declare const publishedDefaultStore: (hippoRoot: string, rules?: StoreRules) => HippoStore & StoreGroups;
9
9
  /** Runs `fn` on a store runtime of its own, disposed with the work `fn` detached on it once `fn`
10
10
  * settles, or closed by its exit hook if the process exits first. */
11
- export declare function withStoreRuntime<T>(fn: (runtime: StoreRuntime) => Promise<T>): Promise<T>;
11
+ export declare function withStoreRuntime<T>(fn: (runtime: StoreRuntime) => Promise<T>, opts?: StoreRuntimeOptions): Promise<T>;
12
12
  /** hippo.db as a server serves it, with an exit hook that closes what the server opened if
13
13
  * close() never runs. */
14
14
  export declare function defaultServerRuntime(hippoRoot: string, opts?: ServerRuntimeOptions): SqliteServerRuntime;
@@ -7,8 +7,8 @@ export { decodeVector, EMBEDDING_MODEL_META_KEY, encodeVector, OTHER_STORE_MARKE
7
7
  export const publishedDefaultStore = sqliteStoreWith;
8
8
  /** Runs `fn` on a store runtime of its own, disposed with the work `fn` detached on it once `fn`
9
9
  * settles, or closed by its exit hook if the process exits first. */
10
- export async function withStoreRuntime(fn) {
11
- const runtime = new StoreRuntime();
10
+ export async function withStoreRuntime(fn, opts = {}) {
11
+ const runtime = new StoreRuntime(opts);
12
12
  const onExit = () => runtime.closeNow();
13
13
  process.once('exit', onExit);
14
14
  try {
@@ -2,7 +2,7 @@
2
2
  "id": "hippo-memory",
3
3
  "name": "Hippo Memory",
4
4
  "description": "Make your agent's memory work like a brain. Hippo is long-term memory for coding agents.",
5
- "version": "3.5.1",
5
+ "version": "3.6.0",
6
6
 
7
7
  "configSchema": {
8
8
  "type": "object",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hippo-memory",
3
- "version": "3.5.1",
3
+ "version": "3.6.0",
4
4
  "type": "module",
5
5
  "description": "Make your agent's memory work like a brain. Hippo is long-term memory for coding agents.",
6
6
  "main": "index.ts",
@@ -2,7 +2,7 @@
2
2
  "id": "hippo-memory",
3
3
  "name": "Hippo Memory",
4
4
  "description": "Make your agent's memory work like a brain. Hippo is long-term memory for coding agents.",
5
- "version": "3.5.1",
5
+ "version": "3.6.0",
6
6
  "configSchema": {
7
7
  "type": "object",
8
8
  "additionalProperties": false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hippo-memory",
3
- "version": "3.5.1",
3
+ "version": "3.6.0",
4
4
  "description": "Make your agent's memory work like a brain. Hippo is long-term memory for coding agents.",
5
5
  "mcpName": "io.github.kitfunso/hippo-memory",
6
6
  "type": "module",