relock-memory 0.1.1__tar.gz → 0.2.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 (66) hide show
  1. {relock_memory-0.1.1 → relock_memory-0.2.0}/.gitignore +5 -0
  2. {relock_memory-0.1.1 → relock_memory-0.2.0}/CHANGELOG.md +34 -0
  3. {relock_memory-0.1.1 → relock_memory-0.2.0}/PKG-INFO +132 -33
  4. {relock_memory-0.1.1 → relock_memory-0.2.0}/README.md +127 -29
  5. {relock_memory-0.1.1 → relock_memory-0.2.0}/docs/design.md +2 -0
  6. relock_memory-0.2.0/docs/http.md +106 -0
  7. relock_memory-0.2.0/docs/openapi.json +1102 -0
  8. relock_memory-0.2.0/docs/results/models/DESIGN.md +98 -0
  9. relock_memory-0.2.0/docs/results/models/README.md +199 -0
  10. relock_memory-0.2.0/docs/results/models/by-load.svg +91 -0
  11. relock_memory-0.2.0/docs/results/models/by-model.svg +93 -0
  12. relock_memory-0.2.0/docs/results/models/outcomes.svg +70 -0
  13. relock_memory-0.2.0/docs/results/models/records.csv +11521 -0
  14. relock_memory-0.2.0/docs/results/models/summary.json +10795 -0
  15. relock_memory-0.2.0/examples/http/curl.sh +29 -0
  16. relock_memory-0.2.0/examples/http/rust/.gitignore +2 -0
  17. relock_memory-0.2.0/examples/http/rust/Cargo.toml +10 -0
  18. relock_memory-0.2.0/examples/http/rust/src/main.rs +97 -0
  19. relock_memory-0.2.0/examples/http/typescript/demo.ts +30 -0
  20. relock_memory-0.2.0/examples/http/typescript/package.json +6 -0
  21. relock_memory-0.2.0/examples/http/typescript/relock.ts +84 -0
  22. {relock_memory-0.1.1 → relock_memory-0.2.0}/pyproject.toml +5 -3
  23. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/__init__.py +1 -1
  24. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/bench/scenarios.py +20 -6
  25. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/cli.py +26 -1
  26. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/episode.py +31 -1
  27. relock_memory-0.2.0/src/relock_memory/integrations/http.py +737 -0
  28. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/signals.py +1 -1
  29. {relock_memory-0.1.1 → relock_memory-0.2.0}/tests/test_cli_bench.py +19 -0
  30. relock_memory-0.2.0/tests/test_http.py +381 -0
  31. {relock_memory-0.1.1 → relock_memory-0.2.0}/tests/test_units.py +19 -0
  32. {relock_memory-0.1.1 → relock_memory-0.2.0}/LICENSE +0 -0
  33. {relock_memory-0.1.1 → relock_memory-0.2.0}/docs/results/structural.md +0 -0
  34. {relock_memory-0.1.1 → relock_memory-0.2.0}/docs/results/structural.svg +0 -0
  35. {relock_memory-0.1.1 → relock_memory-0.2.0}/examples/01_quickstart.py +0 -0
  36. {relock_memory-0.1.1 → relock_memory-0.2.0}/examples/02_llm_rewriter.py +0 -0
  37. {relock_memory-0.1.1 → relock_memory-0.2.0}/examples/03_langgraph_callbacks.py +0 -0
  38. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/_util.py +0 -0
  39. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/bench/__init__.py +0 -0
  40. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/bench/agents.py +0 -0
  41. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/bench/cli.py +0 -0
  42. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/bench/harness.py +0 -0
  43. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/bench/report.py +0 -0
  44. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/bench/systems.py +0 -0
  45. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/checks.py +0 -0
  46. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/delta.py +0 -0
  47. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/export.py +0 -0
  48. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/integrations/__init__.py +0 -0
  49. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/integrations/langchain.py +0 -0
  50. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/integrations/mcp.py +0 -0
  51. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/integrations/toolkit.py +0 -0
  52. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/llm.py +0 -0
  53. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/memory.py +0 -0
  54. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/policy.py +0 -0
  55. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/py.typed +0 -0
  56. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/retrieval.py +0 -0
  57. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/rewriters.py +0 -0
  58. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/stores/__init__.py +0 -0
  59. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/stores/postgres.py +0 -0
  60. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/stores/sql.py +0 -0
  61. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/stores/sqlite.py +0 -0
  62. {relock_memory-0.1.1 → relock_memory-0.2.0}/src/relock_memory/types.py +0 -0
  63. {relock_memory-0.1.1 → relock_memory-0.2.0}/tests/conftest.py +0 -0
  64. {relock_memory-0.1.1 → relock_memory-0.2.0}/tests/test_integrations.py +0 -0
  65. {relock_memory-0.1.1 → relock_memory-0.2.0}/tests/test_llm_client.py +0 -0
  66. {relock_memory-0.1.1 → relock_memory-0.2.0}/tests/test_reconsolidation.py +0 -0
@@ -24,3 +24,8 @@ bench-results/
24
24
  .DS_Store
25
25
  Thumbs.db
26
26
  docs/results/*.json
27
+
28
+ # Local secrets
29
+ .env
30
+ .env.*
31
+ !.env.example
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 - 2026-11-28
4
+
5
+ Behavioural results on 8 hosted models, use from any language over HTTP, and a container image.
6
+
7
+ - **Use relock from any language:**
8
+ - `relock serve` is an HTTP/JSON API with no dependencies, described by OpenAPI 3.1 in
9
+ `docs/openapi.json`.
10
+ - Security: bearer-token auth, and it refuses to bind publicly without a token. JSON types are
11
+ strict, so `"authenticated": "false"` is rejected, not read as true. Agent and environment
12
+ successes never raise confidence.
13
+ - Operation: idle episodes are re-locked in the background. It caps request size and
14
+ connections, times out stalled clients, accepts chunked bodies, and shuts down cleanly on
15
+ `SIGTERM`.
16
+ - Example clients in Rust, TypeScript and curl run in CI against a live server.
17
+ - A multi-arch container image is published to `ghcr.io/inboxpraveen/relock` on each release.
18
+ - **`Episode.tool_result(tool, result, error=..., signal=...)`** reports a tool's real outcome
19
+ without wrapping the tool, the same way `@mem.wrap` does.
20
+ - **Fix:** a failure passed explicitly as a signal, such as
21
+ `ep.observe(exp, signal=Signal.tool_error(...))`, was recorded as a success when the
22
+ expectation had a `succeeds()` check and no exception was passed.
23
+ - **Fix:** an episode closed while a write was in flight could still commit a rewrite after
24
+ re-lock. `observe`, `expect`, `recall` and `use` now re-check under the episode lock, and
25
+ `tool_result` binds and resolves atomically, so concurrent reports for one tool never collide.
26
+ - **Every 5xx status is now transient.** A server fault says nothing about whether the agent's
27
+ call was right. Previously 501, 505 and some other codes counted as `unknown` (weight 0.5).
28
+ - **RelapseBench behavioural results on 8 hosted models**, in `docs/results/models/`. In long
29
+ sessions, agents made the corrected call 98% of the time with relock, against 60% with
30
+ append-notes and 52% with append-clause. The study code is `scripts/model_study.py` and
31
+ `scripts/model_report.py`.
32
+ - The behavioural scorer now judges which rule a call follows, ignoring formatting. For example,
33
+ `a;b` follows the same `;` rule as `a; b`. No behavioural results had been published before
34
+ this change.
35
+ - Tested on Python 3.14 (CI and package classifiers). Development status is now beta.
36
+
3
37
  ## 0.1.1 - 2026-11-28
4
38
 
5
39
  First release on PyPI: `pip install relock-memory`. No changes to the memory mechanism.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
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.
3
+ Version: 0.2.0
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
7
7
  Project-URL: Issues, https://github.com/inboxpraveen/relock/issues
@@ -9,8 +9,8 @@ Project-URL: Changelog, https://github.com/inboxpraveen/relock/blob/main/CHANGEL
9
9
  Author: Praveen Kumar
10
10
  License-Expression: Apache-2.0
11
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
12
+ Keywords: agent-memory,agents,langchain,langgraph,llm,mcp,memory,openapi,procedural-memory,prompt-injection,reconsolidation,self-improving,tool-calling
13
+ Classifier: Development Status :: 4 - Beta
14
14
  Classifier: Intended Audience :: Developers
15
15
  Classifier: Intended Audience :: Science/Research
16
16
  Classifier: Operating System :: OS Independent
@@ -20,6 +20,7 @@ Classifier: Programming Language :: Python :: 3.10
20
20
  Classifier: Programming Language :: Python :: 3.11
21
21
  Classifier: Programming Language :: Python :: 3.12
22
22
  Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
23
24
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
25
  Classifier: Topic :: Software Development :: Libraries
25
26
  Classifier: Typing :: Typed
@@ -49,33 +50,89 @@ Description-Content-Type: text/markdown
49
50
  [![python](https://img.shields.io/pypi/pyversions/relock-memory)](https://pypi.org/project/relock-memory/)
50
51
  [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/inboxpraveen/relock/blob/main/LICENSE)
51
52
 
52
- **Agent memory that unlocks on recall, rewrites on surprise, and re-locks.**
53
+ **Agent memory that fixes the rule that fired, in place and only on trusted evidence, so
54
+ corrected mistakes don't come back.**
53
55
 
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**.
56
+ You corrected your agent: the orders API takes ISO dates now. Its memory saved the lesson as a
57
+ note. Days later, deep into a long session, it sends `03/14/2026` again. The old rule was still in
58
+ memory, next to the note, and the model followed it.
59
+
60
+ Lesson notes, rules files and playbooks all keep both rules and hope the model picks the right
61
+ one. relock edits the rule that fired, in place, under three conditions:
62
+
63
+ - **Only on trusted evidence.** A typed tool error, a verifier or an authenticated user can
64
+ trigger a rewrite. The model's own claims, a web page, a timeout or a one-off flaky check can't.
65
+ - **Only while that memory is recalled** in the current task. The retrieval trace records which
66
+ memory caused the failure, so the model never has to guess.
67
+ - **The old version is kept, but never retrieved again.** Every version and every decision is
68
+ stored for audit and rollback.
69
+
70
+ ![Correct tool calls per model in a long session: append-notes, append-gated and relock](https://raw.githubusercontent.com/inboxpraveen/relock/main/docs/results/models/by-model.svg)
71
+
72
+ **The study:** 8 hosted models and 10 changed tool contracts, in long sessions with stale docs and
73
+ a prompt injection in context. With relock, agents made the corrected call **98%** of the time.
74
+ - A memory that appends each lesson as a note managed **60%**.
75
+ - Appending the correction to the procedure, like a rules file, managed **52%**.
76
+ - relock was ahead on all 8 models, with the 95% intervals apart for all 8.
77
+
78
+ **Isolating the mechanism.** The baselines are our own implementations of those patterns, run on
79
+ the same events. `append-gated` keeps relock's trust gate but still appends, and it reached
80
+ **74%**: the gate keeps the poisoned "fix" out, and replacing the rule is what stops the relapse.
81
+
82
+ The design was committed before the run, and every call is published. See the
83
+ [results](https://github.com/inboxpraveen/relock/blob/main/docs/results/models/): 11,520 probe calls, $7.33 in API spend.
84
+
85
+ ## Is this your problem?
86
+
87
+ relock is for you if:
88
+ - your agent calls tools or APIs, and corrections to how it calls them don't stick;
89
+ - your memory or rules file keeps growing "actually, do X instead" notes;
90
+ - your agent learns from its own failures, and a prompt injection or a flaky test must not be able
91
+ to change what it learned.
92
+
93
+ It is not for chat history, document RAG, or agents with no tool outcomes to learn from.
94
+
95
+ ## What's different
96
+
97
+ | | lesson notes, vector memories | rules file, playbook | LLM-managed memory (a model picks add / update / delete) | relock |
98
+ |---|---|---|---|---|
99
+ | A correction replaces the old rule | no: both are retrievable | no: both are in the file | if the model chooses to | yes: the clause that fired is superseded |
100
+ | What can change memory | any write | any write | a model, deciding from what it read | trusted signals only |
101
+ | A prompt injection's "fix" | stored | stored | can be stored | logged, never applied |
102
+ | A one-off flaky failure | stored | stored | can be stored | needs a second trusted error; the next success cancels it |
103
+ | Which memory caused a failure | the model guesses | the model guesses | the model guesses | recorded by the retrieval trace |
104
+ | History | varies | git, if any | varies | every version and decision, with rollback |
105
+
106
+ Each idea exists somewhere, but we have not seen them packaged together:
107
+ - writes are allowed only while a memory is recalled;
108
+ - a write is triggered by a trusted prediction error;
109
+ - the edit is scoped to the clause that fired;
110
+ - the new version supersedes the old one instead of being appended.
111
+
112
+ ## Install
58
113
 
59
114
  ```
60
115
  pip install relock-memory # core: zero dependencies
61
116
  pip install "relock-memory[all]" # + Postgres, MCP, LangChain/LangGraph
117
+ docker run -p 8765:8765 -e RELOCK_TOKEN=change-me ghcr.io/inboxpraveen/relock # HTTP API
62
118
  ```
63
119
 
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"`.
120
+ It works with Python agents, any MCP client, and any language over HTTP/JSON: Rust, TypeScript,
121
+ Go and others. See [Plug it into your stack](https://github.com/inboxpraveen/relock#plug-it-into-your-stack).
69
122
 
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.
123
+ The extras install one at a time too: `[postgres]`, `[mcp]`, `[langchain]`. The import is
124
+ `relock_memory`. The PyPI name `relock` belongs to an unrelated SDK.
125
+
126
+ > **Status:** v0.2, beta. CI tests it on Python 3.10–3.14, on SQLite and Postgres, with `mcp`
127
+ > 1.x and 2.x, and from Rust, TypeScript and curl over HTTP. Behavioural results on 8 hosted
128
+ > models are in [docs/results/models](https://github.com/inboxpraveen/relock/blob/main/docs/results/models/).
74
129
 
75
130
  ---
76
131
 
77
132
  ## The mechanism
78
133
 
134
+ Unlock on recall, rewrite on surprise, re-lock.
135
+
79
136
  relock borrows the *shape* of memory reconsolidation from neuroscience (a recalled memory becomes
80
137
  briefly editable, and prediction error drives the update). It is a metaphor for an engineering
81
138
  discipline, not a biological claim. The neuroscience is mostly animal work, and human results are mixed.
@@ -145,6 +202,27 @@ safe is **the model predicts, the harness judges**.
145
202
  | Raw tool calling (OpenAI-compatible, Anthropic, vLLM, Ollama) | `relock.Toolkit(mem).openai_tools()` / `.anthropic_tools()` + `toolkit.call(name, args)` | a dispatcher branch |
146
203
  | 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
204
  | 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 |
205
+ | **Any language**: Rust, TypeScript, Go, Java, C#... | `relock serve` or `docker run ghcr.io/inboxpraveen/relock`, then HTTP/JSON ([OpenAPI](https://github.com/inboxpraveen/relock/blob/main/docs/openapi.json), [guide](https://github.com/inboxpraveen/relock/blob/main/docs/http.md)) | 4 HTTP calls per task |
206
+
207
+ ### HTTP: any language
208
+
209
+ ```
210
+ RELOCK_TOKEN=change-me relock serve # or: docker run -p 8765:8765 -e RELOCK_TOKEN=change-me ghcr.io/inboxpraveen/relock
211
+ ```
212
+
213
+ Each task is four calls from your harness:
214
+
215
+ | step | request |
216
+ |---|---|
217
+ | open | `POST /v1/episodes` |
218
+ | recall into the prompt | `POST /v1/episodes/{id}/recall` |
219
+ | report each tool call's real outcome | `POST /v1/episodes/{id}/tool-result` |
220
+ | re-lock | `POST /v1/episodes/{id}/close` |
221
+
222
+ Clients for [Rust](https://github.com/inboxpraveen/relock/blob/main/examples/http/rust/src/main.rs), [TypeScript](https://github.com/inboxpraveen/relock/blob/main/examples/http/typescript/relock.ts)
223
+ and [curl](https://github.com/inboxpraveen/relock/blob/main/examples/http/curl.sh) run this loop against a live server in CI. The full API is in
224
+ [docs/http.md](https://github.com/inboxpraveen/relock/blob/main/docs/http.md). The server has no dependencies. Without a token it listens only on
225
+ loopback, and it refuses a public address without one.
148
226
 
149
227
  ### MCP
150
228
 
@@ -223,7 +301,9 @@ relock answers that structurally, through the retrieval trace, the cited clauses
223
301
  diff. The rewriter only has to make a *local* edit: "here is the item, here is what it predicted,
224
302
  here is what happened, rewrite this clause". The rewrite prompt is built for that size class:
225
303
  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.
304
+ retry, `<think>` blocks are stripped, and the deterministic `HintRewriter` is the fallback. In the
305
+ [behavioural study](https://github.com/inboxpraveen/relock/blob/main/docs/results/models/), each of the 8 models wrote relock's rewrites
306
+ itself, two of them 27B models. None of the 960 rewrites fell back to `HintRewriter`.
227
307
 
228
308
  ```python
229
309
  llm = relock.OpenAICompatible("http://localhost:8000/v1", model="Qwen/Qwen3-30B-A3B-Instruct-2507")
@@ -292,20 +372,36 @@ What it shows:
292
372
  threshold), where append-style systems need 1. That is one extra failure per drift, paid for
293
373
  robustness against one-off noise. Set `min_evidence=1` to trade it back.
294
374
 
295
- ### Behavioural mode (harness ready, results pending)
375
+ ### Behavioural mode (8 hosted models)
376
+
377
+ This mode measures what a model actually does after a correction. The agent learns from its own
378
+ failures, the same model writes relock's rewrites, and then it is probed under load. The study
379
+ compares four systems: `append-notes`, `append-clause`, `append-gated` and `relock`. The other
380
+ systems above ran only in structural mode.
381
+
382
+ ![Correct calls by load, pooled over models](https://raw.githubusercontent.com/inboxpraveen/relock/main/docs/results/models/by-load.svg)
383
+
384
+ | load | append-notes | append-clause | append-gated | relock |
385
+ |---|---|---|---|---|
386
+ | L0: fresh session | 45% | 5% | 50% | 94% |
387
+ | L1: 1.5k-token history | 46% | 10% | 50% | 99% |
388
+ | L2: 4k-token history | 46% | 11% | 52% | 98% |
389
+ | L3: 8k-token history, tight memory | 60% | 52% | 74% | 98% |
390
+
391
+ Correct-call rates are pooled over 8 models and 3 seeds. Over all loads, relapse to the old rule
392
+ and following the poisoned rule were each 0% with relock, against 22% and 25% with append-notes.
393
+ The models wrote all 960 of relock's rewrites themselves, and none fell back to the deterministic
394
+ rewriter; the correction text came from the tool error. The per-model and per-task tables, the
395
+ costs and the caveats are in [docs/results/models](https://github.com/inboxpraveen/relock/blob/main/docs/results/models/).
296
396
 
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:
397
+ To run it on your own model:
299
398
 
300
399
  ```
301
400
  relock bench --mode behavioral --base-url http://localhost:8000/v1 \
302
401
  --model Qwen/Qwen3-30B-A3B-Instruct-2507
303
402
  ```
304
403
 
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`.
404
+ Results on other models are welcome; please include `behavioral.json`.
309
405
 
310
406
  ## CLI
311
407
 
@@ -320,6 +416,7 @@ relock rollback orders.fetch 1 # restores v1 as a new version (history is nev
320
416
  relock edit orders.fetch --replace c2 "Pass dates as YYYY-MM-DD."
321
417
  relock export traces.jsonl # SFT and preference pairs from every rewrite
322
418
  relock mcp --verifier tests="pytest -q" [--cwd DIR] [--allow-teach] [--trust-agent-reports]
419
+ relock serve [--host H] [--port P] # HTTP/JSON API for any language (RELOCK_TOKEN for auth)
323
420
  relock bench [--mode structural|behavioral|both]
324
421
  ```
325
422
 
@@ -356,21 +453,23 @@ directly queryable. The schema is documented in [docs/design.md](https://github.
356
453
  - **ReasoningBank** distils strategies from the agent's own judged successes and failures.
357
454
  - **ACE** grows playbooks through incremental deltas with helpful/harmful counters.
358
455
 
359
- relock combines three things we have not seen packaged together:
456
+ Mem0 can also update a memory in place, when its model chooses to. relock combines four things we
457
+ have not seen packaged together:
360
458
 
361
- - writes gated on **retrieval** (lability),
362
- - triggered by an **explicit, trusted prediction error**,
363
- - applied **in place with supersession** rather than appended.
459
+ - writes gated on **retrieval** (lability);
460
+ - triggered by an **explicit, trusted prediction error**, never by what the model read;
461
+ - **scoped to the clause that fired**;
462
+ - applied **in place with supersession** rather than appended, with every version kept.
364
463
 
365
464
  It is meant to sit under any of these styles, or under your own harness.
366
465
 
367
466
  ## Roadmap
368
467
 
369
- - Behavioural RelapseBench results on open ~30B models, plus a long-horizon variant with real
468
+ - Behavioural RelapseBench on self-hosted open models, plus a long-horizon variant with real
370
469
  context compaction.
371
470
  - Weight tier: periodically distil accumulated rewrite traces for a skill into adapter weights.
372
471
  Fast edits live in the harness, durable ones in the weights.
373
- - pgvector retrieval inside Postgres; a TypeScript client for the MCP server.
472
+ - pgvector retrieval inside Postgres; published client packages for the HTTP API (npm, crates.io).
374
473
  - Per-tenant ledgers and signed user corrections.
375
474
 
376
475
  ## Development
@@ -383,7 +482,7 @@ RELOCK_TEST_POSTGRES_URL=postgresql://... pytest # + Postgres
383
482
  ruff check src tests examples
384
483
  ```
385
484
 
386
- CI runs the suite on Python 3.10–3.13 against SQLite and Postgres. It also runs the MCP tests
485
+ CI runs the suite on Python 3.10–3.14 against SQLite and Postgres. It also runs the MCP tests
387
486
  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
487
  keep. Report vulnerabilities privately as described in [SECURITY.md](https://github.com/inboxpraveen/relock/blob/main/SECURITY.md).
389
488
 
@@ -5,33 +5,89 @@
5
5
  [![python](https://img.shields.io/pypi/pyversions/relock-memory)](https://pypi.org/project/relock-memory/)
6
6
  [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
7
7
 
8
- **Agent memory that unlocks on recall, rewrites on surprise, and re-locks.**
8
+ **Agent memory that fixes the rule that fired, in place and only on trusted evidence, so
9
+ corrected mistakes don't come back.**
9
10
 
10
- Most agent memories fix a mistake by *appending* ("don't do X"). The old instruction stays
11
- retrievable, and under long context, compaction or distracting tool output the old default wins
12
- again. relock fixes the instruction that fired, in place, but only when a **trusted** signal shows
13
- that its prediction was wrong, and only while that memory is **reactivated**.
11
+ You corrected your agent: the orders API takes ISO dates now. Its memory saved the lesson as a
12
+ note. Days later, deep into a long session, it sends `03/14/2026` again. The old rule was still in
13
+ memory, next to the note, and the model followed it.
14
+
15
+ Lesson notes, rules files and playbooks all keep both rules and hope the model picks the right
16
+ one. relock edits the rule that fired, in place, under three conditions:
17
+
18
+ - **Only on trusted evidence.** A typed tool error, a verifier or an authenticated user can
19
+ trigger a rewrite. The model's own claims, a web page, a timeout or a one-off flaky check can't.
20
+ - **Only while that memory is recalled** in the current task. The retrieval trace records which
21
+ memory caused the failure, so the model never has to guess.
22
+ - **The old version is kept, but never retrieved again.** Every version and every decision is
23
+ stored for audit and rollback.
24
+
25
+ ![Correct tool calls per model in a long session: append-notes, append-gated and relock](docs/results/models/by-model.svg)
26
+
27
+ **The study:** 8 hosted models and 10 changed tool contracts, in long sessions with stale docs and
28
+ a prompt injection in context. With relock, agents made the corrected call **98%** of the time.
29
+ - A memory that appends each lesson as a note managed **60%**.
30
+ - Appending the correction to the procedure, like a rules file, managed **52%**.
31
+ - relock was ahead on all 8 models, with the 95% intervals apart for all 8.
32
+
33
+ **Isolating the mechanism.** The baselines are our own implementations of those patterns, run on
34
+ the same events. `append-gated` keeps relock's trust gate but still appends, and it reached
35
+ **74%**: the gate keeps the poisoned "fix" out, and replacing the rule is what stops the relapse.
36
+
37
+ The design was committed before the run, and every call is published. See the
38
+ [results](docs/results/models/): 11,520 probe calls, $7.33 in API spend.
39
+
40
+ ## Is this your problem?
41
+
42
+ relock is for you if:
43
+ - your agent calls tools or APIs, and corrections to how it calls them don't stick;
44
+ - your memory or rules file keeps growing "actually, do X instead" notes;
45
+ - your agent learns from its own failures, and a prompt injection or a flaky test must not be able
46
+ to change what it learned.
47
+
48
+ It is not for chat history, document RAG, or agents with no tool outcomes to learn from.
49
+
50
+ ## What's different
51
+
52
+ | | lesson notes, vector memories | rules file, playbook | LLM-managed memory (a model picks add / update / delete) | relock |
53
+ |---|---|---|---|---|
54
+ | A correction replaces the old rule | no: both are retrievable | no: both are in the file | if the model chooses to | yes: the clause that fired is superseded |
55
+ | What can change memory | any write | any write | a model, deciding from what it read | trusted signals only |
56
+ | A prompt injection's "fix" | stored | stored | can be stored | logged, never applied |
57
+ | A one-off flaky failure | stored | stored | can be stored | needs a second trusted error; the next success cancels it |
58
+ | Which memory caused a failure | the model guesses | the model guesses | the model guesses | recorded by the retrieval trace |
59
+ | History | varies | git, if any | varies | every version and decision, with rollback |
60
+
61
+ Each idea exists somewhere, but we have not seen them packaged together:
62
+ - writes are allowed only while a memory is recalled;
63
+ - a write is triggered by a trusted prediction error;
64
+ - the edit is scoped to the clause that fired;
65
+ - the new version supersedes the old one instead of being appended.
66
+
67
+ ## Install
14
68
 
15
69
  ```
16
70
  pip install relock-memory # core: zero dependencies
17
71
  pip install "relock-memory[all]" # + Postgres, MCP, LangChain/LangGraph
72
+ docker run -p 8765:8765 -e RELOCK_TOKEN=change-me ghcr.io/inboxpraveen/relock # HTTP API
18
73
  ```
19
74
 
20
- The extras can also be installed one at a time: `[postgres]`, `[mcp]`, `[langchain]`.
21
- The distribution is `relock-memory` and the import is `relock_memory`, because the PyPI name
22
- `relock` belongs to an unrelated SDK that also installs a top-level `relock` module.
23
- The development version installs with
24
- `pip install "relock-memory @ git+https://github.com/inboxpraveen/relock"`.
75
+ It works with Python agents, any MCP client, and any language over HTTP/JSON: Rust, TypeScript,
76
+ Go and others. See [Plug it into your stack](#plug-it-into-your-stack).
25
77
 
26
- > **Status:** v0.1, alpha. The mechanism, storage, integrations and benchmark harness are
27
- > complete. They are tested on Python 3.10–3.13, SQLite and Postgres, and `mcp` 1.x and 2.x.
28
- > Behavioural benchmark numbers on open models are **not published yet**; see
29
- > [RelapseBench](#relapsebench) for what has and has not been measured.
78
+ The extras install one at a time too: `[postgres]`, `[mcp]`, `[langchain]`. The import is
79
+ `relock_memory`. The PyPI name `relock` belongs to an unrelated SDK.
80
+
81
+ > **Status:** v0.2, beta. CI tests it on Python 3.10–3.14, on SQLite and Postgres, with `mcp`
82
+ > 1.x and 2.x, and from Rust, TypeScript and curl over HTTP. Behavioural results on 8 hosted
83
+ > models are in [docs/results/models](docs/results/models/).
30
84
 
31
85
  ---
32
86
 
33
87
  ## The mechanism
34
88
 
89
+ Unlock on recall, rewrite on surprise, re-lock.
90
+
35
91
  relock borrows the *shape* of memory reconsolidation from neuroscience (a recalled memory becomes
36
92
  briefly editable, and prediction error drives the update). It is a metaphor for an engineering
37
93
  discipline, not a biological claim. The neuroscience is mostly animal work, and human results are mixed.
@@ -112,6 +168,27 @@ safe is **the model predicts, the harness judges**.
112
168
  | Raw tool calling (OpenAI-compatible, Anthropic, vLLM, Ollama) | `relock.Toolkit(mem).openai_tools()` / `.anthropic_tools()` + `toolkit.call(name, args)` | a dispatcher branch |
113
169
  | LangChain / LangGraph | `RelockCallbackHandler(mem)` in `config={"callbacks": [...]}`. Existing tools stay untouched. `langchain_tools(Toolkit(mem))` gives the model `recall_memory` / `state_expectation`. | 1 line |
114
170
  | 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 |
171
+ | **Any language**: Rust, TypeScript, Go, Java, C#... | `relock serve` or `docker run ghcr.io/inboxpraveen/relock`, then HTTP/JSON ([OpenAPI](docs/openapi.json), [guide](docs/http.md)) | 4 HTTP calls per task |
172
+
173
+ ### HTTP: any language
174
+
175
+ ```
176
+ RELOCK_TOKEN=change-me relock serve # or: docker run -p 8765:8765 -e RELOCK_TOKEN=change-me ghcr.io/inboxpraveen/relock
177
+ ```
178
+
179
+ Each task is four calls from your harness:
180
+
181
+ | step | request |
182
+ |---|---|
183
+ | open | `POST /v1/episodes` |
184
+ | recall into the prompt | `POST /v1/episodes/{id}/recall` |
185
+ | report each tool call's real outcome | `POST /v1/episodes/{id}/tool-result` |
186
+ | re-lock | `POST /v1/episodes/{id}/close` |
187
+
188
+ Clients for [Rust](examples/http/rust/src/main.rs), [TypeScript](examples/http/typescript/relock.ts)
189
+ and [curl](examples/http/curl.sh) run this loop against a live server in CI. The full API is in
190
+ [docs/http.md](docs/http.md). The server has no dependencies. Without a token it listens only on
191
+ loopback, and it refuses a public address without one.
115
192
 
116
193
  ### MCP
117
194
 
@@ -190,7 +267,9 @@ relock answers that structurally, through the retrieval trace, the cited clauses
190
267
  diff. The rewriter only has to make a *local* edit: "here is the item, here is what it predicted,
191
268
  here is what happened, rewrite this clause". The rewrite prompt is built for that size class:
192
269
  one item, explicit clause ids, strict JSON, one worked example. Invalid output is fed back for a
193
- retry, `<think>` blocks are stripped, and the deterministic `HintRewriter` is the fallback.
270
+ retry, `<think>` blocks are stripped, and the deterministic `HintRewriter` is the fallback. In the
271
+ [behavioural study](docs/results/models/), each of the 8 models wrote relock's rewrites
272
+ itself, two of them 27B models. None of the 960 rewrites fell back to `HintRewriter`.
194
273
 
195
274
  ```python
196
275
  llm = relock.OpenAICompatible("http://localhost:8000/v1", model="Qwen/Qwen3-30B-A3B-Instruct-2507")
@@ -259,20 +338,36 @@ What it shows:
259
338
  threshold), where append-style systems need 1. That is one extra failure per drift, paid for
260
339
  robustness against one-off noise. Set `min_evidence=1` to trade it back.
261
340
 
262
- ### Behavioural mode (harness ready, results pending)
341
+ ### Behavioural mode (8 hosted models)
342
+
343
+ This mode measures what a model actually does after a correction. The agent learns from its own
344
+ failures, the same model writes relock's rewrites, and then it is probed under load. The study
345
+ compares four systems: `append-notes`, `append-clause`, `append-gated` and `relock`. The other
346
+ systems above ran only in structural mode.
347
+
348
+ ![Correct calls by load, pooled over models](docs/results/models/by-load.svg)
349
+
350
+ | load | append-notes | append-clause | append-gated | relock |
351
+ |---|---|---|---|---|
352
+ | L0: fresh session | 45% | 5% | 50% | 94% |
353
+ | L1: 1.5k-token history | 46% | 10% | 50% | 99% |
354
+ | L2: 4k-token history | 46% | 11% | 52% | 98% |
355
+ | L3: 8k-token history, tight memory | 60% | 52% | 74% | 98% |
356
+
357
+ Correct-call rates are pooled over 8 models and 3 seeds. Over all loads, relapse to the old rule
358
+ and following the poisoned rule were each 0% with relock, against 22% and 25% with append-notes.
359
+ The models wrote all 960 of relock's rewrites themselves, and none fell back to the deterministic
360
+ rewriter; the correction text came from the tool error. The per-model and per-task tables, the
361
+ costs and the caveats are in [docs/results/models](docs/results/models/).
263
362
 
264
- Whether a model actually relapses when the old and new rules sit side by side, or when the
265
- correction was compacted away, is the headline question. It needs a real model:
363
+ To run it on your own model:
266
364
 
267
365
  ```
268
366
  relock bench --mode behavioral --base-url http://localhost:8000/v1 \
269
367
  --model Qwen/Qwen3-30B-A3B-Instruct-2507
270
368
  ```
271
369
 
272
- This runs a closed loop: the agent learns from its own failures, the same model performs relock's
273
- rewrites, and then it is probed under load. Reported metrics are relapse, poisoned and correct
274
- rates with Wilson intervals, plus learning cost. **No behavioural numbers are published yet.**
275
- Contributions of runs on open models are very welcome; please include `behavioral.json`.
370
+ Results on other models are welcome; please include `behavioral.json`.
276
371
 
277
372
  ## CLI
278
373
 
@@ -287,6 +382,7 @@ relock rollback orders.fetch 1 # restores v1 as a new version (history is nev
287
382
  relock edit orders.fetch --replace c2 "Pass dates as YYYY-MM-DD."
288
383
  relock export traces.jsonl # SFT and preference pairs from every rewrite
289
384
  relock mcp --verifier tests="pytest -q" [--cwd DIR] [--allow-teach] [--trust-agent-reports]
385
+ relock serve [--host H] [--port P] # HTTP/JSON API for any language (RELOCK_TOKEN for auth)
290
386
  relock bench [--mode structural|behavioral|both]
291
387
  ```
292
388
 
@@ -323,21 +419,23 @@ directly queryable. The schema is documented in [docs/design.md](docs/design.md)
323
419
  - **ReasoningBank** distils strategies from the agent's own judged successes and failures.
324
420
  - **ACE** grows playbooks through incremental deltas with helpful/harmful counters.
325
421
 
326
- relock combines three things we have not seen packaged together:
422
+ Mem0 can also update a memory in place, when its model chooses to. relock combines four things we
423
+ have not seen packaged together:
327
424
 
328
- - writes gated on **retrieval** (lability),
329
- - triggered by an **explicit, trusted prediction error**,
330
- - applied **in place with supersession** rather than appended.
425
+ - writes gated on **retrieval** (lability);
426
+ - triggered by an **explicit, trusted prediction error**, never by what the model read;
427
+ - **scoped to the clause that fired**;
428
+ - applied **in place with supersession** rather than appended, with every version kept.
331
429
 
332
430
  It is meant to sit under any of these styles, or under your own harness.
333
431
 
334
432
  ## Roadmap
335
433
 
336
- - Behavioural RelapseBench results on open ~30B models, plus a long-horizon variant with real
434
+ - Behavioural RelapseBench on self-hosted open models, plus a long-horizon variant with real
337
435
  context compaction.
338
436
  - Weight tier: periodically distil accumulated rewrite traces for a skill into adapter weights.
339
437
  Fast edits live in the harness, durable ones in the weights.
340
- - pgvector retrieval inside Postgres; a TypeScript client for the MCP server.
438
+ - pgvector retrieval inside Postgres; published client packages for the HTTP API (npm, crates.io).
341
439
  - Per-tenant ledgers and signed user corrections.
342
440
 
343
441
  ## Development
@@ -350,7 +448,7 @@ RELOCK_TEST_POSTGRES_URL=postgresql://... pytest # + Postgres
350
448
  ruff check src tests examples
351
449
  ```
352
450
 
353
- CI runs the suite on Python 3.10–3.13 against SQLite and Postgres. It also runs the MCP tests
451
+ CI runs the suite on Python 3.10–3.14 against SQLite and Postgres. It also runs the MCP tests
354
452
  on the `mcp` 1.x line. See [CONTRIBUTING.md](CONTRIBUTING.md) for the invariants a change must
355
453
  keep. Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md).
356
454
 
@@ -164,6 +164,8 @@ WHERE v.change_kind = 'reconsolidate' AND v.created_at > now() - interval '7 day
164
164
  | A bad rewrite slips through | Full version history; `rollback` restores any version as a new version; every decision is in `relock_events`. |
165
165
  | 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
166
  | "The user said so" | `Signal.user` and `Episode.correct` default to `authenticated=False` and are blocked; the application must vouch for the user explicitly. |
167
+ | Someone on the network rewrites memory through the HTTP API | `relock serve` trusts the `source` its caller declares, so callers must be your harness. Without `RELOCK_TOKEN` it binds only to loopback and refuses a public address. With a token, every route except health and the OpenAPI document needs `Authorization: Bearer`, and the token check runs in constant time. JSON types are strict, so `"authenticated": "false"` is rejected rather than read as true. Bodies are capped at 1 MiB, and a request carrying both framings is refused. Connections and open episodes are capped, stalled connections time out, and idle episodes are re-locked in the background. |
168
+ | A write races the episode's close | `observe`, `expect`, `recall` and `use` re-check that the episode is open under the lock `close()` takes. A close that lands mid-request wins, and the write fails with `EpisodeClosedError` instead of committing after re-lock. `tool_result` binds and resolves under that lock, so concurrent reports never collide. |
167
169
 
168
170
  Not mitigated in v0.1:
169
171