mnemo-engine 0.7.0__tar.gz → 0.8.0__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 (53) hide show
  1. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/PKG-INFO +1 -1
  2. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/Cargo.lock +2 -2
  3. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/Cargo.toml +1 -1
  4. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/benches/recall.rs +38 -0
  5. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/bin/mnemo.rs +374 -5
  6. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/lib.rs +7 -2
  7. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/mcp.rs +307 -9
  8. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/memory.rs +258 -0
  9. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/store.rs +711 -34
  10. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/tests/integration.rs +764 -3
  11. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo-python/Cargo.lock +2 -2
  12. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo-python/Cargo.toml +1 -1
  13. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo-python/src/lib.rs +368 -24
  14. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/pyproject.toml +1 -1
  15. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/README.md +0 -0
  16. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/.gitignore +0 -0
  17. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/README.md +0 -0
  18. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/benches/cache.rs +0 -0
  19. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/benches/corpus.rs +0 -0
  20. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/benches/embed_overhead.rs +0 -0
  21. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/benches/open.rs +0 -0
  22. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/benches/write.rs +0 -0
  23. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/deny.toml +0 -0
  24. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/ann_defaults_v0_6_0.rs +0 -0
  25. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/ann_diagnose.rs +0 -0
  26. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/ann_recall_grid.rs +0 -0
  27. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/ann_recall_grid_v2.rs +0 -0
  28. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/embedder_server.py +0 -0
  29. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/file_size_breakdown.rs +0 -0
  30. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/quickstart.rs +0 -0
  31. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/ranking_v2.rs +0 -0
  32. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/examples/session.rs +0 -0
  33. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/cache.rs +0 -0
  34. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/crypto.rs +0 -0
  35. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/embed.rs +0 -0
  36. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/embed_cmd.rs +0 -0
  37. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/error.rs +0 -0
  38. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/format.rs +0 -0
  39. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/index.rs +0 -0
  40. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/pager.rs +0 -0
  41. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/result_cache.rs +0 -0
  42. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/session.rs +0 -0
  43. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/src/wal.rs +0 -0
  44. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/tests/cli_smoke.rs +0 -0
  45. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/tests/dur1_torn_header.rs +0 -0
  46. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/tests/fix1_correctness_sweep.rs +0 -0
  47. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/tests/proptest_store.proptest-regressions +0 -0
  48. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/tests/proptest_store.rs +0 -0
  49. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo/tests/sec1_nonce_uniqueness.rs +0 -0
  50. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo-python/.gitignore +0 -0
  51. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo-python/README.md +0 -0
  52. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/mnemo-python/test_mnemo.py +0 -0
  53. {mnemo_engine-0.7.0 → mnemo_engine-0.8.0}/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.7.0
3
+ Version: 0.8.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: 3
6
6
  Classifier: License :: OSI Approved :: Apache Software License
@@ -610,7 +610,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
610
610
 
611
611
  [[package]]
612
612
  name = "mnemo-engine"
613
- version = "0.7.0"
613
+ version = "0.8.0"
614
614
  dependencies = [
615
615
  "aes-gcm",
616
616
  "argon2",
@@ -634,7 +634,7 @@ dependencies = [
634
634
 
635
635
  [[package]]
636
636
  name = "mnemo-node"
637
- version = "0.7.0"
637
+ version = "0.8.0"
638
638
  dependencies = [
639
639
  "mnemo-engine",
640
640
  "napi",
@@ -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.7.0"
13
+ version = "0.8.0"
14
14
  edition = "2021"
15
15
  rust-version = "1.75"
16
16
  # `benches/corpus.rs` is a shared helper module pulled into real benches
@@ -112,10 +112,48 @@ fn bench_recall_1m(c: &mut Criterion) {
112
112
  bench_recall_pair(c, 1_000_000, "1m", 10);
113
113
  }
114
114
 
115
+ /// Phase 12.1 lane-A REVIEW remeasure: first recall on a *fresh*
116
+ /// `Mnemo` handle. Opens the cached 100K corpus, issues a single
117
+ /// recall, closes the handle — repeated per Criterion iteration. The
118
+ /// pre-v0.8.0 code called `ensure_key_caches()` inside recall itself,
119
+ /// which decrypted every live record on the first call — roughly 1 s
120
+ /// at 100K with hardware AES. Post-fix, the first recall only decrypts
121
+ /// the ANN shortlist plus whatever the widen / exact-scan loop needs
122
+ /// (typically a few hundred records), so this cell should sit near
123
+ /// the pure per-query cost of `ivfpq_recall_100k`.
124
+ fn bench_first_recall_fresh_handle_100k(c: &mut Criterion) {
125
+ use mnemo_engine::{RecallRequest, ScoreWeights};
126
+ let cached = setup_cached_corpus(100_000, DIMENSIONS);
127
+ let queries = gen_clustered_vectors(DIMENSIONS, 20, 0xDEAD_BEEF, 100);
128
+ let mut group = c.benchmark_group("ivfpq_first_recall_fresh_handle_100k");
129
+ group.sample_size(20);
130
+ group.bench_function("first_recall", |b| {
131
+ let mut i = 0usize;
132
+ b.iter(|| {
133
+ // Open a *fresh* handle every iteration so the key-cache
134
+ // lazy init (removed in v0.8.0) and page-cache are cold.
135
+ // Use `open_corpus_with_index` so the IVF+PQ path is live;
136
+ // the "fresh handle" invariant we want to measure is the
137
+ // one that pre-v0.8.0 would have paid for key-cache init
138
+ // on every first recall.
139
+ let mut db = open_corpus_with_index(&cached);
140
+ let q = &queries[i % queries.len()];
141
+ i += 1;
142
+ let req = RecallRequest::new(q.clone())
143
+ .top_k(10)
144
+ .track_access(false)
145
+ .weights(ScoreWeights::default());
146
+ let _ = black_box(db.recall(&req).unwrap());
147
+ });
148
+ });
149
+ group.finish();
150
+ }
151
+
115
152
  criterion_group!(
116
153
  recall_benches,
117
154
  bench_recall_10k,
118
155
  bench_recall_100k,
119
156
  bench_recall_1m,
157
+ bench_first_recall_fresh_handle_100k,
120
158
  );
121
159
  criterion_main!(recall_benches);
@@ -113,6 +113,17 @@ enum Command {
113
113
  /// Optional JSON object of extra metadata key/values.
114
114
  #[arg(long)]
115
115
  metadata: Option<String>,
116
+ /// Phase 12.1: optional upsert key. When set, this `remember`
117
+ /// behaves as a keyed write: if a live memory already holds this
118
+ /// `(scope_owner, key)` slot, the prior record is marked
119
+ /// `_mnemo.superseded_by` and a new record is inserted; if the
120
+ /// incoming content, type, importance and user metadata match
121
+ /// the live record exactly, the write is a no-op and nothing is
122
+ /// changed. Prefer `--key` for facts that replace earlier ones
123
+ /// (versions, current status, user preferences). Prints the id
124
+ /// plus one of `added`/`superseded`/`unchanged` on stdout.
125
+ #[arg(long)]
126
+ key: Option<String>,
116
127
  /// Embedder command. Shell-style quoted but **not** executed
117
128
  /// via a shell — e.g. `"python3 embedder.py"` or `"my-embed
118
129
  /// --model=foo"`. Protocol: child reads one JSON string per
@@ -314,6 +325,33 @@ enum Command {
314
325
  /// command can run alongside a writer holding the exclusive lock.
315
326
  #[arg(long)]
316
327
  no_track: bool,
328
+ /// Phase 12.6: restrict recall to this session_id.
329
+ #[arg(long)]
330
+ session: Option<String>,
331
+ /// Phase 12.6: repeatable metadata filter, applied before
332
+ /// scoring. Shorthand forms, matched left-to-right:
333
+ ///
334
+ /// * `key=value` — metadata[key] equals value
335
+ /// * `key:exists` — metadata[key] is present
336
+ /// * `key:in=a,b,c` — metadata[key] is one of the comma-split values
337
+ /// * `key:gte=NUM` / `key:lte=NUM` — numeric lower / upper bound
338
+ ///
339
+ /// Values are parsed as JSON when the leading char is one of
340
+ /// `[`, `{`, `"`, `-`, `0..9`, `t`, `f`, or `n` (true / false /
341
+ /// null); otherwise treated as a string. Multiple `--filter`s
342
+ /// AND together. For complex / nested filters, use the Python
343
+ /// or MCP APIs.
344
+ #[arg(long = "filter", value_name = "EXPR")]
345
+ filter: Vec<String>,
346
+ /// Phase 12.8: cap the total UTF-8 bytes of returned `content`
347
+ /// fields. Stops adding hits once the running sum would exceed
348
+ /// this many bytes. The top-1 hit is always returned, even if
349
+ /// it alone is over budget. A trailing "(truncated: N hits
350
+ /// dropped by --max-bytes)" line goes to stderr whenever the
351
+ /// budget cuts something. Roughly 4 bytes per token for
352
+ /// English text.
353
+ #[arg(long)]
354
+ max_bytes: Option<usize>,
317
355
  /// Embedder command for `--text` (same contract as
318
356
  /// `mnemo remember --embed-cmd`). Ignored when `--query` /
319
357
  /// `--query-file` is used.
@@ -337,6 +375,71 @@ enum Command {
337
375
  #[arg(long, default_value = "demo.mnemo")]
338
376
  path: String,
339
377
  },
378
+ /// Edit a memory in place (Phase 12.1). Keeps the ULID, `created_at`
379
+ /// and access stats; any of `--text`, `--importance`, `--metadata`,
380
+ /// `--ttl-secs` may change. `--text` re-embeds through the registered
381
+ /// embedder (`--embed-cmd` + `--embed-name` required). An identical
382
+ /// patch is a no-op and prints `unchanged`.
383
+ Update {
384
+ /// Path to the `.mnemo` file.
385
+ path: String,
386
+ /// ULID of the memory to update.
387
+ id: String,
388
+ /// New content text; re-embeds through the embedder you supply
389
+ /// via `--embed-cmd` + `--embed-name`.
390
+ #[arg(long)]
391
+ text: Option<String>,
392
+ /// New importance in `[0, 1]`.
393
+ #[arg(long)]
394
+ importance: Option<f32>,
395
+ /// Replace user-visible metadata with this JSON object. Reserved
396
+ /// `_mnemo.*` keys on the record are preserved. Pass `{}` to
397
+ /// clear user metadata.
398
+ #[arg(long)]
399
+ metadata: Option<String>,
400
+ /// Set the TTL (seconds). Pass `--clear-ttl` to drop any
401
+ /// existing TTL instead.
402
+ #[arg(long, conflicts_with = "clear_ttl")]
403
+ ttl_secs: Option<i64>,
404
+ /// Clear any TTL on this memory.
405
+ #[arg(long)]
406
+ clear_ttl: bool,
407
+ /// Embedder command for `--text` (same contract as
408
+ /// `mnemo remember --embed-cmd`).
409
+ #[arg(long, requires = "text")]
410
+ embed_cmd: Option<String>,
411
+ /// Embedder identity for `--text`; must match the manifest.
412
+ #[arg(long, requires = "text")]
413
+ embed_name: Option<String>,
414
+ /// Whether the embedder returns unit-normalized vectors.
415
+ #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
416
+ embed_normalize: bool,
417
+ /// Per-request embedder timeout in seconds.
418
+ #[arg(long, default_value_t = 60)]
419
+ embed_timeout: u64,
420
+ #[arg(long)]
421
+ passphrase: Option<String>,
422
+ },
423
+ /// Walk the full chain for a keyed slot (Phase 12.1), newest first.
424
+ /// Entry 0 is the live record (or empty if the slot is empty);
425
+ /// subsequent entries are the superseded history.
426
+ History {
427
+ /// Path to the `.mnemo` file.
428
+ path: String,
429
+ /// Keyed slot name (passed to `mnemo remember --key` /
430
+ /// `remember_keyed`).
431
+ #[arg(long)]
432
+ key: String,
433
+ /// Query the private slot for this agent. Omit for the shared
434
+ /// slot (one per file).
435
+ #[arg(long)]
436
+ agent: Option<String>,
437
+ /// Output format.
438
+ #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
439
+ format: OutputFormat,
440
+ #[arg(long)]
441
+ passphrase: Option<String>,
442
+ },
340
443
  /// List the restorable snapshots (one per committed flush).
341
444
  Snapshots {
342
445
  /// Path to the `.mnemo` file.
@@ -600,6 +703,82 @@ fn parse_ulid(s: &str) -> std::result::Result<Ulid, String> {
600
703
  Ulid::from_string(s.trim()).map_err(|e| format!("bad ULID '{s}': {e}"))
601
704
  }
602
705
 
706
+ /// Phase 12.6: parse one `--filter` expression and append it to `f`.
707
+ ///
708
+ /// Grammar (left-to-right first match wins):
709
+ ///
710
+ /// * `key:exists` → [`FilterTerm::Exists`]
711
+ /// * `key:in=a,b,c` → [`FilterTerm::In`] over the comma-split values
712
+ /// * `key:gte=NUM` → [`FilterTerm::Range`] with `min = Some(NUM)`
713
+ /// * `key:lte=NUM` → [`FilterTerm::Range`] with `max = Some(NUM)`
714
+ /// * `key=value` → [`FilterTerm::Eq`] with the value parsed below
715
+ ///
716
+ /// Values are tried as JSON first (so numbers, booleans, null, arrays
717
+ /// and quoted strings round-trip through serde cleanly); anything else
718
+ /// is treated as a plain string.
719
+ fn parse_filter_expr(
720
+ expr: &str,
721
+ f: mnemo_engine::Filter,
722
+ ) -> std::result::Result<mnemo_engine::Filter, String> {
723
+ // `key:exists` — no `=` at all.
724
+ if let Some(key) = expr.strip_suffix(":exists") {
725
+ if key.is_empty() {
726
+ return Err(format!("empty key in --filter '{expr}'"));
727
+ }
728
+ return Ok(f.metadata_exists(key.to_string()));
729
+ }
730
+ // Everything else needs a `=`.
731
+ let (lhs, rhs) = expr
732
+ .split_once('=')
733
+ .ok_or_else(|| format!("bad --filter '{expr}': expected key=value or key:op=value"))?;
734
+
735
+ // Split off a `:op` suffix on the lhs (e.g. `score:gte`).
736
+ let (key, op) = match lhs.split_once(':') {
737
+ Some((k, o)) => (k, Some(o)),
738
+ None => (lhs, None),
739
+ };
740
+ if key.is_empty() {
741
+ return Err(format!("empty key in --filter '{expr}'"));
742
+ }
743
+
744
+ match op {
745
+ Some("in") => {
746
+ let values: Vec<serde_json::Value> = rhs
747
+ .split(',')
748
+ .map(|s| parse_filter_value(s.trim()))
749
+ .collect();
750
+ Ok(f.metadata_in(key.to_string(), values))
751
+ }
752
+ Some("gte") => {
753
+ let n: f64 = rhs
754
+ .parse()
755
+ .map_err(|e| format!("bad :gte number in --filter '{expr}': {e}"))?;
756
+ Ok(f.metadata_range(key.to_string(), Some(n), None))
757
+ }
758
+ Some("lte") => {
759
+ let n: f64 = rhs
760
+ .parse()
761
+ .map_err(|e| format!("bad :lte number in --filter '{expr}': {e}"))?;
762
+ Ok(f.metadata_range(key.to_string(), None, Some(n)))
763
+ }
764
+ Some(other) => Err(format!(
765
+ "unknown operator ':{other}' in --filter '{expr}' (want :exists, :in, :gte, :lte)"
766
+ )),
767
+ None => Ok(f.metadata_eq(key.to_string(), parse_filter_value(rhs))),
768
+ }
769
+ }
770
+
771
+ /// Parse one filter value. Try JSON first so numbers, booleans, null and
772
+ /// quoted strings deserialize cleanly; otherwise fall back to a plain
773
+ /// string.
774
+ fn parse_filter_value(s: &str) -> serde_json::Value {
775
+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(s) {
776
+ v
777
+ } else {
778
+ serde_json::Value::String(s.to_string())
779
+ }
780
+ }
781
+
603
782
  fn parse_memory_types(s: &str) -> std::result::Result<Vec<MemoryType>, String> {
604
783
  s.split(',')
605
784
  .map(|t| t.trim())
@@ -970,6 +1149,7 @@ fn run() -> std::result::Result<(), String> {
970
1149
  importance,
971
1150
  agent,
972
1151
  metadata,
1152
+ key,
973
1153
  embed_cmd,
974
1154
  embed_name,
975
1155
  embed_normalize,
@@ -1027,9 +1207,33 @@ fn run() -> std::result::Result<(), String> {
1027
1207
  }
1028
1208
  // (Scope defaults to Private; add `--shared` later if the
1029
1209
  // CLI needs to opt into Scope::Shared.)
1030
- let id = db.remember(memory).map_err(fmt)?;
1031
- db.flush().map_err(fmt)?;
1032
- println!("{id}");
1210
+ //
1211
+ // Phase 12.1: when `--key` is given, take the keyed-upsert
1212
+ // path (supersede / no-op / add), and print `id\toutcome`
1213
+ // so scripts can distinguish the three states. Without
1214
+ // `--key`, keep the original single-ULID stdout for
1215
+ // backward compatibility.
1216
+ match key {
1217
+ None => {
1218
+ let id = db.remember(memory).map_err(fmt)?;
1219
+ db.flush().map_err(fmt)?;
1220
+ println!("{id}");
1221
+ }
1222
+ Some(k) => {
1223
+ let (id, outcome) = db.remember_keyed(memory, &k).map_err(fmt)?;
1224
+ db.flush().map_err(fmt)?;
1225
+ let outcome_str = match outcome {
1226
+ mnemo_engine::WriteOutcome::Added => "added",
1227
+ mnemo_engine::WriteOutcome::Superseded => "superseded",
1228
+ mnemo_engine::WriteOutcome::Unchanged => "unchanged",
1229
+ // `Updated` isn't reachable on a keyed remember —
1230
+ // that's the `mnemo update` path. Treat it as
1231
+ // `superseded` so the enum match stays total.
1232
+ mnemo_engine::WriteOutcome::Updated => "superseded",
1233
+ };
1234
+ println!("{id}\t{outcome_str}");
1235
+ }
1236
+ }
1033
1237
  }
1034
1238
  Command::Index {
1035
1239
  path,
@@ -1324,6 +1528,9 @@ fn run() -> std::result::Result<(), String> {
1324
1528
  n_probe,
1325
1529
  n_rerank,
1326
1530
  no_track,
1531
+ session,
1532
+ filter,
1533
+ max_bytes,
1327
1534
  embed_cmd,
1328
1535
  embed_name,
1329
1536
  embed_normalize,
@@ -1422,6 +1629,20 @@ fn run() -> std::result::Result<(), String> {
1422
1629
  if let Some(n) = n_rerank {
1423
1630
  req = req.n_rerank(n);
1424
1631
  }
1632
+ // Phase 12.6: parse --session and the repeatable --filter
1633
+ // expressions into a single `Filter`. Empty filter == no
1634
+ // constraints.
1635
+ let mut f = mnemo_engine::Filter::default();
1636
+ if let Some(s) = session {
1637
+ f = f.with_session(s);
1638
+ }
1639
+ for expr in filter {
1640
+ f = parse_filter_expr(&expr, f)?;
1641
+ }
1642
+ req = req.filter(f);
1643
+ if let Some(b) = max_bytes {
1644
+ req = req.max_bytes(b);
1645
+ }
1425
1646
 
1426
1647
  // If the vector branch didn't pre-open, open now with the
1427
1648
  // same fallback semantics.
@@ -1436,7 +1657,7 @@ fn run() -> std::result::Result<(), String> {
1436
1657
  if effective_no_track {
1437
1658
  req = req.track_access(false);
1438
1659
  }
1439
- let hits = db.recall(&req).map_err(fmt)?;
1660
+ let resp = db.recall_budgeted(&req).map_err(fmt)?;
1440
1661
  // R-001.4: a tracking recall mutates the catalog's
1441
1662
  // `accessed_at` / `access_count` in memory. Flush before
1442
1663
  // exit so the bumps reach disk — otherwise the usage
@@ -1447,9 +1668,157 @@ fn run() -> std::result::Result<(), String> {
1447
1668
  if !effective_no_track {
1448
1669
  db.flush().map_err(fmt)?;
1449
1670
  }
1450
- print_recall_hits(&hits, format);
1671
+ print_recall_hits(&resp.hits, format);
1672
+ // Phase 12.8: if the max_bytes budget cut anything, say
1673
+ // so on stderr so pipelines / scripts know the result is
1674
+ // bounded. The stdout format stays unchanged so existing
1675
+ // parsers keep working.
1676
+ if resp.truncated {
1677
+ eprintln!(
1678
+ "(truncated: hits dropped by --max-bytes; rerun with a larger \
1679
+ budget or smaller --top-k to see more)"
1680
+ );
1681
+ }
1451
1682
  }
1452
1683
  Command::Demo { path } => demo(&path).map_err(fmt)?,
1684
+ Command::Update {
1685
+ path,
1686
+ id,
1687
+ text,
1688
+ importance,
1689
+ metadata,
1690
+ ttl_secs,
1691
+ clear_ttl,
1692
+ embed_cmd,
1693
+ embed_name,
1694
+ embed_normalize,
1695
+ embed_timeout,
1696
+ passphrase: pp,
1697
+ } => {
1698
+ use mnemo_engine::{EmbedCmd, EmbedderIdentity, MemoryPatch, WriteOutcome};
1699
+ let pp = passphrase(&pp)?;
1700
+ let ulid = parse_ulid(&id)?;
1701
+ let mut db = Mnemo::open(&path, &pp).map_err(fmt)?;
1702
+
1703
+ let mut patch = MemoryPatch::default();
1704
+ if let Some(i) = importance {
1705
+ patch.importance = Some(i);
1706
+ }
1707
+ if let Some(meta_str) = metadata {
1708
+ let parsed: serde_json::Value = serde_json::from_str(&meta_str)
1709
+ .map_err(|e| format!("invalid --metadata JSON: {e}"))?;
1710
+ let obj = parsed
1711
+ .as_object()
1712
+ .ok_or_else(|| "--metadata must be a JSON object".to_string())?;
1713
+ patch.metadata = Some(obj.clone());
1714
+ }
1715
+ if clear_ttl {
1716
+ patch.ttl_secs = Some(None);
1717
+ } else if let Some(ttl) = ttl_secs {
1718
+ patch.ttl_secs = Some(Some(ttl));
1719
+ }
1720
+
1721
+ let outcome = match text {
1722
+ Some(t) => {
1723
+ let ecmd = embed_cmd.ok_or_else(|| {
1724
+ "--text requires --embed-cmd and --embed-name".to_string()
1725
+ })?;
1726
+ let ename = embed_name.ok_or_else(|| {
1727
+ "--text requires --embed-cmd and --embed-name".to_string()
1728
+ })?;
1729
+ let identity = EmbedderIdentity {
1730
+ name: ename,
1731
+ dimensions: db.dimensions(),
1732
+ normalize: embed_normalize,
1733
+ };
1734
+ let embedder = EmbedCmd::new(&ecmd, identity)
1735
+ .map_err(fmt)?
1736
+ .with_timeout(std::time::Duration::from_secs(embed_timeout));
1737
+ db.set_embedder(embedder).map_err(fmt)?;
1738
+ db.update_text(&ulid, &t, patch).map_err(fmt)?
1739
+ }
1740
+ None => db.update(&ulid, patch).map_err(fmt)?,
1741
+ };
1742
+ db.flush().map_err(fmt)?;
1743
+ let outcome_str = match outcome {
1744
+ WriteOutcome::Updated => "updated",
1745
+ WriteOutcome::Unchanged => "unchanged",
1746
+ // Not reachable on `update`, but keep the match total.
1747
+ WriteOutcome::Added => "updated",
1748
+ WriteOutcome::Superseded => "updated",
1749
+ };
1750
+ println!("{id}\t{outcome_str}");
1751
+ }
1752
+ Command::History {
1753
+ path,
1754
+ key,
1755
+ agent,
1756
+ format,
1757
+ passphrase: pp,
1758
+ } => {
1759
+ let pp = passphrase(&pp)?;
1760
+ let mut db = Mnemo::open_read_only(&path, &pp).map_err(fmt)?;
1761
+ let chain = db.history(&key, agent.as_deref()).map_err(fmt)?;
1762
+ match format {
1763
+ OutputFormat::Table => {
1764
+ if chain.is_empty() {
1765
+ println!("no history for key={key}");
1766
+ } else {
1767
+ for (i, m) in chain.iter().enumerate() {
1768
+ let state = if i == 0 { "live" } else { "superseded" };
1769
+ println!(
1770
+ "{state:<10} {id} created_at={ct} {content}",
1771
+ id = m.id,
1772
+ ct = m.created_at,
1773
+ content = truncate(&m.content, 80),
1774
+ );
1775
+ }
1776
+ }
1777
+ }
1778
+ OutputFormat::Json => {
1779
+ let arr: Vec<_> = chain
1780
+ .iter()
1781
+ .enumerate()
1782
+ .map(|(i, m)| {
1783
+ let mut v = memory_to_json(m, false);
1784
+ if let Some(obj) = v.as_object_mut() {
1785
+ obj.insert(
1786
+ "state".into(),
1787
+ serde_json::Value::String(
1788
+ (if i == 0 { "live" } else { "superseded" }).into(),
1789
+ ),
1790
+ );
1791
+ }
1792
+ v
1793
+ })
1794
+ .collect();
1795
+ println!(
1796
+ "{}",
1797
+ serde_json::to_string_pretty(
1798
+ &serde_json::json!({ "count": arr.len(), "chain": arr }),
1799
+ )
1800
+ .unwrap_or_else(|_| "{}".into())
1801
+ );
1802
+ }
1803
+ OutputFormat::Jsonl => {
1804
+ for (i, m) in chain.iter().enumerate() {
1805
+ let mut v = memory_to_json(m, false);
1806
+ if let Some(obj) = v.as_object_mut() {
1807
+ obj.insert(
1808
+ "state".into(),
1809
+ serde_json::Value::String(
1810
+ (if i == 0 { "live" } else { "superseded" }).into(),
1811
+ ),
1812
+ );
1813
+ }
1814
+ println!(
1815
+ "{}",
1816
+ serde_json::to_string(&v).unwrap_or_else(|_| "{}".into())
1817
+ );
1818
+ }
1819
+ }
1820
+ }
1821
+ }
1453
1822
  Command::Snapshots {
1454
1823
  path,
1455
1824
  passphrase: pp,
@@ -69,7 +69,11 @@ pub use embed::{Embedder, EmbedderIdentity};
69
69
  pub use embed_cmd::{EmbedCmd, DEFAULT_EMBED_TIMEOUT};
70
70
  pub use error::{MnemoError, Result};
71
71
  pub use index::{IndexConfig, IndexInfo};
72
- pub use memory::{Memory, MemoryType, Metric, Scope, ScoreWeights};
72
+ pub use memory::{
73
+ Filter, FilterTerm, Memory, MemoryPatch, MemoryType, Metric, Scope, ScoreWeights, WriteOutcome,
74
+ MNEMO_META_INVALID_AT, MNEMO_META_KEY, MNEMO_META_NS, MNEMO_META_SUPERSEDED_BY,
75
+ MNEMO_META_SUPERSEDES, MNEMO_META_UPDATED_AT,
76
+ };
73
77
  pub use result_cache::{
74
78
  CacheBudget, CacheFlushPolicy, CachePutOpts, CacheStats, CachedValue, SemanticCachePutOpts,
75
79
  DEFAULT_BATCH_MAX_AGE, DEFAULT_BATCH_MAX_DIRTY, DEFAULT_MAX_BYTES, DEFAULT_MAX_ENTRIES,
@@ -77,7 +81,8 @@ pub use result_cache::{
77
81
  };
78
82
  pub use session::{Role, Session, Turn};
79
83
  pub use store::{
80
- CompactReport, Mnemo, MnemoConfig, RecallRequest, RecallResult, SnapshotInfo, Stats,
84
+ CompactReport, Mnemo, MnemoConfig, RecallRequest, RecallResponse, RecallResult, SnapshotInfo,
85
+ Stats,
81
86
  };
82
87
 
83
88
  /// Re-export of [`ulid::Ulid`], the identifier type used for memories.