amfs-http-server 0.3.55__tar.gz → 0.3.61__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.
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: amfs-http-server
3
- Version: 0.3.55
3
+ Version: 0.3.61
4
4
  Summary: AMFS HTTP/REST API server with SSE support
5
5
  License-Expression: Apache-2.0
6
6
  Requires-Python: >=3.11
7
- Requires-Dist: amfs-core>=0.3.45
8
- Requires-Dist: amfs>=0.5.37
7
+ Requires-Dist: amfs-core>=0.3.52
8
+ Requires-Dist: amfs>=0.5.40
9
9
  Requires-Dist: fastapi>=0.115
10
10
  Requires-Dist: httpx>=0.27
11
11
  Requires-Dist: sse-starlette>=2.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "amfs-http-server"
3
- version = "0.3.55"
3
+ version = "0.3.61"
4
4
  description = "AMFS HTTP/REST API server with SSE support"
5
5
  requires-python = ">=3.11"
6
6
  license = "Apache-2.0"
@@ -13,7 +13,7 @@ dependencies = [
13
13
  # this tree is what test_dependency_floors forbids.
14
14
  # 0.5.18 for AgentMemory.as_agent, which the agent detail page calls to list
15
15
  # an agent's entries as that agent rather than as the server.
16
- "amfs>=0.5.37",
16
+ "amfs>=0.5.40",
17
17
  # 0.3.23 is real in the silent way: the write path calls
18
18
  # adapter.scope_counts(), which is a default on AdapterABC from 0.3.23. On an
19
19
  # older core the adapters that do not override it — filesystem, S3 — have no
@@ -27,7 +27,7 @@ dependencies = [
27
27
  # unexpected keyword, _scope_block swallows it, and the block disappears —
28
28
  # while an adapter that ignored the argument instead would name another
29
29
  # agent's private keys. Either way the floor is what makes the rule real.
30
- "amfs-core>=0.3.45",
30
+ "amfs-core>=0.3.52",
31
31
  "fastapi>=0.115",
32
32
  # 0.37 is where uvicorn.run() grew timeout_worker_healthcheck, which
33
33
  # main() passes unconditionally; on anything older that is a TypeError
@@ -0,0 +1,396 @@
1
+ """Byte-faithful capture of a proxied chat completion (t2-8e, OSS half).
2
+
3
+ The memory proxy forwards an OpenAI-shaped request to a frontier model and
4
+ hands the answer back. What training needs from that exchange is the whole of
5
+ it — the request body as sent (model, every message in the history, the tool
6
+ schemas, the sampling options), and the response as received, reassembled
7
+ from the SSE deltas when it streamed — kept as it was on the wire rather than
8
+ as a paraphrase, and tied to the bytes by hash so a reader can tell a faithful
9
+ copy from a reconstruction.
10
+
11
+ This module is the data shape and the capture surface. It does not select,
12
+ render or train — that is the Pro side's — and it is **off by default**:
13
+ ``capture_enabled(request)`` is true only when ``AMFS_PROXY_CAPTURE=true`` or
14
+ when the hosting layer has installed an opt-in resolver (``set_opt_in``) that
15
+ says so for this request's account. Captured text goes through the secret
16
+ scanner before anything is persisted; a blocked message is replaced by a
17
+ marker, never written.
18
+
19
+ The payload travels as ``session_metadata["capture"]`` on a
20
+ :class:`~amfs_core.models.DecisionTrace` with no outcome — a capture is not
21
+ evidence and moves no confidence — persisted through the adapter's
22
+ ``save_trace`` and sealed by whatever seal path the server has. Retention is
23
+ the trace store's.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import logging
31
+ import os
32
+ import uuid
33
+ from collections.abc import Callable, Iterable
34
+ from datetime import UTC, datetime
35
+ from typing import Any
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ #: ``session_metadata`` key the payload travels under, and its shape version.
40
+ CAPTURE_KEY = "capture"
41
+ CAPTURE_VERSION = 1
42
+ #: The attribute stamped on a capture trace so a reader can find them.
43
+ CAPTURE_ATTRIBUTE = "capture"
44
+ CAPTURE_SOURCE_OPENROUTER = "openrouter_proxy"
45
+ #: Environment switch. Default off.
46
+ CAPTURE_ENV = "AMFS_PROXY_CAPTURE"
47
+ #: Request keys kept byte-for-byte. Everything else on the body is dropped so
48
+ #: a caller's unrelated extension fields do not ride into the trace store.
49
+ REQUEST_KEYS: tuple[str, ...] = (
50
+ "model",
51
+ "messages",
52
+ "tools",
53
+ "tool_choice",
54
+ "functions",
55
+ "function_call",
56
+ "temperature",
57
+ "top_p",
58
+ "max_tokens",
59
+ "max_completion_tokens",
60
+ "stop",
61
+ "seed",
62
+ "response_format",
63
+ "parallel_tool_calls",
64
+ "reasoning",
65
+ "n",
66
+ )
67
+ #: Marker left where the scanner blocked a message outright.
68
+ REDACTED = "[redacted by SafetyGate]"
69
+
70
+ _OptIn = Callable[[Any], bool]
71
+ _opt_in: _OptIn | None = None
72
+
73
+
74
+ def set_opt_in(resolver: _OptIn | None) -> None:
75
+ """Install the per-account opt-in. The hosting layer passes a callable
76
+ taking the request and answering whether this account asked for capture;
77
+ ``None`` removes it. The environment switch remains a global override."""
78
+ global _opt_in
79
+ _opt_in = resolver
80
+
81
+
82
+ def capture_enabled(request: Any = None) -> bool:
83
+ """Whether this exchange is captured. Default-off: the env switch, or the
84
+ installed opt-in resolver saying yes for this request."""
85
+ if os.environ.get(CAPTURE_ENV, "false").strip().lower() in ("1", "true", "yes", "on"):
86
+ return True
87
+ if _opt_in is None or request is None:
88
+ return False
89
+ try:
90
+ return bool(_opt_in(request))
91
+ except Exception: # noqa: BLE001 - an opt-in that errors is an opt-out
92
+ logger.debug("capture opt-in resolver raised; treating as off", exc_info=True)
93
+ return False
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # SSE reassembly
98
+ # ---------------------------------------------------------------------------
99
+
100
+
101
+ def reassemble_sse(chunks: Iterable[bytes]) -> dict[str, Any]:
102
+ """Rebuild one chat completion from its streamed deltas.
103
+
104
+ Follows the OpenAI streaming shape: each ``data:`` line is a chunk whose
105
+ ``choices[i].delta`` carries a piece of ``content``, ``role``, or a piece
106
+ of a tool call addressed by ``index`` (name and arguments arrive in
107
+ fragments); ``finish_reason`` lands on the last delta of a choice;
108
+ ``usage`` on a trailing chunk when the caller asked for it; ``[DONE]``
109
+ ends the stream. Returns a non-streaming-shaped response — ``choices[]``
110
+ with a full ``message`` — plus ``stream: true`` and the number of chunks
111
+ so a reader knows how it was obtained. Lines that are not JSON are kept
112
+ under ``unparsed`` rather than dropped.
113
+ """
114
+ buffer = b"".join(chunks)
115
+ text = buffer.decode("utf-8", errors="replace")
116
+ choices: dict[int, dict[str, Any]] = {}
117
+ head: dict[str, Any] = {}
118
+ usage: Any = None
119
+ unparsed: list[str] = []
120
+ n_chunks = 0
121
+ for raw_line in text.replace("\r\n", "\n").split("\n"):
122
+ line = raw_line.strip()
123
+ if not line or line.startswith(":"):
124
+ continue
125
+ if not line.startswith("data:"):
126
+ unparsed.append(line)
127
+ continue
128
+ data = line[5:].strip()
129
+ if data == "[DONE]":
130
+ break
131
+ try:
132
+ chunk = json.loads(data)
133
+ except ValueError:
134
+ unparsed.append(line)
135
+ continue
136
+ n_chunks += 1
137
+ for key in ("id", "model", "created", "system_fingerprint", "object", "provider"):
138
+ if key in chunk and key not in head:
139
+ head[key] = chunk[key]
140
+ if chunk.get("usage") is not None:
141
+ usage = chunk["usage"]
142
+ for choice in chunk.get("choices") or []:
143
+ idx = int(choice.get("index", 0) or 0)
144
+ slot = choices.setdefault(
145
+ idx,
146
+ {
147
+ "index": idx,
148
+ "message": {"role": "assistant", "content": ""},
149
+ "finish_reason": None,
150
+ "_tool_calls": {},
151
+ },
152
+ )
153
+ delta = choice.get("delta") or {}
154
+ if delta.get("role"):
155
+ slot["message"]["role"] = delta["role"]
156
+ piece = delta.get("content")
157
+ if isinstance(piece, str):
158
+ slot["message"]["content"] += piece
159
+ if delta.get("reasoning") is not None:
160
+ slot["message"]["reasoning"] = (slot["message"].get("reasoning") or "") + str(
161
+ delta["reasoning"]
162
+ )
163
+ for tc in delta.get("tool_calls") or []:
164
+ t_idx = int(tc.get("index", len(slot["_tool_calls"])) or 0)
165
+ target = slot["_tool_calls"].setdefault(
166
+ t_idx,
167
+ {"id": None, "type": "function", "function": {"name": "", "arguments": ""}},
168
+ )
169
+ if tc.get("id"):
170
+ target["id"] = tc["id"]
171
+ if tc.get("type"):
172
+ target["type"] = tc["type"]
173
+ fn = tc.get("function") or {}
174
+ if fn.get("name"):
175
+ target["function"]["name"] += fn["name"]
176
+ if fn.get("arguments"):
177
+ target["function"]["arguments"] += fn["arguments"]
178
+ if choice.get("finish_reason"):
179
+ slot["finish_reason"] = choice["finish_reason"]
180
+ out_choices = []
181
+ for idx in sorted(choices):
182
+ slot = choices[idx]
183
+ tool_calls = [slot["_tool_calls"][k] for k in sorted(slot["_tool_calls"])]
184
+ message = dict(slot["message"])
185
+ if tool_calls:
186
+ message["tool_calls"] = tool_calls
187
+ if message.get("content") == "":
188
+ message["content"] = None
189
+ out_choices.append(
190
+ {"index": idx, "message": message, "finish_reason": slot["finish_reason"]}
191
+ )
192
+ result: dict[str, Any] = {
193
+ **head,
194
+ "object": head.get("object", "chat.completion"),
195
+ "choices": out_choices,
196
+ "stream": True,
197
+ "chunks": n_chunks,
198
+ }
199
+ if usage is not None:
200
+ result["usage"] = usage
201
+ if unparsed:
202
+ result["unparsed"] = unparsed[:50]
203
+ return result
204
+
205
+
206
+ # ---------------------------------------------------------------------------
207
+ # The payload
208
+ # ---------------------------------------------------------------------------
209
+
210
+
211
+ def _sha256(data: bytes) -> str:
212
+ return hashlib.sha256(data).hexdigest()
213
+
214
+
215
+ def _scan(text: Any, scanner: Callable[[str], str | None] | None) -> Any:
216
+ if scanner is None or not isinstance(text, str) or not text:
217
+ return text
218
+ scanned = scanner(text)
219
+ return REDACTED if scanned is None else scanned
220
+
221
+
222
+ def _redact_tree(value: Any, scanner: Callable[[str], str | None] | None) -> Any:
223
+ """Run *scanner* over **every** string leaf of *value*, whatever the
224
+ shape: message ``content`` as text or parts, ``reasoning``, tool-call
225
+ arguments, tool results, tool schemas, and any field a provider adds
226
+ that this module has never heard of. Structure is preserved; dict keys
227
+ are not scanned (they are field names, not text). Enumerating the known
228
+ text fields was how ``reasoning`` and the ``tools`` schemas were stored
229
+ unscanned."""
230
+ if isinstance(value, str):
231
+ return _scan(value, scanner)
232
+ if isinstance(value, dict):
233
+ return {k: _redact_tree(v, scanner) for k, v in value.items()}
234
+ if isinstance(value, list):
235
+ return [_redact_tree(v, scanner) for v in value]
236
+ if isinstance(value, tuple):
237
+ return [_redact_tree(v, scanner) for v in value]
238
+ return value
239
+
240
+
241
+ def _redact_messages(messages: Any, scanner: Callable[[str], str | None] | None) -> Any:
242
+ """Scan every text field a message can carry. A list of messages in, the
243
+ same shape out; kept as the named entry point the tests and the trace
244
+ builder use, implemented as the structural walk."""
245
+ if not isinstance(messages, list):
246
+ return messages
247
+ return _redact_tree(messages, scanner)
248
+
249
+
250
+ def tool_calls_of(response: dict[str, Any]) -> list[dict[str, Any]]:
251
+ """The tool calls the model made, in the :class:`amfs_core.models.ToolCall`
252
+ shape ``DecisionTrace.tool_calls`` carries (``tool_name``, ``arguments``,
253
+ ``source``), parsed from the response's first choice. The result is not
254
+ known at capture time — the caller's agent runs the tool — so each call
255
+ stands as requested. Arguments that are not JSON are kept as text."""
256
+ calls: list[dict[str, Any]] = []
257
+ try:
258
+ message = (response.get("choices") or [{}])[0].get("message") or {}
259
+ except (AttributeError, IndexError, TypeError):
260
+ return calls
261
+ for tc in message.get("tool_calls") or []:
262
+ fn = (tc or {}).get("function") or {}
263
+ raw = fn.get("arguments")
264
+ args: Any = raw
265
+ if isinstance(raw, str):
266
+ try:
267
+ args = json.loads(raw)
268
+ except ValueError:
269
+ args = {"_raw": raw}
270
+ calls.append(
271
+ {
272
+ "tool_name": str(fn.get("name") or "tool"),
273
+ "arguments": args if isinstance(args, dict) else {"_raw": args},
274
+ "source": "capture",
275
+ }
276
+ )
277
+ return calls
278
+
279
+
280
+ def capture_payload(
281
+ request_body: dict[str, Any],
282
+ response: dict[str, Any],
283
+ *,
284
+ raw_request: bytes | None = None,
285
+ raw_response: bytes | None = None,
286
+ upstream_status: int | None = None,
287
+ scanner: Callable[[str], str | None] | None = None,
288
+ source: str = CAPTURE_SOURCE_OPENROUTER,
289
+ scope: str | None = None,
290
+ injected_facts: int = 0,
291
+ ) -> dict[str, Any]:
292
+ """The capture, redacted and hashed.
293
+
294
+ ``request`` keeps the fields in :data:`REQUEST_KEYS` as the caller sent
295
+ them — the full message history and the tool schemas included —
296
+ ``response`` is the upstream object (reassembled when streamed), both with
297
+ every text field run through *scanner*. The hashes are of the **raw**
298
+ bytes before redaction, so a holder of the original can verify the capture
299
+ is of that exchange; the redacted text itself is what is stored.
300
+ """
301
+ # The whole of both objects, not the fields known to hold text: tool
302
+ # schemas, reasoning, provider extensions and anything else a caller sends
303
+ # or a model returns are stored, so all of it is scanned.
304
+ request = _redact_tree({k: request_body[k] for k in REQUEST_KEYS if k in request_body}, scanner)
305
+ redacted_response = _redact_tree(dict(response or {}), scanner)
306
+ payload: dict[str, Any] = {
307
+ "capture_version": CAPTURE_VERSION,
308
+ "source": source,
309
+ "captured_at": datetime.now(UTC).isoformat(),
310
+ "scope": scope,
311
+ "injected_facts": int(injected_facts),
312
+ "request": request,
313
+ "response": redacted_response,
314
+ "upstream_status": upstream_status,
315
+ "streamed": bool(response.get("stream")) if isinstance(response, dict) else False,
316
+ }
317
+ if raw_request is not None:
318
+ payload["request_sha256"] = _sha256(raw_request)
319
+ payload["request_bytes"] = len(raw_request)
320
+ if raw_response is not None:
321
+ payload["response_sha256"] = _sha256(raw_response)
322
+ payload["response_bytes"] = len(raw_response)
323
+ return payload
324
+
325
+
326
+ def capture_trace(
327
+ payload: dict[str, Any],
328
+ *,
329
+ agent_id: str,
330
+ session_id: str | None = None,
331
+ namespace: str = "default",
332
+ scope: str | None = None,
333
+ ) -> Any:
334
+ """A :class:`DecisionTrace` carrying *payload*: no outcome, the model's
335
+ tool calls on ``tool_calls``, the last user turn as ``task_input`` and
336
+ the assistant's text as ``response_text`` (what the sealed record and the
337
+ training exporters already read), the whole capture under
338
+ ``session_metadata.capture``."""
339
+ from amfs_core.models import DecisionTrace, SessionMetadata
340
+
341
+ messages = (payload.get("request") or {}).get("messages") or []
342
+ task_input = None
343
+ for m in reversed(messages):
344
+ if isinstance(m, dict) and m.get("role") == "user":
345
+ c = m.get("content")
346
+ task_input = (
347
+ c
348
+ if isinstance(c, str)
349
+ else json.dumps(c, ensure_ascii=False)
350
+ if c is not None
351
+ else None
352
+ )
353
+ break
354
+ response = payload.get("response") or {}
355
+ try:
356
+ response_text = (response.get("choices") or [{}])[0].get("message", {}).get("content")
357
+ except (AttributeError, IndexError, TypeError):
358
+ response_text = None
359
+ meta = SessionMetadata(
360
+ attributes={
361
+ CAPTURE_ATTRIBUTE: payload.get("source", CAPTURE_SOURCE_OPENROUTER),
362
+ "source": "proxy",
363
+ },
364
+ **{CAPTURE_KEY: payload},
365
+ )
366
+ return DecisionTrace(
367
+ id=str(uuid.uuid4()),
368
+ agent_id=agent_id,
369
+ session_id=session_id or f"capture-{uuid.uuid4().hex[:12]}",
370
+ outcome_ref=None,
371
+ outcome_type=None,
372
+ decision_summary=f"captured {payload.get('source')} exchange"
373
+ + (f" on {scope}" if scope else ""),
374
+ task_input=task_input,
375
+ response_text=response_text if isinstance(response_text, str) else None,
376
+ tool_calls=tool_calls_of(response),
377
+ session_metadata=meta,
378
+ namespace=namespace,
379
+ )
380
+
381
+
382
+ __all__ = [
383
+ "CAPTURE_ATTRIBUTE",
384
+ "CAPTURE_ENV",
385
+ "CAPTURE_KEY",
386
+ "CAPTURE_SOURCE_OPENROUTER",
387
+ "CAPTURE_VERSION",
388
+ "REDACTED",
389
+ "REQUEST_KEYS",
390
+ "capture_enabled",
391
+ "capture_payload",
392
+ "capture_trace",
393
+ "reassemble_sse",
394
+ "set_opt_in",
395
+ "tool_calls_of",
396
+ ]
@@ -135,6 +135,13 @@ class RetrieveRequest(BaseModel):
135
135
 
136
136
  query: str
137
137
  entity_path: str | None = None
138
+ # Widens entity_path to that path and everything beneath it, on both the
139
+ # semantic and the lexical channel (see SearchRequest.include_descendants
140
+ # and amfs_core.scope). Off by default so an exact-match caller keeps
141
+ # getting exactly what it asked for. For a caller whose scope is a prefix
142
+ # rather than an entity — a served model trained on `research/*` with no
143
+ # path on the request — an exact match on the prefix finds nothing.
144
+ include_descendants: bool = False
138
145
  min_confidence: float = 0.0
139
146
  limit: int = 10
140
147
  semantic_weight: float = 0.5
@@ -13,7 +13,8 @@ Design principles:
13
13
  - Non-blocking: memory retrieval and write-back are synchronous SDK calls, so
14
14
  they run in a threadpool (``asyncio.to_thread``) to keep the event loop free.
15
15
  Write-back and trace sealing are fire-and-forget background tasks.
16
- - Streaming: ``stream: true`` is passed through as an SSE byte stream.
16
+ - Streaming: ``stream: true`` is passed through as an SSE byte stream; with capture
17
+ on, the bytes are also held and reassembled into one response once it ends.
17
18
 
18
19
  Configuration (env):
19
20
  - OPENROUTER_API_KEY upstream key (required to enable the route)
@@ -22,6 +23,9 @@ Configuration (env):
22
23
  - AMFS_PROXY_WRITE_BACK "true" to enable fact write-back (default false)
23
24
  - AMFS_PROXY_SAFETY_GATE "false" to disable the Pro SafetyGate on write-back
24
25
  (default true; no-op when amfs_safety is absent)
26
+ - AMFS_PROXY_CAPTURE "true" to capture each exchange byte-faithfully as a
27
+ trace with no outcome (default false; a hosting layer
28
+ can opt accounts in per request via amfs_http.capture.set_opt_in)
25
29
 
26
30
  TODO(integration-test): tests/integration/test_openrouter_proxy.py exercises the
27
31
  inject/forward/write-back path against a mocked upstream; it is skipped in unit
@@ -34,7 +38,20 @@ import asyncio
34
38
  import json
35
39
  import logging
36
40
  import os
37
- from typing import Any, Callable
41
+ from collections.abc import Callable
42
+ from datetime import UTC
43
+ from typing import Any
44
+
45
+ # The route's ``request: Request`` annotation must resolve in *this* module's
46
+ # globals: with ``from __future__ import annotations`` FastAPI evaluates the
47
+ # string against them, and when ``Request`` was imported inside
48
+ # ``mount_openrouter_proxy`` the lookup failed silently — FastAPI then treated
49
+ # ``request`` as a required query parameter and every call to the proxy
50
+ # returned 422. Module-level import, so the annotation resolves.
51
+ try:
52
+ from fastapi import Request
53
+ except ImportError: # pragma: no cover - fastapi is a dependency of this package
54
+ Request = Any # type: ignore[assignment,misc]
38
55
 
39
56
  logger = logging.getLogger(__name__)
40
57
 
@@ -42,6 +59,10 @@ BASE_URL = os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")
42
59
  API_KEY = os.environ.get("OPENROUTER_API_KEY", "")
43
60
  INJECT_LIMIT = int(os.environ.get("AMFS_PROXY_INJECT_LIMIT", "5"))
44
61
  WRITE_BACK = os.environ.get("AMFS_PROXY_WRITE_BACK", "false").lower() == "true"
62
+
63
+ #: The upstream HTTP client, created on mount. Module-level so a test can put
64
+ #: a mock transport behind the mounted route.
65
+ _upstream_client: Any = None
45
66
  # Auto-run the Pro SafetyGate on write-back when available (secret block + PII
46
67
  # redact). Disabled explicitly with AMFS_PROXY_SAFETY_GATE=false. Soft/optional:
47
68
  # the gate lives in the Pro ``amfs_safety`` package; OSS-only deployments skip it.
@@ -67,7 +88,7 @@ def _gate_value(mem: Any, scope: str, key: str, value: Any) -> tuple[bool, Any]:
67
88
  _SAFETY_GATE_CACHE["gate"] = SafetyGate(adapter=adapter)
68
89
  gate = _SAFETY_GATE_CACHE["gate"]
69
90
 
70
- from datetime import datetime, timezone
91
+ from datetime import datetime
71
92
 
72
93
  from amfs_core.models import MemoryEntry, Provenance
73
94
 
@@ -78,7 +99,7 @@ def _gate_value(mem: Any, scope: str, key: str, value: Any) -> tuple[bool, Any]:
78
99
  provenance=Provenance(
79
100
  agent_id="openrouter-proxy",
80
101
  session_id="proxy",
81
- written_at=datetime.now(timezone.utc),
102
+ written_at=datetime.now(UTC),
82
103
  ),
83
104
  confidence=0.5,
84
105
  )
@@ -186,6 +207,63 @@ def _write_back(get_memory: Callable[[], Any], scope: str | None,
186
207
  logger.debug("proxy: write-back failed", exc_info=True)
187
208
 
188
209
 
210
+ def _capture_exchange(
211
+ get_memory: Callable[[], Any],
212
+ *,
213
+ request_body: dict[str, Any],
214
+ response: dict[str, Any],
215
+ raw_request: bytes,
216
+ raw_response: bytes | None,
217
+ upstream_status: int | None,
218
+ scope: str | None,
219
+ injected_facts: int,
220
+ agent_id: str,
221
+ ) -> str | None:
222
+ """Byte-faithful capture of one exchange as a trace with no outcome
223
+ (:mod:`amfs_http.capture`, t2-8e). Redacted by the secret scanner before
224
+ anything is written; best-effort, never raises into the request."""
225
+ from amfs_core.capture import scan_captured_text
226
+
227
+ from amfs_http import capture as cap
228
+
229
+ try:
230
+ mem = get_memory()
231
+ adapter = getattr(mem, "_adapter", None)
232
+
233
+ def _scanner(text: str) -> str | None:
234
+ return scan_captured_text(text, adapter=adapter, agent_id=agent_id)
235
+
236
+ payload = cap.capture_payload(
237
+ request_body, response, raw_request=raw_request, raw_response=raw_response,
238
+ upstream_status=upstream_status, scanner=_scanner, scope=scope,
239
+ injected_facts=injected_facts,
240
+ )
241
+ trace = cap.capture_trace(
242
+ payload, agent_id=agent_id, namespace=getattr(mem, "namespace", "default"), scope=scope,
243
+ )
244
+ save = getattr(adapter, "save_trace", None)
245
+ if not callable(save):
246
+ return None
247
+ saved = save(trace)
248
+ # Sealed by whatever seal path the server has (Pro traces), so the
249
+ # capture is content-addressed like every other trace. The raw
250
+ # session metadata is passed because the OSS model drops undeclared
251
+ # keys and the payload travels in one.
252
+ try:
253
+ from amfs_http import server as _server
254
+
255
+ seal = getattr(_server, "_auto_seal_trace", None)
256
+ if callable(seal):
257
+ meta = trace.session_metadata.model_dump() if trace.session_metadata else None
258
+ seal(mem, saved, session_metadata=meta)
259
+ except Exception: # noqa: BLE001 - the OSS row stands on its own
260
+ logger.debug("proxy: capture seal skipped", exc_info=True)
261
+ return getattr(saved, "id", None) or trace.id
262
+ except Exception: # noqa: BLE001
263
+ logger.debug("proxy: capture failed", exc_info=True)
264
+ return None
265
+
266
+
189
267
  def mount_openrouter_proxy(app, *, get_memory: Callable[[], Any]) -> None:
190
268
  """Mount POST /api/v1/proxy/chat/completions if OpenRouter is configured."""
191
269
  if not is_configured():
@@ -193,10 +271,17 @@ def mount_openrouter_proxy(app, *, get_memory: Callable[[], Any]) -> None:
193
271
  return
194
272
 
195
273
  import httpx
196
- from fastapi import Request
197
274
  from fastapi.responses import JSONResponse, StreamingResponse
198
275
 
199
- client = httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0))
276
+ from amfs_http import capture as cap
277
+
278
+ global _upstream_client
279
+ if _upstream_client is None:
280
+ _upstream_client = httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0))
281
+
282
+ def _client():
283
+ # Resolved per request so a test (or a reload) can swap the client.
284
+ return _upstream_client
200
285
 
201
286
  def _scope_of(request: Request, body: dict[str, Any]) -> str | None:
202
287
  return (body.get("amfs_scope")
@@ -222,32 +307,69 @@ def mount_openrouter_proxy(app, *, get_memory: Callable[[], Any]) -> None:
222
307
  scope = _scope_of(request, body)
223
308
  messages = body.get("messages") or []
224
309
  query = _last_user_text(messages)
310
+ # Capture is decided per request and off by default (t2-8e): the env
311
+ # switch or the hosting layer's per-account opt-in. The request body
312
+ # is kept as the caller sent it — before injection — because that is
313
+ # the exchange the caller's agent had; the injected facts are counted.
314
+ capturing = cap.capture_enabled(request)
315
+ sent_body = dict(body) if capturing else None
316
+ capture_agent = (request.headers.get("X-AMFS-Agent-Id") or body.get("amfs_agent_id")
317
+ or "openrouter-proxy")
318
+ injected = 0
225
319
 
226
320
  # 1) Retrieve + inject memory (fail-open, off the event loop).
227
321
  try:
228
322
  facts = await asyncio.to_thread(_retrieve_facts, get_memory, scope, query)
229
323
  if facts:
230
324
  body = {**body, "messages": _inject(messages, facts)}
325
+ injected = len(facts)
231
326
  except Exception: # noqa: BLE001
232
327
  logger.debug("proxy: injection skipped", exc_info=True)
233
328
 
234
329
  body.pop("amfs_scope", None)
330
+ body.pop("amfs_agent_id", None)
331
+ if sent_body is not None:
332
+ sent_body.pop("amfs_scope", None)
333
+ sent_body.pop("amfs_agent_id", None)
235
334
  url = f"{BASE_URL}/chat/completions"
236
335
  headers = _upstream_headers(request)
237
336
 
238
- # 2a) Streaming: pass the SSE stream straight through.
337
+ def _schedule_capture(
338
+ response: dict[str, Any], raw_response: bytes | None, status: int | None
339
+ ) -> None:
340
+ if sent_body is None:
341
+ return
342
+ asyncio.create_task(asyncio.to_thread(
343
+ _capture_exchange, get_memory,
344
+ request_body=sent_body, response=response, raw_request=raw,
345
+ raw_response=raw_response, upstream_status=status, scope=scope,
346
+ injected_facts=injected, agent_id=capture_agent,
347
+ ))
348
+
349
+ # 2a) Streaming: pass the SSE stream straight through. With capture on
350
+ # the bytes are also accumulated and reassembled once the stream ends;
351
+ # with it off nothing is held and the path is as it was.
239
352
  if body.get("stream"):
240
353
  async def _iter():
241
- async with client.stream("POST", url, headers=headers, json=body) as resp:
354
+ held: list[bytes] = []
355
+ status: int | None = None
356
+ async with _client().stream("POST", url, headers=headers, json=body) as resp:
357
+ status = resp.status_code
242
358
  async for chunk in resp.aiter_raw():
359
+ if capturing:
360
+ held.append(chunk)
243
361
  yield chunk
244
- # NOTE: write-back on streamed responses requires accumulating the
245
- # SSE deltas; deferred (TODO) to keep streaming zero-overhead.
362
+ if capturing:
363
+ try:
364
+ joined = b"".join(held)
365
+ _schedule_capture(cap.reassemble_sse([joined]), joined, status)
366
+ except Exception: # noqa: BLE001
367
+ logger.debug("proxy: stream capture failed", exc_info=True)
246
368
  return StreamingResponse(_iter(), media_type="text/event-stream")
247
369
 
248
370
  # 2b) Non-streaming: forward, then schedule background write-back.
249
371
  try:
250
- resp = await client.post(url, headers=headers, json=body)
372
+ resp = await _client().post(url, headers=headers, json=body)
251
373
  except Exception: # noqa: BLE001
252
374
  logger.warning("proxy: upstream request failed", exc_info=True)
253
375
  return JSONResponse({"error": "upstream unavailable"}, status_code=502)
@@ -261,6 +383,8 @@ def mount_openrouter_proxy(app, *, get_memory: Callable[[], Any]) -> None:
261
383
  if WRITE_BACK and answer:
262
384
  asyncio.create_task(
263
385
  asyncio.to_thread(_write_back, get_memory, scope, query, answer))
386
+ if capturing and isinstance(data, dict):
387
+ _schedule_capture(data, resp.content or None, resp.status_code)
264
388
 
265
389
  return JSONResponse(data, status_code=resp.status_code)
266
390
 
@@ -2270,6 +2270,7 @@ async def write_entry(
2270
2270
  _ns = _async_adapter._namespace if _async_adapter else mem.namespace
2271
2271
  _branch = entry.branch or "main"
2272
2272
  _confidence = entry.confidence
2273
+ _refs = [r for r in (req.pattern_refs or []) if isinstance(r, str) and "/" in r and r != _ek]
2273
2274
 
2274
2275
  if _async_adapter is not None:
2275
2276
  async def _bg_async_side_effects() -> None:
@@ -2307,6 +2308,31 @@ async def write_entry(
2307
2308
  )
2308
2309
  except Exception:
2309
2310
  logger.debug("bg: Failed to materialize wrote edge", exc_info=True)
2311
+ # ``references`` edges from pattern_refs — the graph
2312
+ # ``propagate_failure`` walks. The sync path gets them from
2313
+ # ``AgentMemory._materialize_pattern_ref_edges``; this path writes
2314
+ # the entry through the adapter directly, so until here a hosted
2315
+ # writer's pattern_refs reached the graph only on a backfill, and
2316
+ # a failure on the parent never propagated to what cited it.
2317
+ # Only when the async write is the one that stored the entry: on
2318
+ # the sync fallback ``handle.write`` has already materialised them,
2319
+ # and a second upsert would bump ``evidence_count`` for one write.
2320
+ for _ref in _refs if _used_async else ():
2321
+ try:
2322
+ await _async_adapter.upsert_graph_edge(
2323
+ GraphEdge(
2324
+ source_entity=_ek,
2325
+ source_type="entry",
2326
+ relation="references",
2327
+ target_entity=_ref,
2328
+ target_type="entry",
2329
+ provenance={"agent_id": _agent, "trigger": "write"},
2330
+ ),
2331
+ namespace=_ns,
2332
+ branch=_branch,
2333
+ )
2334
+ except Exception:
2335
+ logger.debug("bg: Failed to materialize references edge for %s", _ref, exc_info=True)
2310
2336
 
2311
2337
  asyncio.create_task(_bg_async_side_effects())
2312
2338
  else:
@@ -2949,6 +2975,7 @@ async def retrieve_entries(
2949
2975
  sq = SemanticQuery(
2950
2976
  text=qtext,
2951
2977
  entity_path=req.entity_path,
2978
+ include_descendants=req.include_descendants,
2952
2979
  min_confidence=req.min_confidence,
2953
2980
  limit=pool,
2954
2981
  embedding=query_vectors.get(qtext),
@@ -2969,6 +2996,7 @@ async def retrieve_entries(
2969
2996
  sq_lex = SearchQuery(
2970
2997
  query=topical,
2971
2998
  entity_path=req.entity_path,
2999
+ include_descendants=req.include_descendants,
2972
3000
  min_confidence=req.min_confidence,
2973
3001
  limit=pool,
2974
3002
  sort_by="confidence",
@@ -5311,7 +5339,14 @@ async def save_trace(
5311
5339
  ) -> dict[str, Any]:
5312
5340
  """Persist a decision trace (used by HttpAdapter.save_trace)."""
5313
5341
  body = await req.json()
5314
- trace = DecisionTrace.model_validate(body)
5342
+ # The body is read raw (the seal below prefers it to the parsed model), so
5343
+ # validation is explicit here and a malformed trace is a 422 naming the
5344
+ # field, as it would be for a typed body — not a 500 with the detail in
5345
+ # the server log only.
5346
+ try:
5347
+ trace = DecisionTrace.model_validate(body)
5348
+ except ValidationError as exc:
5349
+ raise HTTPException(status_code=422, detail=exc.errors(include_url=False)) from exc
5315
5350
  mem = _get_memory()
5316
5351
  if trace.agent_id:
5317
5352
  _link_agent_owner_once(req, trace.agent_id, mem.namespace)
@@ -5853,6 +5888,7 @@ def reuse_summary(
5853
5888
  days: int = 7,
5854
5889
  limit: int = 10,
5855
5890
  agent: str | None = None,
5891
+ writer: str | None = None,
5856
5892
  _auth: str | None = Depends(verify_api_key),
5857
5893
  ) -> dict[str, Any]:
5858
5894
  """Reuse over a window: how much, of what, by which agents, and across which.
@@ -5875,6 +5911,12 @@ def reuse_summary(
5875
5911
  ``limit`` by reuse volume first, so a caller keeping the rows that name its
5876
5912
  agent would silently lose a quiet agent's reuse and could not tell that apart
5877
5913
  from the agent having none.
5914
+
5915
+ ``writer`` narrows it to one agent as WRITER — the reads of memory it wrote —
5916
+ so ``cross_surface`` is exactly how many times other agents took from it and
5917
+ ``by_agent`` names them. Same reasoning, other side of the handoff. Both may
5918
+ be given. The answer echoes ``writer`` so a caller can tell this server
5919
+ applied it from an older one that ignored the parameter.
5878
5920
  """
5879
5921
  days = max(1, min(int(days or 7), 365))
5880
5922
  limit = max(1, min(int(limit or 10), 100))
@@ -5892,27 +5934,32 @@ def reuse_summary(
5892
5934
  "reason": "reuse events need the Postgres adapter",
5893
5935
  }
5894
5936
  agent = agent or None
5937
+ writer = writer or None
5895
5938
  kwargs: dict[str, Any] = {
5896
5939
  "since": since,
5897
5940
  "limit": limit,
5898
5941
  "visible_agents": _visible_agent_ids(request),
5899
5942
  }
5900
- if agent is not None:
5901
- # This server carries no dependency on the adapter package — it duck-types
5902
- # whatever backend it was handed — so an adapter predating the parameter is
5903
- # a real deployment, not a hypothetical. Passing the keyword blindly would
5904
- # raise TypeError and take out the whole endpoint, including the
5905
- # account-wide answer that still works. Refusing just the narrowed question
5906
- # keeps a stale pairing degraded rather than broken.
5907
- if "agent" not in inspect.signature(summarise).parameters:
5943
+ # This server carries no dependency on the adapter package — it duck-types
5944
+ # whatever backend it was handed — so an adapter predating a parameter is a
5945
+ # real deployment, not a hypothetical. Passing the keyword blindly would
5946
+ # raise TypeError and take out the whole endpoint, including the
5947
+ # account-wide answer that still works. Refusing just the narrowed question
5948
+ # keeps a stale pairing degraded rather than broken.
5949
+ accepted = inspect.signature(summarise).parameters
5950
+ for name, value, side in (("agent", agent, "agent"), ("writer", writer, "writer")):
5951
+ if value is None:
5952
+ continue
5953
+ if name not in accepted:
5908
5954
  return {
5909
5955
  "since": since.isoformat(),
5910
5956
  "days": days,
5911
5957
  "available": False,
5912
5958
  "agent": agent,
5913
- "reason": "this backend cannot scope reuse to one agent",
5959
+ "writer": writer,
5960
+ "reason": f"this backend cannot scope reuse to one {side}",
5914
5961
  }
5915
- kwargs["agent"] = agent
5962
+ kwargs[name] = value
5916
5963
 
5917
5964
  summary = summarise(**kwargs)
5918
5965
  return {
@@ -5920,10 +5967,64 @@ def reuse_summary(
5920
5967
  "days": days,
5921
5968
  "available": True,
5922
5969
  "agent": agent,
5970
+ "writer": writer,
5923
5971
  **summary,
5924
5972
  }
5925
5973
 
5926
5974
 
5975
+ @app.get("/api/v1/learning")
5976
+ def learning_curve_endpoint(
5977
+ request: Request,
5978
+ days: int = 90,
5979
+ agent: str | None = None,
5980
+ entity_path: str | None = None,
5981
+ window: int = 10,
5982
+ episodes: int = 12,
5983
+ _auth: str | None = Depends(verify_api_key),
5984
+ ) -> dict[str, Any]:
5985
+ """The number: success over sessions, and recovery after regime shifts.
5986
+
5987
+ ``amfs_core.learning.learning_curve`` over the outcomes in the window —
5988
+ the agent's sessions in order, cut into ``episodes`` bins, with the first
5989
+ and latest ``window`` sessions as the headline, and for every entry the
5990
+ agent relied on that was discredited in the window, how many sessions it
5991
+ took the rolling rate to get back to where it was. ``verified_share`` says
5992
+ how much of the curve was decided outside the agent.
5993
+
5994
+ Scoped to the agents the caller may see, like ``/reuse``; ``agent`` and
5995
+ ``entity_path`` narrow on top of that. ``days`` is clamped so a
5996
+ hand-written URL cannot ask for an unbounded scan, and the series is the
5997
+ newest 5000 sessions in the window: ``truncated`` says when there were
5998
+ more, and ``span.from`` where the curve actually starts.
5999
+ """
6000
+ from amfs_core.learning import MAX_EPISODES, learning_curve
6001
+
6002
+ days = max(1, min(int(days or 90), 365))
6003
+ window = max(3, min(int(window or 10), 100))
6004
+ episodes = max(1, min(int(episodes or 12), MAX_EPISODES))
6005
+ since = datetime.now(UTC) - timedelta(days=days)
6006
+ head = {
6007
+ "since": since.isoformat(),
6008
+ "days": days,
6009
+ "agent": agent or None,
6010
+ "entity_path": entity_path or None,
6011
+ }
6012
+ adapter = _get_memory()._adapter
6013
+ series = getattr(adapter, "learning_series", None)
6014
+ if series is None:
6015
+ return {**head, "available": False, "reason": "the learning curve needs the Postgres adapter"}
6016
+ data = series(
6017
+ since=since,
6018
+ agent=agent or None,
6019
+ entity_path=entity_path or None,
6020
+ visible_agents=_visible_agent_ids(request),
6021
+ )
6022
+ curve = learning_curve(
6023
+ data.get("sessions") or [], shifts=data.get("shifts") or [], window=window, episodes=episodes
6024
+ )
6025
+ return {**head, "available": True, "truncated": bool(data.get("truncated")), **curve}
6026
+
6027
+
5927
6028
  @app.get("/api/v1/agents/{agent_id:path}/memory-graph")
5928
6029
  def agent_memory_graph(
5929
6030
  request: Request,