| 1 |
"""An `AsyncAnthropic`-shaped stub backed by an in-memory store. |
| 2 |
|
| 3 |
A memory store is a folder: path → content. `MemoryServer` is that dict |
| 4 |
plus a log of the writes the code under test sent it. The SDK-shaped |
| 5 |
resource `SessionMemoryStores` actually calls is a private adapter. |
| 6 |
|
| 7 |
Paths are bare (`"push.md"`); the leading `/` the wire uses is added |
| 8 |
and stripped internally so tests use one path vocabulary throughout. |
| 9 |
""" |
| 10 |
|
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
import hashlib |
| 14 |
from types import SimpleNamespace |
| 15 |
from typing import Any |
| 16 |
from collections.abc import Mapping, Callable, Awaitable, AsyncIterator |
| 17 |
|
| 18 |
import httpx2 |
| 19 |
|
| 20 |
from anthropic import APIStatusError |
| 21 |
|
| 22 |
|
| 23 |
def _sha(content: str) -> str: |
| 24 |
return hashlib.sha256(content.encode("utf-8")).hexdigest() |
| 25 |
|
| 26 |
|
| 27 |
def _status_error(code: int) -> APIStatusError: |
| 28 |
request = httpx2.Request("POST", "https://api.example/v1/memory") |
| 29 |
return APIStatusError(f"status {code}", response=httpx2.Response(code, request=request), body=None) |
| 30 |
|
| 31 |
|
| 32 |
class MemoryServer: |
| 33 |
"""The test's view of one remote memory store. |
| 34 |
|
| 35 |
`files` is its current state (path → content); `received` is every |
| 36 |
write the code under test sent it. Arranging via `write` / |
| 37 |
`delete` changes `files` without touching `received` — only |
| 38 |
the sync's own requests are recorded. |
| 39 |
""" |
| 40 |
|
| 41 |
def __init__(self, initial: Mapping[str, str | None]) -> None: |
| 42 |
# A `None` value is a memory with null content — the wire allows it. |
| 43 |
self.files: dict[str, str | None] = dict(initial) |
| 44 |
self.received: list[tuple[Any, ...]] = [] |
| 45 |
# Reject create/update content larger than this with a 400, like the |
| 46 |
# real server's per-memory cap. |
| 47 |
self.max_content_bytes: int | None = None |
| 48 |
# Session lookups the code under test performed (the worker shares one |
| 49 |
# fetch between the skills and memory downloads). |
| 50 |
self.retrieves: list[str] = [] |
| 51 |
# Single-memory content fetches (the sync's content pass), in arrival |
| 52 |
# order — a test asserting "no content moved" checks this stays empty. |
| 53 |
self.content_fetches: list[str] = [] |
| 54 |
# Called with the path as each content fetch arrives — raise to break |
| 55 |
# the fetch, or delete the path to race it against a server delete. |
| 56 |
self.fetch_hook: Callable[[str], None] | None = None |
| 57 |
# Awaited with the path as each create/update arrives, before the |
| 58 |
# request is recorded — park it to hold an upload open. |
| 59 |
self.upload_hook: Callable[[str], Awaitable[None]] | None = None |
| 60 |
|
| 61 |
def write(self, path: str, content: str) -> None: |
| 62 |
self.files[path] = content |
| 63 |
|
| 64 |
def delete(self, path: str) -> None: |
| 65 |
del self.files[path] |
| 66 |
|
| 67 |
|
| 68 |
# Requests recorded on `server.received`, in domain terms: paths and |
| 69 |
# content. `was` is the pre-image content the request's precondition |
| 70 |
# guards on — the builder computes the sha. |
| 71 |
|
| 72 |
|
| 73 |
def created(path: str, content: str) -> tuple[Any, ...]: |
| 74 |
return ("create", path, content) |
| 75 |
|
| 76 |
|
| 77 |
def updated(path: str, content: str, *, was: str) -> tuple[Any, ...]: |
| 78 |
return ("update", path, content, _sha(was)) |
| 79 |
|
| 80 |
|
| 81 |
def deleted(path: str, *, was: str) -> tuple[Any, ...]: |
| 82 |
return ("delete", path, _sha(was)) |
| 83 |
|
| 84 |
|
| 85 |
class _Resource: |
| 86 |
"""Adapts a `MemoryServer` to the `client.beta.memory_stores.memories` shape. |
| 87 |
|
| 88 |
Items are built on the fly from `server.files` so there is no cached |
| 89 |
state to drift; ids are derived from paths so there is no id table. |
| 90 |
""" |
| 91 |
|
| 92 |
def __init__(self, server: MemoryServer, *, noise: bool = False) -> None: |
| 93 |
self._server = server |
| 94 |
self._noise = noise |
| 95 |
|
| 96 |
def _item(self, path: str, *, view: str = "full") -> Any: |
| 97 |
content = self._server.files[path] |
| 98 |
return SimpleNamespace( |
| 99 |
type="memory", |
| 100 |
id=f"mem:{path}", |
| 101 |
path="/" + path, |
| 102 |
content=content if view == "full" else None, |
| 103 |
content_sha256=_sha(content or ""), |
| 104 |
) |
| 105 |
|
| 106 |
def list(self, memory_store_id: str, *, view: str = "basic", **_: Any) -> AsyncIterator[Any]: |
| 107 |
async def _iter() -> AsyncIterator[Any]: |
| 108 |
if self._noise: |
| 109 |
# Depth-limited listings roll directories up as prefixes; |
| 110 |
# only `memory` items carry content. |
| 111 |
yield SimpleNamespace(type="memory_prefix", path="/projects/") |
| 112 |
if memory_store_id == "memstore_broken": |
| 113 |
# One memory is listed, then the pager explodes. |
| 114 |
yield SimpleNamespace( |
| 115 |
type="memory", |
| 116 |
id="mem:half", |
| 117 |
path="/half.md", |
| 118 |
content="partial" if view == "full" else None, |
| 119 |
content_sha256=_sha("partial"), |
| 120 |
) |
| 121 |
raise RuntimeError("list exploded") |
| 122 |
for path in list(self._server.files): |
| 123 |
yield self._item(path, view=view) |
| 124 |
|
| 125 |
return _iter() |
| 126 |
|
| 127 |
async def retrieve(self, memory_id: str, *, memory_store_id: str, view: str = "basic") -> Any: # noqa: ARG002 |
| 128 |
path = memory_id.removeprefix("mem:") |
| 129 |
self._server.content_fetches.append(path) |
| 130 |
if self._server.fetch_hook is not None: |
| 131 |
self._server.fetch_hook(path) |
| 132 |
if path not in self._server.files: |
| 133 |
raise _status_error(404) |
| 134 |
return self._item(path, view=view) |
| 135 |
|
| 136 |
def _check_size(self, content: str) -> None: |
| 137 |
cap = self._server.max_content_bytes |
| 138 |
if cap is not None and len(content.encode()) > cap: |
| 139 |
raise _status_error(400) |
| 140 |
|
| 141 |
async def create(self, _memory_store_id: str, *, path: str, content: str) -> Any: |
| 142 |
bare = path.lstrip("/") |
| 143 |
if self._server.upload_hook is not None: |
| 144 |
await self._server.upload_hook(bare) |
| 145 |
self._server.received.append(created(bare, content)) |
| 146 |
self._check_size(content) |
| 147 |
self._server.files[bare] = content |
| 148 |
return self._item(bare) |
| 149 |
|
| 150 |
async def update( |
| 151 |
self, |
| 152 |
memory_id: str, |
| 153 |
*, |
| 154 |
memory_store_id: str, # noqa: ARG002 |
| 155 |
content: str, |
| 156 |
precondition: dict[str, str], |
| 157 |
) -> Any: |
| 158 |
path = memory_id.removeprefix("mem:") |
| 159 |
if self._server.upload_hook is not None: |
| 160 |
await self._server.upload_hook(path) |
| 161 |
self._server.received.append(("update", path, content, precondition["content_sha256"])) |
| 162 |
self._check_size(content) |
| 163 |
if path not in self._server.files: |
| 164 |
raise _status_error(404) |
| 165 |
if _sha(self._server.files[path] or "") != precondition["content_sha256"]: |
| 166 |
raise _status_error(409) |
| 167 |
self._server.files[path] = content |
| 168 |
return self._item(path) |
| 169 |
|
| 170 |
async def delete( |
| 171 |
self, |
| 172 |
memory_id: str, |
| 173 |
*, |
| 174 |
memory_store_id: str, # noqa: ARG002 |
| 175 |
expected_content_sha256: str | None = None, |
| 176 |
) -> Any: |
| 177 |
path = memory_id.removeprefix("mem:") |
| 178 |
self._server.received.append(("delete", path, expected_content_sha256)) |
| 179 |
if path not in self._server.files: |
| 180 |
raise _status_error(404) |
| 181 |
if expected_content_sha256 is not None and _sha(self._server.files[path] or "") != expected_content_sha256: |
| 182 |
raise _status_error(409) |
| 183 |
del self._server.files[path] |
| 184 |
return SimpleNamespace(id=memory_id, type="memory_deleted") |
| 185 |
|
| 186 |
|
| 187 |
def fake_anthropic( |
| 188 |
initial: Mapping[str, str | None], |
| 189 |
*, |
| 190 |
access: str | None = None, |
| 191 |
broken_store: bool = False, |
| 192 |
broken_store_last: bool = False, |
| 193 |
no_stores: bool = False, |
| 194 |
mount_path: str | None = None, |
| 195 |
noise: bool = False, |
| 196 |
) -> tuple[Any, MemoryServer]: |
| 197 |
"""An `AsyncAnthropic`-shaped client with one memory store named `notes`. |
| 198 |
|
| 199 |
The store lands at `{workdir}/memory/notes`. Returns the client to |
| 200 |
hand to `SessionMemoryStores` and the server handle for the test. |
| 201 |
`broken_store` attaches a second store, ahead of `notes`, whose |
| 202 |
listing explodes after one memory; `broken_store_last` puts it after, |
| 203 |
so `notes` lands first and the failure comes later. `no_stores` |
| 204 |
attaches no memory store at all. `noise` adds a non-store resource |
| 205 |
to the session and a `memory_prefix` rollup to every listing. |
| 206 |
""" |
| 207 |
server = MemoryServer(initial) |
| 208 |
resources: list[Any] = ( |
| 209 |
[] |
| 210 |
if no_stores |
| 211 |
else [ |
| 212 |
SimpleNamespace( |
| 213 |
type="memory_store", |
| 214 |
memory_store_id="memstore_notes", |
| 215 |
mount_path=mount_path, |
| 216 |
name="notes", |
| 217 |
access=access, |
| 218 |
) |
| 219 |
] |
| 220 |
) |
| 221 |
if noise: |
| 222 |
resources.insert(0, SimpleNamespace(type="file", file_id="file_1")) |
| 223 |
if broken_store or broken_store_last: |
| 224 |
broken = SimpleNamespace( |
| 225 |
type="memory_store", memory_store_id="memstore_broken", mount_path=None, name="broken", access=None |
| 226 |
) |
| 227 |
if broken_store_last: |
| 228 |
resources.append(broken) |
| 229 |
else: |
| 230 |
resources.insert(0, broken) |
| 231 |
|
| 232 |
async def _retrieve(session_id: str) -> Any: |
| 233 |
server.retrieves.append(session_id) |
| 234 |
return SimpleNamespace(agent=SimpleNamespace(skills=[]), resources=resources) |
| 235 |
|
| 236 |
client = SimpleNamespace( |
| 237 |
beta=SimpleNamespace( |
| 238 |
sessions=SimpleNamespace(retrieve=_retrieve), |
| 239 |
memory_stores=SimpleNamespace(memories=_Resource(server, noise=noise)), |
| 240 |
) |
| 241 |
) |
| 242 |
return client, server |