spm-client 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,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: spm-client
3
+ Version: 0.2.0
4
+ Summary: SPM client: evidence-gated memory (ingest, recall, read, receipts) and the compatible Gateway.
5
+ Author: Veridical Tech, Inc.
6
+ License-Expression: LicenseRef-Proprietary
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: httpx<1,>=0.27
10
+ Provides-Extra: test
11
+ Requires-Dist: pytest<10,>=8; extra == "test"
12
+ Requires-Dist: respx<1,>=0.21; extra == "test"
13
+ Requires-Dist: httpx<1,>=0.27; extra == "test"
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest<10,>=8; extra == "dev"
16
+ Requires-Dist: pytest-asyncio<2,>=0.24; extra == "dev"
17
+ Requires-Dist: respx<1,>=0.21; extra == "dev"
18
+
19
+ # SPM Python client
20
+
21
+ Client for SPM's evidence-gated memory: store observations, recall with a
22
+ verdict, read the exact cited text, export, and subscribe to lifecycle events.
23
+ The OpenAI-compatible Gateway methods remain available at the bottom.
24
+
25
+ **Status**: pre-release (0.2.0). The licence is proprietary (see the
26
+ repository `LICENSE`); the package is safe to install and use, and the API
27
+ below is versioned with `/v2`.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install spm-client
33
+ # or, in this repository:
34
+ pip install -e sdk/python
35
+ ```
36
+
37
+ ## Memory
38
+
39
+ ```python
40
+ from spm_client import SpmClient
41
+
42
+ with SpmClient("your-api-key", base_url="https://api.spmos.ai") as client:
43
+ client.remember(
44
+ "Acme 完成 A 轮融资 8000 万元",
45
+ idempotency_key="acme-financing-2026-11",
46
+ topic="financing",
47
+ user_partition="ent-91330",
48
+ source_timestamp="2026-11-30T00:00:00Z",
49
+ )
50
+
51
+ result = client.recall("Acme 最近融资多少", user_partition="ent-91330", topics=["financing"])
52
+ if result["gate_reason"] == "passed":
53
+ print(result["answer"])
54
+ for ref in result["evidence_refs"]:
55
+ print(ref["source_id"], ref["console_url"])
56
+ print(client.read([r["read_token"] for r in result["evidence_refs"]])["spans"])
57
+ else:
58
+ print("no supporting memory:", result["gate_reason"])
59
+ ```
60
+
61
+ `gate_reason` is `passed` or a refusal (`no_candidate`,
62
+ `no_semantic_support`, `superseded`, …). Treat a refusal as information, not
63
+ an error: it means no stored source supports the claim.
64
+
65
+ ### Conventions
66
+
67
+ - `idempotency_key` (≥8 chars) makes a write safe to retry; the same key with
68
+ a different payload is a conflict.
69
+ - Re-observing the same `source_id` with changed content increments its
70
+ version instead of creating a second source.
71
+ - `user_partition` isolates an entity or end user; the key needs
72
+ `memory:partition` for it.
73
+ - Read tokens live ~300 seconds — call `read` soon after `recall`.
74
+ - Limits: 12 000 chars per source, `top_k` ≤ 100, 500 items per batch, 32
75
+ read tokens per call.
76
+
77
+ ### Export and deletion
78
+
79
+ ```python
80
+ bundle = client.export(user_partition="ent-91330") # checksummed
81
+ client.import_bundle(bundle, user_partition="ent-copy") # ids are re-tagged
82
+ client.purge(source_id="s1") # signed receipt
83
+ client.wipe_partition("ent-91330") # per-source receipts
84
+ ```
85
+
86
+ ### Events
87
+
88
+ ```python
89
+ sub = client.subscribe("https://hooks.example/spm", ["source.accepted", "source.purged"])
90
+ # Deliveries carry X-SPM-Signature: t=<ts>,v1=<hmac-sha256 of "ts.body">
91
+ client.replay_events(since_id="evt_...")
92
+ client.unsubscribe(sub["id"])
93
+ ```
94
+
95
+ ## Errors
96
+
97
+ ```python
98
+ from spm_client import AuthError, NotFoundError, QuotaError, ServerError, SpmError
99
+
100
+ try:
101
+ client.recall("q")
102
+ except AuthError:
103
+ ...
104
+ except QuotaError:
105
+ ...
106
+ except ServerError as exc:
107
+ print(exc.status_code, exc)
108
+ ```
109
+
110
+ All errors carry the server's `code` when it sent one.
111
+
112
+ ## Gateway
113
+
114
+ `SpmClient` also speaks the OpenAI/Anthropic-compatible Gateway:
115
+
116
+ ```python
117
+ with SpmClient("your-api-key") as client:
118
+ reply = client.session().send("Hello, remember my name is Alice.")
119
+ print(reply)
120
+ ```
121
+
122
+ | Method | Description |
123
+ |---|---|
124
+ | `client.health()` | Gateway health |
125
+ | `client.chat(messages, model=..., stream=...)` | Raw chat completion |
126
+ | `client.session(system_prompt=...)` | Stateful `ChatSession` |
127
+ | `client.list_receipts()` | Request receipts |
128
+
129
+ ## API reference (memory)
130
+
131
+ | Method | Endpoint |
132
+ |---|---|
133
+ | `remember(text, idempotency_key=..., …)` | `POST /v2/ingest` |
134
+ | `remember_many(items)` | `POST /v2/ingest/batch` |
135
+ | `recall(query, topics=..., since=..., until=..., …)` | `POST /v2/recall` |
136
+ | `recall_text(query, …)` | recall + read joined |
137
+ | `read(tokens)` | `POST /v2/read` |
138
+ | `purge(source_id=...)` | `POST /v2/purge` |
139
+ | `partitions()` / `export_partition(p)` / `wipe_partition(p)` | `/v2/partitions…` |
140
+ | `export()` / `import_bundle(bundle)` | `/v2/export`, `/v2/import` |
141
+ | `subscribe` / `subscriptions` / `unsubscribe` / `replay_events` | `/v2/events…` |
@@ -0,0 +1,123 @@
1
+ # SPM Python client
2
+
3
+ Client for SPM's evidence-gated memory: store observations, recall with a
4
+ verdict, read the exact cited text, export, and subscribe to lifecycle events.
5
+ The OpenAI-compatible Gateway methods remain available at the bottom.
6
+
7
+ **Status**: pre-release (0.2.0). The licence is proprietary (see the
8
+ repository `LICENSE`); the package is safe to install and use, and the API
9
+ below is versioned with `/v2`.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install spm-client
15
+ # or, in this repository:
16
+ pip install -e sdk/python
17
+ ```
18
+
19
+ ## Memory
20
+
21
+ ```python
22
+ from spm_client import SpmClient
23
+
24
+ with SpmClient("your-api-key", base_url="https://api.spmos.ai") as client:
25
+ client.remember(
26
+ "Acme 完成 A 轮融资 8000 万元",
27
+ idempotency_key="acme-financing-2026-11",
28
+ topic="financing",
29
+ user_partition="ent-91330",
30
+ source_timestamp="2026-11-30T00:00:00Z",
31
+ )
32
+
33
+ result = client.recall("Acme 最近融资多少", user_partition="ent-91330", topics=["financing"])
34
+ if result["gate_reason"] == "passed":
35
+ print(result["answer"])
36
+ for ref in result["evidence_refs"]:
37
+ print(ref["source_id"], ref["console_url"])
38
+ print(client.read([r["read_token"] for r in result["evidence_refs"]])["spans"])
39
+ else:
40
+ print("no supporting memory:", result["gate_reason"])
41
+ ```
42
+
43
+ `gate_reason` is `passed` or a refusal (`no_candidate`,
44
+ `no_semantic_support`, `superseded`, …). Treat a refusal as information, not
45
+ an error: it means no stored source supports the claim.
46
+
47
+ ### Conventions
48
+
49
+ - `idempotency_key` (≥8 chars) makes a write safe to retry; the same key with
50
+ a different payload is a conflict.
51
+ - Re-observing the same `source_id` with changed content increments its
52
+ version instead of creating a second source.
53
+ - `user_partition` isolates an entity or end user; the key needs
54
+ `memory:partition` for it.
55
+ - Read tokens live ~300 seconds — call `read` soon after `recall`.
56
+ - Limits: 12 000 chars per source, `top_k` ≤ 100, 500 items per batch, 32
57
+ read tokens per call.
58
+
59
+ ### Export and deletion
60
+
61
+ ```python
62
+ bundle = client.export(user_partition="ent-91330") # checksummed
63
+ client.import_bundle(bundle, user_partition="ent-copy") # ids are re-tagged
64
+ client.purge(source_id="s1") # signed receipt
65
+ client.wipe_partition("ent-91330") # per-source receipts
66
+ ```
67
+
68
+ ### Events
69
+
70
+ ```python
71
+ sub = client.subscribe("https://hooks.example/spm", ["source.accepted", "source.purged"])
72
+ # Deliveries carry X-SPM-Signature: t=<ts>,v1=<hmac-sha256 of "ts.body">
73
+ client.replay_events(since_id="evt_...")
74
+ client.unsubscribe(sub["id"])
75
+ ```
76
+
77
+ ## Errors
78
+
79
+ ```python
80
+ from spm_client import AuthError, NotFoundError, QuotaError, ServerError, SpmError
81
+
82
+ try:
83
+ client.recall("q")
84
+ except AuthError:
85
+ ...
86
+ except QuotaError:
87
+ ...
88
+ except ServerError as exc:
89
+ print(exc.status_code, exc)
90
+ ```
91
+
92
+ All errors carry the server's `code` when it sent one.
93
+
94
+ ## Gateway
95
+
96
+ `SpmClient` also speaks the OpenAI/Anthropic-compatible Gateway:
97
+
98
+ ```python
99
+ with SpmClient("your-api-key") as client:
100
+ reply = client.session().send("Hello, remember my name is Alice.")
101
+ print(reply)
102
+ ```
103
+
104
+ | Method | Description |
105
+ |---|---|
106
+ | `client.health()` | Gateway health |
107
+ | `client.chat(messages, model=..., stream=...)` | Raw chat completion |
108
+ | `client.session(system_prompt=...)` | Stateful `ChatSession` |
109
+ | `client.list_receipts()` | Request receipts |
110
+
111
+ ## API reference (memory)
112
+
113
+ | Method | Endpoint |
114
+ |---|---|
115
+ | `remember(text, idempotency_key=..., …)` | `POST /v2/ingest` |
116
+ | `remember_many(items)` | `POST /v2/ingest/batch` |
117
+ | `recall(query, topics=..., since=..., until=..., …)` | `POST /v2/recall` |
118
+ | `recall_text(query, …)` | recall + read joined |
119
+ | `read(tokens)` | `POST /v2/read` |
120
+ | `purge(source_id=...)` | `POST /v2/purge` |
121
+ | `partitions()` / `export_partition(p)` / `wipe_partition(p)` | `/v2/partitions…` |
122
+ | `export()` / `import_bundle(bundle)` | `/v2/export`, `/v2/import` |
123
+ | `subscribe` / `subscriptions` / `unsubscribe` / `replay_events` | `/v2/events…` |
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "spm-client"
7
+ version = "0.2.0"
8
+ description = "SPM client: evidence-gated memory (ingest, recall, read, receipts) and the compatible Gateway."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "LicenseRef-Proprietary"
12
+ authors = [
13
+ { name = "Veridical Tech, Inc." },
14
+ ]
15
+ dependencies = [
16
+ "httpx>=0.27,<1",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ test = ["pytest>=8,<10", "respx>=0.21,<1", "httpx>=0.27,<1"]
21
+ dev = ["pytest>=8,<10", "pytest-asyncio>=0.24,<2", "respx>=0.21,<1"]
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["."]
25
+ include = ["spm_client*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,487 @@
1
+ """SPM-Maverick Python SDK.
2
+
3
+ Minimal client for the SPM-Polaris Gateway and MCP endpoints.
4
+ Design: transparent session state, typed errors, OpenAI-compatible chat.
5
+
6
+ Install (local dev):
7
+ pip install -e sdk/python
8
+
9
+ PyPI publish blocked by LEGAL_RELEASE_BLOCKER until legal sign-off.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ import os
16
+ import uuid
17
+ from typing import Any, Iterator, Mapping
18
+
19
+ import httpx
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ __version__ = "0.1.0"
25
+ __all__ = [
26
+ "SpmClient",
27
+ "ChatSession",
28
+ "SpmError",
29
+ "AuthError",
30
+ "QuotaError",
31
+ "NotFoundError",
32
+ "ServerError",
33
+ ]
34
+
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # Typed error hierarchy
38
+ # ---------------------------------------------------------------------------
39
+
40
+
41
+ class SpmError(Exception):
42
+ """Base exception for all SPM client errors."""
43
+
44
+ def __init__(self, message: str, *, status_code: int | None = None, raw: Any = None) -> None:
45
+ super().__init__(message)
46
+ self.status_code = status_code
47
+ self.raw = raw
48
+
49
+
50
+ class AuthError(SpmError):
51
+ """Raised on 401/403 responses (invalid or missing API key)."""
52
+
53
+
54
+ class QuotaError(SpmError):
55
+ """Raised on 429 responses (rate limit or quota exceeded)."""
56
+
57
+
58
+ class NotFoundError(SpmError):
59
+ """Raised on 404 responses."""
60
+
61
+
62
+ class ServerError(SpmError):
63
+ """Raised on 5xx responses."""
64
+
65
+
66
+ def _format_error_message(resp: httpx.Response, base_msg: str) -> str:
67
+ """Augment a raw HTTP error with cause + fix guidance."""
68
+ status = resp.status_code
69
+ if status in {401, 403}:
70
+ return (
71
+ f"{base_msg}\n"
72
+ "Invalid or expired API key. Check SPM_API_KEY. "
73
+ "Rotate at [dashboard]/api-keys."
74
+ )
75
+ if status == 429:
76
+ retry_after_raw = resp.headers.get("Retry-After", "")
77
+ try:
78
+ retry_after = int(retry_after_raw)
79
+ retry_msg = f"{retry_after}s"
80
+ except (ValueError, TypeError):
81
+ retry_msg = "unknown"
82
+ return (
83
+ f"{base_msg}\n"
84
+ f"Rate limit exceeded. Retry after {retry_msg}. "
85
+ "See docs/rate-limiting."
86
+ )
87
+ if status >= 500:
88
+ corr_id = (
89
+ resp.headers.get("X-Correlation-Id")
90
+ or resp.headers.get("X-Request-Id", "unknown")
91
+ )
92
+ return (
93
+ f"{base_msg}\n"
94
+ f"Server error ({status}). Check service health at /health. "
95
+ f"Correlation ID: {corr_id}"
96
+ )
97
+ return base_msg
98
+
99
+
100
+ def _raise_for_status(resp: httpx.Response) -> None:
101
+ if resp.is_success:
102
+ return
103
+ try:
104
+ body = resp.json()
105
+ msg = body.get("error", {}).get("message", resp.text) if isinstance(body, dict) else resp.text
106
+ except Exception:
107
+ msg = resp.text or f"HTTP {resp.status_code}"
108
+ msg = _format_error_message(resp, msg)
109
+ if resp.status_code in {401, 403}:
110
+ raise AuthError(msg, status_code=resp.status_code, raw=resp.text)
111
+ if resp.status_code == 429:
112
+ raise QuotaError(msg, status_code=resp.status_code, raw=resp.text)
113
+ if resp.status_code == 404:
114
+ raise NotFoundError(msg, status_code=resp.status_code, raw=resp.text)
115
+ if resp.status_code >= 500:
116
+ raise ServerError(msg, status_code=resp.status_code, raw=resp.text)
117
+ raise SpmError(msg, status_code=resp.status_code, raw=resp.text)
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Client
122
+ # ---------------------------------------------------------------------------
123
+
124
+
125
+ class SpmClient:
126
+ """Low-level HTTP client for the SPM-Polaris Gateway.
127
+
128
+ Args:
129
+ api_key: Bearer key issued by the SPM-Polaris console.
130
+ base_url: Gateway base URL, e.g. ``https://api.example.com``.
131
+ timeout: Per-request timeout in seconds (default 120s for streaming).
132
+ """
133
+
134
+ @classmethod
135
+ def from_env(cls) -> "SpmClient":
136
+ """Create a client from environment variables.
137
+
138
+ Reads ``SPM_API_KEY`` and ``SPM_GATEWAY_URL``. Raises :class:`ValueError`
139
+ with an actionable message if any required variable is missing or empty.
140
+ """
141
+ api_key = os.environ.get("SPM_API_KEY", "").strip()
142
+ base_url = os.environ.get("SPM_GATEWAY_URL", "").strip()
143
+
144
+ missing: list[str] = []
145
+ if not api_key:
146
+ missing.append(" SPM_API_KEY — your API key from the SPM dashboard")
147
+ if not base_url:
148
+ missing.append(" SPM_GATEWAY_URL — e.g. http://localhost:18081 for local dev")
149
+
150
+ if missing:
151
+ raise ValueError(
152
+ "Cannot create SpmClient from environment. Missing variables:\n"
153
+ + "\n".join(missing)
154
+ + "\n\nSet these variables or pass api_key and base_url directly to SpmClient()."
155
+ )
156
+
157
+ return cls(api_key=api_key, base_url=base_url)
158
+
159
+ def __init__(
160
+ self,
161
+ api_key: str,
162
+ *,
163
+ base_url: str = "http://localhost:18081",
164
+ timeout: float = 120.0,
165
+ ) -> None:
166
+ self.api_key = api_key
167
+ self.base_url = base_url.rstrip("/")
168
+ self._http = httpx.Client(
169
+ base_url=self.base_url,
170
+ headers={"Authorization": f"Bearer {api_key}"},
171
+ timeout=timeout,
172
+ )
173
+
174
+ def close(self) -> None:
175
+ self._http.close()
176
+
177
+ def __enter__(self) -> "SpmClient":
178
+ return self
179
+
180
+ def __exit__(self, *_: Any) -> None:
181
+ self.close()
182
+
183
+ def health(self) -> dict[str, Any]:
184
+ """Return the gateway health status dict."""
185
+ resp = self._http.get("/health")
186
+ _raise_for_status(resp)
187
+ return resp.json()
188
+
189
+ def chat(
190
+ self,
191
+ messages: list[dict[str, str]],
192
+ *,
193
+ model: str = "gpt-4o-mini",
194
+ stream: bool = False,
195
+ **kwargs: Any,
196
+ ) -> dict[str, Any] | Iterator[str]:
197
+ """Send a chat-completion request.
198
+
199
+ When ``stream=True`` returns an iterator of raw SSE data lines.
200
+ When ``stream=False`` returns the decoded response dict.
201
+ """
202
+ payload: dict[str, Any] = {"model": model, "messages": messages, "stream": stream, **kwargs}
203
+ if stream:
204
+ return self._stream_chat(payload)
205
+ resp = self._http.post("/v1/chat/completions", json=payload)
206
+ _raise_for_status(resp)
207
+ return resp.json()
208
+
209
+ def _stream_chat(self, payload: dict[str, Any]) -> Iterator[str]:
210
+ with self._http.stream("POST", "/v1/chat/completions", json=payload) as resp:
211
+ _raise_for_status(resp)
212
+ for line in resp.iter_lines():
213
+ if line.startswith("data: "):
214
+ data = line[6:]
215
+ if data.strip() == "[DONE]":
216
+ break
217
+ yield data
218
+
219
+ # -- memory plane (/v2) ------------------------------------------------
220
+
221
+ def remember(
222
+ self,
223
+ text: str,
224
+ *,
225
+ idempotency_key: str,
226
+ source_id: str | None = None,
227
+ topic: str = "general",
228
+ source_kind: str = "",
229
+ source_timestamp: str = "",
230
+ user_partition: str = "",
231
+ ) -> dict[str, Any]:
232
+ """Store one observation. Repeating the key is idempotent."""
233
+ payload: dict[str, Any] = {"text": text, "idempotency_key": idempotency_key, "topic": topic}
234
+ if source_id:
235
+ payload["source_id"] = source_id
236
+ if source_kind:
237
+ payload["source_kind"] = source_kind
238
+ if source_timestamp:
239
+ payload["source_timestamp"] = source_timestamp
240
+ if user_partition:
241
+ payload["user_partition"] = user_partition
242
+ resp = self._http.post("/v2/ingest", json=payload)
243
+ _raise_for_status(resp)
244
+ return resp.json()
245
+
246
+ def remember_many(self, items: list[dict[str, Any]], *, stop_on_error: bool = False) -> dict[str, Any]:
247
+ """Ingest up to 500 observations; per-item outcomes are returned."""
248
+ if len(items) > 500:
249
+ raise ValueError("at most 500 items per call")
250
+ resp = self._http.post("/v2/ingest/batch", json={"items": items, "stop_on_error": stop_on_error})
251
+ _raise_for_status(resp)
252
+ return resp.json()
253
+
254
+ def recall(
255
+ self,
256
+ query: str,
257
+ *,
258
+ top_k: int = 20,
259
+ topics: list[str] | None = None,
260
+ since: str = "",
261
+ until: str = "",
262
+ user_partition: str = "",
263
+ ) -> dict[str, Any]:
264
+ """Recall evidence. Check ``gate_reason`` before trusting ``answer``."""
265
+ payload: dict[str, Any] = {"query": query, "top_k": top_k}
266
+ if topics:
267
+ payload["topics"] = topics
268
+ if since:
269
+ payload["since"] = since
270
+ if until:
271
+ payload["until"] = until
272
+ if user_partition:
273
+ payload["user_partition"] = user_partition
274
+ resp = self._http.post("/v2/recall", json=payload)
275
+ _raise_for_status(resp)
276
+ return resp.json()
277
+
278
+ def read(self, read_tokens: list[str], *, user_partition: str = "") -> dict[str, Any]:
279
+ """Resolve recall read tokens to chunked source text (tokens live ~300 s)."""
280
+ if len(read_tokens) > 32:
281
+ raise ValueError("at most 32 read tokens per call")
282
+ payload: dict[str, Any] = {"read_tokens": read_tokens}
283
+ if user_partition:
284
+ payload["user_partition"] = user_partition
285
+ resp = self._http.post("/v2/read", json=payload)
286
+ _raise_for_status(resp)
287
+ return resp.json()
288
+
289
+ def recall_text(self, query: str, **kwargs: Any) -> str:
290
+ """Recall and join the exact text of every readable evidence item."""
291
+ result = self.recall(query, **kwargs)
292
+ tokens = [ref["read_token"] for ref in result.get("evidence_refs", []) if ref.get("read_token")]
293
+ if not tokens:
294
+ return ""
295
+ spans = self.read(tokens, user_partition=kwargs.get("user_partition", "")).get("spans", [])
296
+ return "\n".join(
297
+ chunk.get("text", "")
298
+ for span in spans
299
+ for chunk in span.get("chunks", [])
300
+ )
301
+
302
+ def purge(self, *, source_id: str) -> dict[str, Any]:
303
+ """Delete one source; the response carries a signed receipt."""
304
+ resp = self._http.post("/v2/purge", json={"source_id": source_id})
305
+ _raise_for_status(resp)
306
+ return resp.json()
307
+
308
+ def partitions(self, *, prefix: str = "", limit: int = 200) -> dict[str, Any]:
309
+ resp = self._http.get("/v2/partitions", params={"prefix": prefix, "limit": limit})
310
+ _raise_for_status(resp)
311
+ return resp.json()
312
+
313
+ def export_partition(self, partition: str) -> dict[str, Any]:
314
+ resp = self._http.post(f"/v2/partitions/{partition}/export")
315
+ _raise_for_status(resp)
316
+ return resp.json()
317
+
318
+ def wipe_partition(self, partition: str) -> dict[str, Any]:
319
+ resp = self._http.post(f"/v2/partitions/{partition}/wipe")
320
+ _raise_for_status(resp)
321
+ return resp.json()
322
+
323
+ def export(self, *, user_partition: str = "") -> dict[str, Any]:
324
+ """Whole-scope portable bundle with a checksum."""
325
+ resp = self._http.post("/v2/export", json={"user_partition": user_partition})
326
+ _raise_for_status(resp)
327
+ return resp.json()
328
+
329
+ def import_bundle(
330
+ self, bundle: dict[str, Any], *, user_partition: str = "", conflict: str = "skip"
331
+ ) -> dict[str, Any]:
332
+ resp = self._http.post(
333
+ "/v2/import",
334
+ json={"bundle": bundle, "user_partition": user_partition, "conflict": conflict},
335
+ )
336
+ _raise_for_status(resp)
337
+ return resp.json()
338
+
339
+ def subscribe(
340
+ self, url: str, events: list[str]
341
+ ) -> dict[str, Any]:
342
+ """Register an HMAC-signed webhook; the secret is returned once."""
343
+ resp = self._http.post("/v2/events/subscriptions", json={"url": url, "events": events})
344
+ _raise_for_status(resp)
345
+ return resp.json()
346
+
347
+ def subscriptions(self) -> list[dict[str, Any]]:
348
+ resp = self._http.get("/v2/events/subscriptions")
349
+ _raise_for_status(resp)
350
+ return resp.json()
351
+
352
+ def unsubscribe(self, subscription_id: str) -> dict[str, Any]:
353
+ resp = self._http.delete(f"/v2/events/subscriptions/{subscription_id}")
354
+ _raise_for_status(resp)
355
+ return resp.json()
356
+
357
+ def replay_events(self, *, since_id: str = "") -> dict[str, Any]:
358
+ resp = self._http.post("/v2/events/replay", json={"since_id": since_id})
359
+ _raise_for_status(resp)
360
+ return resp.json()
361
+
362
+ def list_receipts(self, *, limit: int = 20, cursor: str | None = None) -> dict[str, Any]:
363
+ """List recent request receipts for audit and debugging.
364
+
365
+ Args:
366
+ limit: Maximum number of receipts to return.
367
+ cursor: Opaque pagination cursor from a previous response (cursor-based
368
+ pagination — the gateway does not accept an ``offset`` parameter).
369
+ """
370
+ params: dict[str, Any] = {"limit": limit}
371
+ if cursor is not None:
372
+ params["cursor"] = cursor
373
+ resp = self._http.get("/v1/spm/requests", params=params)
374
+ _raise_for_status(resp)
375
+ return resp.json()
376
+
377
+ def get_receipt(self, receipt_id: str) -> dict[str, Any]:
378
+ """Fetch a single request receipt by ID."""
379
+ resp = self._http.get(f"/v1/spm/requests/{receipt_id}")
380
+ _raise_for_status(resp)
381
+ return resp.json()
382
+
383
+ def session(
384
+ self, *, session_id: str | None = None, system_prompt: str | None = None
385
+ ) -> "ChatSession":
386
+ """Create a stateful chat session backed by this client."""
387
+ return ChatSession(client=self, session_id=session_id, system_prompt=system_prompt)
388
+
389
+
390
+ # ---------------------------------------------------------------------------
391
+ # Session
392
+ # ---------------------------------------------------------------------------
393
+
394
+
395
+ class ChatSession:
396
+ """Stateful chat session with transparent message history management.
397
+
398
+ Maintains the full conversation history so callers only need to pass
399
+ the latest user message. Memory is managed server-side; the session
400
+ only tracks the local message list for context formatting.
401
+
402
+ Args:
403
+ client: An :class:`SpmClient` instance.
404
+ session_id: Opaque identifier forwarded as ``X-Session-Id``. A UUID
405
+ is generated if not provided.
406
+ system_prompt: Optional system message prepended to every request.
407
+ """
408
+
409
+ def __init__(
410
+ self,
411
+ client: SpmClient,
412
+ *,
413
+ session_id: str | None = None,
414
+ system_prompt: str | None = None,
415
+ ) -> None:
416
+ self._client = client
417
+ self.session_id = session_id or str(uuid.uuid4())
418
+ self._history: list[dict[str, str]] = []
419
+ if system_prompt:
420
+ self._history.append({"role": "system", "content": system_prompt})
421
+
422
+ def send(self, content: str, *, model: str = "gpt-4o-mini", stream: bool = False, **kwargs: Any) -> str | Iterator[str]:
423
+ """Send a user message and return the assistant reply.
424
+
425
+ The history is updated automatically. When ``stream=True``, returns
426
+ an iterator of text chunks and the history is updated lazily on
427
+ exhaustion.
428
+ """
429
+ if stream:
430
+ # Append user message INSIDE the generator so a discarded iterator
431
+ # (caller breaks early) leaves history in a consistent state.
432
+ return self._stream_reply(content, model=model, **kwargs)
433
+ pending_user = {"role": "user", "content": content}
434
+ self._history.append(pending_user)
435
+ try:
436
+ result = self._client.chat(self._history, model=model, stream=False, **kwargs)
437
+ # Guard for tool-call responses where content may be None.
438
+ message = result.get("choices", [{}])[0].get("message", {})
439
+ reply: str = message.get("content") or ""
440
+ self._history.append({"role": "assistant", "content": reply})
441
+ return reply
442
+ except BaseException:
443
+ if self._history and self._history[-1] is pending_user:
444
+ self._history.pop()
445
+ raise
446
+
447
+ def _stream_reply(self, content: str, **kwargs: Any) -> Iterator[str]:
448
+ # Append user message only after the generator starts executing so that
449
+ # abandoning the iterator before first iteration is harmless.
450
+ self._history.append({"role": "user", "content": content})
451
+ chunks: list[str] = []
452
+ try:
453
+ for raw in self._client.chat(self._history, stream=True, **kwargs):
454
+ try:
455
+ data = json.loads(raw)
456
+ delta = data["choices"][0]["delta"].get("content", "")
457
+ if delta:
458
+ chunks.append(delta)
459
+ yield delta
460
+ except Exception:
461
+ logger.debug("stream parse error", exc_info=True)
462
+ continue
463
+ finally:
464
+ # Runs on normal exhaustion, early break (GeneratorExit), or
465
+ # any exception. If chunks is empty the assistant never replied
466
+ # (or was interrupted) — pop the user message so history stays
467
+ # in an alternating user/assistant pattern.
468
+ if chunks:
469
+ self._history.append({"role": "assistant", "content": "".join(chunks)})
470
+ elif self._history and self._history[-1] == {"role": "user", "content": content}:
471
+ self._history.pop()
472
+
473
+ @property
474
+ def history(self) -> list[dict[str, str]]:
475
+ """Return a copy of the current conversation history."""
476
+ return list(self._history)
477
+
478
+ def reset(self, *, keep_system: bool = True) -> None:
479
+ """Clear the conversation history.
480
+
481
+ Args:
482
+ keep_system: If True, retain the initial system message (default).
483
+ """
484
+ if keep_system and self._history and self._history[0]["role"] == "system":
485
+ self._history = [self._history[0]]
486
+ else:
487
+ self._history = []
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: spm-client
3
+ Version: 0.2.0
4
+ Summary: SPM client: evidence-gated memory (ingest, recall, read, receipts) and the compatible Gateway.
5
+ Author: Veridical Tech, Inc.
6
+ License-Expression: LicenseRef-Proprietary
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: httpx<1,>=0.27
10
+ Provides-Extra: test
11
+ Requires-Dist: pytest<10,>=8; extra == "test"
12
+ Requires-Dist: respx<1,>=0.21; extra == "test"
13
+ Requires-Dist: httpx<1,>=0.27; extra == "test"
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest<10,>=8; extra == "dev"
16
+ Requires-Dist: pytest-asyncio<2,>=0.24; extra == "dev"
17
+ Requires-Dist: respx<1,>=0.21; extra == "dev"
18
+
19
+ # SPM Python client
20
+
21
+ Client for SPM's evidence-gated memory: store observations, recall with a
22
+ verdict, read the exact cited text, export, and subscribe to lifecycle events.
23
+ The OpenAI-compatible Gateway methods remain available at the bottom.
24
+
25
+ **Status**: pre-release (0.2.0). The licence is proprietary (see the
26
+ repository `LICENSE`); the package is safe to install and use, and the API
27
+ below is versioned with `/v2`.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install spm-client
33
+ # or, in this repository:
34
+ pip install -e sdk/python
35
+ ```
36
+
37
+ ## Memory
38
+
39
+ ```python
40
+ from spm_client import SpmClient
41
+
42
+ with SpmClient("your-api-key", base_url="https://api.spmos.ai") as client:
43
+ client.remember(
44
+ "Acme 完成 A 轮融资 8000 万元",
45
+ idempotency_key="acme-financing-2026-11",
46
+ topic="financing",
47
+ user_partition="ent-91330",
48
+ source_timestamp="2026-11-30T00:00:00Z",
49
+ )
50
+
51
+ result = client.recall("Acme 最近融资多少", user_partition="ent-91330", topics=["financing"])
52
+ if result["gate_reason"] == "passed":
53
+ print(result["answer"])
54
+ for ref in result["evidence_refs"]:
55
+ print(ref["source_id"], ref["console_url"])
56
+ print(client.read([r["read_token"] for r in result["evidence_refs"]])["spans"])
57
+ else:
58
+ print("no supporting memory:", result["gate_reason"])
59
+ ```
60
+
61
+ `gate_reason` is `passed` or a refusal (`no_candidate`,
62
+ `no_semantic_support`, `superseded`, …). Treat a refusal as information, not
63
+ an error: it means no stored source supports the claim.
64
+
65
+ ### Conventions
66
+
67
+ - `idempotency_key` (≥8 chars) makes a write safe to retry; the same key with
68
+ a different payload is a conflict.
69
+ - Re-observing the same `source_id` with changed content increments its
70
+ version instead of creating a second source.
71
+ - `user_partition` isolates an entity or end user; the key needs
72
+ `memory:partition` for it.
73
+ - Read tokens live ~300 seconds — call `read` soon after `recall`.
74
+ - Limits: 12 000 chars per source, `top_k` ≤ 100, 500 items per batch, 32
75
+ read tokens per call.
76
+
77
+ ### Export and deletion
78
+
79
+ ```python
80
+ bundle = client.export(user_partition="ent-91330") # checksummed
81
+ client.import_bundle(bundle, user_partition="ent-copy") # ids are re-tagged
82
+ client.purge(source_id="s1") # signed receipt
83
+ client.wipe_partition("ent-91330") # per-source receipts
84
+ ```
85
+
86
+ ### Events
87
+
88
+ ```python
89
+ sub = client.subscribe("https://hooks.example/spm", ["source.accepted", "source.purged"])
90
+ # Deliveries carry X-SPM-Signature: t=<ts>,v1=<hmac-sha256 of "ts.body">
91
+ client.replay_events(since_id="evt_...")
92
+ client.unsubscribe(sub["id"])
93
+ ```
94
+
95
+ ## Errors
96
+
97
+ ```python
98
+ from spm_client import AuthError, NotFoundError, QuotaError, ServerError, SpmError
99
+
100
+ try:
101
+ client.recall("q")
102
+ except AuthError:
103
+ ...
104
+ except QuotaError:
105
+ ...
106
+ except ServerError as exc:
107
+ print(exc.status_code, exc)
108
+ ```
109
+
110
+ All errors carry the server's `code` when it sent one.
111
+
112
+ ## Gateway
113
+
114
+ `SpmClient` also speaks the OpenAI/Anthropic-compatible Gateway:
115
+
116
+ ```python
117
+ with SpmClient("your-api-key") as client:
118
+ reply = client.session().send("Hello, remember my name is Alice.")
119
+ print(reply)
120
+ ```
121
+
122
+ | Method | Description |
123
+ |---|---|
124
+ | `client.health()` | Gateway health |
125
+ | `client.chat(messages, model=..., stream=...)` | Raw chat completion |
126
+ | `client.session(system_prompt=...)` | Stateful `ChatSession` |
127
+ | `client.list_receipts()` | Request receipts |
128
+
129
+ ## API reference (memory)
130
+
131
+ | Method | Endpoint |
132
+ |---|---|
133
+ | `remember(text, idempotency_key=..., …)` | `POST /v2/ingest` |
134
+ | `remember_many(items)` | `POST /v2/ingest/batch` |
135
+ | `recall(query, topics=..., since=..., until=..., …)` | `POST /v2/recall` |
136
+ | `recall_text(query, …)` | recall + read joined |
137
+ | `read(tokens)` | `POST /v2/read` |
138
+ | `purge(source_id=...)` | `POST /v2/purge` |
139
+ | `partitions()` / `export_partition(p)` / `wipe_partition(p)` | `/v2/partitions…` |
140
+ | `export()` / `import_bundle(bundle)` | `/v2/export`, `/v2/import` |
141
+ | `subscribe` / `subscriptions` / `unsubscribe` / `replay_events` | `/v2/events…` |
@@ -0,0 +1,10 @@
1
+ README.md
2
+ pyproject.toml
3
+ spm_client/__init__.py
4
+ spm_client.egg-info/PKG-INFO
5
+ spm_client.egg-info/SOURCES.txt
6
+ spm_client.egg-info/dependency_links.txt
7
+ spm_client.egg-info/requires.txt
8
+ spm_client.egg-info/top_level.txt
9
+ tests/test_client.py
10
+ tests/test_memory_plane.py
@@ -0,0 +1,11 @@
1
+ httpx<1,>=0.27
2
+
3
+ [dev]
4
+ pytest<10,>=8
5
+ pytest-asyncio<2,>=0.24
6
+ respx<1,>=0.21
7
+
8
+ [test]
9
+ pytest<10,>=8
10
+ respx<1,>=0.21
11
+ httpx<1,>=0.27
@@ -0,0 +1 @@
1
+ spm_client
@@ -0,0 +1,246 @@
1
+ """Integration tests for SpmClient against a mock gateway."""
2
+ import json
3
+ import os
4
+
5
+ import httpx
6
+ import pytest
7
+ import respx
8
+
9
+ from spm_client import (
10
+ AuthError,
11
+ ChatSession,
12
+ NotFoundError,
13
+ QuotaError,
14
+ ServerError,
15
+ SpmClient,
16
+ SpmError,
17
+ )
18
+
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # from_env tests
22
+ # ---------------------------------------------------------------------------
23
+
24
+
25
+ def test_from_env_success(monkeypatch):
26
+ """from_env() creates a client when both env vars are set."""
27
+ monkeypatch.setenv("SPM_API_KEY", "test-key-123")
28
+ monkeypatch.setenv("SPM_GATEWAY_URL", "http://localhost:18081")
29
+ client = SpmClient.from_env()
30
+ assert client.api_key == "test-key-123"
31
+ assert client.base_url == "http://localhost:18081"
32
+ client.close()
33
+
34
+
35
+ def test_from_env_missing_key_raises(monkeypatch):
36
+ """from_env() raises ValueError with helpful message when SPM_API_KEY is missing."""
37
+ monkeypatch.delenv("SPM_API_KEY", raising=False)
38
+ monkeypatch.setenv("SPM_GATEWAY_URL", "http://localhost:18081")
39
+ with pytest.raises(ValueError, match="SPM_API_KEY"):
40
+ SpmClient.from_env()
41
+
42
+
43
+ def test_from_env_missing_url_raises(monkeypatch):
44
+ """from_env() raises ValueError with helpful message when SPM_GATEWAY_URL is missing."""
45
+ monkeypatch.setenv("SPM_API_KEY", "test-key-123")
46
+ monkeypatch.delenv("SPM_GATEWAY_URL", raising=False)
47
+ with pytest.raises(ValueError, match="SPM_GATEWAY_URL"):
48
+ SpmClient.from_env()
49
+
50
+
51
+ def test_from_env_empty_key_raises(monkeypatch):
52
+ """from_env() raises ValueError when SPM_API_KEY is empty string (not None)."""
53
+ monkeypatch.setenv("SPM_API_KEY", "")
54
+ monkeypatch.setenv("SPM_GATEWAY_URL", "http://localhost:18081")
55
+ with pytest.raises(ValueError, match="SPM_API_KEY"):
56
+ SpmClient.from_env()
57
+
58
+
59
+ def test_from_env_empty_url_raises(monkeypatch):
60
+ """from_env() raises ValueError when SPM_GATEWAY_URL is empty string (not None)."""
61
+ monkeypatch.setenv("SPM_API_KEY", "test-key-123")
62
+ monkeypatch.setenv("SPM_GATEWAY_URL", "")
63
+ with pytest.raises(ValueError, match="SPM_GATEWAY_URL"):
64
+ SpmClient.from_env()
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # ChatSession tests
69
+ # ---------------------------------------------------------------------------
70
+
71
+
72
+ @respx.mock
73
+ def test_chat_session_creates_and_sends():
74
+ """ChatSession.send() returns the assistant reply and updates history."""
75
+ respx.post("http://localhost:18081/v1/chat/completions").mock(
76
+ return_value=httpx.Response(
77
+ 200,
78
+ json={
79
+ "choices": [{"message": {"role": "assistant", "content": "4"}}]
80
+ },
81
+ )
82
+ )
83
+ with SpmClient("key", base_url="http://localhost:18081") as client:
84
+ session = client.session()
85
+ reply = session.send("What is 2+2?")
86
+ assert reply == "4"
87
+ assert len(session.history) == 2
88
+ assert session.history[0]["role"] == "user"
89
+ assert session.history[1]["role"] == "assistant"
90
+
91
+
92
+ @respx.mock
93
+ def test_auth_error_raises_auth_error():
94
+ """401 response raises AuthError with actionable message."""
95
+ respx.post("http://localhost:18081/v1/chat/completions").mock(
96
+ return_value=httpx.Response(
97
+ 401,
98
+ json={"error": {"message": "Unauthorized"}},
99
+ )
100
+ )
101
+ with SpmClient("bad-key", base_url="http://localhost:18081") as client:
102
+ session = client.session()
103
+ with pytest.raises(AuthError) as exc_info:
104
+ session.send("hello")
105
+ assert exc_info.value.status_code == 401
106
+ assert "SPM_API_KEY" in str(exc_info.value)
107
+ assert "api-keys" in str(exc_info.value)
108
+
109
+
110
+ @respx.mock
111
+ def test_quota_error_raises_quota_error():
112
+ """429 response raises QuotaError with retry_after info."""
113
+ respx.post("http://localhost:18081/v1/chat/completions").mock(
114
+ return_value=httpx.Response(
115
+ 429,
116
+ headers={"Retry-After": "30"},
117
+ json={"error": {"message": "Rate limit exceeded"}},
118
+ )
119
+ )
120
+ with SpmClient("key", base_url="http://localhost:18081") as client:
121
+ session = client.session()
122
+ with pytest.raises(QuotaError) as exc_info:
123
+ session.send("hello")
124
+ assert exc_info.value.status_code == 429
125
+ assert "30" in str(exc_info.value)
126
+ assert "Rate limit" in str(exc_info.value)
127
+
128
+
129
+ @respx.mock
130
+ def test_server_error_raises_server_error():
131
+ """500 response raises ServerError with correlation ID."""
132
+ respx.post("http://localhost:18081/v1/chat/completions").mock(
133
+ return_value=httpx.Response(
134
+ 500,
135
+ headers={"X-Correlation-Id": "req-abc-123"},
136
+ json={"error": {"message": "Internal server error"}},
137
+ )
138
+ )
139
+ with SpmClient("key", base_url="http://localhost:18081") as client:
140
+ session = client.session()
141
+ with pytest.raises(ServerError) as exc_info:
142
+ session.send("hello")
143
+ assert exc_info.value.status_code == 500
144
+ assert "req-abc-123" in str(exc_info.value)
145
+ assert "Correlation ID" in str(exc_info.value)
146
+
147
+
148
+ @respx.mock
149
+ def test_quota_error_with_http_date_retry_after():
150
+ """429 response with HTTP-date Retry-After header degrades gracefully."""
151
+ respx.post("http://localhost:18081/v1/chat/completions").mock(
152
+ return_value=httpx.Response(
153
+ 429,
154
+ headers={"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"},
155
+ json={"error": {"message": "Rate limit exceeded"}},
156
+ )
157
+ )
158
+ with SpmClient("key", base_url="http://localhost:18081") as client:
159
+ session = client.session()
160
+ with pytest.raises(QuotaError) as exc_info:
161
+ session.send("hello")
162
+ assert exc_info.value.status_code == 429
163
+ assert "unknown" in str(exc_info.value) # Non-integer header fallback
164
+
165
+
166
+ @respx.mock
167
+ def test_network_timeout_raises_spm_error():
168
+ """Network timeout raises SpmError wrapping the httpx exception."""
169
+ respx.post("http://localhost:18081/v1/chat/completions").mock(
170
+ side_effect=httpx.TimeoutException("Request timed out")
171
+ )
172
+ with SpmClient("key", base_url="http://localhost:18081") as client:
173
+ session = client.session()
174
+ with pytest.raises(httpx.TimeoutException):
175
+ session.send("hello")
176
+ assert session.history == []
177
+
178
+
179
+ @respx.mock
180
+ def test_failed_send_rolls_back_user_message_before_retry():
181
+ """A failed non-streaming send is absent from the next request history."""
182
+ route = respx.post("http://localhost:18081/v1/chat/completions")
183
+ route.side_effect = [
184
+ httpx.TimeoutException("Request timed out"),
185
+ httpx.Response(
186
+ 200,
187
+ json={"choices": [{"message": {"role": "assistant", "content": "ok"}}]},
188
+ ),
189
+ ]
190
+ with SpmClient("key", base_url="http://localhost:18081") as client:
191
+ session = client.session(system_prompt="Be concise")
192
+ with pytest.raises(httpx.TimeoutException):
193
+ session.send("secret failed")
194
+
195
+ assert session.history == [{"role": "system", "content": "Be concise"}]
196
+ assert session.send("retry") == "ok"
197
+
198
+ retry_payload = json.loads(route.calls[1].request.content)
199
+ assert retry_payload["messages"] == [
200
+ {"role": "system", "content": "Be concise"},
201
+ {"role": "user", "content": "retry"},
202
+ ]
203
+ assert session.history == [
204
+ {"role": "system", "content": "Be concise"},
205
+ {"role": "user", "content": "retry"},
206
+ {"role": "assistant", "content": "ok"},
207
+ ]
208
+
209
+
210
+ def test_reply_extraction_failure_rolls_back_only_pending_user():
211
+ """Malformed non-streaming reply data preserves pre-existing history."""
212
+ class FakeClient:
213
+ def chat(self, messages, **kwargs):
214
+ assert messages[-1] == {"role": "user", "content": "bad reply"}
215
+ return []
216
+
217
+ session = ChatSession(FakeClient(), system_prompt="Keep context")
218
+ with pytest.raises(AttributeError):
219
+ session.send("bad reply")
220
+
221
+ assert session.history == [{"role": "system", "content": "Keep context"}]
222
+
223
+
224
+ @respx.mock
225
+ def test_stream_parse_error_logged_and_skipped():
226
+ """Stream parse errors are logged at debug level and chunks are skipped."""
227
+ # Mock a streaming response with one valid chunk and one malformed chunk
228
+ def stream_lines():
229
+ yield b"data: " + b'{"choices": [{"delta": {"content": "Hello"}}]}\n'
230
+ yield b"data: {malformed json\n" # Invalid JSON
231
+ yield b"data: " + b'{"choices": [{"delta": {"content": " world"}}]}\n'
232
+ yield b"data: [DONE]\n"
233
+
234
+ respx.post("http://localhost:18081/v1/chat/completions").mock(
235
+ return_value=httpx.Response(
236
+ 200,
237
+ content=b"".join(stream_lines()),
238
+ headers={"Content-Type": "text/event-stream"},
239
+ )
240
+ )
241
+ with SpmClient("key", base_url="http://localhost:18081") as client:
242
+ session = client.session()
243
+ chunks = list(session.send("test", stream=True))
244
+ # Only valid chunks should be yielded (malformed chunk silently skipped)
245
+ assert chunks == ["Hello", " world"]
246
+ assert len(session.history) == 2 # user + assistant message appended
@@ -0,0 +1,108 @@
1
+ """Memory-plane methods on SpmClient (ingest, recall, read, export, events)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import respx
6
+ from httpx import Response
7
+
8
+ from spm_client import SpmClient
9
+
10
+ BASE = "https://api.example.test"
11
+
12
+
13
+ def _client() -> SpmClient:
14
+ return SpmClient("k", base_url=BASE)
15
+
16
+
17
+ @respx.mock
18
+ def test_remember_sends_topic_and_idempotency() -> None:
19
+ route = respx.post(f"{BASE}/v2/ingest").mock(
20
+ return_value=Response(200, json={"status": "accepted", "candidate_count": 2, "source_id": "s1"})
21
+ )
22
+ with _client() as client:
23
+ result = client.remember("专利 3 件", idempotency_key="idem-1", topic="patent", user_partition="ent-1")
24
+ assert result["source_id"] == "s1"
25
+ body = route.calls[0].request.content
26
+ assert b'"topic":"patent"' in body.replace(b", ", b",").replace(b": ", b":")
27
+
28
+
29
+ @respx.mock
30
+ def test_recall_passes_filters_and_returns_refusal() -> None:
31
+ route = respx.post(f"{BASE}/v2/recall").mock(
32
+ return_value=Response(200, json={"answer": "", "evidence_count": 0, "gate_reason": "no_candidate", "evidence_refs": []})
33
+ )
34
+ with _client() as client:
35
+ result = client.recall("融资", topics=["financing"], since="2026-01-01T00:00:00Z")
36
+ assert result["gate_reason"] == "no_candidate"
37
+ assert route.calls[0].request.content.count(b"financing") == 1
38
+
39
+
40
+ @respx.mock
41
+ def test_recall_text_joins_chunks() -> None:
42
+ respx.post(f"{BASE}/v2/recall").mock(
43
+ return_value=Response(
44
+ 200,
45
+ json={
46
+ "answer": "x",
47
+ "evidence_count": 1,
48
+ "gate_reason": "passed",
49
+ "evidence_refs": [{"source_id": "s1", "read_token": "t1"}],
50
+ },
51
+ )
52
+ )
53
+ respx.post(f"{BASE}/v2/read").mock(
54
+ return_value=Response(
55
+ 200,
56
+ json={
57
+ "spans": [
58
+ {
59
+ "source_id": "s1",
60
+ "chunks": [{"index": 0, "text": "第一段"}, {"index": 1, "text": "第二段"}],
61
+ "chunks_total": 2,
62
+ "chunks_returned": 2,
63
+ "tokens_total": 8,
64
+ "tokens_returned": 8,
65
+ "tokens_dropped": 0,
66
+ "content_truncated": False,
67
+ }
68
+ ],
69
+ "not_found": [],
70
+ "truncated": 0,
71
+ },
72
+ )
73
+ )
74
+ with _client() as client:
75
+ assert client.recall_text("q") == "第一段\n第二段"
76
+
77
+
78
+ @respx.mock
79
+ def test_error_code_surfaces() -> None:
80
+ respx.post(f"{BASE}/v2/purge").mock(
81
+ return_value=Response(404, json={"detail": {"code": "PURGE_TARGET_NOT_FOUND"}})
82
+ )
83
+ with _client() as client:
84
+ try:
85
+ client.purge(source_id="missing")
86
+ except Exception as exc: # NotFoundError subclass
87
+ assert "PURGE_TARGET_NOT_FOUND" in str(exc)
88
+ else: # pragma: no cover
89
+ raise AssertionError("expected an error")
90
+
91
+
92
+ def test_read_token_limit_is_local() -> None:
93
+ with _client() as client:
94
+ try:
95
+ client.read(["t"] * 33)
96
+ except ValueError as exc:
97
+ assert "32" in str(exc)
98
+ else: # pragma: no cover
99
+ raise AssertionError("expected ValueError")
100
+
101
+
102
+ @respx.mock
103
+ def test_subscribe_returns_secret() -> None:
104
+ respx.post(f"{BASE}/v2/events/subscriptions").mock(
105
+ return_value=Response(200, json={"id": "sub_1", "url": "https://h", "events": ["source.accepted"], "secret": "s"})
106
+ )
107
+ with _client() as client:
108
+ assert client.subscribe("https://h", ["source.accepted"])["secret"] == "s"