relock-memory 0.2.2__tar.gz → 0.3.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 (76) hide show
  1. {relock_memory-0.2.2 → relock_memory-0.3.0}/CHANGELOG.md +75 -0
  2. {relock_memory-0.2.2 → relock_memory-0.3.0}/PKG-INFO +61 -1
  3. {relock_memory-0.2.2 → relock_memory-0.3.0}/README.md +60 -0
  4. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/design.md +17 -6
  5. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/http.md +6 -1
  6. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/openapi.json +32 -2
  7. {relock_memory-0.2.2 → relock_memory-0.3.0}/pyproject.toml +1 -1
  8. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/__init__.py +3 -1
  9. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/_util.py +23 -1
  10. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/cli.py +48 -1
  11. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/episode.py +90 -36
  12. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/integrations/http.py +37 -6
  13. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/integrations/mcp.py +6 -3
  14. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/integrations/toolkit.py +29 -10
  15. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/memory.py +183 -32
  16. relock_memory-0.3.0/src/relock_memory/retrieval.py +222 -0
  17. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/rewriters.py +11 -0
  18. relock_memory-0.3.0/src/relock_memory/stores/postgres.py +160 -0
  19. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/stores/sql.py +323 -43
  20. relock_memory-0.3.0/src/relock_memory/stores/sqlite.py +65 -0
  21. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/types.py +8 -0
  22. {relock_memory-0.2.2 → relock_memory-0.3.0}/tests/test_http.py +32 -0
  23. relock_memory-0.3.0/tests/test_production.py +550 -0
  24. relock_memory-0.2.2/src/relock_memory/retrieval.py +0 -137
  25. relock_memory-0.2.2/src/relock_memory/stores/postgres.py +0 -41
  26. relock_memory-0.2.2/src/relock_memory/stores/sqlite.py +0 -38
  27. {relock_memory-0.2.2 → relock_memory-0.3.0}/.gitignore +0 -0
  28. {relock_memory-0.2.2 → relock_memory-0.3.0}/LICENSE +0 -0
  29. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/assets/architecture.svg +0 -0
  30. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/assets/hero.svg +0 -0
  31. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/assets/lifecycle.svg +0 -0
  32. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/assets/logo.svg +0 -0
  33. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/assets/social.png +0 -0
  34. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/assets/social.svg +0 -0
  35. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/models/DESIGN.md +0 -0
  36. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/models/README.md +0 -0
  37. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/models/by-load.svg +0 -0
  38. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/models/by-model.svg +0 -0
  39. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/models/outcomes.svg +0 -0
  40. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/models/records.csv +0 -0
  41. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/models/summary.json +0 -0
  42. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/structural.md +0 -0
  43. {relock_memory-0.2.2 → relock_memory-0.3.0}/docs/results/structural.svg +0 -0
  44. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/01_quickstart.py +0 -0
  45. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/02_llm_rewriter.py +0 -0
  46. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/03_langgraph_callbacks.py +0 -0
  47. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/http/curl.sh +0 -0
  48. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/http/rust/.gitignore +0 -0
  49. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/http/rust/Cargo.toml +0 -0
  50. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/http/rust/src/main.rs +0 -0
  51. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/http/typescript/demo.ts +0 -0
  52. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/http/typescript/package.json +0 -0
  53. {relock_memory-0.2.2 → relock_memory-0.3.0}/examples/http/typescript/relock.ts +0 -0
  54. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/bench/__init__.py +0 -0
  55. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/bench/agents.py +0 -0
  56. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/bench/cli.py +0 -0
  57. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/bench/harness.py +0 -0
  58. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/bench/report.py +0 -0
  59. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/bench/scenarios.py +0 -0
  60. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/bench/systems.py +0 -0
  61. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/checks.py +0 -0
  62. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/delta.py +0 -0
  63. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/export.py +0 -0
  64. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/integrations/__init__.py +0 -0
  65. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/integrations/langchain.py +0 -0
  66. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/llm.py +0 -0
  67. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/policy.py +0 -0
  68. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/py.typed +0 -0
  69. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/signals.py +0 -0
  70. {relock_memory-0.2.2 → relock_memory-0.3.0}/src/relock_memory/stores/__init__.py +0 -0
  71. {relock_memory-0.2.2 → relock_memory-0.3.0}/tests/conftest.py +0 -0
  72. {relock_memory-0.2.2 → relock_memory-0.3.0}/tests/test_cli_bench.py +0 -0
  73. {relock_memory-0.2.2 → relock_memory-0.3.0}/tests/test_integrations.py +0 -0
  74. {relock_memory-0.2.2 → relock_memory-0.3.0}/tests/test_llm_client.py +0 -0
  75. {relock_memory-0.2.2 → relock_memory-0.3.0}/tests/test_reconsolidation.py +0 -0
  76. {relock_memory-0.2.2 → relock_memory-0.3.0}/tests/test_units.py +0 -0
@@ -1,5 +1,80 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 - 2026-11-28
4
+
5
+ Production hardening: multi-agent attribution, storage robustness, scale, retention and logging.
6
+
7
+ **Breaking:**
8
+
9
+ - A wrapped tool's outcome is attributed only to the episode in the caller's context. The
10
+ fallback to "the only open episode in the process" is gone: it attributed one agent's tool
11
+ calls to another agent's episode. In worker threads, use `ep.run(fn, ...)` or
12
+ `with ep.activate():`.
13
+ - Database failures raise `StoreError` (and lost unique-key races `ConflictError`) instead of raw
14
+ `sqlite3` / `psycopg` exceptions. The driver's exception is chained as the cause.
15
+ - `GET /v1/items` returns a page: at most `limit` items (default 500), with `total` and
16
+ `next_after` (pass it back as `after`). Clients that expect every item in one response must
17
+ follow `next_after`.
18
+ - `policy` is now a keyword of `Memory.episode` (it sets that episode's write policy) instead of
19
+ being stored as metadata.
20
+ - The database schema is v2. The first 0.3 process upgrades a 0.2 database in place; 0.2
21
+ processes keep working against it. On a large Postgres ledger, run `relock init` once at a
22
+ quiet time before rolling out, since the upgrade builds indexes over the events table.
23
+
24
+ **Multiple agents:**
25
+
26
+ - `Episode.activate()` and `Episode.run(fn, ...)` carry an episode into worker threads.
27
+ - Separate `Toolkit` instances keep separate episodes.
28
+ - A wrapped tool that runs outside every episode while others are open logs a warning, once per
29
+ tool.
30
+ - `Memory.episode(policy=...)` and `Toolkit(policy=...)` set trust per agent.
31
+ - `build_server(trust_agent_reports=True)` widens trust for the MCP server's own episodes only.
32
+ Before, it replaced the shared `Memory`'s policy.
33
+
34
+ **Storage:**
35
+
36
+ - Postgres serves concurrent calls from a connection pool (`pool_size`, default 5). It checks idle
37
+ connections before use and discards dropped ones, so after a database restart each pooled
38
+ connection fails at most one call.
39
+ `connect_timeout` defaults to 10 s.
40
+ - Replicas starting together on an empty database no longer race: schema creation takes an
41
+ advisory lock, and an up-to-date database is opened without DDL.
42
+ - `add(exist_ok=True)` holds when several processes seed the same keys at once.
43
+ - A database written by a newer relock is refused with a clear message.
44
+ - SQLite reads no longer queue behind writers in other processes, and several processes can
45
+ create a new database file at once.
46
+
47
+ **Scale:**
48
+
49
+ - After a content change, each process re-reads only the items that changed. At 100,000 items,
50
+ recall right after a change went from about 5 s to 0.2 s.
51
+ - Confirmations no longer reload every item. At 20,000 items, recall after a confirmation went
52
+ from 162 ms to 3 ms.
53
+ - BM25 keeps an incremental inverted index, and `kinds` / `tags` filters reuse it.
54
+ - Long episodes keep only open expectations in memory, so per-call cost stays flat.
55
+ - The embedding cache drops vectors of versions that are no longer active.
56
+
57
+ **Retention:**
58
+
59
+ - `Memory.prune(older_than)` and `relock prune --older-than 30d [--dry-run]` delete old audit
60
+ detail and never touch items or versions. An episode goes only if nothing depends on it.
61
+ Episodes a crashed process left open are marked `abandoned`.
62
+ - `stats` reports open episodes, retrievals and events.
63
+ - Error text, reasons and queries stored in the ledger are capped at 2000 characters.
64
+
65
+ **Logging and audit:**
66
+
67
+ - Every ledger event is logged on the `relock_memory` logger: content changes and failures at
68
+ INFO with ids and a short reason, routine events at DEBUG, payloads only at DEBUG.
69
+ - New `conflict` and `rewrite_deferred` events, so every case where evidence did not produce a
70
+ rewrite leaves a trace. `declined` carries the rewriter's reason, such as an unreachable LLM.
71
+ - A failing `on_event` hook, LLM rewriter failures and fallbacks, and lost database connections
72
+ are logged instead of passing silently. `LLMRewriter.last_error` no longer leaks from one
73
+ request into the next.
74
+ - `episode_open` records the episode's metadata.
75
+ - `relock --log-level` (or `RELOCK_LOG_LEVEL`) logs to stderr, so `relock mcp` can show events
76
+ without disturbing its stdio protocol.
77
+
3
78
  ## 0.2.2 - 2026-11-28
4
79
 
5
80
  Documentation only; no code changes.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: relock-memory
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: Agent memory that fixes the rule that fired, in place and only on trusted evidence, so corrected mistakes don't come back. Python, HTTP (any language), MCP.
5
5
  Project-URL: Homepage, https://github.com/inboxpraveen/relock
6
6
  Project-URL: Repository, https://github.com/inboxpraveen/relock
@@ -430,6 +430,8 @@ relock show orders.fetch [--version 1]
430
430
  relock history orders.fetch # clause-level diffs across versions
431
431
  relock pending orders.fetch # pending evidence vs. the rewrite threshold, and what was blocked
432
432
  relock events --item orders.fetch # audit log: recalls, predictions, gate decisions, rewrites
433
+ relock prune --older-than 30d [--dry-run] # delete old audit detail; items and versions stay
434
+ relock stats # row counts, to watch growth
433
435
  relock rollback orders.fetch 1 # restores v1 as a new version (history is never destroyed)
434
436
  relock edit orders.fetch --replace c2 "Pass dates as YYYY-MM-DD."
435
437
  relock export traces.jsonl # SFT and preference pairs from every rewrite
@@ -439,6 +441,7 @@ relock bench [--mode structural|behavioral|both]
439
441
  ```
440
442
 
441
443
  The database is `--db`, or `$RELOCK_DB`, or `./relock.db`. Postgres URLs work everywhere.
444
+ `--log-level INFO` (or `$RELOCK_LOG_LEVEL`) logs relock events to stderr.
442
445
 
443
446
  ## Configuration
444
447
 
@@ -465,6 +468,63 @@ Storage is SQLite by default (WAL mode, safe across processes) or Postgres with
465
468
  `pip install "relock-memory[postgres]"`. Postgres uses `JSONB` and `TIMESTAMPTZ`, so the ledger is
466
469
  directly queryable. The schema is documented in [docs/design.md](https://github.com/inboxpraveen/relock/blob/main/docs/design.md).
467
470
 
471
+ ## Running in production
472
+
473
+ **Logs and audit.** Every ledger event is logged on the `relock_memory` logger as it is stored.
474
+ Content changes, prediction errors, blocked or declined writes, conflicts and deferred rewrites
475
+ log at INFO, with the episode, item, version and a short reason (for a failure, the first 300
476
+ characters of what went wrong, which can include the tool's error message). Routine recalls and
477
+ confirmations log at DEBUG. Full payloads, such as clause text and complete tool errors, are
478
+ attached to the record as `record.relock_event` only at DEBUG, since they can carry user data. A
479
+ failing `on_event` hook, an LLM rewriter that can't be reached and a lost database connection are
480
+ logged as warnings. `on_event` runs synchronously as each event is stored, so keep it fast or hand
481
+ events to a queue. The full trail stays queryable with `relock events` or SQL; every version keeps
482
+ its delta, reason, author and the error ids that justified it.
483
+
484
+ **Errors.** A database failure raises `relock.StoreError` naming the store, with the driver's
485
+ exception as its cause. A lost connection is discarded and the next call reconnects. A write that
486
+ lost a race to another process raises `relock.ConflictError`; inside an episode it becomes a
487
+ `conflict` decision instead, since the evidence was about a version that no longer exists.
488
+
489
+ **Several agents in one process.** Give each agent its own episode, or its own `Toolkit`. A
490
+ wrapped tool's outcome goes to the episode in the caller's context only: inside `with ep:`, inside
491
+ `with ep.activate():`, or in work submitted with `ep.run(fn, ...)` (plain threads don't inherit
492
+ the context; asyncio tasks do). `mem.episode(task, policy=...)` sets the write policy for one
493
+ agent. A wrapped tool that runs outside every episode is not recorded; if other episodes are
494
+ open at the time, a warning names the tool.
495
+
496
+ **Growth and retention.** Items and versions grow only when memory changes. The audit tables grow
497
+ with use: each wrapped tool call adds an expectation and about two events. Prune them on a
498
+ schedule:
499
+
500
+ ```
501
+ relock prune --older-than 30d --dry-run # counts only
502
+ relock prune --older-than 30d
503
+ ```
504
+
505
+ Pruning deletes an episode's retrievals, expectations, errors and events only when no version was
506
+ written in it and none of its errors is, or may become, evidence for a rewrite. Episodes that must
507
+ stay lose just their per-call confirmations. Episodes a crashed process left open are marked
508
+ `abandoned`; the age must exceed the longest an episode stays open in any replica. SQLite keeps
509
+ its file size until `VACUUM`.
510
+
511
+ **Postgres.** `PostgresStore(dsn, pool_size=5)` serves concurrent calls from a connection pool.
512
+ It checks idle connections before use, replaces ones the server dropped, and fails fast on an
513
+ unreachable host (`connect_timeout` 10 s unless the DSN sets one). Replicas starting together on
514
+ an empty database are safe. The HTTP server keeps open episodes in memory, so with several
515
+ replicas route each episode's requests to the same one ([docs/http.md](https://github.com/inboxpraveen/relock/blob/main/docs/http.md)).
516
+
517
+ **Upgrading from 0.2.** The first 0.3 process to open a 0.2 database upgrades its schema in place.
518
+ On a large Postgres ledger, run `relock init` once at a quiet time first, since the upgrade builds
519
+ indexes over the events table. 0.2 processes keep working against the upgraded database.
520
+
521
+ **Scale.** On one laptop with SQLite: at 20,000 items, recall takes 16 ms, a wrapped tool call
522
+ 2.3 ms, and recall right after a confirmation 2.7 ms. At 100,000 items, recall takes about
523
+ 130 ms, and recall right after another process adds or rewrites an item about 0.2 s, since only
524
+ changed items are re-read. Long episodes stay flat per call. Loading memory costs about 3 KB of
525
+ heap per short item, and the first recall in a new process reads every item: about 1 s at 20,000
526
+ items and 7 s at 100,000.
527
+
468
528
  ## How it relates to other work
469
529
 
470
530
  - **Mem0** maintains memories with add/update/delete operations chosen by an LLM.
@@ -385,6 +385,8 @@ relock show orders.fetch [--version 1]
385
385
  relock history orders.fetch # clause-level diffs across versions
386
386
  relock pending orders.fetch # pending evidence vs. the rewrite threshold, and what was blocked
387
387
  relock events --item orders.fetch # audit log: recalls, predictions, gate decisions, rewrites
388
+ relock prune --older-than 30d [--dry-run] # delete old audit detail; items and versions stay
389
+ relock stats # row counts, to watch growth
388
390
  relock rollback orders.fetch 1 # restores v1 as a new version (history is never destroyed)
389
391
  relock edit orders.fetch --replace c2 "Pass dates as YYYY-MM-DD."
390
392
  relock export traces.jsonl # SFT and preference pairs from every rewrite
@@ -394,6 +396,7 @@ relock bench [--mode structural|behavioral|both]
394
396
  ```
395
397
 
396
398
  The database is `--db`, or `$RELOCK_DB`, or `./relock.db`. Postgres URLs work everywhere.
399
+ `--log-level INFO` (or `$RELOCK_LOG_LEVEL`) logs relock events to stderr.
397
400
 
398
401
  ## Configuration
399
402
 
@@ -420,6 +423,63 @@ Storage is SQLite by default (WAL mode, safe across processes) or Postgres with
420
423
  `pip install "relock-memory[postgres]"`. Postgres uses `JSONB` and `TIMESTAMPTZ`, so the ledger is
421
424
  directly queryable. The schema is documented in [docs/design.md](docs/design.md).
422
425
 
426
+ ## Running in production
427
+
428
+ **Logs and audit.** Every ledger event is logged on the `relock_memory` logger as it is stored.
429
+ Content changes, prediction errors, blocked or declined writes, conflicts and deferred rewrites
430
+ log at INFO, with the episode, item, version and a short reason (for a failure, the first 300
431
+ characters of what went wrong, which can include the tool's error message). Routine recalls and
432
+ confirmations log at DEBUG. Full payloads, such as clause text and complete tool errors, are
433
+ attached to the record as `record.relock_event` only at DEBUG, since they can carry user data. A
434
+ failing `on_event` hook, an LLM rewriter that can't be reached and a lost database connection are
435
+ logged as warnings. `on_event` runs synchronously as each event is stored, so keep it fast or hand
436
+ events to a queue. The full trail stays queryable with `relock events` or SQL; every version keeps
437
+ its delta, reason, author and the error ids that justified it.
438
+
439
+ **Errors.** A database failure raises `relock.StoreError` naming the store, with the driver's
440
+ exception as its cause. A lost connection is discarded and the next call reconnects. A write that
441
+ lost a race to another process raises `relock.ConflictError`; inside an episode it becomes a
442
+ `conflict` decision instead, since the evidence was about a version that no longer exists.
443
+
444
+ **Several agents in one process.** Give each agent its own episode, or its own `Toolkit`. A
445
+ wrapped tool's outcome goes to the episode in the caller's context only: inside `with ep:`, inside
446
+ `with ep.activate():`, or in work submitted with `ep.run(fn, ...)` (plain threads don't inherit
447
+ the context; asyncio tasks do). `mem.episode(task, policy=...)` sets the write policy for one
448
+ agent. A wrapped tool that runs outside every episode is not recorded; if other episodes are
449
+ open at the time, a warning names the tool.
450
+
451
+ **Growth and retention.** Items and versions grow only when memory changes. The audit tables grow
452
+ with use: each wrapped tool call adds an expectation and about two events. Prune them on a
453
+ schedule:
454
+
455
+ ```
456
+ relock prune --older-than 30d --dry-run # counts only
457
+ relock prune --older-than 30d
458
+ ```
459
+
460
+ Pruning deletes an episode's retrievals, expectations, errors and events only when no version was
461
+ written in it and none of its errors is, or may become, evidence for a rewrite. Episodes that must
462
+ stay lose just their per-call confirmations. Episodes a crashed process left open are marked
463
+ `abandoned`; the age must exceed the longest an episode stays open in any replica. SQLite keeps
464
+ its file size until `VACUUM`.
465
+
466
+ **Postgres.** `PostgresStore(dsn, pool_size=5)` serves concurrent calls from a connection pool.
467
+ It checks idle connections before use, replaces ones the server dropped, and fails fast on an
468
+ unreachable host (`connect_timeout` 10 s unless the DSN sets one). Replicas starting together on
469
+ an empty database are safe. The HTTP server keeps open episodes in memory, so with several
470
+ replicas route each episode's requests to the same one ([docs/http.md](docs/http.md)).
471
+
472
+ **Upgrading from 0.2.** The first 0.3 process to open a 0.2 database upgrades its schema in place.
473
+ On a large Postgres ledger, run `relock init` once at a quiet time first, since the upgrade builds
474
+ indexes over the events table. 0.2 processes keep working against the upgraded database.
475
+
476
+ **Scale.** On one laptop with SQLite: at 20,000 items, recall takes 16 ms, a wrapped tool call
477
+ 2.3 ms, and recall right after a confirmation 2.7 ms. At 100,000 items, recall takes about
478
+ 130 ms, and recall right after another process adds or rewrites an item about 0.2 s, since only
479
+ changed items are re-read. Long episodes stay flat per call. Loading memory costs about 3 KB of
480
+ heap per short item, and the first recall in a new process reads every item: about 1 s at 20,000
481
+ items and 7 s at 100,000.
482
+
423
483
  ## How it relates to other work
424
484
 
425
485
  - **Mem0** maintains memories with add/update/delete operations chosen by an LLM.
@@ -97,8 +97,12 @@ inertia with fake "it worked" reports and make a poisoned procedure harder to fi
97
97
 
98
98
  ## Attribution of tool outcomes
99
99
 
100
- A wrapped tool (`@mem.wrap`) or the LangChain callback handler looks up the active episode, using
101
- the context variable first and then the only open episode in the process. It then resolves:
100
+ A wrapped tool (`@mem.wrap`) or the LangChain callback handler looks up the episode active in the
101
+ caller's context (a context variable). Inside `with mem.episode(...)`, `with ep.activate():` and
102
+ `ep.run(fn, ...)` it is that episode; asyncio tasks inherit it, plain worker threads do not. There
103
+ is no process-wide fallback: with several agents in one process, a tool outcome is attributed only
104
+ to the episode of the agent that made the call. A wrapped tool that runs outside every episode
105
+ while some are open is not recorded, and a warning names it (once per tool). It then resolves:
102
106
 
103
107
  1. any open, explicit expectation that names this tool for a labile item;
104
108
  2. otherwise, an automatic `succeeds()` expectation for each labile item whose `tools` contains the
@@ -129,14 +133,20 @@ All tables are prefixed `relock_`. SQLite stores JSON and timestamps as `TEXT`.
129
133
 
130
134
  | table | key columns |
131
135
  |---|---|
132
- | `items` | `id`, `key` (unique), `current_version`, `archived` |
136
+ | `items` | `id`, `key` (unique), `current_version`, `archived`, `rev` (revision of its last content change) |
133
137
  | `versions` | `(item_id, version)` PK, `status`, `title`, `clauses`, `clause_seq`, `tags`, `tools`, `meta`, `alpha`, `beta`, `confirmations`, `failures`, `parent_version`, `superseded_by`, `change_kind`, `delta`, `reason`, `episode_id`, `evidence`, `author` |
134
- | `episodes` | `id`, `task`, `status`, `meta`, `started_at`, `ended_at` |
138
+ | `episodes` | `id`, `task`, `status` (open/closed/abandoned), `meta`, `started_at`, `ended_at` |
135
139
  | `retrievals` | `episode_id`, `item_id`, `version`, `query`, `rank`, `score` (the reactivation trace) |
136
140
  | `expectations` | `id`, `episode_id`, `item_id`, `version`, `statement`, `clause_ids`, `tool`, `check_spec`, `status` (open/confirmed/violated/void), `outcome`, `signal` |
137
141
  | `errors` | `id`, `expectation_id`, `item_id`, `version`, `source`, `error_class`, `weight`, `authoritative`, `diff`, `status` (pending/blocked/cancelled/consumed/stale), `reason` |
138
142
  | `events` | append-only audit log: `type`, `episode_id`, `item_id`, `version`, `data` |
139
- | `meta` | `schema_version`, `revision` (bumped on every content change; used for cross-process cache invalidation) |
143
+ | `meta` | `schema_version` (2), `revision` (bumped on every content change; with `items.rev`, lets each process refresh only the items that changed) |
144
+
145
+ A database from relock 0.2 (schema v1) is upgraded in place by the first 0.3 process that opens
146
+ it. The upgrade adds `items.rev` and some indexes; 0.2 processes keep working against it, and their
147
+ changes are still picked up by time. `Memory.prune` (`relock prune`) deletes old audit detail
148
+ (retrievals, expectations, errors and events of episodes nothing depends on) and never items or
149
+ versions.
140
150
 
141
151
  Example query on Postgres:
142
152
 
@@ -160,7 +170,8 @@ WHERE v.change_kind = 'reconsolidate' AND v.created_at > now() - interval '7 day
160
170
  | Fake confirmations make a poisoned item sticky | Only trusted confirmations raise confidence and inertia. |
161
171
  | Rewriter edits unrelated parts of an item | `edit_scope="cited"` locks every clause the failed prediction did not rely on, when it cites clauses. Uncited predictions, such as `@mem.wrap` auto-expectations, leave every clause editable, so the choice falls to the rewriter. `HintRewriter` picks the clause most similar to the correction. Cite clauses when you use an LLM rewriter. |
162
172
  | Repeated rewrites collapse an item | Edits are small clause deltas (`max_ops`, `max_clause_chars`); one rewrite per item per episode. |
163
- | Concurrent episodes overwrite each other | Compare-and-swap on `current_version`; stale evidence becomes `CONFLICT`. |
173
+ | Concurrent episodes overwrite each other | Compare-and-swap on `current_version`; stale evidence becomes `CONFLICT`, recorded as a `conflict` event. |
174
+ | One agent's tool outcome rewrites another agent's memory | Outcomes go only to the episode in the caller's context; there is no process-wide fallback. `Toolkit` instances keep separate episodes, and `policy=` sets trust per episode. |
164
175
  | A bad rewrite slips through | Full version history; `rollback` restores any version as a new version; every decision is in `relock_events`. |
165
176
  | Late edits after the context is gone | Closed episodes raise `EpisodeClosedError` on any write. Episodes the toolkit or MCP server opened themselves are re-locked after `idle_timeout` seconds (default 1800) without a call, so a client that never ends its task does not keep items editable. |
166
177
  | "The user said so" | `Signal.user` and `Episode.correct` default to `authenticated=False` and are blocked; the application must vouch for the user explicitly. |
@@ -56,7 +56,7 @@ Items are attributed to a tool through the `tools` list given when the item is a
56
56
  | request | use |
57
57
  |---|---|
58
58
  | `POST /v1/items` | Add a procedure: `title`, `clauses`, optional `key`, `tools`, `exist_ok`. |
59
- | `GET /v1/items`, `GET /v1/items/{ref}`, `GET /v1/items/{ref}/history` | Read active items, one item, or every version of it. |
59
+ | `GET /v1/items`, `GET /v1/items/{ref}`, `GET /v1/items/{ref}/history` | Read active items (a page at a time: `limit`, default 500, and `after`, the previous page's `next_after`), one item, or every version of it. |
60
60
  | `POST /v1/episodes/{id}/use` | Load an item by key, which makes it editable without a search. |
61
61
  | `POST /v1/episodes/{id}/expect` | Record an explicit prediction. `clauses` limits which clauses can be rewritten; `tool` binds the prediction to a tool. |
62
62
  | `POST /v1/episodes/{id}/observe` | Resolve one expectation. `source` is `tool` (default), `verifier`, `agent` or `environment`. |
@@ -98,6 +98,11 @@ Errors are JSON, `{"error": {"code": "...", "message": "..."}}`, with these stat
98
98
  framings is refused.
99
99
  - **Shutdown:** on `SIGTERM` (for example `docker stop`) the server re-locks every open episode
100
100
  and closes the database before exiting.
101
+ - **Logs:** the server logs requests and every ledger event at INFO to stderr: rewrites,
102
+ prediction errors, blocked or declined writes and conflicts, each with episode and item ids.
103
+ Set `RELOCK_LOG_LEVEL=DEBUG` to include event payloads, or `WARNING` to keep only problems.
104
+ - **Retention:** the ledger grows with every tool call. Run `relock prune --older-than 30d`
105
+ from a scheduled job (see the README's production notes).
101
106
  - **Replicas:** open episodes live in the server process. With more than one replica on a shared
102
107
  Postgres database, send each episode's requests to the same replica, for example with sticky
103
108
  routing on the episode id.
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.1.0",
3
3
  "info": {
4
4
  "title": "relock",
5
- "version": "0.2.2",
5
+ "version": "0.3.0",
6
6
  "summary": "Agent memory that fixes the rule that fired, in place and only on trusted evidence, so corrected mistakes don't come back.",
7
7
  "description": "Language-neutral API for relock. Call it from your harness, the code that runs tools and checks results, never from the model. Loop: POST /episodes, /recall (put `context` in the prompt), report each tool call with /tool-result, then /close. Authenticate with `Authorization: Bearer $RELOCK_TOKEN` when the server has a token.",
8
8
  "license": {
@@ -326,7 +326,27 @@
326
326
  },
327
327
  "/v1/items": {
328
328
  "get": {
329
- "summary": "List active items",
329
+ "summary": "List active items, ordered by id, a page at a time",
330
+ "parameters": [
331
+ {
332
+ "name": "limit",
333
+ "in": "query",
334
+ "schema": {
335
+ "type": "integer",
336
+ "default": 500,
337
+ "minimum": 1,
338
+ "maximum": 5000
339
+ }
340
+ },
341
+ {
342
+ "name": "after",
343
+ "in": "query",
344
+ "schema": {
345
+ "type": "string"
346
+ },
347
+ "description": "Return items after this item id: pass the previous page's next_after."
348
+ }
349
+ ],
330
350
  "responses": {
331
351
  "200": {
332
352
  "description": "OK",
@@ -340,6 +360,16 @@
340
360
  "items": {
341
361
  "$ref": "#/components/schemas/Item"
342
362
  }
363
+ },
364
+ "total": {
365
+ "type": "integer"
366
+ },
367
+ "next_after": {
368
+ "type": [
369
+ "string",
370
+ "null"
371
+ ],
372
+ "description": "null on the last page"
343
373
  }
344
374
  }
345
375
  }
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "relock-memory"
7
- version = "0.2.2"
7
+ version = "0.3.0"
8
8
  description = "Agent memory that fixes the rule that fired, in place and only on trusted evidence, so corrected mistakes don't come back. Python, HTTP (any language), MCP."
9
9
  dynamic = ["readme"]
10
10
  license = "Apache-2.0"
@@ -47,10 +47,11 @@ from .types import (
47
47
  Observation,
48
48
  Recall,
49
49
  RelockError,
50
+ StoreError,
50
51
  Verdict,
51
52
  )
52
53
 
53
- __version__ = "0.2.2"
54
+ __version__ = "0.3.0"
54
55
 
55
56
  __all__ = [
56
57
  "BM25Retriever",
@@ -86,6 +87,7 @@ __all__ = [
86
87
  "SQLiteStore",
87
88
  "Signal",
88
89
  "Source",
90
+ "StoreError",
89
91
  "ToolError",
90
92
  "Toolkit",
91
93
  "TransientToolError",
@@ -7,7 +7,7 @@ import os
7
7
  import re
8
8
  import threading
9
9
  import time
10
- from datetime import datetime, timezone
10
+ from datetime import datetime, timedelta, timezone
11
11
  from typing import Any
12
12
 
13
13
  _ID_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz" # Crockford-ish base32, lowercase
@@ -115,6 +115,28 @@ def approx_tokens(text: str) -> int:
115
115
  return max(1, (len(text) + 3) // 4)
116
116
 
117
117
 
118
+ _AGE_UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
119
+
120
+
121
+ def parse_age(value: Any) -> timedelta:
122
+ """``timedelta`` or a string such as ``"90s"``, ``"45m"``, ``"12h"``, ``"30d"``, ``"2w"``."""
123
+ if isinstance(value, timedelta):
124
+ age = value
125
+ else:
126
+ text = str(value).strip().lower()
127
+ unit = text[-1:] if text[-1:] in _AGE_UNITS else ""
128
+ try:
129
+ number = float(text[: len(text) - len(unit)] if unit else text)
130
+ except ValueError:
131
+ raise ValueError(f"invalid age {value!r}: use a number with s, m, h, d or w, e.g. '30d'") from None
132
+ if not unit:
133
+ raise ValueError(f"invalid age {value!r}: give a unit (s, m, h, d or w), e.g. '30d'")
134
+ age = timedelta(seconds=number * _AGE_UNITS[unit])
135
+ if age < timedelta(0):
136
+ raise ValueError("age must not be negative")
137
+ return age
138
+
139
+
118
140
  def truncate(text: str, limit: int) -> str:
119
141
  if len(text) <= limit:
120
142
  return text
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import argparse
6
6
  import json
7
+ import logging
7
8
  import os
8
9
  import sys
9
10
  from typing import Any
@@ -144,6 +145,35 @@ def cmd_events(args: argparse.Namespace, mem: Memory) -> int:
144
145
  return 0
145
146
 
146
147
 
148
+ def _age_arg(text: str) -> str:
149
+ from ._util import parse_age
150
+
151
+ try:
152
+ parse_age(text)
153
+ except ValueError as e:
154
+ raise argparse.ArgumentTypeError(str(e)) from None
155
+ return text
156
+
157
+
158
+ def cmd_prune(args: argparse.Namespace, mem: Memory) -> int:
159
+ counts = mem.prune(args.older_than, dry_run=args.dry_run)
160
+ if args.json:
161
+ _out(counts)
162
+ return 0
163
+ verb = "would delete" if args.dry_run else "deleted"
164
+ print(f"{verb} {counts['episodes']} episode(s) older than {args.older_than}: {counts['expectations']} "
165
+ f"expectation(s), {counts['errors']} error(s), {counts['retrievals']} retrieval(s), "
166
+ f"{counts['events']} event(s)")
167
+ print(f"{verb} per-call detail of kept episodes: {counts['expectations_trimmed']} expectation(s), "
168
+ f"{counts['events_trimmed']} event(s)")
169
+ if counts["episodes_abandoned"]:
170
+ print(f"{'would mark' if args.dry_run else 'marked'} {counts['episodes_abandoned']} idle open episode(s) "
171
+ "as abandoned")
172
+ if not args.dry_run and not str(args.db).startswith(("postgres://", "postgresql://")):
173
+ print("SQLite keeps the file size until you run: sqlite3 <db> VACUUM")
174
+ return 0
175
+
176
+
147
177
  def cmd_stats(args: argparse.Namespace, mem: Memory) -> int:
148
178
  _out(mem.stats())
149
179
  return 0
@@ -198,6 +228,10 @@ def build_parser() -> argparse.ArgumentParser:
198
228
  p = argparse.ArgumentParser(prog="relock", description="Agent memory that unlocks on recall, rewrites on "
199
229
  "surprise, and re-locks.")
200
230
  p.add_argument("--version", action="version", version=f"relock {__version__}")
231
+ p.add_argument("--log-level", default=os.environ.get("RELOCK_LOG_LEVEL"),
232
+ choices=["DEBUG", "INFO", "WARNING", "ERROR"], type=str.upper,
233
+ help="log relock events to stderr at this level (default: $RELOCK_LOG_LEVEL; "
234
+ "'serve' logs INFO when unset)")
201
235
  p.add_argument("--db", default=os.environ.get("RELOCK_DB", "relock.db"),
202
236
  help="SQLite path or postgresql:// URL (default: $RELOCK_DB or ./relock.db)")
203
237
  sub = p.add_subparsers(dest="cmd", required=True)
@@ -260,6 +294,12 @@ def build_parser() -> argparse.ArgumentParser:
260
294
  sp.add_argument("--limit", type=int, default=50)
261
295
  sp.add_argument("--json", action="store_true")
262
296
 
297
+ sp = add("prune", cmd_prune, "Delete old audit detail (items and versions are always kept).")
298
+ sp.add_argument("--older-than", required=True, metavar="AGE", type=_age_arg,
299
+ help="e.g. 30d, 12h, 2w; must exceed the longest an episode stays open in any process")
300
+ sp.add_argument("--dry-run", action="store_true", help="only count what would be deleted")
301
+ sp.add_argument("--json", action="store_true")
302
+
263
303
  add("stats", cmd_stats, "Ledger counters.")
264
304
  sp = add("export", cmd_export, "Export rewrite traces as JSONL (SFT / preference pairs).")
265
305
  sp.add_argument("out")
@@ -315,11 +355,18 @@ def main(argv: list[str] | None = None) -> int:
315
355
  return bench_main(rest)
316
356
  if rest:
317
357
  parser.error(f"unrecognized arguments: {' '.join(rest)}")
358
+ if args.log_level: # stderr only: stdout carries command output and the MCP stdio protocol
359
+ logging.basicConfig(level=args.log_level, stream=sys.stderr,
360
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s")
318
361
  if getattr(args, "mcp", False):
319
362
  return cmd_mcp(args)
320
363
  if getattr(args, "serve", False):
321
364
  return cmd_serve(args)
322
- mem = Memory(args.db)
365
+ try:
366
+ mem = Memory(args.db)
367
+ except RelockError as e:
368
+ print(f"error: {e}", file=sys.stderr)
369
+ return 1
323
370
  try:
324
371
  return int(args.fn(args, mem) or 0)
325
372
  except (RelockError, KeyError, ValueError) as e: