mnemo-engine 0.13.1__tar.gz → 0.13.2__tar.gz

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 (67) hide show
  1. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/PKG-INFO +2 -2
  2. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/README.md +1 -1
  3. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/Cargo.lock +3 -3
  4. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/Cargo.toml +1 -1
  5. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/README.md +31 -9
  6. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/bin/mnemo/inspect.html +36 -19
  7. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/bin/mnemo/inspect.rs +42 -15
  8. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/bin/mnemo.rs +38 -5
  9. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/maintenance.rs +107 -13
  10. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/mod.rs +3 -0
  11. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/open.rs +15 -0
  12. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo-python/Cargo.lock +2 -2
  13. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo-python/Cargo.toml +8 -6
  14. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo-python/README.md +1 -1
  15. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo-python/src/lib.rs +53 -8
  16. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo-python/test_mnemo.py +71 -0
  17. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/pyproject.toml +1 -1
  18. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/.gitignore +0 -0
  19. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/benches/corpus.rs +0 -0
  20. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/deny.toml +0 -0
  21. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/ann_defaults_v0_6_0.rs +0 -0
  22. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/ann_diagnose.rs +0 -0
  23. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/ann_recall_grid.rs +0 -0
  24. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/ann_recall_grid_v2.rs +0 -0
  25. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/embedder_server.py +0 -0
  26. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/file_size_breakdown.rs +0 -0
  27. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/open_rss.rs +0 -0
  28. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/quickstart.rs +0 -0
  29. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/ranking_v2.rs +0 -0
  30. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/session.rs +0 -0
  31. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/examples/thread_profile.rs +0 -0
  32. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/bin/mnemo/export.rs +0 -0
  33. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/cache.rs +0 -0
  34. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/crypto.rs +0 -0
  35. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/embed.rs +0 -0
  36. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/embed_cmd.rs +0 -0
  37. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/error.rs +0 -0
  38. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/format.rs +0 -0
  39. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/freelist.rs +0 -0
  40. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/index.rs +0 -0
  41. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/keyslot.rs +0 -0
  42. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/lib.rs +0 -0
  43. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/mcp.rs +0 -0
  44. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/memory.rs +0 -0
  45. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/pager.rs +0 -0
  46. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/result_cache.rs +0 -0
  47. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/session.rs +0 -0
  48. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/ann.rs +0 -0
  49. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/cache_api.rs +0 -0
  50. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/continuation.rs +0 -0
  51. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/crud.rs +0 -0
  52. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/essence.rs +0 -0
  53. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/flush.rs +0 -0
  54. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/header_graft_tests.rs +0 -0
  55. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/hooks.rs +0 -0
  56. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/keyed.rs +0 -0
  57. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/load.rs +0 -0
  58. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/recall.rs +0 -0
  59. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/records.rs +0 -0
  60. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/snapshots.rs +0 -0
  61. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/store/threads.rs +0 -0
  62. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/text.rs +0 -0
  63. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/transcript.rs +0 -0
  64. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/veccol.rs +0 -0
  65. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo/src/wal.rs +0 -0
  66. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/mnemo-python/.gitignore +0 -0
  67. {mnemo_engine-0.13.1 → mnemo_engine-0.13.2}/python/mnemo_engine/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mnemo-engine
3
- Version: 0.13.1
3
+ Version: 0.13.2
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: 3
6
6
  Classifier: License :: OSI Approved :: Apache Software License
@@ -188,7 +188,7 @@ its own agent.
188
188
  | `set_turn_compress_after(secs)` | v9 files: compress thread turns once they're older than `secs` (default 7 days; `0` compresses at write). This handle only |
189
189
  | `memories()` | Enumerate every live (non-deleted, non-expired) memory as a list of dicts |
190
190
  | `dimensions()` | Embedding dimensionality this database was created with (also on `stats()["dimensions"]`) |
191
- | `rekey(new_passphrase, fast=False)` | Change the passphrase. Re-derives the KEK and re-wraps the DEK; encrypted pages are not rewritten (O(1) in db size). `fast=True` uses the cheap-Argon2 test params — omit for production. If it raises, the file may already be under the new secret, or may move to it at the next write: close without writing more, then try both secrets |
191
+ | `rekey(new_passphrase, fast=False)` | Change the passphrase. Re-derives the KEK and re-wraps the DEK; encrypted pages are not rewritten (O(1) in db size). `fast=True` uses the cheap-Argon2 test params — omit for production. If it raises, the old passphrase is still in force (the one exception is an error that says the file may open with either). If it returns but couldn't scrub every copy of the old key wrap, it emits a `RuntimeWarning`: the call succeeded and the new passphrase is in force (where warnings are errors, it goes to `sys.unraisablehook` and the call still returns) |
192
192
  | `set_embedder(fn, *, name, dimensions, normalize=True)` | Register a Python callable `embed(texts: list[str]) -> list[list[float]]` as this handle's text embedder (Phase 3). Dimension-checks against the database's width; identity-checks against (and on first use upserts) the scaffold manifest's `embedder_name` / `embedder_dimensions` / `embedder_normalize` keys, so swapping embedders between opens fails loudly |
193
193
  | `remember_text(content, memory_type, **kwargs)` | Embed `content` via the registered embedder and `remember` the result. Accepts the same per-memory kwargs as `remember` (`agent_id`, `importance`, `session_id`, `ttl_secs`, `shared`, `metadata`) |
194
194
  | `recall_text(query, top_k=10, memory_types=None, agent_id=None, track_access=True, n_probe=None, n_rerank=None, filter=None, max_bytes=None, keywords=None, keyword_weight=None)` | Embed `query` via the registered embedder and run `recall`. Same return shape and kwargs as `recall`. `keywords` (v9 files): identifiers or exact terms to match (a version, a PR number, a function name), not the question; their BM25 score is added with weight `keyword_weight` (default 0.5) |
@@ -174,7 +174,7 @@ its own agent.
174
174
  | `set_turn_compress_after(secs)` | v9 files: compress thread turns once they're older than `secs` (default 7 days; `0` compresses at write). This handle only |
175
175
  | `memories()` | Enumerate every live (non-deleted, non-expired) memory as a list of dicts |
176
176
  | `dimensions()` | Embedding dimensionality this database was created with (also on `stats()["dimensions"]`) |
177
- | `rekey(new_passphrase, fast=False)` | Change the passphrase. Re-derives the KEK and re-wraps the DEK; encrypted pages are not rewritten (O(1) in db size). `fast=True` uses the cheap-Argon2 test params — omit for production. If it raises, the file may already be under the new secret, or may move to it at the next write: close without writing more, then try both secrets |
177
+ | `rekey(new_passphrase, fast=False)` | Change the passphrase. Re-derives the KEK and re-wraps the DEK; encrypted pages are not rewritten (O(1) in db size). `fast=True` uses the cheap-Argon2 test params — omit for production. If it raises, the old passphrase is still in force (the one exception is an error that says the file may open with either). If it returns but couldn't scrub every copy of the old key wrap, it emits a `RuntimeWarning`: the call succeeded and the new passphrase is in force (where warnings are errors, it goes to `sys.unraisablehook` and the call still returns) |
178
178
  | `set_embedder(fn, *, name, dimensions, normalize=True)` | Register a Python callable `embed(texts: list[str]) -> list[list[float]]` as this handle's text embedder (Phase 3). Dimension-checks against the database's width; identity-checks against (and on first use upserts) the scaffold manifest's `embedder_name` / `embedder_dimensions` / `embedder_normalize` keys, so swapping embedders between opens fails loudly |
179
179
  | `remember_text(content, memory_type, **kwargs)` | Embed `content` via the registered embedder and `remember` the result. Accepts the same per-memory kwargs as `remember` (`agent_id`, `importance`, `session_id`, `ttl_secs`, `shared`, `metadata`) |
180
180
  | `recall_text(query, top_k=10, memory_types=None, agent_id=None, track_access=True, n_probe=None, n_rerank=None, filter=None, max_bytes=None, keywords=None, keyword_weight=None)` | Embed `query` via the registered embedder and run `recall`. Same return shape and kwargs as `recall`. `keywords` (v9 files): identifiers or exact terms to match (a version, a PR number, a function name), not the question; their BM25 score is added with weight `keyword_weight` (default 0.5) |
@@ -821,7 +821,7 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
821
821
 
822
822
  [[package]]
823
823
  name = "mnemo-engine"
824
- version = "0.13.1"
824
+ version = "0.13.2"
825
825
  dependencies = [
826
826
  "aes-gcm",
827
827
  "argon2",
@@ -850,7 +850,7 @@ dependencies = [
850
850
 
851
851
  [[package]]
852
852
  name = "mnemo-node"
853
- version = "0.13.1"
853
+ version = "0.13.2"
854
854
  dependencies = [
855
855
  "mnemo-engine",
856
856
  "napi",
@@ -860,7 +860,7 @@ dependencies = [
860
860
 
861
861
  [[package]]
862
862
  name = "mnemo-uniffi"
863
- version = "0.13.1"
863
+ version = "0.13.2"
864
864
  dependencies = [
865
865
  "mnemo-engine",
866
866
  "serde_json",
@@ -10,7 +10,7 @@
10
10
  # The CLI binary name stays `mnemo`, so users still invoke `mnemo` on
11
11
  # the command line after `cargo install mnemo-engine`.
12
12
  name = "mnemo-engine"
13
- version = "0.13.1"
13
+ version = "0.13.2"
14
14
  edition = "2021"
15
15
  rust-version = "1.75"
16
16
  # `benches/corpus.rs` is a shared helper module pulled into real benches
@@ -332,6 +332,17 @@ rewrites the file under a fresh DEK. `Mnemo::export_rekeyed` writes a copy
332
332
  under a fresh DEK and a new secret, sharing no key material with the
333
333
  source. Rotation can't erase old ciphertext the storage hardware still holds: flash keeps rewritten blocks until it reuses them, and that's out of the engine's hands.
334
334
 
335
+ **A `rekey` that fails leaves the old secret in force** (REKEY-1, v0.13.2),
336
+ for the handle and for the file, including after later writes and a
337
+ close. It takes effect at one point, the write of the new page 0; a
338
+ failure before that puts the old header back. The one exception is a
339
+ failure to write the new page 0 followed by a failure to put the old one
340
+ back; the error then says the file may open with either secret. Once the
341
+ new page 0 is on disk, scrubbing the old key wrap from the file is
342
+ hygiene: if part of it fails, `rekey` still succeeds, and
343
+ `Mnemo::rekey_cleanup_error` (a warning in the CLI, a `RuntimeWarning` in
344
+ Python) says what was left. `--rotate` covers it.
345
+
335
346
  The file is a sequence of fixed **8 KiB pages**:
336
347
 
337
348
  - **Page 0** — the header (plaintext): magic, version, KDF parameters, salt,
@@ -912,7 +923,7 @@ cargo run --bin mnemo -- export agent.mnemo --git -o memory.md
912
923
  `mnemo inspect` serves a read-only web view of a file on your machine:
913
924
 
914
925
  ```sh
915
- cargo run --bin mnemo -- inspect agent.mnemo # prints a URL with a token: open it in your browser
926
+ cargo run --bin mnemo -- inspect agent.mnemo # prints a link that works once: open it in your browser
916
927
  cargo run --bin mnemo -- inspect app.mnemo --key-file app.key # a raw-key file (32 bytes or 64 hex digits)
917
928
  cargo run --bin mnemo -- inspect agent.mnemo --open # opens the browser for you
918
929
  ```
@@ -920,7 +931,9 @@ cargo run --bin mnemo -- inspect agent.mnemo --open # opens the browser for yo
920
931
  The passphrase comes from the prompt or `MNEMO_PASSPHRASE`. Copy the
921
932
  printed URL into your browser, or pass `--open`, which hands the browser a
922
933
  private local page (owner-only, deleted once it has loaded) that forwards
923
- to the URL.
934
+ to the URL. On Linux, a browser installed as a snap or a flatpak (Ubuntu's
935
+ default Firefox is a snap) has its own private `/tmp` and can't read that
936
+ page, so copy the printed link instead.
924
937
 
925
938
  - **Views:** memories (filter by type, agent, keyed or not, and thread;
926
939
  keyword search with BM25, no embedder needed), keyed history (each
@@ -933,14 +946,23 @@ to the URL.
933
946
  reads it again (one passphrase derivation). If a writer has the file
934
947
  open at that moment, it says so and keeps the last read.
935
948
  - **It stays on your machine.** It binds `127.0.0.1` only (a random free
936
- port unless `--port`), and the printed URL carries a random token. Every
937
- data request must carry that token and a `Host` of the loopback address and
949
+ port unless `--port`). The printed link carries a random one-time code,
950
+ which the page exchanges for a random session token on its first load
951
+ and keeps for that tab only. **The link works once** (since v0.13.2): the
952
+ code is refused after that, so the copy the browser's history records
953
+ (or `--open`'s forwarding page) opens nothing. A refresh keeps working;
954
+ another tab needs a new link (run `mnemo inspect` again). Every data
955
+ request must carry the token and a `Host` of the loopback address and
938
956
  port, which stops other sites' pages (DNS rebinding included). Only `GET`
939
- is served, with no CORS, and no endpoint writes the file. Nothing is
940
- written to disk. Once the page has loaded, it keeps the token for that
941
- tab only and takes it out of the address bar. The browser's history
942
- still records the first visit; the token stops working when the
943
- inspector stops.
957
+ is served, with no CORS, and no endpoint writes the file. **What it
958
+ writes to disk:** without `--open`, nothing. With `--open`, one small
959
+ page that forwards the browser to the link, in a new folder under the
960
+ system temp directory (on macOS and Linux, a folder only you can open,
961
+ holding a page only you can read). It's removed (with
962
+ its folder) as soon as the page has exchanged the link's code, or after
963
+ 60 seconds if it never does. If the inspector is stopped before that, the
964
+ page can be left behind, holding a code that no longer works. The token
965
+ stops working when the inspector stops.
944
966
  - **It stops when it's left alone.** After `--idle-timeout` without a
945
967
  request from the page (30 minutes by default; `90s`, `1h`, or `0` for
946
968
  never) it wipes the passphrase or key from memory and exits. It holds
@@ -91,27 +91,43 @@
91
91
  <main id="main"></main>
92
92
  <script>
93
93
  "use strict";
94
- // The token arrives in the URL once. Keep it for this tab only and take it
95
- // out of the address bar, so it isn't on the screen or in a copied link. The
96
- // browser's history still records the first visit; the token stops working
97
- // when the inspector stops.
98
- const TOKEN = (() => {
99
- const fromUrl = new URLSearchParams(location.search).get("t");
100
- if (fromUrl) {
101
- try { sessionStorage.setItem("mnemo-inspect-token", fromUrl); } catch (e) {}
102
- history.replaceState(null, "", location.pathname);
103
- return fromUrl;
94
+ // The printed link carries a one-time code, not the token. The page takes it
95
+ // out of the address bar and exchanges it once for the session token, which
96
+ // it keeps for this tab only. The server refuses the code after that, so the
97
+ // copy in the browser's history (and in `--open`'s forwarding page) is dead.
98
+ const TOKEN_KEY = "mnemo-inspect-token";
99
+ let TOKEN = "";
100
+ function storedToken() {
101
+ try { return sessionStorage.getItem(TOKEN_KEY) || ""; } catch (e) { return ""; }
102
+ }
103
+ async function session() {
104
+ const code = new URLSearchParams(location.search).get("c");
105
+ if (!code) return { token: storedToken() };
106
+ history.replaceState(null, "", location.pathname);
107
+ // A page the browser renders ahead of time waits until it's shown, so a
108
+ // prerender that's thrown away doesn't use up the link.
109
+ if (document.prerendering) {
110
+ await new Promise(r => document.addEventListener("prerenderingchange", r, { once: true }));
104
111
  }
105
- try { return sessionStorage.getItem("mnemo-inspect-token") || ""; } catch (e) { return ""; }
106
- })();
112
+ const r = await fetch("/api/session?" + new URLSearchParams({ c: code }).toString())
113
+ .catch(() => { throw new Error(STOPPED); });
114
+ if (!r.ok) return { token: storedToken(), used: true };
115
+ const { token } = await r.json();
116
+ try { sessionStorage.setItem(TOKEN_KEY, token); } catch (e) {}
117
+ return { token };
118
+ }
107
119
  const main = document.getElementById("main");
108
120
  let view = "memories";
109
121
  const state = { q: "", type: "", agent: "", keyed: "", thread: "", key: null, threadId: null };
110
122
 
123
+ // RB-004.5 item 4: once the server has stopped (`--idle-timeout`, or
124
+ // Ctrl-C), a request can't connect; say that instead of the browser's text.
125
+ const STOPPED = "The inspector has stopped (after --idle-timeout without use, or Ctrl-C), " +
126
+ "so this page can't read the file any more. Run `mnemo inspect <file>` again for a new link.";
111
127
  function api(path, params) {
112
128
  const u = new URLSearchParams(params || {});
113
129
  u.set("t", TOKEN);
114
- return fetch(path + "?" + u.toString()).then(async r => {
130
+ return fetch(path + "?" + u.toString()).catch(() => { throw new Error(STOPPED); }).then(async r => {
115
131
  const body = await r.json().catch(() => ({ error: r.statusText }));
116
132
  if (!r.ok) throw new Error(body.error || r.statusText);
117
133
  return body;
@@ -297,12 +313,13 @@ document.getElementById("reload").addEventListener("click", async () => {
297
313
  catch (e) { document.getElementById("loaded").textContent = "reload failed: " + e.message; }
298
314
  finally { btn.disabled = false; btn.textContent = "Reload"; }
299
315
  });
300
- if (!TOKEN) {
301
- main.replaceChildren(el("p", { class: "error" },
302
- "This tab has no access token. Open the URL that `mnemo inspect` printed."));
303
- } else {
304
- header(); render();
305
- }
316
+ session().then(s => {
317
+ TOKEN = s.token;
318
+ if (TOKEN) { header(); render(); return; }
319
+ main.replaceChildren(el("p", { class: "error" }, s.used
320
+ ? "This link has already been used. Each link `mnemo inspect` prints opens one tab; run it again for a new one."
321
+ : "This tab has no access. Open the link that `mnemo inspect` printed."));
322
+ }, fail);
306
323
  </script>
307
324
  </body>
308
325
  </html>
@@ -9,9 +9,11 @@
9
9
  //! keyword recall), so it needs no embedder and works on v8 files too.
10
10
  //!
11
11
  //! **How it serves.** A small HTTP/1.1 server on `std::net::TcpListener`,
12
- //! bound to `127.0.0.1` only. Every request must carry the random token
13
- //! from the printed URL and a `Host` header naming the loopback address and
14
- //! this port (against DNS rebinding and other sites' pages). Only `GET` is
12
+ //! bound to `127.0.0.1` only. The printed URL carries a one-time code,
13
+ //! which the page exchanges once (`/api/session`) for the random session
14
+ //! token; every data request must carry that token, and every request a
15
+ //! `Host` header naming the loopback address and this port (against DNS
16
+ //! rebinding and other sites' pages). Only `GET` is
15
17
  //! served, with no CORS headers, and no endpoint changes the file. The page
16
18
  //! is one static HTML file compiled in (`inspect.html`).
17
19
 
@@ -400,7 +402,7 @@ pub fn bind(port: Option<u16>) -> std::io::Result<TcpListener> {
400
402
  TcpListener::bind(("127.0.0.1", port.unwrap_or(0)))
401
403
  }
402
404
 
403
- /// A random token for the URL: 32 bytes from the engine's key generator.
405
+ /// A random token (or link code): 32 bytes from the engine's key generator.
404
406
  pub fn new_token() -> String {
405
407
  Mnemo::generate_key()
406
408
  .iter()
@@ -468,12 +470,14 @@ pub fn parse_idle(s: &str) -> Result<Option<Duration>, String> {
468
470
  pub fn serve(
469
471
  listener: TcpListener,
470
472
  token: String,
473
+ code: String,
471
474
  state: Arc<Mutex<State>>,
472
475
  watch: Arc<Watch>,
473
476
  idle: Option<Duration>,
474
477
  ) -> std::io::Result<()> {
475
478
  let port = listener.local_addr()?.port();
476
479
  let token = Arc::new(Zeroizing::new(token));
480
+ let code = Arc::new(Mutex::new(Some(Zeroizing::new(code))));
477
481
  if let Some(idle) = idle {
478
482
  let (state, watch) = (state.clone(), watch.clone());
479
483
  std::thread::spawn(move || loop {
@@ -493,9 +497,10 @@ pub fn serve(
493
497
  }
494
498
  for stream in listener.incoming() {
495
499
  let Ok(stream) = stream else { continue };
496
- let (token, state, watch) = (token.clone(), state.clone(), watch.clone());
500
+ let (token, code, state, watch) =
501
+ (token.clone(), code.clone(), state.clone(), watch.clone());
497
502
  std::thread::spawn(move || {
498
- let _ = handle(stream, &token, port, &state, &watch);
503
+ let _ = handle(stream, &token, &code, port, &state, &watch);
499
504
  });
500
505
  }
501
506
  Ok(())
@@ -605,6 +610,7 @@ fn respond_json(s: &mut TcpStream, status: &str, v: &Value) -> std::io::Result<(
605
610
  fn handle(
606
611
  mut s: TcpStream,
607
612
  token: &str,
613
+ code: &Mutex<Option<Zeroizing<String>>>,
608
614
  port: u16,
609
615
  state: &Mutex<State>,
610
616
  watch: &Watch,
@@ -666,15 +672,10 @@ fn handle(
666
672
  "Allow: GET\r\n",
667
673
  );
668
674
  }
669
- // The page holds no data, so it's served without the token: after it
670
- // moves the token out of the address bar, a refresh still loads. Every
675
+ // The page holds no data, so it's served without a code or the token: a
676
+ // refresh still loads, and it then reads the token its tab kept. Every
671
677
  // API route below needs the token.
672
678
  if req.path == "/" {
673
- // Only the browser that has the token counts as having loaded it.
674
- if req.query.get("t").is_some_and(|t| same(t, token)) {
675
- watch.page_served.store(true, Ordering::Relaxed);
676
- watch.touch();
677
- }
678
679
  return respond(
679
680
  &mut s,
680
681
  "200 OK",
@@ -685,6 +686,32 @@ fn handle(
685
686
  form-action 'none'; frame-ancestors 'none'\r\n",
686
687
  );
687
688
  }
689
+ // The printed link's one-time code, exchanged once for the token. After
690
+ // that the code opens nothing, so a copy of the link (the browser's
691
+ // history, the `--open` page) is dead.
692
+ if req.path == "/api/session" {
693
+ let mut slot = code.lock().unwrap_or_else(|p| p.into_inner());
694
+ let ok = req
695
+ .query
696
+ .get("c")
697
+ .is_some_and(|c| slot.as_deref().is_some_and(|k| same(c, k)));
698
+ if !ok {
699
+ return respond(
700
+ &mut s,
701
+ "403 Forbidden",
702
+ "text/plain",
703
+ b"this link has been used, or is wrong",
704
+ "",
705
+ );
706
+ }
707
+ *slot = None;
708
+ drop(slot);
709
+ // The browser that exchanged the code is the one that loaded the
710
+ // page (`--open` removes its forwarding page once this is set).
711
+ watch.page_served.store(true, Ordering::Relaxed);
712
+ watch.touch();
713
+ return respond_json(&mut s, "200 OK", &json!({ "token": token }));
714
+ }
688
715
  if !req.query.get("t").is_some_and(|t| same(t, token)) {
689
716
  return respond(
690
717
  &mut s,
@@ -966,11 +993,11 @@ mod tests {
966
993
 
967
994
  #[test]
968
995
  fn the_redirect_page_is_private_and_points_at_the_url() {
969
- let url = "http://127.0.0.1:9/?t=abc123";
996
+ let url = "http://127.0.0.1:9/?c=abc123";
970
997
  let (dir, page) = write_redirect(url).unwrap();
971
998
  let body = std::fs::read_to_string(&page).unwrap();
972
999
  assert!(
973
- body.contains("content=\"0;url=http://127.0.0.1:9/?t=abc123\""),
1000
+ body.contains("content=\"0;url=http://127.0.0.1:9/?c=abc123\""),
974
1001
  "{body}"
975
1002
  );
976
1003
  #[cfg(unix)]
@@ -364,7 +364,10 @@ enum Command {
364
364
  port: Option<u16>,
365
365
  /// Open the page in the default browser. The browser gets a
366
366
  /// private local page that forwards to the URL (deleted once it has
367
- /// loaded), not the URL itself.
367
+ /// loaded), not the URL itself. On Linux, a browser installed as a
368
+ /// snap or a flatpak (Ubuntu's default Firefox is a snap) has its
369
+ /// own private /tmp and can't read that page: copy the printed link
370
+ /// instead.
368
371
  #[arg(long)]
369
372
  open: bool,
370
373
  /// Stop after this long without a request from the page: `30m`,
@@ -1464,9 +1467,29 @@ fn run() -> std::result::Result<(), String> {
1464
1467
  let pp = passphrase(&pp)?;
1465
1468
  let new = new_passphrase(&new, "MNEMO_NEW_PASSPHRASE")?;
1466
1469
  let mut db = Mnemo::open(&path, &pp).map_err(fmt)?;
1470
+ // RB-005.4 item 4: REKEY-1 makes an error leave the old passphrase
1471
+ // in force, so say so. The one exception (the old header couldn't
1472
+ // be written back) says "may open with either secret" itself.
1467
1473
  db.rekey(&new, mnemo_engine::KdfParams::secure())
1468
- .map_err(fmt)?;
1474
+ .map_err(|e| {
1475
+ let msg = fmt(e);
1476
+ if msg.contains("may open with either secret") {
1477
+ msg
1478
+ } else {
1479
+ format!("{msg}; the passphrase was not changed")
1480
+ }
1481
+ })?;
1482
+ // REKEY-1: the rekey took effect; part of the old wrap's cleanup
1483
+ // didn't. `--rotate` rewrites the file, which covers it.
1484
+ let left = db.rekey_cleanup_error().map(str::to_owned);
1469
1485
  db.close().map_err(fmt)?;
1486
+ if let (Some(left), false) = (&left, rotate) {
1487
+ eprintln!(
1488
+ "warning: the new passphrase is in force, but part of the old key \
1489
+ wrap's cleanup failed ({left}); run `mnemo rekey --rotate` to be sure \
1490
+ the old passphrase opens nothing"
1491
+ );
1492
+ }
1470
1493
  if rotate {
1471
1494
  let r = Mnemo::compact_file(&path, &new).map_err(fmt)?;
1472
1495
  println!(
@@ -2016,10 +2039,13 @@ fn run() -> std::result::Result<(), String> {
2016
2039
  .map_err(|e| format!("binding 127.0.0.1: {e}"))?
2017
2040
  .port();
2018
2041
  let token = inspect::new_token();
2019
- let url = format!("http://127.0.0.1:{port}/?t={token}");
2042
+ // The link carries a one-time code; the page exchanges it for
2043
+ // the token on its first load.
2044
+ let code = inspect::new_token();
2045
+ let url = format!("http://127.0.0.1:{port}/?c={code}");
2020
2046
  println!("inspecting {path} (read-only; the file is read once and closed)");
2021
2047
  println!("{url}");
2022
- println!("press Ctrl-C to stop");
2048
+ println!("the link opens one tab (it works once); press Ctrl-C to stop");
2023
2049
  {
2024
2050
  use std::io::Write;
2025
2051
  let _ = std::io::stdout().flush();
@@ -2028,12 +2054,19 @@ fn run() -> std::result::Result<(), String> {
2028
2054
  if open {
2029
2055
  if let Err(e) = inspect::open_browser(&url, watch.clone()) {
2030
2056
  eprintln!("warning: couldn't open a browser ({e}); open the URL above");
2057
+ } else if cfg!(target_os = "linux") {
2058
+ // RB-004.5 item 5: a snap or flatpak browser can't read
2059
+ // the forwarding page under /tmp (tested: snap Firefox).
2060
+ eprintln!(
2061
+ "note: if the browser says the file can't be found (a snap or \
2062
+ flatpak browser can't read /tmp), copy the link above instead"
2063
+ );
2031
2064
  }
2032
2065
  }
2033
2066
  let state = std::sync::Arc::new(std::sync::Mutex::new(inspect::State::new(
2034
2067
  path, secret, loaded,
2035
2068
  )));
2036
- inspect::serve(listener, token, state, watch, idle)
2069
+ inspect::serve(listener, token, code, state, watch, idle)
2037
2070
  .map_err(|e| format!("serving: {e}"))?;
2038
2071
  }
2039
2072
  Command::Recall {
@@ -123,9 +123,15 @@ impl Mnemo {
123
123
  /// [`Mnemo::compact_file`] (`mnemo rekey --rotate`), which rewrites the
124
124
  /// file under a fresh data key. Rotation can't erase old ciphertext the storage hardware still holds: flash keeps rewritten blocks until it reuses them, and that's out of the engine's hands.
125
125
  ///
126
- /// **If it returns an error, the file may already be under the new secret,
127
- /// or may move to it at the next write** (RB-004.2). Close the handle
128
- /// without writing anything more, then try both secrets.
126
+ /// **An error means the old secret is still in force,** for this handle
127
+ /// and for the file, including after later writes and a close (REKEY-1).
128
+ /// The one exception is when the new header's write fails and putting
129
+ /// the old one back fails too: the error then says so, and the file may
130
+ /// open with either secret.
131
+ ///
132
+ /// `Ok` means the new secret is in force. Scrubbing the old wrap
133
+ /// afterwards is hygiene; if part of it fails, the rekey still succeeds
134
+ /// and [`Mnemo::rekey_cleanup_error`] says what was left.
129
135
  pub fn rekey(&mut self, new_passphrase: &str, kdf: KdfParams) -> Result<()> {
130
136
  self.rekey_secret(new_passphrase.as_bytes(), kdf)
131
137
  }
@@ -135,9 +141,7 @@ impl Mnemo {
135
141
  /// wrapped DEK changes; pages aren't rewritten, and it doesn't revoke
136
142
  /// the old key (see [`Mnemo::rekey`]).
137
143
  ///
138
- /// **If it returns an error, the file may already be under the new secret,
139
- /// or may move to it at the next write** (RB-004.2). Close the handle
140
- /// without writing anything more, then try both secrets.
144
+ /// Errors and the cleanup report work as in [`Mnemo::rekey`].
141
145
  pub fn rekey_with_key(&mut self, new_key: &[u8; crypto::KEY_LEN]) -> Result<()> {
142
146
  self.rekey_secret(new_key, KdfParams::raw_key())
143
147
  }
@@ -146,6 +150,7 @@ impl Mnemo {
146
150
  if self.read_only {
147
151
  return Err(MnemoError::ReadOnly);
148
152
  }
153
+ self.rekey_cleanup = None;
149
154
  self.flush()?;
150
155
  let new_salt = crypto::random_salt();
151
156
  let new_kek = crypto::derive_kek(secret, &new_salt, kdf)?;
@@ -166,6 +171,11 @@ impl Mnemo {
166
171
  old_wrap.extend_from_slice(&self.header.dek_nonce);
167
172
  old_wrap.extend_from_slice(&self.header.wrapped_dek);
168
173
 
174
+ // REKEY-1 (RB-004.2): until the new page 0 is on disk, a failure puts
175
+ // these back, so an `Err` means "still the old secret".
176
+ let before = self.header.clone();
177
+ let before_kdf = self.kdf;
178
+
169
179
  self.header.salt = new_salt;
170
180
  self.header.dek_nonce = new_nonce;
171
181
  self.header.wrapped_dek = wrapped_dek;
@@ -186,21 +196,105 @@ impl Mnemo {
186
196
  self.header.wal_start = new_start;
187
197
  self.header.wal_pages = new_pages;
188
198
  self.header.wal_seq += 1;
189
- self.relocate_header_through_wal(old_wal_start)?;
190
- // SEC-2 (RB-001.30): the old region holds page-0 images with the old
191
- // wrap; `relocate_header_through_wal` only zeroed its first frame
192
- // header. Zero all of it, then overwrite any other stale copy of
193
- // the old wrap in the file (an earlier, grown or relocated region).
199
+
200
+ // The steps of `relocate_header_through_wal`, apart, so a failure
201
+ // can be told from one before page 0 and one after it.
202
+ self.header.write_counter = self.pager.write_counter;
203
+ let mut page = self.header.to_page();
204
+ if let Err(e) = self.header.apply_seal(&mut page, self.pager.dek()) {
205
+ return Err(self.undo_rekey(before, before_kdf, None, false, e));
206
+ }
207
+ let frames = vec![(0u64, page.to_vec())];
208
+ let txn_id = self.header.wal_seq;
209
+ if let Err(e) = wal::commit(self.pager.file_mut(), new_start, new_pages, txn_id, &frames) {
210
+ let region = Some((new_start, new_pages));
211
+ return Err(self.undo_rekey(before, before_kdf, region, false, e));
212
+ }
213
+ if let Err(e) = self
214
+ .pager
215
+ .write_raw(0, &page)
216
+ .and_then(|_| self.pager.sync())
217
+ {
218
+ let region = Some((new_start, new_pages));
219
+ return Err(self.undo_rekey(before, before_kdf, region, true, e));
220
+ }
221
+
222
+ // The new page 0 is on disk: the new secret is in force, and nothing
223
+ // below fails the rekey. SEC-2 (RB-001.30): zero the old region's
224
+ // first frame header (so no scan reads it as a WAL), then all of it
225
+ // (its frames hold page-0 images with the old wrap), then any other
226
+ // stale copy of the old wrap in the file (an earlier, grown or
227
+ // relocated region). Each step runs even if the one before failed.
194
228
  // Hygiene only: a copy of the file taken before the rekey still
195
229
  // opens with the old secret (see `rekey`).
196
- wal::scrub_region(self.pager.file_mut(), old_wal_start, new_pages)?;
197
- scrub_bytes(self.pager.file_mut(), &old_wrap)?;
230
+ let mut left = Vec::new();
231
+ if let Err(e) = wal::invalidate_region(self.pager.file_mut(), old_wal_start) {
232
+ left.push(format!("clearing the old WAL region's first frame: {e}"));
233
+ }
234
+ if let Err(e) = wal::scrub_region(self.pager.file_mut(), old_wal_start, new_pages) {
235
+ left.push(format!("zeroing the old WAL region: {e}"));
236
+ }
237
+ if let Err(e) = scrub_bytes(self.pager.file_mut(), &old_wrap) {
238
+ left.push(format!("overwriting other copies of the old key wrap: {e}"));
239
+ }
240
+ self.rekey_cleanup = (!left.is_empty()).then(|| left.join("; "));
198
241
  // FMT-9 (a): the old region is freed by the next commit (see
199
242
  // `ensure_wal_capacity`).
200
243
  self.release_pages(old_wal_start, new_pages);
201
244
  Ok(())
202
245
  }
203
246
 
247
+ /// REKEY-1: a rekey failed before its new page 0 was on disk. Put the
248
+ /// header and the KDF back, so the handle (and every later write) uses
249
+ /// the old secret. Then, best effort: zero the new WAL region, whose
250
+ /// commit wraps the data key under the new secret, so a later
251
+ /// torn-header scan can't find it; and, if page 0 may have been
252
+ /// written, write the old one back.
253
+ fn undo_rekey(
254
+ &mut self,
255
+ before: crate::format::Header,
256
+ before_kdf: KdfParams,
257
+ new_region: Option<(u64, u64)>,
258
+ page0_written: bool,
259
+ err: MnemoError,
260
+ ) -> MnemoError {
261
+ self.header = before;
262
+ self.kdf = before_kdf;
263
+ if let Some((start, pages)) = new_region {
264
+ let _ = wal::scrub_region(self.pager.file_mut(), start, pages);
265
+ }
266
+ if !page0_written {
267
+ return err;
268
+ }
269
+ self.header.write_counter = self.pager.write_counter;
270
+ let mut page = self.header.to_page();
271
+ let put_back = self
272
+ .header
273
+ .apply_seal(&mut page, self.pager.dek())
274
+ .and_then(|_| self.pager.write_raw(0, &page))
275
+ .and_then(|_| self.pager.sync());
276
+ match put_back {
277
+ Ok(()) => err,
278
+ // `mnemo rekey` looks for "may open with either secret" to leave
279
+ // out its "the passphrase was not changed": keep the phrase.
280
+ Err(again) => MnemoError::Io(std::io::Error::other(format!(
281
+ "rekey failed writing the new header ({err}), and the old header \
282
+ couldn't be written back ({again}): the file may open with either \
283
+ secret; close it without writing and try both"
284
+ ))),
285
+ }
286
+ }
287
+
288
+ /// REKEY-1 (RB-004.2): after a successful [`Mnemo::rekey`] or
289
+ /// [`Mnemo::rekey_with_key`], what couldn't be scrubbed of the old key
290
+ /// wrap, or `None` if it all was. The rekey took effect either way; what
291
+ /// is left is plaintext key-wrap bytes the old secret could still use, so
292
+ /// to be sure, rotate (`compact_file`) as [`Mnemo::rekey`] describes.
293
+ /// Each rekey resets it.
294
+ pub fn rekey_cleanup_error(&self) -> Option<&str> {
295
+ self.rekey_cleanup.as_deref()
296
+ }
297
+
204
298
  /// SEC-2 (RB-001.30): write a copy of this database at `dest` under a
205
299
  /// **fresh data key**, protected by `passphrase` through `kdf`. It goes
206
300
  /// through the compaction path (live memories, the result cache and
@@ -997,6 +997,9 @@ pub struct Mnemo {
997
997
  superseded: Option<std::collections::HashSet<u128>>,
998
998
  /// R-004.2: thread layers + onboarding ids, built by the same lazy scan.
999
999
  layers: Option<LayerCache>,
1000
+ /// REKEY-1 (RB-004.2): what the last successful rekey couldn't scrub
1001
+ /// once the new secret was in force (see [`Mnemo::rekey_cleanup_error`]).
1002
+ rekey_cleanup: Option<String>,
1000
1003
  /// FMT-9e: thread turns are compressed once older than this many
1001
1004
  /// seconds (`0`: at write). Per handle, not persisted.
1002
1005
  turn_compress_after: i64,
@@ -327,6 +327,7 @@ impl Mnemo {
327
327
  key_index: None,
328
328
  superseded: None,
329
329
  layers: None,
330
+ rekey_cleanup: None,
330
331
  turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
331
332
  free: FreeList::default(),
332
333
  pending_free: Vec::new(),
@@ -706,6 +707,7 @@ impl Mnemo {
706
707
  key_index: None,
707
708
  superseded: None,
708
709
  layers: None,
710
+ rekey_cleanup: None,
709
711
  turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
710
712
  free,
711
713
  pending_free: Vec::new(),
@@ -829,6 +831,18 @@ impl Mnemo {
829
831
  Err(parse_err) => {
830
832
  let recoverable = scan_header_recovery_candidates(&mut file, secret)?;
831
833
  return Err(match (parse_err, recoverable) {
834
+ // RB-004.5 item 2: as for a pending WAL (RB-003.3), a
835
+ // pre-v9 file can't be opened read-write, so the advice
836
+ // names the step that does heal it.
837
+ (_, Some(frames))
838
+ if page_zero_header(&frames).is_some_and(|h| h.version < VERSION_V9) =>
839
+ {
840
+ MnemoError::NeedsWriteOpen {
841
+ reason: "torn header page in a pre-v9 file; run `mnemo compact \
842
+ <file>` (with `--key-file <key>` for a raw-key file), \
843
+ which recovers it and converts the file to v9",
844
+ }
845
+ }
832
846
  (_, Some(_)) => MnemoError::NeedsWriteOpen {
833
847
  reason: "torn header page needs recovery from WAL",
834
848
  },
@@ -958,6 +972,7 @@ impl Mnemo {
958
972
  key_index: None,
959
973
  superseded: None,
960
974
  layers: None,
975
+ rekey_cleanup: None,
961
976
  turn_compress_after: DEFAULT_TURN_COMPRESS_AFTER_SECS,
962
977
  free,
963
978
  pending_free: Vec::new(),
@@ -449,7 +449,7 @@ dependencies = [
449
449
 
450
450
  [[package]]
451
451
  name = "mnemo-engine"
452
- version = "0.13.1"
452
+ version = "0.13.2"
453
453
  dependencies = [
454
454
  "aes-gcm",
455
455
  "argon2",
@@ -472,7 +472,7 @@ dependencies = [
472
472
 
473
473
  [[package]]
474
474
  name = "mnemo-python"
475
- version = "0.13.1"
475
+ version = "0.13.2"
476
476
  dependencies = [
477
477
  "mnemo-engine",
478
478
  "pyo3",
@@ -4,7 +4,7 @@
4
4
  # fields below are still useful for `cargo publish --dry-run` to lint
5
5
  # cleanly and for `cargo doc` to render coherently.
6
6
  name = "mnemo-python"
7
- version = "0.13.1"
7
+ version = "0.13.2"
8
8
  edition = "2021"
9
9
  rust-version = "1.75"
10
10
  description = "Python (PyO3) bindings for the Mnemo encrypted agent-memory engine; built by maturin into the mnemo-engine wheel on PyPI"
@@ -39,11 +39,13 @@ pyo3 = { version = "=0.22.6", features = ["extension-module", "abi3-py38"] }
39
39
  serde_json = "1.0"
40
40
 
41
41
  [features]
42
- # HOOKS-1: the engine's `MNEMO_DEV_*` switches, for the test wheel only.
43
- # `test_mnemo.py` sets `MNEMO_DEV_ANN_MIN_FACTS=0` so small v9 files build
44
- # an index; CI's test build passes `--features dev-hooks`. The released
45
- # wheels (release.yml) are built without it and ignore the variable.
46
- dev-hooks = ["mnemo_core/dev-hooks"]
42
+ # HOOKS-1: the engine's `MNEMO_DEV_*` switches and its write failpoint
43
+ # (`_dev_set_writes_until_fail`), for the test wheel only. `test_mnemo.py`
44
+ # sets `MNEMO_DEV_ANN_MIN_FACTS=0` so small v9 files build an index, and
45
+ # fails a rekey's cleanup on purpose; CI's test build passes
46
+ # `--features dev-hooks`. The released wheels (release.yml) are built
47
+ # without it, so they ignore the variable and have no failpoint.
48
+ dev-hooks = ["mnemo_core/dev-hooks", "mnemo_core/failpoints"]
47
49
 
48
50
  [profile.release]
49
51
  lto = true
@@ -174,7 +174,7 @@ its own agent.
174
174
  | `set_turn_compress_after(secs)` | v9 files: compress thread turns once they're older than `secs` (default 7 days; `0` compresses at write). This handle only |
175
175
  | `memories()` | Enumerate every live (non-deleted, non-expired) memory as a list of dicts |
176
176
  | `dimensions()` | Embedding dimensionality this database was created with (also on `stats()["dimensions"]`) |
177
- | `rekey(new_passphrase, fast=False)` | Change the passphrase. Re-derives the KEK and re-wraps the DEK; encrypted pages are not rewritten (O(1) in db size). `fast=True` uses the cheap-Argon2 test params — omit for production. If it raises, the file may already be under the new secret, or may move to it at the next write: close without writing more, then try both secrets |
177
+ | `rekey(new_passphrase, fast=False)` | Change the passphrase. Re-derives the KEK and re-wraps the DEK; encrypted pages are not rewritten (O(1) in db size). `fast=True` uses the cheap-Argon2 test params — omit for production. If it raises, the old passphrase is still in force (the one exception is an error that says the file may open with either). If it returns but couldn't scrub every copy of the old key wrap, it emits a `RuntimeWarning`: the call succeeded and the new passphrase is in force (where warnings are errors, it goes to `sys.unraisablehook` and the call still returns) |
178
178
  | `set_embedder(fn, *, name, dimensions, normalize=True)` | Register a Python callable `embed(texts: list[str]) -> list[list[float]]` as this handle's text embedder (Phase 3). Dimension-checks against the database's width; identity-checks against (and on first use upserts) the scaffold manifest's `embedder_name` / `embedder_dimensions` / `embedder_normalize` keys, so swapping embedders between opens fails loudly |
179
179
  | `remember_text(content, memory_type, **kwargs)` | Embed `content` via the registered embedder and `remember` the result. Accepts the same per-memory kwargs as `remember` (`agent_id`, `importance`, `session_id`, `ttl_secs`, `shared`, `metadata`) |
180
180
  | `recall_text(query, top_k=10, memory_types=None, agent_id=None, track_access=True, n_probe=None, n_rerank=None, filter=None, max_bytes=None, keywords=None, keyword_weight=None)` | Embed `query` via the registered embedder and run `recall`. Same return shape and kwargs as `recall`. `keywords` (v9 files): identifiers or exact terms to match (a version, a PR number, a function name), not the question; their BM25 score is added with weight `keyword_weight` (default 0.5) |
@@ -126,6 +126,37 @@ mod exc {
126
126
  );
127
127
  }
128
128
 
129
+ /// REKEY-1: a rekey that succeeded but couldn't scrub every copy of the
130
+ /// old key wrap says so as a `RuntimeWarning` (the new secret is in force).
131
+ /// RB-005.3: the rekey has already happened, so the warning never becomes
132
+ /// the call's failure. Where warnings are errors (`-W error`), the
133
+ /// exception goes to `sys.unraisablehook` and the call returns normally.
134
+ fn warn_rekey_cleanup(py: Python<'_>, core: &Core) {
135
+ if let Some(left) = core.rekey_cleanup_error() {
136
+ let msg = format!(
137
+ "rekey succeeded, but part of the old key wrap's cleanup failed ({left}); \
138
+ to be sure the old secret opens nothing, compact the file (compact_file)"
139
+ );
140
+ if let Err(e) = PyErr::warn_bound(
141
+ py,
142
+ &py.get_type_bound::<pyo3::exceptions::PyRuntimeWarning>(),
143
+ &msg,
144
+ 1,
145
+ ) {
146
+ e.write_unraisable_bound(py, None);
147
+ }
148
+ }
149
+ }
150
+
151
+ /// HOOKS-1 test hook, in the test wheel only (`dev-hooks`): fail the
152
+ /// `n`th engine write from now on this thread (`0` is the next one, a
153
+ /// negative value disarms). One-shot, like `mnemo_engine::__failpoints`.
154
+ #[cfg(feature = "dev-hooks")]
155
+ #[pyfunction]
156
+ fn _dev_set_writes_until_fail(n: i64) {
157
+ mnemo_core::__failpoints::set_writes_until_fail(n)
158
+ }
159
+
129
160
  /// Map a core error onto its Python exception type (the message is the
130
161
  /// engine's, unchanged).
131
162
  fn to_py(e: mnemo_core::MnemoError) -> PyErr {
@@ -1630,9 +1661,13 @@ impl Mnemo {
1630
1661
  /// `False` so the new KEK inherits the same protection level as
1631
1662
  /// the file's original creation-time parameters.
1632
1663
  ///
1633
- /// If it raises, the file may already be under the new secret, or may
1634
- /// move to it at the next write: close the handle without writing
1635
- /// anything more, then try both secrets.
1664
+ /// If it raises, the old secret is still in force, including after later
1665
+ /// writes; the one exception is an error that says the file may open with
1666
+ /// either secret. If it returns but couldn't scrub every copy of the old
1667
+ /// key wrap, it emits a `RuntimeWarning` saying what was left. A
1668
+ /// `RuntimeWarning` from this call means it succeeded: the new secret is
1669
+ /// in force. Where warnings are errors (`-W error`), the warning goes to
1670
+ /// `sys.unraisablehook` instead, and the call still returns normally.
1636
1671
  #[pyo3(signature = (new_passphrase, fast=false))]
1637
1672
  fn rekey(&mut self, py: Python<'_>, new_passphrase: &str, fast: bool) -> PyResult<()> {
1638
1673
  // FIX-1 R-001.5: `fast=False` now really does "inherit the
@@ -1652,7 +1687,9 @@ impl Mnemo {
1652
1687
  // Python thread for no reason.
1653
1688
  let core = self.core_mut()?;
1654
1689
  py.allow_threads(|| core.rekey(new_passphrase, kdf))
1655
- .map_err(to_py)
1690
+ .map_err(to_py)?;
1691
+ warn_rekey_cleanup(py, core);
1692
+ Ok(())
1656
1693
  }
1657
1694
 
1658
1695
  /// Switch this database to (or rotate) a raw 256-bit key (32 bytes, e.g.
@@ -1660,14 +1697,20 @@ impl Mnemo {
1660
1697
  /// minimal Argon2id parameters, so later `open_with_key` calls skip the
1661
1698
  /// KDF cost. Only the wrapped data key changes.
1662
1699
  ///
1663
- /// If it raises, the file may already be under the new secret, or may
1664
- /// move to it at the next write: close the handle without writing
1665
- /// anything more, then try both secrets.
1700
+ /// If it raises, the old secret is still in force, including after later
1701
+ /// writes; the one exception is an error that says the file may open with
1702
+ /// either secret. If it returns but couldn't scrub every copy of the old
1703
+ /// key wrap, it emits a `RuntimeWarning` saying what was left. A
1704
+ /// `RuntimeWarning` from this call means it succeeded: the new secret is
1705
+ /// in force. Where warnings are errors (`-W error`), the warning goes to
1706
+ /// `sys.unraisablehook` instead, and the call still returns normally.
1666
1707
  fn rekey_with_key(&mut self, py: Python<'_>, key: &[u8]) -> PyResult<()> {
1667
1708
  let key = key_from_bytes(key)?;
1668
1709
  let core = self.core_mut()?;
1669
1710
  py.allow_threads(|| core.rekey_with_key(&key))
1670
- .map_err(to_py)
1711
+ .map_err(to_py)?;
1712
+ warn_rekey_cleanup(py, core);
1713
+ Ok(())
1671
1714
  }
1672
1715
 
1673
1716
  /// Return the database's self-describing onboarding memories (those tagged
@@ -2758,6 +2801,8 @@ fn mnemo_engine(m: &Bound<'_, PyModule>) -> PyResult<()> {
2758
2801
  m.add_function(wrap_pyfunction!(compact_file, m)?)?;
2759
2802
  m.add_function(wrap_pyfunction!(compact_file_with_key, m)?)?;
2760
2803
  m.add_function(wrap_pyfunction!(build_info, m)?)?;
2804
+ #[cfg(feature = "dev-hooks")]
2805
+ m.add_function(wrap_pyfunction!(_dev_set_writes_until_fail, m)?)?;
2761
2806
  m.add("__version__", env!("CARGO_PKG_VERSION"))?;
2762
2807
  Ok(())
2763
2808
  }
@@ -420,6 +420,76 @@ def test_rekey_and_reopen_with_new_passphrase():
420
420
  print("ok rekey + reopen with new passphrase; old is rejected")
421
421
 
422
422
 
423
+ _REKEY_CLEANUP_UNDER_W_ERROR = r"""
424
+ import sys, warnings
425
+ import mnemo_engine as mnemo
426
+ path = sys.argv[1]
427
+ caught = []
428
+ sys.unraisablehook = lambda u: caught.append(u.exc_type)
429
+ assert warnings.filters[0][0] == "error", warnings.filters[0]
430
+ db = mnemo.open(path, "old-pw", dimensions=2)
431
+ db.remember("survive-rekey", "semantic", [1.0, 0.0])
432
+ db.flush()
433
+ mnemo._dev_set_writes_until_fail(2)
434
+ try:
435
+ db.rekey("new-pw", fast=True)
436
+ finally:
437
+ mnemo._dev_set_writes_until_fail(-1)
438
+ db.close()
439
+ assert caught == [RuntimeWarning], caught
440
+ print("returned")
441
+ """
442
+
443
+
444
+ def test_rekey_cleanup_warning_never_fails_the_call():
445
+ """RB-005.3: a rekey whose cleanup is cut short has still succeeded,
446
+ so it warns, and under `-W error` the warning goes to
447
+ `sys.unraisablehook` instead of raising. The failpoint (test wheel
448
+ only) fails the third write, the first cleanup step after the new
449
+ header is on disk (`mnemo/tests/rekey_cut.rs`)."""
450
+ import subprocess
451
+ import sys
452
+ import warnings
453
+ assert hasattr(mnemo, "_dev_set_writes_until_fail"), "build the test wheel with --features dev-hooks"
454
+ with tempfile.TemporaryDirectory() as d:
455
+ # As a plain warning.
456
+ path = os.path.join(d, "w.mnemo")
457
+ db = mnemo.open(path, "old-pw", dimensions=2)
458
+ db.remember("survive-rekey", "semantic", [1.0, 0.0])
459
+ db.flush()
460
+ mnemo._dev_set_writes_until_fail(2)
461
+ try:
462
+ with warnings.catch_warnings(record=True) as seen:
463
+ warnings.simplefilter("always")
464
+ db.rekey("new-pw", fast=True)
465
+ finally:
466
+ mnemo._dev_set_writes_until_fail(-1)
467
+ db.close()
468
+ kinds = [w.category for w in seen]
469
+ assert kinds == [RuntimeWarning], kinds
470
+ assert "rekey succeeded" in str(seen[0].message), seen[0].message
471
+
472
+ # Under `-W error`, in a fresh interpreter.
473
+ path = os.path.join(d, "e.mnemo")
474
+ r = subprocess.run(
475
+ [sys.executable, "-W", "error", "-c", _REKEY_CLEANUP_UNDER_W_ERROR, path],
476
+ capture_output=True, text=True,
477
+ )
478
+ assert r.returncode == 0 and r.stdout.strip() == "returned", (r.returncode, r.stdout, r.stderr)
479
+
480
+ # Both rekeys took effect: the new passphrase opens, the old one doesn't.
481
+ for p in (os.path.join(d, "w.mnemo"), path):
482
+ try:
483
+ mnemo.open(p, "old-pw")
484
+ raise AssertionError("old passphrase should have been rejected after rekey")
485
+ except mnemo.WrongPassphraseError:
486
+ pass
487
+ db2 = mnemo.open(p, "new-pw")
488
+ assert db2.memories()[0]["content"] == "survive-rekey"
489
+ db2.close()
490
+ print("ok rekey: a cleanup warning never fails the call, even under -W error (RB-005.3)")
491
+
492
+
423
493
  def _fake_embedder(dims=4):
424
494
  """A tiny deterministic in-test embedder: hashes a string onto one
425
495
  axis and emits a unit spike there. Deps-free so this test file still
@@ -1343,6 +1413,7 @@ if __name__ == "__main__":
1343
1413
  test_batched_cache_uncommitted_is_a_miss()
1344
1414
  test_cache_budget_evicts_lru()
1345
1415
  test_rekey_and_reopen_with_new_passphrase()
1416
+ test_rekey_cleanup_warning_never_fails_the_call()
1346
1417
  test_set_embedder_and_text_round_trip()
1347
1418
  test_set_embedder_dim_mismatch_rejected()
1348
1419
  test_set_embedder_identity_mismatch_rejected_after_reopen()
@@ -15,7 +15,7 @@ build-backend = "maturin"
15
15
  # sites unchanged). See the "Breaking: import name" section in
16
16
  # CHANGELOG.md for the full migration.
17
17
  name = "mnemo-engine"
18
- version = "0.13.1"
18
+ version = "0.13.2"
19
19
  description = "Encrypted, portable agent-memory engine — Python bindings"
20
20
  readme = "README.md"
21
21
  requires-python = ">=3.8"