polign-recall 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.
@@ -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 2026 Polign, Inc.
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,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: polign-recall
3
+ Version: 0.2.0
4
+ Summary: Typed, correctable agent memory through Recall's MCP server
5
+ Author: Polign
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/Polign/recall
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # polign-recall
14
+
15
+ A Python client for Recall's typed, correctable agent memory. Requires Python
16
+ 3.10+ and `polign` CLI v0.6.4+ on PATH. No Python runtime dependencies.
17
+
18
+ ```sh
19
+ pip install ./python
20
+ polign-server -store fs:./recall-data
21
+ ```
22
+
23
+ In another terminal:
24
+
25
+ ```python
26
+ from polign_recall import Client
27
+
28
+ with Client() as memory:
29
+ memory.remember("user", "prefers_editor", "vim")
30
+ changed = memory.remember("user", "prefers_editor", "neovim")
31
+ print(memory.recall("user", "prefers_editor")[0].value) # neovim
32
+ print(memory.history("user", "prefers_editor")) # both statements
33
+ memory.forget("user", "prefers_editor", "neovim")
34
+ ```
35
+
36
+ The client owns a long-lived `polign mcp -memory-only -write` subprocess and
37
+ shares the Go implementation's validation and fold. Set `POLIGN_URL`,
38
+ `POLIGN_API_KEY`, and `POLIGN_COLLECTION` in the environment, or pass
39
+ `env={...}` to Client. Use `write=False` for a read-only connection.
40
+
41
+ `remember(text=..., statements=[...])` accepts proposals from your agent's model;
42
+ the client does not run a second model. Every statement must have subject,
43
+ predicate, typed value, and evidence quoting the text exactly. Read `predicates()`
44
+ to build your extractor prompt. No separate extraction tool is required.
45
+
46
+ `recall(..., as_of=...)` accepts an RFC3339 string or timezone-aware datetime.
47
+ `forget` requires a typed value or explicit `all=True`; false and zero remain
48
+ values. Forgetting retracts a belief and retains its historical events.
49
+
50
+ Errors raise `RecallError` with a code and, for a failed extraction batch, any
51
+ reported partial results. Calls are serialized, timeout after 120 seconds by
52
+ default, and never automatically retry writes. A timeout closes the transport;
53
+ inspect history using a new client before retrying an uncertain write.
@@ -0,0 +1,41 @@
1
+ # polign-recall
2
+
3
+ A Python client for Recall's typed, correctable agent memory. Requires Python
4
+ 3.10+ and `polign` CLI v0.6.4+ on PATH. No Python runtime dependencies.
5
+
6
+ ```sh
7
+ pip install ./python
8
+ polign-server -store fs:./recall-data
9
+ ```
10
+
11
+ In another terminal:
12
+
13
+ ```python
14
+ from polign_recall import Client
15
+
16
+ with Client() as memory:
17
+ memory.remember("user", "prefers_editor", "vim")
18
+ changed = memory.remember("user", "prefers_editor", "neovim")
19
+ print(memory.recall("user", "prefers_editor")[0].value) # neovim
20
+ print(memory.history("user", "prefers_editor")) # both statements
21
+ memory.forget("user", "prefers_editor", "neovim")
22
+ ```
23
+
24
+ The client owns a long-lived `polign mcp -memory-only -write` subprocess and
25
+ shares the Go implementation's validation and fold. Set `POLIGN_URL`,
26
+ `POLIGN_API_KEY`, and `POLIGN_COLLECTION` in the environment, or pass
27
+ `env={...}` to Client. Use `write=False` for a read-only connection.
28
+
29
+ `remember(text=..., statements=[...])` accepts proposals from your agent's model;
30
+ the client does not run a second model. Every statement must have subject,
31
+ predicate, typed value, and evidence quoting the text exactly. Read `predicates()`
32
+ to build your extractor prompt. No separate extraction tool is required.
33
+
34
+ `recall(..., as_of=...)` accepts an RFC3339 string or timezone-aware datetime.
35
+ `forget` requires a typed value or explicit `all=True`; false and zero remain
36
+ values. Forgetting retracts a belief and retains its historical events.
37
+
38
+ Errors raise `RecallError` with a code and, for a failed extraction batch, any
39
+ reported partial results. Calls are serialized, timeout after 120 seconds by
40
+ default, and never automatically retry writes. A timeout closes the transport;
41
+ inspect history using a new client before retrying an uncertain write.
@@ -0,0 +1,5 @@
1
+ """Recall client. Uses the installed `polign mcp` executable over stdio."""
2
+ from .client import Belief, Client, Event, RecallError, RememberResult, ExtractionResult
3
+
4
+ __all__ = ["Belief", "Client", "Event", "RecallError", "RememberResult", "ExtractionResult"]
5
+ __version__ = "0.2.0"
@@ -0,0 +1,265 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import os
6
+ import queue
7
+ import subprocess
8
+ import threading
9
+ import time
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from typing import Any, Mapping, Sequence
13
+
14
+ Value = str | float | bool
15
+ _MISSING = object()
16
+
17
+
18
+ class RecallError(Exception):
19
+ """A tool or transport failure. Writes are never retried automatically."""
20
+
21
+ def __init__(self, message: str, *, code: str = "tool_error", partial: Any = None):
22
+ super().__init__(message)
23
+ self.code = code
24
+ self.partial = partial
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Belief:
29
+ subject: str
30
+ predicate: str
31
+ value: Value
32
+ confidence: float
33
+ source: str
34
+ kind: str
35
+ observed_at: str
36
+ event_id: str
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Event:
41
+ id: str
42
+ kind: str
43
+ subject: str
44
+ predicate: str
45
+ value: Value | None
46
+ confidence: float
47
+ source: str
48
+ observed_at: str
49
+ retraction: bool = False
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class RememberResult:
54
+ stored: Belief
55
+ already_known: bool
56
+ superseded: tuple[Belief, ...]
57
+
58
+ @classmethod
59
+ def decode(cls, data: dict[str, Any]) -> RememberResult:
60
+ return cls(Belief(**data["stored"]), data.get("already_known", False),
61
+ tuple(Belief(**b) for b in data.get("superseded", [])))
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class ExtractionResult:
66
+ proposals: tuple[dict[str, Any], ...]
67
+ results: tuple[RememberResult, ...]
68
+
69
+
70
+ class Client:
71
+ """Owns one MCP subprocess. Thread-safe, with serialized calls and timeouts.
72
+
73
+ Environment overrides extend the inherited environment. Credentials belong
74
+ in POLIGN_API_KEY, not command-line arguments. The default enables memory
75
+ writes; pass write=False to expose only read operations.
76
+ """
77
+
78
+ def __init__(self, *, command: Sequence[str] | None = None,
79
+ env: Mapping[str, str] | None = None, timeout: float = 120,
80
+ write: bool = True):
81
+ if not math.isfinite(timeout) or timeout <= 0:
82
+ raise ValueError("timeout must be finite and positive")
83
+ self.timeout = timeout
84
+ self._lock = threading.RLock()
85
+ self._responses: queue.Queue[Any] = queue.Queue()
86
+ self._id = 0
87
+ self._closed = False
88
+ argv = list(command) if command is not None else ["polign", "mcp", "-memory-only"] + (["-write"] if write else [])
89
+ try:
90
+ self._process = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
91
+ stderr=None, env={**os.environ, **(env or {})})
92
+ except OSError as exc:
93
+ # The documented contract is that failures arrive as RecallError.
94
+ # A missing binary is the most common first run, and it must not
95
+ # escape as a bare OSError with no hint about what to install.
96
+ raise RecallError(f"could not start {argv[0]!r}: {exc}",
97
+ code="transport_error") from exc
98
+ self._reader = threading.Thread(target=self._read, daemon=True)
99
+ self._reader.start()
100
+ try:
101
+ self._rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
102
+ "clientInfo": {"name": "polign-recall-python", "version": "0.1.0"}})
103
+ self._send({"jsonrpc": "2.0", "method": "notifications/initialized"})
104
+ except BaseException:
105
+ self.close()
106
+ raise
107
+
108
+ def _read(self) -> None:
109
+ try:
110
+ assert self._process.stdout is not None
111
+ while True:
112
+ line = self._process.stdout.readline((8 << 20) + 1)
113
+ if not line:
114
+ raise EOFError("MCP server closed stdout")
115
+ if len(line) > 8 << 20:
116
+ raise ValueError("MCP response exceeds 8 MiB")
117
+ self._responses.put(json.loads(line))
118
+ except Exception as exc:
119
+ self._responses.put(exc)
120
+
121
+ def _send(self, message: dict[str, Any]) -> None:
122
+ payload = (json.dumps(message, allow_nan=False) + "\n").encode()
123
+ assert self._process.stdin is not None
124
+ # The write has to be bounded like the read. A server that stops
125
+ # draining its stdin blocks this call forever once the payload passes
126
+ # the pipe buffer, and the blocked call holds the lock close() needs, so
127
+ # no other thread can even shut the client down.
128
+ failure: list[BaseException] = []
129
+ done = threading.Event()
130
+
131
+ def write() -> None:
132
+ try:
133
+ self._process.stdin.write(payload)
134
+ self._process.stdin.flush()
135
+ except BaseException as exc: # re-raised on the calling thread
136
+ failure.append(exc)
137
+ finally:
138
+ done.set()
139
+
140
+ threading.Thread(target=write, daemon=True).start()
141
+ if not done.wait(self.timeout):
142
+ # close() ends the child, which unblocks the writer. The lock is
143
+ # reentrant and held by this thread, so this cannot deadlock.
144
+ self.close()
145
+ raise RecallError("MCP write timed out; the server stopped reading its input",
146
+ code="timeout")
147
+ if failure:
148
+ exc = failure[0]
149
+ if isinstance(exc, (OSError, ValueError)):
150
+ raise RecallError(str(exc), code="transport_error") from exc
151
+ raise exc
152
+
153
+ def _rpc(self, method: str, params: dict[str, Any]) -> Any:
154
+ with self._lock:
155
+ if self._closed:
156
+ raise RecallError("client is closed", code="closed")
157
+ self._id += 1
158
+ self._send({"jsonrpc": "2.0", "id": self._id, "method": method, "params": params})
159
+ deadline = time.monotonic() + self.timeout
160
+ while True:
161
+ try:
162
+ response = self._responses.get(timeout=max(0.0, deadline - time.monotonic()))
163
+ except queue.Empty as exc:
164
+ self.close()
165
+ raise RecallError("MCP call timed out; write outcome may be unknown", code="timeout") from exc
166
+ if isinstance(response, Exception):
167
+ self.close()
168
+ raise RecallError(str(response), code="transport_error") from response
169
+ # Anything carrying a method is a notification or a request the
170
+ # server started, not an answer to this call, and an older id is
171
+ # a reply to a call already abandoned. Neither is a protocol
172
+ # violation, and neither should destroy the session.
173
+ if "method" in response or response.get("id") != self._id:
174
+ continue
175
+ break
176
+ if "error" in response:
177
+ raise RecallError(response["error"]["message"], code="protocol_error")
178
+ return response["result"]
179
+
180
+ def _tool(self, name: str, arguments: dict[str, Any]) -> Any:
181
+ result = self._rpc("tools/call", {"name": name, "arguments": arguments})
182
+ try:
183
+ text = "\n".join(c["text"] for c in result["content"] if c["type"] == "text")
184
+ except (KeyError, TypeError) as exc:
185
+ raise RecallError(f"malformed {name} result: {exc}", code="protocol_error") from exc
186
+ if result.get("isError"):
187
+ partial = None
188
+ try:
189
+ partial = json.loads(text).get("partial")
190
+ except (ValueError, AttributeError):
191
+ pass
192
+ raise RecallError(text, partial=partial)
193
+ try:
194
+ return json.loads(text)
195
+ except ValueError as exc:
196
+ raise RecallError(f"malformed {name} result: {exc}", code="protocol_error") from exc
197
+
198
+ def remember(self, subject: str | None = None, predicate: str | None = None,
199
+ value: Any = _MISSING, *, text: str | None = None,
200
+ statements: Sequence[Mapping[str, Any]] | None = None,
201
+ kind: str | None = None, confidence: float | None = None,
202
+ source: str | None = None) -> RememberResult | ExtractionResult:
203
+ if text is not None:
204
+ if any(x is not None for x in (subject, predicate, kind, confidence, source)) or value is not _MISSING:
205
+ raise ValueError("text mode cannot be combined with typed fields")
206
+ if statements is None:
207
+ raise ValueError("text mode requires statements proposed by your agent")
208
+ data = self._tool("remember", {"text": text, "statements": list(statements)})
209
+ return ExtractionResult(tuple(data.get("proposals") or []),
210
+ tuple(RememberResult.decode(r) for r in data["results"]))
211
+ if statements is not None:
212
+ raise ValueError("statements requires original text")
213
+ if subject is None or predicate is None or value is _MISSING:
214
+ raise ValueError("typed remember requires subject, predicate, and value")
215
+ args = {"subject": subject, "predicate": predicate, "value": value}
216
+ args.update({k: v for k, v in {"kind": kind, "confidence": confidence, "source": source}.items() if v is not None})
217
+ return RememberResult.decode(self._tool("remember", args))
218
+
219
+ def recall(self, subject: str | None = None, predicate: str | None = None, *,
220
+ query: str | None = None, as_of: str | datetime | None = None,
221
+ min_confidence: float | None = None, limit: int | None = None) -> list[Belief]:
222
+ if isinstance(as_of, datetime):
223
+ if as_of.tzinfo is None:
224
+ raise ValueError("as_of datetime must include a timezone")
225
+ as_of = as_of.isoformat()
226
+ args = {"subject": subject, "predicate": predicate, "query": query,
227
+ "as_of": as_of, "min_confidence": min_confidence, "limit": limit}
228
+ return [Belief(**b) for b in self._tool("recall", {k: v for k, v in args.items() if v is not None}) or []]
229
+
230
+ def forget(self, subject: str, predicate: str, value: Any = _MISSING, *, all: bool = False) -> int:
231
+ if all == (value is not _MISSING) or value is None:
232
+ raise ValueError("forget requires exactly one typed value or all=True")
233
+ args = {"subject": subject, "predicate": predicate}
234
+ if value is not _MISSING:
235
+ args["value"] = value
236
+ return self._tool("forget", args)["withdrawn"]
237
+
238
+ def history(self, subject: str, predicate: str) -> list[Event]:
239
+ return [Event(**e) for e in self._tool("memory_history", {"subject": subject, "predicate": predicate}) or []]
240
+
241
+ def predicates(self) -> list[dict[str, Any]]:
242
+ return self._tool("list_predicates", {})
243
+
244
+ def close(self) -> None:
245
+ with self._lock:
246
+ if self._closed:
247
+ return
248
+ self._closed = True
249
+ if self._process.poll() is None:
250
+ self._process.terminate()
251
+ try:
252
+ self._process.wait(timeout=5)
253
+ except subprocess.TimeoutExpired:
254
+ self._process.kill()
255
+ self._process.wait()
256
+ self._reader.join(timeout=1)
257
+ for stream in (self._process.stdin, self._process.stdout):
258
+ if stream is not None:
259
+ stream.close()
260
+
261
+ def __enter__(self) -> Client:
262
+ return self
263
+
264
+ def __exit__(self, *args: Any) -> None:
265
+ self.close()
File without changes
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: polign-recall
3
+ Version: 0.2.0
4
+ Summary: Typed, correctable agent memory through Recall's MCP server
5
+ Author: Polign
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/Polign/recall
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # polign-recall
14
+
15
+ A Python client for Recall's typed, correctable agent memory. Requires Python
16
+ 3.10+ and `polign` CLI v0.6.4+ on PATH. No Python runtime dependencies.
17
+
18
+ ```sh
19
+ pip install ./python
20
+ polign-server -store fs:./recall-data
21
+ ```
22
+
23
+ In another terminal:
24
+
25
+ ```python
26
+ from polign_recall import Client
27
+
28
+ with Client() as memory:
29
+ memory.remember("user", "prefers_editor", "vim")
30
+ changed = memory.remember("user", "prefers_editor", "neovim")
31
+ print(memory.recall("user", "prefers_editor")[0].value) # neovim
32
+ print(memory.history("user", "prefers_editor")) # both statements
33
+ memory.forget("user", "prefers_editor", "neovim")
34
+ ```
35
+
36
+ The client owns a long-lived `polign mcp -memory-only -write` subprocess and
37
+ shares the Go implementation's validation and fold. Set `POLIGN_URL`,
38
+ `POLIGN_API_KEY`, and `POLIGN_COLLECTION` in the environment, or pass
39
+ `env={...}` to Client. Use `write=False` for a read-only connection.
40
+
41
+ `remember(text=..., statements=[...])` accepts proposals from your agent's model;
42
+ the client does not run a second model. Every statement must have subject,
43
+ predicate, typed value, and evidence quoting the text exactly. Read `predicates()`
44
+ to build your extractor prompt. No separate extraction tool is required.
45
+
46
+ `recall(..., as_of=...)` accepts an RFC3339 string or timezone-aware datetime.
47
+ `forget` requires a typed value or explicit `all=True`; false and zero remain
48
+ values. Forgetting retracts a belief and retains its historical events.
49
+
50
+ Errors raise `RecallError` with a code and, for a failed extraction batch, any
51
+ reported partial results. Calls are serialized, timeout after 120 seconds by
52
+ default, and never automatically retry writes. A timeout closes the transport;
53
+ inspect history using a new client before retrying an uncertain write.
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ polign_recall/__init__.py
5
+ polign_recall/client.py
6
+ polign_recall/py.typed
7
+ polign_recall.egg-info/PKG-INFO
8
+ polign_recall.egg-info/SOURCES.txt
9
+ polign_recall.egg-info/dependency_links.txt
10
+ polign_recall.egg-info/top_level.txt
11
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ polign_recall
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "polign-recall"
7
+ version = "0.2.0"
8
+ description = "Typed, correctable agent memory through Recall's MCP server"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Polign"}]
14
+ dependencies = []
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/Polign/recall"
18
+
19
+ [tool.setuptools.package-data]
20
+ polign_recall = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,151 @@
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ import sys
5
+ import tempfile
6
+ import unittest
7
+
8
+ from polign_recall import Client, RecallError
9
+
10
+
11
+ FAKE = r'''
12
+ import json, sys, time
13
+ for line in sys.stdin:
14
+ request = json.loads(line)
15
+ if "id" not in request:
16
+ continue
17
+ result = {}
18
+ if request["method"] == "tools/call":
19
+ args = request["params"]["arguments"]
20
+ if args.get("subject") == "timeout":
21
+ time.sleep(30)
22
+ if args.get("subject") == "partial":
23
+ result = {"isError": True, "content": [{"type":"text", "text":json.dumps({"error":"failed", "partial":{"results":[1]}})}]}
24
+ elif request["params"]["name"] == "remember":
25
+ belief = dict(subject=args["subject"], predicate=args["predicate"], value=args["value"], confidence=args.get("confidence",1), source="user_stated", kind="fact", observed_at="2026-09-12T00:00:00Z", event_id="a")
26
+ result = {"content": [{"type":"text", "text":json.dumps({"stored":belief})}]}
27
+ elif request["params"]["name"] == "forget":
28
+ result = {"content": [{"type":"text", "text":json.dumps({"withdrawn": 1 if args.get("value") is False or args.get("value") == 0 else 0})}]}
29
+ else:
30
+ result = {"content": [{"type":"text", "text":"[]"}]}
31
+ print(json.dumps({"jsonrpc":"2.0","id":request["id"],"result":result}),flush=True)
32
+ '''
33
+
34
+
35
+ class TransportTests(unittest.TestCase):
36
+ def setUp(self):
37
+ self.directory = tempfile.TemporaryDirectory()
38
+ self.addCleanup(self.directory.cleanup)
39
+ script = Path(self.directory.name) / "fake.py"
40
+ script.write_text(FAKE)
41
+ self.command = [sys.executable, "-u", str(script)]
42
+
43
+ def test_false_zero_and_cleanup(self):
44
+ with Client(command=self.command) as memory:
45
+ result = memory.remember("user", "enabled", False, confidence=0)
46
+ self.assertIs(result.stored.value, False)
47
+ self.assertEqual(result.stored.confidence, 0)
48
+ self.assertEqual(memory.forget("user", "enabled", False), 1)
49
+ self.assertEqual(memory.forget("project", "port", 0), 1)
50
+ with self.assertRaises(ValueError):
51
+ memory.forget("user", "enabled")
52
+ with self.assertRaises(ValueError):
53
+ memory.forget("user", "enabled", None)
54
+ with self.assertRaises(ValueError):
55
+ memory.remember("user", "score", float("nan"))
56
+ self.assertIsNotNone(memory._process.poll())
57
+ with self.assertRaises(RecallError):
58
+ memory.predicates()
59
+
60
+ def test_partial_results_are_preserved(self):
61
+ with Client(command=self.command) as memory:
62
+ with self.assertRaises(RecallError) as failure:
63
+ memory.remember("partial", "p", "v")
64
+ self.assertEqual(failure.exception.partial, {"results": [1]})
65
+
66
+ def test_timeout_closes_without_retry(self):
67
+ with Client(command=self.command, timeout=0.2) as memory:
68
+ with self.assertRaises(RecallError) as failure:
69
+ memory.recall("timeout")
70
+ self.assertEqual(failure.exception.code, "timeout")
71
+ self.assertIsNotNone(memory._process.poll())
72
+
73
+
74
+ @unittest.skipUnless(os.environ.get("RECALL_TEST_POLIGN"), "set RECALL_TEST_POLIGN and POLIGN_URL for integration")
75
+ class IntegrationTests(unittest.TestCase):
76
+ def connect(self):
77
+ return Client(command=[os.environ["RECALL_TEST_POLIGN"], "mcp", "-memory-only", "-write"])
78
+
79
+ def test_sessions_extraction_history_and_retraction(self):
80
+ subject = "python-integration"
81
+ with self.connect() as memory:
82
+ self.assertEqual(len(memory.predicates()), 15)
83
+ first = memory.remember(subject, "prefers_editor", "vim")
84
+ text = "I now prefer neovim."
85
+ extraction = memory.remember(text=text, statements=[{
86
+ "subject": subject, "predicate": "prefers_editor", "value": "neovim", "evidence": text
87
+ }])
88
+ self.assertEqual(extraction.results[0].stored.value, "neovim")
89
+ self.assertEqual(memory.recall(subject, "prefers_editor")[0].value, "neovim")
90
+ self.assertEqual(memory.recall(subject, "prefers_editor", as_of=first.stored.observed_at)[0].value, "vim")
91
+ with self.assertRaises(RecallError):
92
+ memory.remember(text="valid text", statements=[{
93
+ "subject": subject, "predicate": "name", "value": "made up", "evidence": "fabricated"
94
+ }])
95
+ with self.connect() as memory:
96
+ self.assertEqual(memory.recall(subject, "prefers_editor")[0].value, "neovim")
97
+ self.assertEqual(memory.forget(subject, "prefers_editor", "neovim"), 1)
98
+ self.assertEqual(memory.recall(subject, "prefers_editor"), [])
99
+ self.assertGreaterEqual(len(memory.history(subject, "prefers_editor")), 3)
100
+
101
+
102
+ if __name__ == "__main__":
103
+ unittest.main()
104
+
105
+
106
+ # A server that logs over the protocol, and one that stops reading its input.
107
+ CHATTY = r'''
108
+ import json, sys
109
+ for line in sys.stdin:
110
+ request = json.loads(line)
111
+ if "id" not in request:
112
+ continue
113
+ print(json.dumps({"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"working"}}),flush=True)
114
+ print(json.dumps({"jsonrpc":"2.0","id":request["id"],"result":{"content":[{"type":"text","text":"[]"}]}}),flush=True)
115
+ '''
116
+
117
+ # Answers the handshake, then never reads its input again.
118
+ DEAF = r'''
119
+ import json, sys, time
120
+ request = json.loads(sys.stdin.readline())
121
+ print(json.dumps({"jsonrpc":"2.0","id":request["id"],"result":{"protocolVersion":"2025-06-18"}}),flush=True)
122
+ time.sleep(60)
123
+ '''
124
+
125
+
126
+ class ResilienceTests(unittest.TestCase):
127
+ def setUp(self):
128
+ self.directory = tempfile.TemporaryDirectory()
129
+ self.addCleanup(self.directory.cleanup)
130
+
131
+ def _command(self, source):
132
+ script = Path(self.directory.name) / "server.py"
133
+ script.write_text(source)
134
+ return [sys.executable, "-u", str(script)]
135
+
136
+ def test_server_notifications_do_not_end_the_session(self):
137
+ with Client(command=self._command(CHATTY)) as memory:
138
+ self.assertEqual(memory.predicates(), [])
139
+ self.assertEqual(memory.recall("user", "prefers_editor"), [])
140
+
141
+ def test_a_server_that_never_reads_times_out_instead_of_hanging(self):
142
+ memory = Client(command=self._command(DEAF), timeout=2)
143
+ self.addCleanup(memory.close)
144
+ with self.assertRaises(RecallError) as caught:
145
+ memory.remember("user", "note", "x" * (1 << 20))
146
+ self.assertEqual(caught.exception.code, "timeout")
147
+
148
+ def test_a_missing_binary_is_a_recall_error(self):
149
+ with self.assertRaises(RecallError) as caught:
150
+ Client(command=[str(Path(self.directory.name) / "definitely-absent")])
151
+ self.assertEqual(caught.exception.code, "transport_error")