relock-memory 0.1.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 (48) hide show
  1. relock_memory-0.1.1/.gitignore +26 -0
  2. relock_memory-0.1.1/CHANGELOG.md +53 -0
  3. relock_memory-0.1.1/LICENSE +202 -0
  4. relock_memory-0.1.1/PKG-INFO +390 -0
  5. relock_memory-0.1.1/README.md +357 -0
  6. relock_memory-0.1.1/docs/design.md +185 -0
  7. relock_memory-0.1.1/docs/results/structural.md +84 -0
  8. relock_memory-0.1.1/docs/results/structural.svg +93 -0
  9. relock_memory-0.1.1/examples/01_quickstart.py +60 -0
  10. relock_memory-0.1.1/examples/02_llm_rewriter.py +56 -0
  11. relock_memory-0.1.1/examples/03_langgraph_callbacks.py +51 -0
  12. relock_memory-0.1.1/pyproject.toml +97 -0
  13. relock_memory-0.1.1/src/relock_memory/__init__.py +98 -0
  14. relock_memory-0.1.1/src/relock_memory/_util.py +129 -0
  15. relock_memory-0.1.1/src/relock_memory/bench/__init__.py +1 -0
  16. relock_memory-0.1.1/src/relock_memory/bench/agents.py +76 -0
  17. relock_memory-0.1.1/src/relock_memory/bench/cli.py +79 -0
  18. relock_memory-0.1.1/src/relock_memory/bench/harness.py +224 -0
  19. relock_memory-0.1.1/src/relock_memory/bench/report.py +231 -0
  20. relock_memory-0.1.1/src/relock_memory/bench/scenarios.py +258 -0
  21. relock_memory-0.1.1/src/relock_memory/bench/systems.py +304 -0
  22. relock_memory-0.1.1/src/relock_memory/checks.py +205 -0
  23. relock_memory-0.1.1/src/relock_memory/cli.py +308 -0
  24. relock_memory-0.1.1/src/relock_memory/delta.py +162 -0
  25. relock_memory-0.1.1/src/relock_memory/episode.py +563 -0
  26. relock_memory-0.1.1/src/relock_memory/export.py +62 -0
  27. relock_memory-0.1.1/src/relock_memory/integrations/__init__.py +10 -0
  28. relock_memory-0.1.1/src/relock_memory/integrations/langchain.py +83 -0
  29. relock_memory-0.1.1/src/relock_memory/integrations/mcp.py +176 -0
  30. relock_memory-0.1.1/src/relock_memory/integrations/toolkit.py +241 -0
  31. relock_memory-0.1.1/src/relock_memory/llm.py +150 -0
  32. relock_memory-0.1.1/src/relock_memory/memory.py +339 -0
  33. relock_memory-0.1.1/src/relock_memory/policy.py +134 -0
  34. relock_memory-0.1.1/src/relock_memory/py.typed +0 -0
  35. relock_memory-0.1.1/src/relock_memory/retrieval.py +137 -0
  36. relock_memory-0.1.1/src/relock_memory/rewriters.py +255 -0
  37. relock_memory-0.1.1/src/relock_memory/signals.py +315 -0
  38. relock_memory-0.1.1/src/relock_memory/stores/__init__.py +36 -0
  39. relock_memory-0.1.1/src/relock_memory/stores/postgres.py +41 -0
  40. relock_memory-0.1.1/src/relock_memory/stores/sql.py +528 -0
  41. relock_memory-0.1.1/src/relock_memory/stores/sqlite.py +38 -0
  42. relock_memory-0.1.1/src/relock_memory/types.py +289 -0
  43. relock_memory-0.1.1/tests/conftest.py +64 -0
  44. relock_memory-0.1.1/tests/test_cli_bench.py +136 -0
  45. relock_memory-0.1.1/tests/test_integrations.py +321 -0
  46. relock_memory-0.1.1/tests/test_llm_client.py +119 -0
  47. relock_memory-0.1.1/tests/test_reconsolidation.py +342 -0
  48. relock_memory-0.1.1/tests/test_units.py +353 -0
@@ -0,0 +1,26 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ venv/
9
+ .pytest_cache/
10
+ .ruff_cache/
11
+ .mypy_cache/
12
+ .coverage
13
+ htmlcov/
14
+
15
+ # relock databases created by examples, tests and the CLI
16
+ *.db
17
+ *.db-wal
18
+ *.db-shm
19
+ bench-results/
20
+
21
+ # Editors / OS
22
+ .idea/
23
+ .vscode/
24
+ .DS_Store
25
+ Thumbs.db
26
+ docs/results/*.json
@@ -0,0 +1,53 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 - 2026-11-28
4
+
5
+ First release on PyPI: `pip install relock-memory`. No changes to the memory mechanism.
6
+
7
+ - `relock mcp --cwd DIR` sets the directory the verifier commands run in.
8
+ - README:
9
+ - install from PyPI;
10
+ - MCP setup with `uvx` and `claude mcp add`;
11
+ - links and the results chart also work on the PyPI project page.
12
+ - The release workflow publishes to PyPI only for release events, after the version check.
13
+
14
+ ## 0.1.0 - 2026-11-27
15
+
16
+ First public version.
17
+
18
+ - Core mechanism:
19
+ - versioned clause-level items;
20
+ - episodes with retrieval-gated lability;
21
+ - expectations with programmatic checks;
22
+ - trust, transient, evidence and edit-scope gates;
23
+ - in-place reconsolidation with supersession, rollback and manual edits;
24
+ - an append-only audit log.
25
+ - Storage: SQLite (default, zero dependencies) and Postgres (`[postgres]` extra), with a partial
26
+ unique index enforcing one active version per item and compare-and-swap commits. Ids are
27
+ monotonic within a process.
28
+ - Retrieval: BM25 by default, plus embedding and hybrid retrievers (reciprocal-rank fusion).
29
+ - Rewriters:
30
+ - deterministic `HintRewriter`;
31
+ - `LLMRewriter` for any `Callable[[str], str]`, with JSON repair, retry with feedback and fallback;
32
+ - dependency-free `OpenAICompatible` client.
33
+ - Integrations:
34
+ - tool wrapping for any Python framework (sync and async);
35
+ - framework-agnostic `Toolkit` with OpenAI and Anthropic tool schemas;
36
+ - MCP server (mcp 1.x and 2.x) with server-side trusted verifiers;
37
+ - LangChain/LangGraph callback handler and tools.
38
+ - Safety defaults:
39
+ - Nothing the agent writes steers a rewrite unless the operator trusts agent reports. This
40
+ covers predictions stated through the toolkit or MCP, the clause ids they cite, and
41
+ corrections suggested to `relock_verify`.
42
+ - User corrections require `authenticated=True`.
43
+ - MCP teaching is opt-in (`--allow-teach`).
44
+ - Toolkit-owned episodes re-lock after 30 idle minutes.
45
+ - CLI: `relock add | ls | show | history | pending | events | rollback | edit | archive | stats | export | mcp | bench`.
46
+ - RelapseBench:
47
+ - ten drifting tool contracts and seven memory systems, including two ablations and an
48
+ uncited relock variant;
49
+ - four load levels;
50
+ - a reproducible, model-free structural mode with published results;
51
+ - a behavioural mode for any OpenAI-compatible model, with no results published yet.
52
+ - Export of rewrite traces as SFT and preference pairs.
53
+ - Tested on Python 3.10–3.13; CI workflow for SQLite, Postgres and `mcp` 1.x.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,390 @@
1
+ Metadata-Version: 2.5
2
+ Name: relock-memory
3
+ Version: 0.1.1
4
+ Summary: Agent memory that unlocks on recall, rewrites on surprise, and re-locks. Prediction-error-gated, in-place memory reconsolidation for LLM agents.
5
+ Project-URL: Homepage, https://github.com/inboxpraveen/relock
6
+ Project-URL: Repository, https://github.com/inboxpraveen/relock
7
+ Project-URL: Issues, https://github.com/inboxpraveen/relock/issues
8
+ Project-URL: Changelog, https://github.com/inboxpraveen/relock/blob/main/CHANGELOG.md
9
+ Author: Praveen Kumar
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agent-memory,agents,langchain,langgraph,llm,mcp,memory,procedural-memory,reconsolidation,self-improving
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Provides-Extra: all
28
+ Requires-Dist: langchain-core>=0.3; extra == 'all'
29
+ Requires-Dist: mcp>=1.2; extra == 'all'
30
+ Requires-Dist: psycopg[binary]>=3.1; extra == 'all'
31
+ Provides-Extra: dev
32
+ Requires-Dist: langchain-core>=0.3; extra == 'dev'
33
+ Requires-Dist: mcp>=1.2; extra == 'dev'
34
+ Requires-Dist: psycopg[binary]>=3.1; extra == 'dev'
35
+ Requires-Dist: pytest>=8; extra == 'dev'
36
+ Requires-Dist: ruff>=0.6; extra == 'dev'
37
+ Provides-Extra: langchain
38
+ Requires-Dist: langchain-core>=0.3; extra == 'langchain'
39
+ Provides-Extra: mcp
40
+ Requires-Dist: mcp>=1.2; extra == 'mcp'
41
+ Provides-Extra: postgres
42
+ Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
43
+ Description-Content-Type: text/markdown
44
+
45
+ # relock
46
+
47
+ [![ci](https://github.com/inboxpraveen/relock/actions/workflows/ci.yml/badge.svg)](https://github.com/inboxpraveen/relock/actions/workflows/ci.yml)
48
+ [![pypi](https://img.shields.io/pypi/v/relock-memory)](https://pypi.org/project/relock-memory/)
49
+ [![python](https://img.shields.io/pypi/pyversions/relock-memory)](https://pypi.org/project/relock-memory/)
50
+ [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/inboxpraveen/relock/blob/main/LICENSE)
51
+
52
+ **Agent memory that unlocks on recall, rewrites on surprise, and re-locks.**
53
+
54
+ Most agent memories fix a mistake by *appending* ("don't do X"). The old instruction stays
55
+ retrievable, and under long context, compaction or distracting tool output the old default wins
56
+ again. relock fixes the instruction that fired, in place, but only when a **trusted** signal shows
57
+ that its prediction was wrong, and only while that memory is **reactivated**.
58
+
59
+ ```
60
+ pip install relock-memory # core: zero dependencies
61
+ pip install "relock-memory[all]" # + Postgres, MCP, LangChain/LangGraph
62
+ ```
63
+
64
+ The extras can also be installed one at a time: `[postgres]`, `[mcp]`, `[langchain]`.
65
+ The distribution is `relock-memory` and the import is `relock_memory`, because the PyPI name
66
+ `relock` belongs to an unrelated SDK that also installs a top-level `relock` module.
67
+ The development version installs with
68
+ `pip install "relock-memory @ git+https://github.com/inboxpraveen/relock"`.
69
+
70
+ > **Status:** v0.1, alpha. The mechanism, storage, integrations and benchmark harness are
71
+ > complete. They are tested on Python 3.10–3.13, SQLite and Postgres, and `mcp` 1.x and 2.x.
72
+ > Behavioural benchmark numbers on open models are **not published yet**; see
73
+ > [RelapseBench](https://github.com/inboxpraveen/relock#relapsebench) for what has and has not been measured.
74
+
75
+ ---
76
+
77
+ ## The mechanism
78
+
79
+ relock borrows the *shape* of memory reconsolidation from neuroscience (a recalled memory becomes
80
+ briefly editable, and prediction error drives the update). It is a metaphor for an engineering
81
+ discipline, not a biological claim. The neuroscience is mostly animal work, and human results are mixed.
82
+
83
+ *The state diagram is rendered in the [README on GitHub](https://github.com/inboxpraveen/relock#the-mechanism).*
84
+
85
+ 1. **Reactivation = retrieval.** Only items recalled in the current episode can be edited. The
86
+ retrieval trace answers "which memory caused this?" structurally, so the model never has to.
87
+ 2. **Explicit prediction.** Before acting on a recalled procedure, the harness (or the agent)
88
+ records what it should produce, optionally citing the clauses it relies on.
89
+ 3. **Prediction error is the write trigger.** A mismatch counts only if the signal is trusted
90
+ (typed tool error, verifier, authenticated user) and not transient (timeouts, 429s, 5xx).
91
+ Evidence accumulates until it reaches a threshold, which grows with how often the
92
+ version has been confirmed. A later success cancels a one-off flake.
93
+ 4. **Overwrite in place.** The rewrite is a small clause-level delta (`replace` / `add` /
94
+ `remove`) limited to the clauses that fired. The old version is kept as `superseded` for
95
+ audit and rollback and is never retrievable again. A partial unique index guarantees one active
96
+ version per item, so "do X" and "never do X" can never both be retrieved.
97
+ 5. **Re-lock.** When the episode closes, its editable set closes too. Late writes raise
98
+ `EpisodeClosedError`. Pending evidence carries over to the next episode that recalls the item.
99
+
100
+ ## Quickstart
101
+
102
+ ```python
103
+ import relock_memory as relock
104
+
105
+ mem = relock.Memory("agent.db") # or ":memory:", or "postgresql://..."
106
+ mem.add("Fetch orders by date",
107
+ ["Authenticate with the orders API key before calling get_orders.",
108
+ "Pass the date to get_orders as MM/DD/YYYY."], # stale: the API moved to ISO dates
109
+ key="orders.fetch", tools=["get_orders"], exist_ok=True)
110
+
111
+ @mem.wrap # your real tool; its outcome is the trusted signal
112
+ def get_orders(date: str) -> list[dict]:
113
+ if not is_iso(date):
114
+ raise relock.ToolError("invalid date", correction="Pass the date to get_orders as YYYY-MM-DD.")
115
+ return api.orders(date)
116
+
117
+ with mem.episode("orders for March 14") as ep:
118
+ context = ep.recall("fetch the orders placed on a date").render() # put this in the prompt
119
+ ... # your agent runs; calls to get_orders resolve expectations automatically
120
+ ```
121
+
122
+ After two trusted failures (configurable), clause `c2` is rewritten in place:
123
+
124
+ ```
125
+ $ relock history orders.fetch
126
+ v1 [superseded] create by author at 2026-11-26T18:38:29.454852+00:00
127
+ (c1) Authenticate with the orders API key before calling get_orders.
128
+ (c2) Pass the date to get_orders as MM/DD/YYYY.
129
+ v2 [active] reconsolidate by hint at 2026-11-26T18:38:29.463781+00:00 (episode ep_01m8cjdsjmv8mbp3d065)
130
+ reason: replace c2 with trusted correction
131
+ - (c2) Pass the date to get_orders as MM/DD/YYYY.
132
+ + (c2) Pass the date to get_orders as YYYY-MM-DD.
133
+ ```
134
+
135
+ Run [`examples/01_quickstart.py`](https://github.com/inboxpraveen/relock/blob/main/examples/01_quickstart.py) to see the whole loop in about 60 lines.
136
+
137
+ ## Plug it into your stack
138
+
139
+ relock does not replace your agent framework. It sits beside it. The split that keeps memory
140
+ safe is **the model predicts, the harness judges**.
141
+
142
+ | You use | Integrate with | Effort |
143
+ |---|---|---|
144
+ | Any Python agent (OpenAI Agents SDK, PydanticAI, smolagents, CrewAI, LlamaIndex, AutoGen, your own loop) | `@mem.wrap` on your tools + `with mem.episode()` around a task. Signatures and docstrings are preserved, so framework tool schemas don't change. Sync and async. | 3 lines |
145
+ | Raw tool calling (OpenAI-compatible, Anthropic, vLLM, Ollama) | `relock.Toolkit(mem).openai_tools()` / `.anthropic_tools()` + `toolkit.call(name, args)` | a dispatcher branch |
146
+ | LangChain / LangGraph | `RelockCallbackHandler(mem)` in `config={"callbacks": [...]}`. Existing tools stay untouched. `langchain_tools(Toolkit(mem))` gives the model `recall_memory` / `state_expectation`. | 1 line |
147
+ | Anything that speaks MCP (Claude Code, Cursor, VS Code, OpenAI Agents SDK, LangGraph, PydanticAI...) | `relock mcp --db relock.db --verifier tests="pytest -q"` | config only |
148
+
149
+ ### MCP
150
+
151
+ ```json
152
+ {
153
+ "mcpServers": {
154
+ "relock": {
155
+ "command": "uvx",
156
+ "args": ["--from", "relock-memory[mcp]", "relock", "--db", "/path/to/relock.db", "mcp",
157
+ "--verifier", "tests=pytest -q", "--verifier", "lint=ruff check ."]
158
+ }
159
+ }
160
+ }
161
+ ```
162
+
163
+ [`uvx`](https://docs.astral.sh/uv/) fetches the package the first time the client starts the
164
+ server. If you installed `relock-memory[mcp]` with pip instead, use `"command": "relock"` and drop
165
+ the first two arguments. In Claude Code the same server is one command:
166
+
167
+ ```
168
+ claude mcp add relock -- uvx --from "relock-memory[mcp]" relock --db relock.db mcp --verifier tests="pytest -q"
169
+ ```
170
+
171
+ Verifier commands run in the server's working directory, which depends on the client. Pass
172
+ `--cwd /path/to/project` to pin it.
173
+
174
+ Tools exposed: `relock_begin`, `relock_recall`, `relock_expect`, `relock_verify`, `relock_report`,
175
+ `relock_history`, `relock_end`, plus `relock_teach` if you start the server with `--allow-teach`.
176
+ Items the agent teaches are marked `meta.origin = "agent"`. If a client never calls `relock_end`,
177
+ its episode is re-locked after 30 idle minutes (`--idle-timeout`).
178
+
179
+ Because the agent calls these tools, **nothing the agent writes is trusted by default**:
180
+
181
+ - its `relock_report`s are logged but never rewrite memory;
182
+ - the prediction text it gives `relock_expect` is withheld from the rewriter;
183
+ - a `correction` it suggests to `relock_verify` is ignored.
184
+
185
+ Trusted outcomes come from **verifiers**: commands fixed by whoever starts the server. The agent
186
+ can only pick one by name; the server runs it and reads the exit code itself. Two red verifier
187
+ runs are therefore enough evidence for a rewrite, but the fix comes from the verifier's output
188
+ (with an LLM rewriter) or from a trusted correction, never from the agent's text.
189
+
190
+ For a single-user local sandbox, `--trust-agent-reports` opts in to all three.
191
+
192
+ ## Safety model
193
+
194
+ | Signal | Source | Can rewrite memory? |
195
+ |---|---|---|
196
+ | Exception or typed result from a wrapped tool | `TOOL` | yes, if not transient |
197
+ | `TimeoutError`, `ConnectionError`, HTTP 408/425/429/5xx | `TOOL` (transient) | **never** |
198
+ | Test suite / schema check / grader | `VERIFIER` | yes |
199
+ | Human correction your app has verified (`authenticated=True`) | `USER` | yes, immediately (authoritative) |
200
+ | Human correction without that flag (the default) | `USER` | no |
201
+ | The model's own report | `AGENT` | no (opt-in) |
202
+ | LLM-as-judge / self-critique | `SELF` | no |
203
+ | Web pages, documents, emails, retrieved text | `ENVIRONMENT` | **never** |
204
+
205
+ On top of the trust gate:
206
+
207
+ - An **evidence threshold** stops a single noisy failure from rewriting a good procedure.
208
+ - **Inertia** means well-proven versions need more evidence: `+0.5 * ln(1 + confirmations)`.
209
+ - **Flake damping** cancels a pending error when the same version is later confirmed.
210
+ - **Edit scope** limits a rewrite to the clauses the failed prediction relied on, when it cites
211
+ them (`ep.expect(..., clauses=["c2"])`, or `clause_ids` from the agent). Automatic expectations
212
+ from `@mem.wrap` cite none, so there the rewriter picks the clause. `HintRewriter` replaces the
213
+ clause most similar to the correction.
214
+ - **Optimistic concurrency** turns evidence about a version someone else already rewrote into a `conflict`, never a lost update.
215
+ - A trusted tool whose error message echoes remote content can be marked `detail_trusted=False`. The failure still counts, but its text never reaches the rewriter.
216
+
217
+ Every gate decision is written to an append-only event log (`relock events`).
218
+
219
+ ## Small open models (~30B)
220
+
221
+ The hard part of self-improving memory is credit assignment: which memory caused the failure?
222
+ relock answers that structurally, through the retrieval trace, the cited clauses and the expectation
223
+ diff. The rewriter only has to make a *local* edit: "here is the item, here is what it predicted,
224
+ here is what happened, rewrite this clause". The rewrite prompt is built for that size class:
225
+ one item, explicit clause ids, strict JSON, one worked example. Invalid output is fed back for a
226
+ retry, `<think>` blocks are stripped, and the deterministic `HintRewriter` is the fallback.
227
+
228
+ ```python
229
+ llm = relock.OpenAICompatible("http://localhost:8000/v1", model="Qwen/Qwen3-30B-A3B-Instruct-2507")
230
+ mem = relock.Memory("agent.db", rewriter=relock.LLMRewriter(llm))
231
+ ```
232
+
233
+ `OpenAICompatible` has no dependencies and works with vLLM, SGLang, Ollama, llama.cpp, LM Studio
234
+ and hosted endpoints. Any `Callable[[str], str]` also works as `llm`.
235
+
236
+ Every rewrite is also a labelled training example. `relock export traces.jsonl` writes SFT pairs
237
+ (`prompt` / `completion`) and preference pairs (`rejected` = superseded clauses, `chosen` = new
238
+ clauses), the raw material for distilling the rewriter or consolidating corrections into weights.
239
+
240
+ ## RelapseBench
241
+
242
+ **The question:** once an agent has been taught a correction, how often does the old behaviour come
243
+ back under load, poisoning and noise?
244
+
245
+ Ten tool contracts drift: dates, money units, auth schemes, regions, pagination, encodings, SQL
246
+ quoting, temperature and distance units, recipient separators. Memory starts with the old rule,
247
+ the environment enforces a new one, and a third, wrong rule is used for poisoning. Every system
248
+ then gets the **same** stream of events:
249
+
250
+ 1. typed tool errors that carry the correction, until it is learned;
251
+ 2. successes, two transient timeouts, one prompt injection pushing the wrong rule, and one noisy
252
+ verifier failure that arrives with a wrong "fix".
253
+
254
+ Each system is then probed at four load levels that shrink the memory budget and top-k, add up to
255
+ 120 distractor procedures and pad the context with up to 8k tokens of history containing a stale
256
+ example and the injected text.
257
+
258
+ Systems compared:
259
+
260
+ - `append-notes`: every lesson becomes a new note.
261
+ - `append-clause`: lessons are appended to the item.
262
+ - `ace-style`: our simplified ACE-like playbook with helpful/harmful counters (not the official ACE code).
263
+ - Two ablations of relock: `append-gated`, which keeps relock's gates but appends, and `overwrite-ungated`, which rewrites in place with every gate off.
264
+ - `relock` itself, whose predictions cite the clause they rely on.
265
+ - `relock-uncited`: relock with uncited predictions, like the plain `@mem.wrap` path.
266
+
267
+ ### Structural mode (measured, model-free)
268
+
269
+ ![RelapseBench structural results](https://raw.githubusercontent.com/inboxpraveen/relock/main/docs/results/structural.svg)
270
+
271
+ This mode measures which rules reach the agent's memory context. It does not measure what a
272
+ model does with them. It is deterministic (repeated runs produce identical reports) and takes a
273
+ few seconds: `relock bench`. Full tables are in [docs/results/structural.md](https://github.com/inboxpraveen/relock/blob/main/docs/results/structural.md).
274
+
275
+ What it shows:
276
+
277
+ - **Each mechanism fixes exactly one failure mode.** Gating alone (`append-gated`) keeps the
278
+ poisoned rule out, but the superseded rule stays in context next to the correction in 100% of
279
+ probes. In-place rewriting alone (`overwrite-ungated`) removes the stale rule, but the injected
280
+ rule reaches context in 100% of probes. In 9 of 10 families it overwrote the correction. In the
281
+ tenth it overwrote the wrong clause, because nothing restricted the edit to the clause that
282
+ fired. relock needs both mechanisms to keep the context clean (100% of probes).
283
+ - **Append-style memories carry conflicts.** At the loosest budget (L0), the superseded rule is
284
+ still in context alongside the correction for 90% (`append-notes`) to 100% (`append-clause`,
285
+ `ace-style`) of probes. At the tightest budget (L3), `append-notes` loses the correction entirely
286
+ in 23% of probes.
287
+ - **Citing clauses made no difference here.** `relock-uncited` matches `relock` on every metric.
288
+ The trust gate keeps the poisoned fix out, and the hint rewriter finds the drifting clause by
289
+ similarity. Edit scope guards against a rewriter, typically an LLM, that edits the wrong
290
+ clause. This model-free mode doesn't exercise that case.
291
+ - **The price:** relock needs 2 trusted errors to learn a correction (its default evidence
292
+ threshold), where append-style systems need 1. That is one extra failure per drift, paid for
293
+ robustness against one-off noise. Set `min_evidence=1` to trade it back.
294
+
295
+ ### Behavioural mode (harness ready, results pending)
296
+
297
+ Whether a model actually relapses when the old and new rules sit side by side, or when the
298
+ correction was compacted away, is the headline question. It needs a real model:
299
+
300
+ ```
301
+ relock bench --mode behavioral --base-url http://localhost:8000/v1 \
302
+ --model Qwen/Qwen3-30B-A3B-Instruct-2507
303
+ ```
304
+
305
+ This runs a closed loop: the agent learns from its own failures, the same model performs relock's
306
+ rewrites, and then it is probed under load. Reported metrics are relapse, poisoned and correct
307
+ rates with Wilson intervals, plus learning cost. **No behavioural numbers are published yet.**
308
+ Contributions of runs on open models are very welcome; please include `behavioral.json`.
309
+
310
+ ## CLI
311
+
312
+ ```
313
+ relock add "Run tests" "Run the tests with pytest -q." --key tests.run --tool pytest
314
+ relock ls # active items with confidence and counters
315
+ relock show orders.fetch [--version 1]
316
+ relock history orders.fetch # clause-level diffs across versions
317
+ relock pending orders.fetch # pending evidence vs. the rewrite threshold, and what was blocked
318
+ relock events --item orders.fetch # audit log: recalls, predictions, gate decisions, rewrites
319
+ relock rollback orders.fetch 1 # restores v1 as a new version (history is never destroyed)
320
+ relock edit orders.fetch --replace c2 "Pass dates as YYYY-MM-DD."
321
+ relock export traces.jsonl # SFT and preference pairs from every rewrite
322
+ relock mcp --verifier tests="pytest -q" [--cwd DIR] [--allow-teach] [--trust-agent-reports]
323
+ relock bench [--mode structural|behavioral|both]
324
+ ```
325
+
326
+ The database is `--db`, or `$RELOCK_DB`, or `./relock.db`. Postgres URLs work everywhere.
327
+
328
+ ## Configuration
329
+
330
+ ```python
331
+ relock.WritePolicy(
332
+ min_evidence=2.0, # weighted trusted errors before a rewrite
333
+ inertia=0.5, # extra evidence per ln(1 + confirmations)
334
+ confirmation_cancels=1.0, # a later success cancels this much pending evidence
335
+ rewrite_on="observe", # or "close": rewrite only when the episode ends
336
+ edit_scope="cited", # replace/remove only clauses the prediction relied on
337
+ max_ops=4,
338
+ attribute_undeclared=False, # attribute tool outcomes to recalled items that declare no tools
339
+ )
340
+ relock.WritePolicy.strict() # verifier + user only, higher threshold
341
+ relock.WritePolicy.eager() # one trusted error is enough
342
+ relock.WritePolicy.trust_agent() # also trust the agent's reports (local sandboxes)
343
+ ```
344
+
345
+ Retrieval is BM25 by default (no dependencies). Pass `embed=` (any `list[str] -> list[vector]`
346
+ function) for hybrid BM25 + vector search with reciprocal-rank fusion, or implement the
347
+ one-method `Retriever` protocol. Only active versions are ever candidates.
348
+
349
+ Storage is SQLite by default (WAL mode, safe across processes) or Postgres with
350
+ `pip install "relock-memory[postgres]"`. Postgres uses `JSONB` and `TIMESTAMPTZ`, so the ledger is
351
+ directly queryable. The schema is documented in [docs/design.md](https://github.com/inboxpraveen/relock/blob/main/docs/design.md).
352
+
353
+ ## How it relates to other work
354
+
355
+ - **Mem0** maintains memories with add/update/delete operations chosen by an LLM.
356
+ - **ReasoningBank** distils strategies from the agent's own judged successes and failures.
357
+ - **ACE** grows playbooks through incremental deltas with helpful/harmful counters.
358
+
359
+ relock combines three things we have not seen packaged together:
360
+
361
+ - writes gated on **retrieval** (lability),
362
+ - triggered by an **explicit, trusted prediction error**,
363
+ - applied **in place with supersession** rather than appended.
364
+
365
+ It is meant to sit under any of these styles, or under your own harness.
366
+
367
+ ## Roadmap
368
+
369
+ - Behavioural RelapseBench results on open ~30B models, plus a long-horizon variant with real
370
+ context compaction.
371
+ - Weight tier: periodically distil accumulated rewrite traces for a skill into adapter weights.
372
+ Fast edits live in the harness, durable ones in the weights.
373
+ - pgvector retrieval inside Postgres; a TypeScript client for the MCP server.
374
+ - Per-tenant ledgers and signed user corrections.
375
+
376
+ ## Development
377
+
378
+ ```
379
+ python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate
380
+ pip install -e ".[dev]"
381
+ pytest # SQLite backends
382
+ RELOCK_TEST_POSTGRES_URL=postgresql://... pytest # + Postgres
383
+ ruff check src tests examples
384
+ ```
385
+
386
+ CI runs the suite on Python 3.10–3.13 against SQLite and Postgres. It also runs the MCP tests
387
+ on the `mcp` 1.x line. See [CONTRIBUTING.md](https://github.com/inboxpraveen/relock/blob/main/CONTRIBUTING.md) for the invariants a change must
388
+ keep. Report vulnerabilities privately as described in [SECURITY.md](https://github.com/inboxpraveen/relock/blob/main/SECURITY.md).
389
+
390
+ Apache-2.0. See [LICENSE](https://github.com/inboxpraveen/relock/blob/main/LICENSE).