mnemo-engine 0.7.0__tar.gz → 0.8.1__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.1}/PKG-INFO +1 -1
  2. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/Cargo.lock +2 -2
  3. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/Cargo.toml +1 -1
  4. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/benches/open.rs +41 -1
  5. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/bin/mnemo.rs +395 -5
  6. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/lib.rs +7 -2
  7. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/mcp.rs +328 -9
  8. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/memory.rs +292 -0
  9. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/store.rs +740 -34
  10. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/tests/cli_smoke.rs +99 -0
  11. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/tests/integration.rs +854 -3
  12. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo-python/Cargo.lock +2 -2
  13. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo-python/Cargo.toml +1 -1
  14. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo-python/src/lib.rs +388 -24
  15. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo-python/test_mnemo.py +52 -0
  16. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/pyproject.toml +1 -1
  17. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/README.md +0 -0
  18. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/.gitignore +0 -0
  19. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/README.md +0 -0
  20. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/benches/cache.rs +0 -0
  21. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/benches/corpus.rs +0 -0
  22. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/benches/embed_overhead.rs +0 -0
  23. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/benches/recall.rs +0 -0
  24. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/benches/write.rs +0 -0
  25. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/deny.toml +0 -0
  26. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/ann_defaults_v0_6_0.rs +0 -0
  27. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/ann_diagnose.rs +0 -0
  28. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/ann_recall_grid.rs +0 -0
  29. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/ann_recall_grid_v2.rs +0 -0
  30. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/embedder_server.py +0 -0
  31. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/file_size_breakdown.rs +0 -0
  32. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/quickstart.rs +0 -0
  33. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/ranking_v2.rs +0 -0
  34. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/examples/session.rs +0 -0
  35. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/cache.rs +0 -0
  36. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/crypto.rs +0 -0
  37. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/embed.rs +0 -0
  38. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/embed_cmd.rs +0 -0
  39. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/error.rs +0 -0
  40. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/format.rs +0 -0
  41. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/index.rs +0 -0
  42. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/pager.rs +0 -0
  43. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/result_cache.rs +0 -0
  44. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/session.rs +0 -0
  45. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/src/wal.rs +0 -0
  46. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/tests/dur1_torn_header.rs +0 -0
  47. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/tests/fix1_correctness_sweep.rs +0 -0
  48. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/tests/proptest_store.proptest-regressions +0 -0
  49. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/tests/proptest_store.rs +0 -0
  50. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo/tests/sec1_nonce_uniqueness.rs +0 -0
  51. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo-python/.gitignore +0 -0
  52. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/mnemo-python/README.md +0 -0
  53. {mnemo_engine-0.7.0 → mnemo_engine-0.8.1}/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.1
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.1"
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.1"
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.1"
14
14
  edition = "2021"
15
15
  rust-version = "1.75"
16
16
  # `benches/corpus.rs` is a shared helper module pulled into real benches
@@ -29,7 +29,10 @@ use mnemo_engine::{Memory, MemoryType, Mnemo};
29
29
 
30
30
  #[path = "corpus.rs"]
31
31
  mod corpus;
32
- use corpus::{fast_kdf_cfg, gen_clustered_vectors, secure_kdf_cfg, DIMENSIONS, PASSPHRASE};
32
+ use corpus::{
33
+ fast_kdf_cfg, gen_clustered_vectors, secure_kdf_cfg, setup_cached_corpus, DIMENSIONS,
34
+ PASSPHRASE,
35
+ };
33
36
 
34
37
  const OPEN_CORPUS_SIZE: usize = 100;
35
38
 
@@ -103,9 +106,46 @@ fn bench_open_latency_secure_kdf(c: &mut Criterion) {
103
106
  group.finish();
104
107
  }
105
108
 
109
+ /// Phase 12.1.1 lane-A DISPATCH remeasure (v0.8.1): open latency on an
110
+ /// **indexed** 10K-memory file with fast KDF. This isolates the
111
+ /// non-KDF cost dominated by catalog + ANN-index load. Pairs with the
112
+ /// 100K variant below so the README's "open ~15 ms" line can be
113
+ /// replaced with numbers that reflect what agents actually pay.
114
+ fn bench_open_latency_indexed_10k(c: &mut Criterion) {
115
+ let cached = setup_cached_corpus(10_000, DIMENSIONS);
116
+ let mut group = c.benchmark_group("open");
117
+ group.sample_size(30);
118
+ group.bench_function("open_latency_indexed_10k", |b| {
119
+ b.iter(|| {
120
+ let db = Mnemo::open(&cached, PASSPHRASE).expect("open");
121
+ black_box(db);
122
+ });
123
+ });
124
+ group.finish();
125
+ }
126
+
127
+ /// Phase 12.1.1 lane-A DISPATCH remeasure (v0.8.1): open latency on an
128
+ /// **indexed** 100K-memory file with fast KDF. This is the number
129
+ /// Planner-A called out as "~115 ms in my sandbox" that doesn't
130
+ /// regress v0.7.0 → v0.8.0 but needs its own README mention.
131
+ fn bench_open_latency_indexed_100k(c: &mut Criterion) {
132
+ let cached = setup_cached_corpus(100_000, DIMENSIONS);
133
+ let mut group = c.benchmark_group("open");
134
+ group.sample_size(20);
135
+ group.bench_function("open_latency_indexed_100k", |b| {
136
+ b.iter(|| {
137
+ let db = Mnemo::open(&cached, PASSPHRASE).expect("open");
138
+ black_box(db);
139
+ });
140
+ });
141
+ group.finish();
142
+ }
143
+
106
144
  criterion_group!(
107
145
  open_benches,
108
146
  bench_open_latency_fast_kdf,
109
147
  bench_open_latency_secure_kdf,
148
+ bench_open_latency_indexed_10k,
149
+ bench_open_latency_indexed_100k,
110
150
  );
111
151
  criterion_main!(open_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,79 @@ 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. Slot resolution
426
+ /// matches `mnemo remember --key`: without `--agent` or `--shared`,
427
+ /// walks the default agent's private slot (v0.8.1 bugfix); pass
428
+ /// `--shared` for the shared slot.
429
+ History {
430
+ /// Path to the `.mnemo` file.
431
+ path: String,
432
+ /// Keyed slot name (passed to `mnemo remember --key` /
433
+ /// `remember_keyed`).
434
+ #[arg(long)]
435
+ key: String,
436
+ /// Query the private slot for this agent. Omit for the default
437
+ /// agent's private slot (pre-v0.8.1 this flag was required for
438
+ /// a working chain; it's now optional).
439
+ #[arg(long, conflicts_with = "shared")]
440
+ agent: Option<String>,
441
+ /// Query the shared slot (one per file across every agent)
442
+ /// instead of a private slot. Mutually exclusive with `--agent`.
443
+ #[arg(long, conflicts_with = "agent")]
444
+ shared: bool,
445
+ /// Output format.
446
+ #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
447
+ format: OutputFormat,
448
+ #[arg(long)]
449
+ passphrase: Option<String>,
450
+ },
340
451
  /// List the restorable snapshots (one per committed flush).
341
452
  Snapshots {
342
453
  /// Path to the `.mnemo` file.
@@ -600,6 +711,82 @@ fn parse_ulid(s: &str) -> std::result::Result<Ulid, String> {
600
711
  Ulid::from_string(s.trim()).map_err(|e| format!("bad ULID '{s}': {e}"))
601
712
  }
602
713
 
714
+ /// Phase 12.6: parse one `--filter` expression and append it to `f`.
715
+ ///
716
+ /// Grammar (left-to-right first match wins):
717
+ ///
718
+ /// * `key:exists` → [`FilterTerm::Exists`]
719
+ /// * `key:in=a,b,c` → [`FilterTerm::In`] over the comma-split values
720
+ /// * `key:gte=NUM` → [`FilterTerm::Range`] with `min = Some(NUM)`
721
+ /// * `key:lte=NUM` → [`FilterTerm::Range`] with `max = Some(NUM)`
722
+ /// * `key=value` → [`FilterTerm::Eq`] with the value parsed below
723
+ ///
724
+ /// Values are tried as JSON first (so numbers, booleans, null, arrays
725
+ /// and quoted strings round-trip through serde cleanly); anything else
726
+ /// is treated as a plain string.
727
+ fn parse_filter_expr(
728
+ expr: &str,
729
+ f: mnemo_engine::Filter,
730
+ ) -> std::result::Result<mnemo_engine::Filter, String> {
731
+ // `key:exists` — no `=` at all.
732
+ if let Some(key) = expr.strip_suffix(":exists") {
733
+ if key.is_empty() {
734
+ return Err(format!("empty key in --filter '{expr}'"));
735
+ }
736
+ return Ok(f.metadata_exists(key.to_string()));
737
+ }
738
+ // Everything else needs a `=`.
739
+ let (lhs, rhs) = expr
740
+ .split_once('=')
741
+ .ok_or_else(|| format!("bad --filter '{expr}': expected key=value or key:op=value"))?;
742
+
743
+ // Split off a `:op` suffix on the lhs (e.g. `score:gte`).
744
+ let (key, op) = match lhs.split_once(':') {
745
+ Some((k, o)) => (k, Some(o)),
746
+ None => (lhs, None),
747
+ };
748
+ if key.is_empty() {
749
+ return Err(format!("empty key in --filter '{expr}'"));
750
+ }
751
+
752
+ match op {
753
+ Some("in") => {
754
+ let values: Vec<serde_json::Value> = rhs
755
+ .split(',')
756
+ .map(|s| parse_filter_value(s.trim()))
757
+ .collect();
758
+ Ok(f.metadata_in(key.to_string(), values))
759
+ }
760
+ Some("gte") => {
761
+ let n: f64 = rhs
762
+ .parse()
763
+ .map_err(|e| format!("bad :gte number in --filter '{expr}': {e}"))?;
764
+ Ok(f.metadata_range(key.to_string(), Some(n), None))
765
+ }
766
+ Some("lte") => {
767
+ let n: f64 = rhs
768
+ .parse()
769
+ .map_err(|e| format!("bad :lte number in --filter '{expr}': {e}"))?;
770
+ Ok(f.metadata_range(key.to_string(), None, Some(n)))
771
+ }
772
+ Some(other) => Err(format!(
773
+ "unknown operator ':{other}' in --filter '{expr}' (want :exists, :in, :gte, :lte)"
774
+ )),
775
+ None => Ok(f.metadata_eq(key.to_string(), parse_filter_value(rhs))),
776
+ }
777
+ }
778
+
779
+ /// Parse one filter value. Try JSON first so numbers, booleans, null and
780
+ /// quoted strings deserialize cleanly; otherwise fall back to a plain
781
+ /// string.
782
+ fn parse_filter_value(s: &str) -> serde_json::Value {
783
+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(s) {
784
+ v
785
+ } else {
786
+ serde_json::Value::String(s.to_string())
787
+ }
788
+ }
789
+
603
790
  fn parse_memory_types(s: &str) -> std::result::Result<Vec<MemoryType>, String> {
604
791
  s.split(',')
605
792
  .map(|t| t.trim())
@@ -970,6 +1157,7 @@ fn run() -> std::result::Result<(), String> {
970
1157
  importance,
971
1158
  agent,
972
1159
  metadata,
1160
+ key,
973
1161
  embed_cmd,
974
1162
  embed_name,
975
1163
  embed_normalize,
@@ -1027,9 +1215,33 @@ fn run() -> std::result::Result<(), String> {
1027
1215
  }
1028
1216
  // (Scope defaults to Private; add `--shared` later if the
1029
1217
  // 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}");
1218
+ //
1219
+ // Phase 12.1: when `--key` is given, take the keyed-upsert
1220
+ // path (supersede / no-op / add), and print `id\toutcome`
1221
+ // so scripts can distinguish the three states. Without
1222
+ // `--key`, keep the original single-ULID stdout for
1223
+ // backward compatibility.
1224
+ match key {
1225
+ None => {
1226
+ let id = db.remember(memory).map_err(fmt)?;
1227
+ db.flush().map_err(fmt)?;
1228
+ println!("{id}");
1229
+ }
1230
+ Some(k) => {
1231
+ let (id, outcome) = db.remember_keyed(memory, &k).map_err(fmt)?;
1232
+ db.flush().map_err(fmt)?;
1233
+ let outcome_str = match outcome {
1234
+ mnemo_engine::WriteOutcome::Added => "added",
1235
+ mnemo_engine::WriteOutcome::Superseded => "superseded",
1236
+ mnemo_engine::WriteOutcome::Unchanged => "unchanged",
1237
+ // `Updated` isn't reachable on a keyed remember —
1238
+ // that's the `mnemo update` path. Treat it as
1239
+ // `superseded` so the enum match stays total.
1240
+ mnemo_engine::WriteOutcome::Updated => "superseded",
1241
+ };
1242
+ println!("{id}\t{outcome_str}");
1243
+ }
1244
+ }
1033
1245
  }
1034
1246
  Command::Index {
1035
1247
  path,
@@ -1324,6 +1536,9 @@ fn run() -> std::result::Result<(), String> {
1324
1536
  n_probe,
1325
1537
  n_rerank,
1326
1538
  no_track,
1539
+ session,
1540
+ filter,
1541
+ max_bytes,
1327
1542
  embed_cmd,
1328
1543
  embed_name,
1329
1544
  embed_normalize,
@@ -1422,6 +1637,20 @@ fn run() -> std::result::Result<(), String> {
1422
1637
  if let Some(n) = n_rerank {
1423
1638
  req = req.n_rerank(n);
1424
1639
  }
1640
+ // Phase 12.6: parse --session and the repeatable --filter
1641
+ // expressions into a single `Filter`. Empty filter == no
1642
+ // constraints.
1643
+ let mut f = mnemo_engine::Filter::default();
1644
+ if let Some(s) = session {
1645
+ f = f.with_session(s);
1646
+ }
1647
+ for expr in filter {
1648
+ f = parse_filter_expr(&expr, f)?;
1649
+ }
1650
+ req = req.filter(f);
1651
+ if let Some(b) = max_bytes {
1652
+ req = req.max_bytes(b);
1653
+ }
1425
1654
 
1426
1655
  // If the vector branch didn't pre-open, open now with the
1427
1656
  // same fallback semantics.
@@ -1436,7 +1665,7 @@ fn run() -> std::result::Result<(), String> {
1436
1665
  if effective_no_track {
1437
1666
  req = req.track_access(false);
1438
1667
  }
1439
- let hits = db.recall(&req).map_err(fmt)?;
1668
+ let resp = db.recall_budgeted(&req).map_err(fmt)?;
1440
1669
  // R-001.4: a tracking recall mutates the catalog's
1441
1670
  // `accessed_at` / `access_count` in memory. Flush before
1442
1671
  // exit so the bumps reach disk — otherwise the usage
@@ -1447,9 +1676,170 @@ fn run() -> std::result::Result<(), String> {
1447
1676
  if !effective_no_track {
1448
1677
  db.flush().map_err(fmt)?;
1449
1678
  }
1450
- print_recall_hits(&hits, format);
1679
+ print_recall_hits(&resp.hits, format);
1680
+ // Phase 12.8: if the max_bytes budget cut anything, say
1681
+ // so on stderr so pipelines / scripts know the result is
1682
+ // bounded. The stdout format stays unchanged so existing
1683
+ // parsers keep working.
1684
+ if resp.truncated {
1685
+ eprintln!(
1686
+ "(truncated: hits dropped by --max-bytes; rerun with a larger \
1687
+ budget or smaller --top-k to see more)"
1688
+ );
1689
+ }
1451
1690
  }
1452
1691
  Command::Demo { path } => demo(&path).map_err(fmt)?,
1692
+ Command::Update {
1693
+ path,
1694
+ id,
1695
+ text,
1696
+ importance,
1697
+ metadata,
1698
+ ttl_secs,
1699
+ clear_ttl,
1700
+ embed_cmd,
1701
+ embed_name,
1702
+ embed_normalize,
1703
+ embed_timeout,
1704
+ passphrase: pp,
1705
+ } => {
1706
+ use mnemo_engine::{EmbedCmd, EmbedderIdentity, MemoryPatch, WriteOutcome};
1707
+ let pp = passphrase(&pp)?;
1708
+ let ulid = parse_ulid(&id)?;
1709
+ let mut db = Mnemo::open(&path, &pp).map_err(fmt)?;
1710
+
1711
+ let mut patch = MemoryPatch::default();
1712
+ if let Some(i) = importance {
1713
+ patch.importance = Some(i);
1714
+ }
1715
+ if let Some(meta_str) = metadata {
1716
+ let parsed: serde_json::Value = serde_json::from_str(&meta_str)
1717
+ .map_err(|e| format!("invalid --metadata JSON: {e}"))?;
1718
+ let obj = parsed
1719
+ .as_object()
1720
+ .ok_or_else(|| "--metadata must be a JSON object".to_string())?;
1721
+ patch.metadata = Some(obj.clone());
1722
+ }
1723
+ if clear_ttl {
1724
+ patch.ttl_secs = Some(None);
1725
+ } else if let Some(ttl) = ttl_secs {
1726
+ patch.ttl_secs = Some(Some(ttl));
1727
+ }
1728
+
1729
+ let outcome = match text {
1730
+ Some(t) => {
1731
+ let ecmd = embed_cmd.ok_or_else(|| {
1732
+ "--text requires --embed-cmd and --embed-name".to_string()
1733
+ })?;
1734
+ let ename = embed_name.ok_or_else(|| {
1735
+ "--text requires --embed-cmd and --embed-name".to_string()
1736
+ })?;
1737
+ let identity = EmbedderIdentity {
1738
+ name: ename,
1739
+ dimensions: db.dimensions(),
1740
+ normalize: embed_normalize,
1741
+ };
1742
+ let embedder = EmbedCmd::new(&ecmd, identity)
1743
+ .map_err(fmt)?
1744
+ .with_timeout(std::time::Duration::from_secs(embed_timeout));
1745
+ db.set_embedder(embedder).map_err(fmt)?;
1746
+ db.update_text(&ulid, &t, patch).map_err(fmt)?
1747
+ }
1748
+ None => db.update(&ulid, patch).map_err(fmt)?,
1749
+ };
1750
+ db.flush().map_err(fmt)?;
1751
+ let outcome_str = match outcome {
1752
+ WriteOutcome::Updated => "updated",
1753
+ WriteOutcome::Unchanged => "unchanged",
1754
+ // Not reachable on `update`, but keep the match total.
1755
+ WriteOutcome::Added => "updated",
1756
+ WriteOutcome::Superseded => "updated",
1757
+ };
1758
+ println!("{id}\t{outcome_str}");
1759
+ }
1760
+ Command::History {
1761
+ path,
1762
+ key,
1763
+ agent,
1764
+ shared,
1765
+ format,
1766
+ passphrase: pp,
1767
+ } => {
1768
+ use mnemo_engine::KeyScope;
1769
+ let pp = passphrase(&pp)?;
1770
+ let mut db = Mnemo::open_read_only(&path, &pp).map_err(fmt)?;
1771
+ // v0.8.1 bugfix: default slot matches keyed remember with
1772
+ // the same arguments. No `--shared`, no `--agent` → default
1773
+ // agent's private slot.
1774
+ let scope = if shared {
1775
+ KeyScope::Shared
1776
+ } else {
1777
+ match agent {
1778
+ Some(a) => KeyScope::Private(a),
1779
+ None => KeyScope::private_default(),
1780
+ }
1781
+ };
1782
+ let chain = db.history_in(&key, scope).map_err(fmt)?;
1783
+ match format {
1784
+ OutputFormat::Table => {
1785
+ if chain.is_empty() {
1786
+ println!("no history for key={key}");
1787
+ } else {
1788
+ for (i, m) in chain.iter().enumerate() {
1789
+ let state = if i == 0 { "live" } else { "superseded" };
1790
+ println!(
1791
+ "{state:<10} {id} created_at={ct} {content}",
1792
+ id = m.id,
1793
+ ct = m.created_at,
1794
+ content = truncate(&m.content, 80),
1795
+ );
1796
+ }
1797
+ }
1798
+ }
1799
+ OutputFormat::Json => {
1800
+ let arr: Vec<_> = chain
1801
+ .iter()
1802
+ .enumerate()
1803
+ .map(|(i, m)| {
1804
+ let mut v = memory_to_json(m, false);
1805
+ if let Some(obj) = v.as_object_mut() {
1806
+ obj.insert(
1807
+ "state".into(),
1808
+ serde_json::Value::String(
1809
+ (if i == 0 { "live" } else { "superseded" }).into(),
1810
+ ),
1811
+ );
1812
+ }
1813
+ v
1814
+ })
1815
+ .collect();
1816
+ println!(
1817
+ "{}",
1818
+ serde_json::to_string_pretty(
1819
+ &serde_json::json!({ "count": arr.len(), "chain": arr }),
1820
+ )
1821
+ .unwrap_or_else(|_| "{}".into())
1822
+ );
1823
+ }
1824
+ OutputFormat::Jsonl => {
1825
+ for (i, m) in chain.iter().enumerate() {
1826
+ let mut v = memory_to_json(m, false);
1827
+ if let Some(obj) = v.as_object_mut() {
1828
+ obj.insert(
1829
+ "state".into(),
1830
+ serde_json::Value::String(
1831
+ (if i == 0 { "live" } else { "superseded" }).into(),
1832
+ ),
1833
+ );
1834
+ }
1835
+ println!(
1836
+ "{}",
1837
+ serde_json::to_string(&v).unwrap_or_else(|_| "{}".into())
1838
+ );
1839
+ }
1840
+ }
1841
+ }
1842
+ }
1453
1843
  Command::Snapshots {
1454
1844
  path,
1455
1845
  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, KeyScope, Memory, MemoryPatch, MemoryType, Metric, Scope, ScoreWeights,
74
+ WriteOutcome, 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.