Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(memory): expose calls without memcells (#1502)

rkrkrkkaadabe207f87
diff --git a/core/internal_server.py b/core/internal_server.py
index d981a5f40..4d4bfd142 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -92,6 +92,19 @@ def _memory_log_list_query(request: Request) -> tuple[str | None, int]:
return cursor, limit
+def _memory_log_unlinked_query(request: Request) -> int:
+ items = list(request.query_params.multi_items())
+ if any(key != "limit" for key, _value in items) or len(items) > 1:
+ raise ValueError("invalid unlinked memory log query")
+ raw_limit = items[0][1] if items else "20"
+ if not raw_limit.isascii() or not raw_limit.isdecimal():
+ raise ValueError("invalid unlinked memory log limit")
+ limit = int(raw_limit)
+ if not 1 <= limit <= 20:
+ raise ValueError("invalid unlinked memory log limit")
+ return limit
+
+
def _memory_log_entry_query(request: Request) -> str:
items = list(request.query_params.multi_items())
if len(items) != 1 or items[0][0] != "memcell_id":
@@ -1409,6 +1422,53 @@ def create_app(
content={"status": "failed", "error": "memory_processing_failed"},
)
+ @app.get("/internal/memory/log/unlinked")
+ async def _memory_log_unlinked(request: Request) -> Any:
+ try:
+ limit = _memory_log_unlinked_query(request)
+ access = _memory_log_access(request)
+ except ValueError:
+ return JSONResponse(
+ status_code=400,
+ content={"status": "failed", "error": "memory_invalid_input"},
+ )
+ except MemoryStoreUnavailableError:
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_store_unavailable"},
+ )
+ if access is None:
+ return JSONResponse(
+ status_code=403,
+ content={"status": "failed", "error": "memory_access_denied"},
+ )
+ runtime = _memory_runtime()
+ if runtime is None:
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_runtime_missing"},
+ )
+ try:
+ if access is memory_admin_log_access:
+ return await runtime.admin_log_unlinked_calls_payload(limit)
+ principal_id, project_id = access
+ return await runtime.log_unlinked_calls_payload(
+ principal_id,
+ project_id,
+ limit,
+ )
+ except ValueError:
+ return JSONResponse(
+ status_code=400,
+ content={"status": "failed", "error": "memory_invalid_input"},
+ )
+ except Exception:
+ logger.warning("internal unlinked memory log failed")
+ return JSONResponse(
+ status_code=503,
+ content={"status": "failed", "error": "memory_processing_failed"},
+ )
+
@app.get("/internal/memory/log/entry")
async def _memory_log_entry(request: Request) -> Any:
try:
diff --git a/core/memory/everos_insight/reader.py b/core/memory/everos_insight/reader.py
index e587b3289..328776bb7 100644
--- a/core/memory/everos_insight/reader.py
+++ b/core/memory/everos_insight/reader.py
@@ -199,6 +199,249 @@ class MemoryInsightReader:
for row in rows
)
+ def list_unlinked_calls(
+ self,
+ scope: MemoryReadScope,
+ limit: int,
+ ) -> dict[str, Any]:
+ principal_id, project_id = _validated_scope(scope)
+ return self._list_unlinked_calls(
+ query_filter=_ScopedMemcellFilter(
+ principal_id=principal_id,
+ project_id=project_id,
+ ),
+ limit=limit,
+ )
+
+ def list_admin_unlinked_calls(self, limit: int) -> dict[str, Any]:
+ return self._list_unlinked_calls(
+ query_filter=_ADMIN_MEMCELL_FILTER,
+ limit=limit,
+ )
+
+ def _list_unlinked_calls(
+ self,
+ *,
+ query_filter: _MemcellFilter,
+ limit: int,
+ ) -> dict[str, Any]:
+ if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 20:
+ raise ValueError("limit must be between 1 and 20")
+
+ everos_section = self._memcell_status()
+ capture_section = self._capture_status()
+ _, calls_section = self._read_call_counts(
+ [],
+ capture_available=False,
+ runs_available=False,
+ )
+ sections = _observed_sections(
+ {
+ "everos": everos_section,
+ "capture": capture_section,
+ "calls": calls_section,
+ },
+ observed_at=_utc_observed_at(),
+ )
+ if any(
+ section["status"] != "available"
+ for section in (everos_section, capture_section, calls_section)
+ ):
+ return {
+ "status": "ok",
+ "calls": [],
+ "truncated": False,
+ "sections": sections,
+ }
+
+ rows, query_section = self._read_unlinked_call_rows(
+ query_filter=query_filter,
+ limit=limit + 1,
+ )
+ if rows is None:
+ sections["calls"] = {
+ **query_section,
+ "observed_at": None,
+ }
+ return {
+ "status": "ok",
+ "calls": [],
+ "truncated": False,
+ "sections": sections,
+ }
+
+ projected: list[dict[str, Any]] = []
+ for row in rows:
+ row_scope = _unlinked_call_scope(row)
+ if row_scope is None:
+ continue
+ if (
+ isinstance(query_filter, _ScopedMemcellFilter)
+ and row_scope != (query_filter.principal_id, query_filter.project_id)
+ ):
+ continue
+ principal_id, project_id = row_scope
+ projected.append(
+ {
+ **_call_projection(
+ row,
+ base_urls=self._provider_base_urls,
+ exact_values=self._exact_redaction_values,
+ ),
+ "principal_id": principal_id,
+ "project_id": project_id,
+ }
+ )
+ return {
+ "status": "ok",
+ "calls": projected[:limit],
+ "truncated": len(projected) > limit,
+ "sections": sections,
+ }
+
+ def _read_unlinked_call_rows(
+ self,
+ *,
+ query_filter: _MemcellFilter,
+ limit: int,
+ ) -> tuple[list[sqlite3.Row] | None, dict[str, str]]:
+ if isinstance(query_filter, _ScopedMemcellFilter):
+ scope_sql = (
+ "request_scope.principal_id = :principal_id "
+ "AND request_scope.project_id = :project_id"
+ )
+ scope_args: dict[str, object] = {
+ "principal_id": query_filter.principal_id,
+ "project_id": query_filter.project_id,
+ }
+ elif isinstance(query_filter, _AdminMemcellFilter):
+ scope_sql = "1"
+ scope_args = {}
+ else:
+ raise TypeError("unsupported unlinked-call query filter")
+
+ try:
+ with _read_only(self._paths.call_log_db_path) as conn:
+ _attach_read_only(conn, self._paths.capture_db_path, "capture")
+ _attach_read_only(conn, self._paths.system_db_path, "everos_system")
+ _validate_provider_call_source(conn)
+ rows = list(
+ conn.execute(
+ f"""
+ WITH candidate_calls AS MATERIALIZED (
+ SELECT call.id, call.request_id
+ FROM provider_call AS call
+ INDEXED BY provider_call_request_id_idx
+ WHERE typeof(call.request_id) = 'text'
+ AND call.request_id != ''
+ AND call.memcell_id IS NULL
+ AND call.parent_type IS NOT 'memcell'
+ ),
+ candidate_requests AS MATERIALIZED (
+ SELECT DISTINCT request_id
+ FROM candidate_calls
+ ),
+ request_origins AS MATERIALIZED (
+ SELECT queue.add_request_id AS request_id,
+ queue.principal_id AS principal_id,
+ queue.project_ref AS project_id,
+ queue.session_id AS session_id,
+ queue.provider_timestamp_ms AS provider_timestamp_ms
+ FROM capture.memory_capture_queue AS queue
+ JOIN candidate_requests AS candidate
+ ON candidate.request_id = queue.add_request_id
+ WHERE typeof(queue.add_request_id) = 'text'
+ AND queue.add_request_id != ''
+ AND typeof(queue.principal_id) = 'text'
+ AND typeof(queue.project_ref) = 'text'
+
+ UNION
+
+ SELECT settlement.request_id AS request_id,
+ queue.principal_id AS principal_id,
+ queue.project_ref AS project_id,
+ queue.session_id AS session_id,
+ queue.provider_timestamp_ms AS provider_timestamp_ms
+ FROM capture.memory_flush_settlements AS settlement
+ JOIN candidate_requests AS candidate
+ ON candidate.request_id = settlement.request_id
+ JOIN capture.memory_capture_queue AS queue
+ ON queue.provider_session_ref = settlement.provider_session_ref
+ AND queue.epoch = settlement.epoch
+ AND queue.generation = settlement.generation
+ WHERE settlement.operation_kind = 'flush'
+ AND typeof(settlement.request_id) = 'text'
+ AND settlement.request_id != ''
+ AND typeof(queue.principal_id) = 'text'
+ AND typeof(queue.project_ref) = 'text'
+ ),
+ request_scopes AS MATERIALIZED (
+ SELECT request_id,
+ MIN(principal_id) AS principal_id,
+ MIN(project_id) AS project_id
+ FROM request_origins
+ GROUP BY request_id
+ HAVING MIN(principal_id) = MAX(principal_id)
+ AND MIN(project_id) = MAX(project_id)
+ ),
+ linked_requests AS MATERIALIZED (
+ SELECT DISTINCT origin.request_id
+ FROM request_origins AS origin
+ JOIN everos_system.memcell AS memcell
+ ON memcell.app_id = :app_id
+ AND memcell.project_id = origin.project_id
+ AND length(CAST(memcell.sender_ids_json AS BLOB))
+ <= {_MAX_MEMCELL_SENDER_IDS_JSON_BYTES}
+ AND length(CAST(memcell.message_ids_json AS BLOB))
+ <= {_MAX_MEMCELL_MESSAGE_IDS_JSON_BYTES}
+ AND CASE WHEN json_valid(memcell.sender_ids_json) THEN
+ json_type(memcell.sender_ids_json) = 'array'
+ AND json_array_length(memcell.sender_ids_json) = 1
+ AND json_type(memcell.sender_ids_json, '$[0]') = 'text'
+ AND json_extract(memcell.sender_ids_json, '$[0]') = origin.principal_id
+ ELSE 0 END
+ AND CASE WHEN json_valid(memcell.message_ids_json) THEN
+ EXISTS (
+ SELECT 1
+ FROM json_each(memcell.message_ids_json) AS message_id
+ WHERE message_id.type = 'text'
+ AND message_id.value =
+ 'm_' || origin.session_id || '_'
+ || CAST(origin.provider_timestamp_ms AS TEXT) || '_000'
+ )
+ ELSE 0 END
+ )
+ SELECT call.id, call.started_at_ms, call.duration_ms,
+ call.kind, call.stage, call.model, call.status,
+ call.error, call.finish_reason, call.prompt_tokens,
+ call.completion_tokens, call.request_json,
+ call.response_json, call.request_bytes,
+ call.response_bytes, call.dropped_before,
+ request_scope.principal_id, request_scope.project_id
+ FROM request_scopes AS request_scope
+ JOIN candidate_calls AS candidate_call
+ ON candidate_call.request_id = request_scope.request_id
+ JOIN provider_call AS call
+ ON call.id = candidate_call.id
+ WHERE NOT EXISTS (
+ SELECT 1 FROM linked_requests AS linked
+ WHERE linked.request_id = request_scope.request_id
+ )
+ AND {scope_sql}
+ ORDER BY call.started_at_ms DESC, call.id DESC
+ LIMIT :limit
+ """,
+ {
+ "app_id": _APP_ID,
+ "limit": limit,
+ **scope_args,
+ },
+ )
+ )
+ return rows, {"status": "available"}
+ except _Unavailable as unavailable:
+ return None, {"status": "unavailable", "reason": unavailable.reason}
+
def list_entries(
self,
scope: MemoryReadScope,
@@ -1420,6 +1663,19 @@ def _memcell_scope(row: sqlite3.Row) -> MemoryReadScope | None:
return senders[0], project_id
+def _unlinked_call_scope(row: sqlite3.Row) -> MemoryReadScope | None:
+ principal_id = row["principal_id"]
+ project_id = row["project_id"]
+ if (
+ not isinstance(principal_id, str)
+ or _PRINCIPAL_RE.fullmatch(principal_id) is None
+ or not isinstance(project_id, str)
+ or not is_persisted_memory_project_id(project_id)
+ ):
+ return None
+ return principal_id, project_id
+
+
def _timestamp_ms(value: object) -> int:
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
return value
diff --git a/core/memory/everos_insight/recorder.py b/core/memory/everos_insight/recorder.py
index d7b172743..a20521d56 100644
--- a/core/memory/everos_insight/recorder.py
+++ b/core/memory/everos_insight/recorder.py
@@ -573,6 +573,15 @@ def initialize_call_log(db_path: Path) -> None:
_initialize_schema(conn)
+def call_log_retention_policy() -> dict[str, int]:
+ """Return the product-visible bounds for retained provider-call evidence."""
+
+ return {
+ "max_age_ms": _RETENTION_AGE_MS,
+ "max_rows": _RETENTION_ROWS,
+ }
+
+
def record_preflight_call(
db_path: Path,
*,
diff --git a/core/memory/runtime.py b/core/memory/runtime.py
index e167396cc..bf9b9aa0e 100644
--- a/core/memory/runtime.py
+++ b/core/memory/runtime.py
@@ -46,7 +46,12 @@ from core.memory.everos import (
ProviderHealthSnapshot,
)
from core.memory.everos_insight import MemoryInsightPaths, MemoryInsightReader
-from core.memory.everos_insight.recorder import clear_call_log, maintain_call_log, record_preflight_call
+from core.memory.everos_insight.recorder import (
+ call_log_retention_policy,
+ clear_call_log,
+ maintain_call_log,
+ record_preflight_call,
+)
from core.memory.module import MemoryModule, MemorySessionLifecycleBusyError
from core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLease
from core.memory.maintenance import (
@@ -2113,6 +2118,41 @@ class MemoryRuntime:
warnings=unique_warnings,
)
+ async def log_unlinked_calls_payload(
+ self,
+ principal_id: str,
+ project_id: str,
+ limit: int,
+ ) -> dict[str, Any]:
+ reader = self._insight_reader
+ if not self.available or reader is None:
+ return {"status": "failed", "error": "memory_store_unavailable"}
+ payload = await self._run_insight_read(
+ lambda: reader.list_unlinked_calls((principal_id, project_id), limit)
+ )
+ return self._with_call_log_coverage(payload)
+
+ async def admin_log_unlinked_calls_payload(
+ self,
+ limit: int,
+ ) -> dict[str, Any]:
+ reader = self._insight_reader
+ if not self.available or reader is None:
+ return {"status": "failed", "error": "memory_store_unavailable"}
+ payload = await self._run_insight_read(
+ lambda: reader.list_admin_unlinked_calls(limit)
+ )
+ return self._with_call_log_coverage(payload)
+
+ def _with_call_log_coverage(self, payload: dict[str, Any]) -> dict[str, Any]:
+ if payload.get("status") != "ok":
+ return payload
+ return {
+ **payload,
+ "recorder": dict(self._recorder_health),
+ "retention": call_log_retention_policy(),
+ }
+
async def log_entries_payload(
self,
principal_id: str,
diff --git a/docs/plans/issue-1483-unlinked-provider-calls.md b/docs/plans/issue-1483-unlinked-provider-calls.md
new file mode 100644
index 000000000..8b6f9affb
--- /dev/null
+++ b/docs/plans/issue-1483-unlinked-provider-calls.md
@@ -0,0 +1,82 @@
+# Issue 1483: Provider Calls Without Memcells
+
+## Background
+
+The Memory Processing Record lists memcells and reaches provider-call details only
+through a selected `memcell_id`. A provider call recorded before a request is
+rejected or otherwise stops can therefore exist in the private call log without
+any product-visible path.
+
+## Goal
+
+Expose recent retained provider calls that are not attributable to a memcell in
+the Web Processing Record. Preserve principal/project isolation, the existing
+call projection's redaction and payload bounds, and an honest empty state when
+recording or retained evidence is incomplete.
+
+## Solution
+
+Add a bounded read-only endpoint:
+
+```text
+GET /api/memory/log/unlinked?limit=20
+```
+
+Successful payload:
+
+```json
+{
+ "status": "ok",
+ "calls": [
+ {
+ "id": "call-id",
+ "principal_id": "u-...",
+ "project_id": "default",
+ "started_at_ms": 1722816004000,
+ "duration_ms": 12,
+ "kind": "llm",
+ "stage": "boundary",
+ "model": "model",
+ "status": "error",
+ "error": null,
+ "finish_reason": null,
+ "prompt_tokens": null,
+ "completion_tokens": null,
+ "request": {},
+ "response": null,
+ "request_bytes": 2,
+ "response_bytes": null,
+ "dropped_before": 0
+ }
+ ],
+ "truncated": false,
+ "sections": {
+ "everos": {"status": "available", "observed_at": "..."},
+ "capture": {"status": "available", "observed_at": "..."},
+ "calls": {"status": "available", "observed_at": "..."}
+ },
+ "recorder": {"state": "active", "reason": null},
+ "retention": {"max_age_ms": 1209600000, "max_rows": 5000}
+}
+```
+
+The reader resolves call scope only from an unambiguous `request_id` linkage to
+capture queue or settlement evidence. It excludes request IDs attributable to a
+valid singleton-owner memcell. Malformed scope, cross-scope request-ID
+collisions, or missing attribution are omitted fail-closed.
+
+The Web UI renders the calls with the existing provider-call component and
+shows their principal/project scope. The empty state names unavailable or
+degraded recording and always states the bounded retention policy, so absence
+of retained rows is not presented as proof that no provider call occurred.
+
+No call-log schema or retention behavior changes.
+
+## Todo
+
+- [x] Add scoped and admin reader projections with fixed result bounds.
+- [x] Add runtime, internal socket, UI server, and frontend API contracts.
+- [x] Add the Processing Record UI and English/Chinese copy.
+- [x] Cover unlinked calls, scope isolation, recorder unavailability, redaction,
+ payload bounds, and route validation.
+- [x] Run focused Python/UI tests, Ruff, and the production UI build.
diff --git a/docs/regression/memory-im-attachment-five-platform-acceptance.md b/docs/regression/memory-im-attachment-five-platform-acceptance.md
index d5335ea9c..cf959e4fe 100644
--- a/docs/regression/memory-im-attachment-five-platform-acceptance.md
+++ b/docs/regression/memory-im-attachment-five-platform-acceptance.md
@@ -147,13 +147,15 @@ selected input text and attachment kind/name
(`core/memory/everos_insight/reader.py::_memcell_preview`), not
attachment-derived model output, and therefore are not positive evidence.
-For a rejected SVG, use only the post-baseline processing entries visible in the
-UI. A caption-bearing rejected turn must preserve its caption without showing the
-SVG filename as an attachment in the entry preview. The hermetic
-`MEMORY-IM-ATTACH-010` scenario separately proves that a fully rejected
-caption-bearing attachment does not enter the multimodal provider path; the
-manual run does not try to reconstruct that engineering fact from an
-unobservable UI absence.
+For a rejected SVG, use only the post-baseline Processing Record evidence visible
+in the UI. A caption-bearing rejected turn must preserve its caption without
+showing the SVG filename as an attachment in the entry preview. Also inspect
+**Calls without Memory entries** for the tagged principal/project: a retained
+multimodal call attributable to that rejected turn is a product-visible failure.
+The hermetic `MEMORY-IM-ATTACH-010` scenario remains the positive proof that a
+fully rejected caption-bearing attachment does not enter the multimodal provider
+path. An empty retained-call list is not proof by itself because the view is
+bounded by the displayed recorder health and retention policy.
| Platform | Scenario | Send | Pass condition in Memory > Processing Record |
| --- | --- | --- | --- |
@@ -177,9 +179,11 @@ not **Recording normally**, its Model calls are unavailable/expired, or the
Request/Response evidence cannot be opened. Any row is `INCONCLUSIVE` when the
Processing Record section needed by its pass condition is unavailable. Rejected
rows do not use absence of Model calls as evidence; only the visible
-post-baseline entry conditions in the table decide them. A terminal outcome that
-is present but violates its row is `FAIL`; the 30-minute stop threshold applies
-only when required evidence never becomes observable.
+post-baseline entry conditions in the table and any positively attributed call
+without a Memory entry decide them. A retained multimodal call for the rejected
+turn is `FAIL`; an empty retained-call list is not `PASS` evidence. A terminal
+outcome that is present but violates its row is `FAIL`; the 30-minute stop
+threshold applies only when required evidence never becomes observable.
Before recording `PASS`, state the visible counterfactual: broken accepted-image
processing yields an available terminal call whose response lacks the complete
@@ -287,9 +291,11 @@ Decision:
validating Agent attachment behavior. This run covers Memory capture only.
- Provisioning Telegram or any other platform credentials. A separately
provisioned five-platform target is a precondition, not an acceptance step.
-- Proving the absence of pre-memcell provider calls through the product UI. The
- `MEMORY-IM-ATTACH-010` automated scenario owns the rejection-to-provider
- boundary; issue #1483 tracks product visibility for calls without memcells.
+- Proving absolute absence of pre-memcell provider calls. Processing Record can
+ now expose retained calls without Memory entries and can positively falsify
+ the boundary, but its explicit recorder health and retention bounds mean an
+ empty view is not proof that no call occurred. The `MEMORY-IM-ATTACH-010`
+ automated scenario remains the authoritative rejection-to-provider proof.
- Manually testing captionless, fully filtered Lark or WeChat file-only turns.
`CaptureAdmission.decide()` returns `CaptureSkipped(memory_invalid_input)` when
both text and selected attachments are empty (`core/memory/admission.py`),
@@ -307,9 +313,6 @@ Decision:
- [#1480](https://github.com/avibe-bot/avibe/issues/1480) investigates why an
explicit `vibe watch add --timeout 0` can read back as the default `21600`
despite the repository reader preserving zero.
-- [#1483](https://github.com/avibe-bot/avibe/issues/1483) tracks the missing
- Processing Record surface for provider calls and terminal turns that have no
- memcell.
## Result record
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index de539a883..1b066aa3c 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -929,6 +929,11 @@ def test_memory_log_helpers_forward_structured_query_and_sign_owner(monkeypatch,
user_key="avibe:remote:user-1",
socket_path=socket_path,
)
+ await internal_client.memory_log_unlinked(
+ limit=20,
+ user_key="avibe:remote:user-1",
+ socket_path=socket_path,
+ )
await internal_client.memory_log_entry(
"mc_1",
user_key="avibe:remote:user-1",
@@ -939,6 +944,7 @@ def test_memory_log_helpers_forward_structured_query_and_sign_owner(monkeypatch,
assert [(request.url.path, dict(request.url.params)) for request in captured] == [
("/internal/memory/log", {"cursor": "opaque_cursor", "limit": "17"}),
+ ("/internal/memory/log/unlinked", {"limit": "20"}),
("/internal/memory/log/entry", {"memcell_id": "mc_1"}),
]
for request in captured:
diff --git a/tests/test_memory_insight.py b/tests/test_memory_insight.py
index 0d0ea0d3a..2d26f7985 100644
--- a/tests/test_memory_insight.py
+++ b/tests/test_memory_insight.py
@@ -338,6 +338,296 @@ def _insert_call(paths: MemoryInsightPaths, call_id: str, **values: object) -> N
)
+def test_rejected_pre_memcell_call_is_scope_authorized_and_linked_calls_are_excluded(
+ insight_paths: MemoryInsightPaths,
+) -> None:
+ _insert_queue(
+ insight_paths,
+ "alice-unlinked",
+ ALICE,
+ session="alice-unlinked",
+ timestamp_ms=4_000,
+ add_request_id="request-alice-unlinked",
+ )
+ _insert_call(
+ insight_paths,
+ "call-alice-unlinked",
+ request_id="request-alice-unlinked",
+ stage="boundary",
+ status="error",
+ started_at_ms=5_000,
+ )
+ with sqlite3.connect(insight_paths.capture_db_path) as conn:
+ conn.execute(
+ "UPDATE memory_capture_queue SET state = 'dead', "
+ "last_error = 'memory_provider_response_invalid' "
+ "WHERE add_request_id = 'request-alice-unlinked'"
+ )
+ _insert_queue(
+ insight_paths,
+ "bob-unlinked",
+ BOB,
+ session="bob-unlinked",
+ timestamp_ms=3_000,
+ add_request_id="request-bob-unlinked",
+ )
+ _insert_call(
+ insight_paths,
+ "call-bob-unlinked",
+ request_id="request-bob-unlinked",
+ stage="boundary",
+ started_at_ms=4_000,
+ )
+ _insert_queue(
+ insight_paths,
+ "alice-linked",
+ ALICE,
+ session="alice-linked",
+ timestamp_ms=2_000,
+ add_request_id="request-alice-linked",
+ )
+ _insert_memcell(
+ insight_paths,
+ "mc_alice_linked",
+ ALICE,
+ timestamp_ms=2_100,
+ message_ids=["m_alice-linked_2000_000"],
+ )
+ _insert_call(
+ insight_paths,
+ "call-alice-linked",
+ request_id="request-alice-linked",
+ stage="boundary",
+ )
+
+ reader = MemoryInsightReader(insight_paths)
+ alice = reader.list_unlinked_calls((ALICE, PROJECT), 20)
+ bob = reader.list_unlinked_calls((BOB, PROJECT), 20)
+ admin = reader.list_admin_unlinked_calls(20)
+
+ assert [(call["id"], call["principal_id"], call["project_id"]) for call in alice["calls"]] == [
+ ("call-alice-unlinked", ALICE, PROJECT)
+ ]
+ assert [call["id"] for call in bob["calls"]] == ["call-bob-unlinked"]
+ assert [call["id"] for call in admin["calls"]] == [
+ "call-alice-unlinked",
+ "call-bob-unlinked",
+ ]
+ assert alice["truncated"] is False
+ assert alice["sections"]["calls"]["status"] == "available"
+
+
+def test_unlinked_call_join_is_bounded_before_scanning_retained_history(
+ insight_paths: MemoryInsightPaths,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _insert_queue(
+ insight_paths,
+ "candidate",
+ ALICE,
+ session="candidate",
+ timestamp_ms=5_000,
+ add_request_id="candidate-request",
+ )
+ _insert_call(
+ insight_paths,
+ "candidate-call",
+ request_id="candidate-request",
+ started_at_ms=6_000,
+ )
+
+ history_size = 300
+ with sqlite3.connect(insight_paths.capture_db_path) as conn:
+ conn.executemany(
+ """
+ INSERT INTO memory_capture_queue (
+ source_message_digest, epoch, session_id, provider_session_ref,
+ generation, principal_id, project_ref, provenance, occurred_at_ms,
+ provider_timestamp_ms, state, attempts, add_request_id, add_status,
+ created_at, completed_at
+ ) VALUES (?, 1, ?, ?, 1, ?, ?, 'user_input', ?, ?, 'delivered', 1,
+ ?, 'accumulated', ?, ?)
+ """,
+ [
+ (
+ f"history-{index}",
+ f"history-{index}",
+ ProviderSessionRef(
+ principal_id=ALICE,
+ epoch=1,
+ project_ref=PROJECT,
+ session_id=f"provider-history-{index}",
+ ).serialize(),
+ ALICE,
+ PROJECT,
+ index,
+ index,
+ f"history-request-{index}",
+ "2026-08-04T00:00:00Z",
+ "2026-08-04T00:00:01Z",
+ )
+ for index in range(history_size)
+ ],
+ )
+ with sqlite3.connect(insight_paths.system_db_path) as conn:
+ conn.executemany(
+ "INSERT INTO memcell VALUES (?, 'avibe', ?, 'session', 'user', "
+ "'message', '[]', ?, '{}', ?)",
+ [
+ (
+ f"mc_history_{index}",
+ PROJECT,
+ _json([ALICE]),
+ "2026-08-04T00:00:00+00:00",
+ )
+ for index in range(history_size)
+ ],
+ )
+
+ original_connect = sqlite3.connect
+ progress_counts: list[list[int]] = []
+
+ def bounded_connect(*args, **kwargs):
+ connection = original_connect(*args, **kwargs)
+ database = str(args[0]) if args else str(kwargs.get("database", ""))
+ if database.startswith(insight_paths.call_log_db_path.absolute().as_uri()):
+ progress_count = [0]
+ progress_counts.append(progress_count)
+
+ def stop_expensive_query() -> int:
+ progress_count[0] += 1
+ return int(progress_count[0] > 100)
+
+ connection.set_progress_handler(stop_expensive_query, 1_000)
+ return connection
+
+ monkeypatch.setattr(sqlite3, "connect", bounded_connect)
+
+ result = MemoryInsightReader(insight_paths).list_unlinked_calls(
+ (ALICE, PROJECT),
+ 20,
+ )
+
+ assert [call["id"] for call in result["calls"]] == ["candidate-call"]
+ assert result["sections"]["calls"]["status"] == "available"
+ assert progress_counts[-1][0] <= 100
+
+
+def test_unlinked_calls_fail_closed_for_cross_scope_request_id_collisions(
+ insight_paths: MemoryInsightPaths,
+) -> None:
+ for owner, session in ((ALICE, "alice-collision"), (BOB, "bob-collision")):
+ _insert_queue(
+ insight_paths,
+ session,
+ owner,
+ session=session,
+ timestamp_ms=2_000,
+ add_request_id="shared-request",
+ )
+ _insert_call(insight_paths, "call-collision", request_id="shared-request")
+
+ reader = MemoryInsightReader(insight_paths)
+
+ assert reader.list_unlinked_calls((ALICE, PROJECT), 20)["calls"] == []
+ assert reader.list_unlinked_calls((BOB, PROJECT), 20)["calls"] == []
+ assert reader.list_admin_unlinked_calls(20)["calls"] == []
+
+
+def test_unlinked_calls_keep_existing_projection_redaction_and_bounds(
+ insight_paths: MemoryInsightPaths,
+) -> None:
+ _insert_queue(
+ insight_paths,
+ "bounded-unlinked",
+ ALICE,
+ session="bounded-unlinked",
+ timestamp_ms=2_000,
+ add_request_id="request-bounded-unlinked",
+ )
+ secret = "secret-value"
+ huge = "x" * 20_000
+ _insert_call(
+ insight_paths,
+ "call-bounded-unlinked",
+ request_id="request-bounded-unlinked",
+ request_json=_json({"authorization": secret, "prompt": huge}),
+ response_json=_json({"answer": huge}),
+ request_bytes=len(huge),
+ response_bytes=len(huge),
+ )
+
+ result = MemoryInsightReader(
+ insight_paths,
+ exact_redaction_values=(secret,),
+ ).list_unlinked_calls((ALICE, PROJECT), 20)
+
+ call = result["calls"][0]
+ encoded = json.dumps(call, ensure_ascii=False, separators=(",", ":"))
+ assert secret not in encoded
+ assert "[REDACTED]" in encoded
+ assert set(call["request"]) == {"excerpt", "omitted_bytes"}
+ assert set(call["response"]) == {"excerpt", "omitted_bytes"}
+ assert len(_json(call["request"]).encode()) <= 12_000
+ assert len(_json(call["response"]).encode()) <= 12_000
+
+
+def test_unlinked_calls_are_bounded_and_report_truncation(
+ insight_paths: MemoryInsightPaths,
+) -> None:
+ _insert_queue(
+ insight_paths,
+ "many-unlinked",
+ ALICE,
+ session="many-unlinked",
+ timestamp_ms=2_000,
+ add_request_id="request-many-unlinked",
+ )
+ huge = "x" * 20_000
+ for index in range(21):
+ _insert_call(
+ insight_paths,
+ f"call-many-{index:02d}",
+ request_id="request-many-unlinked",
+ started_at_ms=10_000 + index,
+ request_json=_json({"prompt": huge}),
+ response_json=_json({"answer": huge}),
+ request_bytes=len(huge),
+ response_bytes=len(huge),
+ )
+
+ result = MemoryInsightReader(insight_paths).list_unlinked_calls(
+ (ALICE, PROJECT),
+ 20,
+ )
+
+ assert len(result["calls"]) == 20
+ assert result["truncated"] is True
+ assert result["calls"][0]["id"] == "call-many-20"
+ assert len(json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode()) <= 1_000_000
+
+
+def test_unlinked_calls_report_unavailable_call_log_source(
+ insight_paths: MemoryInsightPaths,
+) -> None:
+ insight_paths.call_log_db_path.unlink()
+
+ result = MemoryInsightReader(insight_paths).list_unlinked_calls(
+ (ALICE, PROJECT),
+ 20,
+ )
+
+ assert result["calls"] == []
+ assert result["truncated"] is False
+ assert result["sections"]["everos"]["status"] == "available"
+ assert result["sections"]["capture"]["status"] == "available"
+ assert result["sections"]["calls"] == {
+ "status": "unavailable",
+ "reason": "missing",
+ "observed_at": None,
+ }
+
+
def test_installation_preflight_calls_exclude_conversation_linked_rows(
insight_paths: MemoryInsightPaths,
) -> None:
diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.py
index 1519444c5..9cf6c0ed3 100644
--- a/tests/test_memory_runtime.py
+++ b/tests/test_memory_runtime.py
@@ -5925,6 +5925,52 @@ async def test_cancelled_insight_read_keeps_lifecycle_lock_until_thread_finishes
await memory_runtime_factory.close(runtime)
+def test_runtime_forwards_unlinked_calls_with_recorder_coverage(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ principal_id = "u-11111111111111111111111111111111"
+ calls: list[tuple[object, ...]] = []
+
+ class Reader:
+ def list_unlinked_calls(self, scope, limit):
+ calls.append(("scoped", scope, limit))
+ return {"status": "ok", "calls": [], "truncated": False, "sections": {}}
+
+ def list_admin_unlinked_calls(self, limit):
+ calls.append(("admin", limit))
+ return {"status": "ok", "calls": [], "truncated": False, "sections": {}}
+
+ runtime = MemoryRuntime(
+ MemoryConfig(),
+ store=MemoryStore(tmp_path / "state" / "memory" / "memory.sqlite"),
+ effective_home=tmp_path,
+ insight_reader=Reader(),
+ )
+ runtime._recorder_health = {
+ "state": "degraded",
+ "reason": "writer_failures",
+ }
+
+ scoped = asyncio.run(runtime.log_unlinked_calls_payload(principal_id, PROJECT, 7))
+ admin = asyncio.run(runtime.admin_log_unlinked_calls_payload(9))
+
+ for payload in (scoped, admin):
+ assert payload["recorder"] == {
+ "state": "degraded",
+ "reason": "writer_failures",
+ }
+ assert payload["retention"] == {
+ "max_age_ms": 14 * 24 * 60 * 60 * 1000,
+ "max_rows": 5_000,
+ }
+ assert calls == [
+ ("scoped", (principal_id, PROJECT), 7),
+ ("admin", 9),
+ ]
+
+
def test_runtime_forwards_scoped_insight_detail(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.py
index 3fba4ca07..6c1c85480 100644
--- a/tests/test_ui_memory_routes.py
+++ b/tests/test_ui_memory_routes.py
@@ -1479,6 +1479,13 @@ def test_memory_log_routes_forward_only_valid_query_and_are_no_store(monkeypatch
"body": {"status": "ok", "entries": [], "next_cursor": None},
}
+ async def memory_log_unlinked(*, limit: int, user_key: str):
+ calls.append(("unlinked", limit, user_key))
+ return {
+ "status_code": 200,
+ "body": {"status": "ok", "calls": [], "truncated": False},
+ }
+
async def memory_log_entry(memcell_id: str, *, user_key: str):
calls.append(("detail", memcell_id, user_key))
return {
@@ -1487,6 +1494,7 @@ def test_memory_log_routes_forward_only_valid_query_and_are_no_store(monkeypatch
}
monkeypatch.setattr(internal_client, "memory_log", memory_log)
+ monkeypatch.setattr(internal_client, "memory_log_unlinked", memory_log_unlinked)
monkeypatch.setattr(internal_client, "memory_log_entry", memory_log_entry)
client = app.test_client()
request_options = {
@@ -1496,19 +1504,24 @@ def test_memory_log_routes_forward_only_valid_query_and_are_no_store(monkeypatch
}
listed = client.get("/api/memory/log?cursor=opaque_cursor&limit=17", **request_options)
+ unlinked = client.get("/api/memory/log/unlinked?limit=20", **request_options)
detail = client.get("/api/memory/log/entry?memcell_id=mc_1", **request_options)
duplicate = client.get("/api/memory/log?limit=1&limit=2", **request_options)
+ invalid_unlinked = client.get("/api/memory/log/unlinked?limit=21", **request_options)
invalid_id = client.get("/api/memory/log/entry?memcell_id=../secret", **request_options)
assert listed.status_code == 200
+ assert unlinked.status_code == 200
assert detail.status_code == 200
assert listed.headers["cache-control"] == "no-store"
+ assert unlinked.headers["cache-control"] == "no-store"
assert detail.headers["cache-control"] == "no-store"
assert calls == [
("list", "opaque_cursor", 17, "avibe:local"),
+ ("unlinked", 20, "avibe:local"),
("detail", "mc_1", "avibe:local"),
]
- for response in (duplicate, invalid_id):
+ for response in (duplicate, invalid_unlinked, invalid_id):
assert response.status_code == 400
assert response.get_json() == {"status": "failed", "error": "memory_invalid_input"}
diff --git a/ui/src/components/settings/memory/MemoryLogPanel.test.tsx b/ui/src/components/settings/memory/MemoryLogPanel.test.tsx
index 398d402a5..c81b4a46a 100644
--- a/ui/src/components/settings/memory/MemoryLogPanel.test.tsx
+++ b/ui/src/components/settings/memory/MemoryLogPanel.test.tsx
@@ -1,7 +1,7 @@
/* @vitest-environment jsdom */
import { useState } from 'react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderToStaticMarkup } from 'react-dom/server';
@@ -10,6 +10,7 @@ import type {
MemoryLogDetailResult,
MemoryLogEntry,
MemoryLogListResult,
+ MemoryUnlinkedCallListResult,
} from '../../../context/ApiContext';
import {
MemoryLogListContent,
@@ -24,6 +25,7 @@ import {
const api = vi.hoisted(() => ({
getMemoryLog: vi.fn(),
+ getMemoryLogUnlinked: vi.fn(),
getMemoryLogEntry: vi.fn(),
}));
const translate = vi.hoisted(() => (key: string, values?: { count?: number }) =>
@@ -43,6 +45,22 @@ vi.mock('../../ui/preview-json', () => ({
default: ({ value }: { value: object }) => <pre data-testid="json-tree">{JSON.stringify(value)}</pre>,
}));
+const unlinkedResult = (
+ calls: Extract<MemoryUnlinkedCallListResult, { status: 'ok' }>['calls'] = [],
+ recorder: { state: string; reason: string | null } = { state: 'active', reason: null },
+): MemoryUnlinkedCallListResult => ({
+ status: 'ok',
+ calls,
+ truncated: false,
+ sections,
+ recorder,
+ retention: { max_age_ms: 14 * 24 * 60 * 60 * 1000, max_rows: 5_000 },
+});
+
+beforeEach(() => {
+ api.getMemoryLogUnlinked.mockResolvedValue(unlinkedResult());
+});
+
afterEach(() => {
cleanup();
vi.clearAllMocks();
@@ -132,6 +150,43 @@ const renderPanel = (props?: Partial<React.ComponentProps<typeof MemoryLogPanel>
);
describe('MemoryLogPanel', () => {
+ it('shows retained provider calls that have no Memory entry under their exact scope', async () => {
+ api.getMemoryLog.mockResolvedValue(listResult([]));
+ api.getMemoryLogUnlinked.mockResolvedValue(unlinkedResult([
+ {
+ ...detailResult().calls[0],
+ id: 'call-unlinked',
+ principal_id: 'u-22222222222222222222222222222222',
+ project_id: 'billing',
+ },
+ ]));
+ const user = userEvent.setup();
+
+ renderPanel();
+
+ expect(await screen.findByText('memory.log.unlinkedTitle')).toBeTruthy();
+ expect(screen.getByText('u-22222222222222222222222222222222')).toBeTruthy();
+ expect(screen.getByText('billing')).toBeTruthy();
+ const callToggle = screen.getByRole('button', { expanded: false });
+ await user.click(callToggle);
+ expect(await screen.findByText(/hello/)).toBeTruthy();
+ expect(screen.getByText(/world/)).toBeTruthy();
+ });
+
+ it('marks an empty unlinked-call list as incomplete when recording is unavailable', async () => {
+ api.getMemoryLog.mockResolvedValue(listResult([]));
+ api.getMemoryLogUnlinked.mockResolvedValue(unlinkedResult(
+ [],
+ { state: 'disabled', reason: null },
+ ));
+
+ renderPanel();
+
+ expect(await screen.findByText('memory.log.unlinkedRecorderIncomplete')).toBeTruthy();
+ expect(screen.getByText('memory.log.unlinkedRetention')).toBeTruthy();
+ expect(screen.getByText('memory.log.unlinkedEmpty')).toBeTruthy();
+ });
+
it.each([
['dead_letter', 'deadLetter'],
['crashed', 'crashed'],
@@ -271,6 +326,7 @@ describe('MemoryLogPanel', () => {
expect(await screen.findByText('Refreshed')).toBeTruthy();
await waitFor(() => expect(screen.queryByText('Initial')).toBeNull());
expect(api.getMemoryLog).toHaveBeenCalledTimes(2);
+ expect(api.getMemoryLogUnlinked).toHaveBeenCalledTimes(2);
});
it('reloads the selected detail when the merged view refresh token changes', async () => {
diff --git a/ui/src/components/settings/memory/MemoryLogPanel.tsx b/ui/src/components/settings/memory/MemoryLogPanel.tsx
index 3e50073f7..d5b55c322 100644
--- a/ui/src/components/settings/memory/MemoryLogPanel.tsx
+++ b/ui/src/components/settings/memory/MemoryLogPanel.tsx
@@ -24,6 +24,7 @@ import type {
MemoryLogSourceStatus,
MemoryLogStep,
MemoryProviderCall,
+ MemoryUnlinkedCallListResult,
} from '../../../context/ApiContext';
import {
MEMORY_LOG_ENTRY_LIMIT,
@@ -31,12 +32,14 @@ import {
memoryLogEnumLabel,
prepareJsonPreview,
} from './memoryLog';
+import { formatMemoryStatusRuntimeFact } from './memoryStatusPresentation';
import { useMemoryResource } from './useMemoryResource';
const PreviewJson = React.lazy(() => import('../../ui/preview-json'));
type MemoryLogListOk = Extract<MemoryLogListResult, { status: 'ok' }>;
type MemoryLogDetailOk = Extract<MemoryLogDetailResult, { status: 'ok' }>;
+type MemoryUnlinkedCallListOk = Extract<MemoryUnlinkedCallListResult, { status: 'ok' }>;
type MemoryLogPage = MemoryLogListOk & { requested_cursor: string | null };
type MemoryLogListState = {
@@ -223,6 +226,94 @@ export const MemoryLogListContent: React.FC<{
);
};
+export const UnlinkedProviderCallsContent: React.FC<{
+ result: MemoryUnlinkedCallListOk | null;
+ loading: boolean;
+ loaded: boolean;
+ error: string | null;
+ forbidden: boolean;
+}> = ({ result, loading, loaded, error, forbidden }) => {
+ const { t } = useTranslation();
+ const retentionDays = result
+ ? Math.max(1, Math.floor(result.retention.max_age_ms / (24 * 60 * 60 * 1000)))
+ : null;
+ const recorderIncomplete = result?.recorder.state !== 'active';
+ const recorderState = result
+ ? formatMemoryStatusRuntimeFact(t, 'recorder', 'state', result.recorder.state)
+ : null;
+ const recorderReason = result?.recorder.reason
+ ? formatMemoryStatusRuntimeFact(t, 'recorder', 'reason', result.recorder.reason)
+ : null;
+
+ return (
+ <section className="flex flex-col gap-2" aria-labelledby="memory-unlinked-calls-title">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h4 id="memory-unlinked-calls-title" className="text-[12.5px] font-semibold text-foreground">
+ {t('memory.log.unlinkedTitle')}
+ </h4>
+ {result ? <Badge variant="secondary">{t('memory.log.providerCalls', { count: result.calls.length })}</Badge> : null}
+ </div>
+ {forbidden ? (
+ <div className="rounded-md border border-border bg-surface px-4 py-3 text-[12px] text-muted">
+ {t('memory.log.forbidden')}
+ </div>
+ ) : !loaded && !result ? (
+ <div className="flex items-center gap-2 px-1 py-3 text-[12px] text-muted">
+ <Loader2 className="size-3.5 animate-spin" />
+ {t('memory.log.unlinkedLoading')}
+ </div>
+ ) : (
+ <>
+ {error ? (
+ <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[12px] text-destructive-ink">
+ {error}
+ </div>
+ ) : null}
+ {result ? <SectionNotices sections={result.sections} /> : null}
+ {result && recorderIncomplete ? (
+ <div className="rounded-md border border-gold/30 bg-gold/[0.06] px-3 py-2 text-[11.5px] text-muted" role="status">
+ {recorderReason
+ ? t('memory.log.unlinkedRecorderIncompleteWithReason', { state: recorderState, reason: recorderReason })
+ : t('memory.log.unlinkedRecorderIncomplete', { state: recorderState })}
+ </div>
+ ) : null}
+ {result ? (
+ <div className="text-[11px] text-muted" role="note">
+ {t('memory.log.unlinkedRetention', {
+ days: retentionDays,
+ maxRows: result.retention.max_rows,
+ })}
+ </div>
+ ) : null}
+ {result?.calls.length ? (
+ <div className="flex flex-col gap-3">
+ {result.calls.map((call) => (
+ <div key={call.id} className="flex min-w-0 flex-col gap-1.5">
+ <MemoryLogScope project_id={call.project_id} principal_id={call.principal_id} />
+ <ProviderCallRow call={call} />
+ </div>
+ ))}
+ </div>
+ ) : result && !error ? (
+ <div className="rounded-md border border-dashed border-border bg-surface px-4 py-4 text-center text-[12px] text-muted">
+ {t('memory.log.unlinkedEmpty')}
+ </div>
+ ) : null}
+ {result?.truncated ? (
+ <div className="text-[11px] text-muted" role="status">{t('memory.log.unlinkedTruncated')}</div>
+ ) : null}
+ {loading && result ? (
+ <div className="flex items-center gap-1.5 text-[11px] text-muted">
+ <Loader2 className="size-3 animate-spin" />
+ {t('memory.log.unlinkedLoading')}
+ </div>
+ ) : null}
+ </>
+ )}
+ </section>
+ );
+};
+
const StepRow: React.FC<{ step: MemoryLogStep }> = ({ step }) => {
const { t } = useTranslation();
const timestamp = step.started_at_ms ?? step.timestamp_ms;
@@ -415,6 +506,12 @@ export const MemoryLogPanel: React.FC<{
failureMessageKey: 'memory.log.loadFailed',
clearErrorOnReload: true,
});
+ const readUnlinked = useCallback(() => api.getMemoryLogUnlinked(20), [api]);
+ const unlinkedRead = useMemoryResource<MemoryUnlinkedCallListOk>({
+ read: readUnlinked,
+ failureMessageKey: 'memory.log.unlinkedLoadFailed',
+ clearErrorOnReload: true,
+ });
const readDetail = useCallback((memcellId: string) => api.getMemoryLogEntry(memcellId), [api]);
const detailRead = useMemoryResource<MemoryLogDetailOk, [string]>({
read: readDetail,
@@ -424,10 +521,12 @@ export const MemoryLogPanel: React.FC<{
});
const { data: listPage, reload: reloadList } = listRead;
+ const { reload: reloadUnlinked } = unlinkedRead;
const { reload: reloadDetail } = detailRead;
useEffect(() => {
void reloadList(null);
- }, [refreshToken, reloadList]);
+ void reloadUnlinked();
+ }, [refreshToken, reloadList, reloadUnlinked]);
useEffect(() => {
if (selected) void reloadDetail(selected);
}, [refreshToken, reloadDetail, selected]);
@@ -468,21 +567,35 @@ export const MemoryLogPanel: React.FC<{
<MemoryLogDetail detail={selectedDetail} onBack={() => setSelected(null)} />
)
) : (
- <MemoryLogListContent
- entries={entries}
- sections={sections}
- loading={listRead.loading}
- loaded={listRead.loaded}
- error={listRead.error}
- forbidden={listRead.forbidden}
- nextCursor={nextCursor}
- limitReached={entries.length >= MEMORY_LOG_ENTRY_LIMIT && nextCursor !== null}
- onOpen={openDetail}
- onRefresh={() => void listRead.reload(null)}
- onLoadMore={() => {
- if (nextCursor && entries.length < MEMORY_LOG_ENTRY_LIMIT) void listRead.reload(nextCursor);
- }}
- />
+ <>
+ <UnlinkedProviderCallsContent
+ result={unlinkedRead.data}
+ loading={unlinkedRead.loading}
+ loaded={unlinkedRead.loaded}
+ error={unlinkedRead.error}
+ forbidden={unlinkedRead.forbidden}
+ />
+ <div className="border-t border-border pt-3">
+ <MemoryLogListContent
+ entries={entries}
+ sections={sections}
+ loading={listRead.loading || unlinkedRead.loading}
+ loaded={listRead.loaded}
+ error={listRead.error}
+ forbidden={listRead.forbidden}
+ nextCursor={nextCursor}
+ limitReached={entries.length >= MEMORY_LOG_ENTRY_LIMIT && nextCursor !== null}
+ onOpen={openDetail}
+ onRefresh={() => {
+ void listRead.reload(null);
+ void unlinkedRead.reload();
+ }}
+ onLoadMore={() => {
+ if (nextCursor && entries.length < MEMORY_LOG_ENTRY_LIMIT) void listRead.reload(nextCursor);
+ }}
+ />
+ </div>
+ </>
)}
</div>
);
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 8eb7bcce1..e8b9c7e81 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -574,6 +574,7 @@ export type ApiContextType = {
) => Promise<MemoryListResult>;
listMemoryProjects: () => Promise<{ status: 'ok'; projects: Array<{ id: string; kind: 'default' | 'named' | 'all' }> } | { status: 'failed'; error?: string }>;
getMemoryLog: (cursor?: string | null, limit?: number) => Promise<MemoryLogListResult>;
+ getMemoryLogUnlinked: (limit?: number) => Promise<MemoryUnlinkedCallListResult>;
getMemoryLogEntry: (memcellId: string) => Promise<MemoryLogDetailResult>;
clearMemory: () => Promise<MemoryClearResult>;
factoryResetMemory: () => Promise<MemoryFactoryResetResult>;
@@ -2141,6 +2142,22 @@ export type MemoryProviderCall = {
dropped_before: number;
};
+export type MemoryUnlinkedProviderCall = MemoryProviderCall & {
+ principal_id: string;
+ project_id: string;
+};
+
+export type MemoryUnlinkedCallListResult =
+ | {
+ status: 'ok';
+ calls: MemoryUnlinkedProviderCall[];
+ truncated: boolean;
+ sections: MemoryLogSections;
+ recorder: { state: string; reason: string | null };
+ retention: { max_age_ms: number; max_rows: number };
+ }
+ | MemoryFailure;
+
export type MemoryLogCurrentState =
| {
status: 'available';
@@ -3421,6 +3438,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (cursor) query.set('cursor', cursor);
return getJson(`/api/memory/log?${query.toString()}`, { handleError: false });
},
+ getMemoryLogUnlinked: (limit = 20) =>
+ getJson(`/api/memory/log/unlinked?limit=${encodeURIComponent(String(limit))}`, { handleError: false }),
getMemoryLogEntry: (memcellId) =>
getJson(`/api/memory/log/entry?memcell_id=${encodeURIComponent(memcellId)}`, { handleError: false }),
clearMemory: () => postJson('/api/memory/clear', { confirm: true }, { handleError: false }),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 4b04ab976..fa624e015 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4377,6 +4377,14 @@
"forbidden": "This processing log isn't available on the current connection.",
"disabledHint": "Enable Memory to view its processing log.",
"empty": "No processed Memory entries yet.",
+ "unlinkedTitle": "Calls without Memory entries",
+ "unlinkedLoading": "Loading retained calls…",
+ "unlinkedLoadFailed": "Couldn't load calls without Memory entries.",
+ "unlinkedEmpty": "No retained calls without a Memory entry were found.",
+ "unlinkedRecorderIncomplete": "Call recording is {{state}}. This list may be incomplete.",
+ "unlinkedRecorderIncompleteWithReason": "Call recording is {{state}} ({{reason}}). This list may be incomplete.",
+ "unlinkedRetention": "Call evidence expires after {{days}} days or when more than {{maxRows}} newer calls are retained.",
+ "unlinkedTruncated": "Only the newest retained calls are shown.",
"refresh": "Refresh",
"loadMore": "Load more",
"limitReached": "Showing the first {{count}} entries. Refresh to see the newest processing activity.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index e59fe7890..266d45636 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4377,6 +4377,14 @@
"forbidden": "当前连接无法访问处理日志。",
"disabledHint": "启用记忆后即可查看处理日志。",
"empty": "还没有已处理的记忆条目。",
+ "unlinkedTitle": "未生成记忆条目的调用",
+ "unlinkedLoading": "正在加载保留的调用…",
+ "unlinkedLoadFailed": "无法加载未生成记忆条目的调用。",
+ "unlinkedEmpty": "未找到仍在保留期内且未生成记忆条目的调用。",
+ "unlinkedRecorderIncomplete": "调用记录当前为{{state}},此列表可能不完整。",
+ "unlinkedRecorderIncompleteWithReason": "调用记录当前为{{state}}({{reason}}),此列表可能不完整。",
+ "unlinkedRetention": "调用证据会在 {{days}} 天后过期,或在新增调用超过 {{maxRows}} 条时被清理。",
+ "unlinkedTruncated": "这里只显示最新保留的调用。",
"refresh": "刷新",
"loadMore": "加载更多",
"limitReached": "当前显示前 {{count}} 条记录。刷新后可查看最新处理活动。",
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 70b3fab99..275a5637a 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -969,6 +969,24 @@ async def memory_log(
)
+async def memory_log_unlinked(
+ *,
+ limit: int,
+ user_key: str,
+ socket_path: Optional[Path] = None,
+ timeout: float = MEMORY_READ_TIMEOUT_SECONDS,
+) -> dict[str, Any]:
+ path = "/internal/memory/log/unlinked"
+ return await _memory_request(
+ "GET",
+ path,
+ params={"limit": limit},
+ headers=_memory_user_key_headers("GET", path, user_key),
+ socket_path=socket_path,
+ timeout=timeout,
+ )
+
+
async def memory_log_entry(
memcell_id: str,
*,
diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.py
index f67c0a64e..496087acd 100644
--- a/vibe/ui_memory_routes.py
+++ b/vibe/ui_memory_routes.py
@@ -79,6 +79,19 @@ def _memory_log_list_query(request: FastAPIRequest) -> tuple[str | None, int]:
return cursor, limit
+def _memory_log_unlinked_query(request: FastAPIRequest) -> int:
+ items = list(request.query_params.multi_items())
+ if any(key != "limit" for key, _value in items) or len(items) > 1:
+ raise ValueError("invalid unlinked memory log query")
+ raw_limit = items[0][1] if items else "20"
+ if not raw_limit.isascii() or not raw_limit.isdecimal():
+ raise ValueError("invalid unlinked memory log limit")
+ limit = int(raw_limit)
+ if not 1 <= limit <= 20:
+ raise ValueError("invalid unlinked memory log limit")
+ return limit
+
+
def _memory_log_entry_query(request: FastAPIRequest) -> str:
items = list(request.query_params.multi_items())
if len(items) != 1 or items[0][0] != "memcell_id":
@@ -1106,6 +1119,30 @@ def register_memory_routes(app) -> None:
return await app.dispatch_native_request(starlette_request, handler)
+ @app.get("/api/memory/log/unlinked", include_in_schema=False)
+ async def memory_log_unlinked_get(starlette_request: FastAPIRequest):
+ async def handler():
+ user_key = _memory_ui_user_key()
+ if user_key is None:
+ return _memory_forbidden_response()
+ try:
+ limit = _memory_log_unlinked_query(starlette_request)
+ except ValueError:
+ return _memory_response(
+ {"status": "failed", "error": "memory_invalid_input"},
+ status_code=400,
+ )
+ from vibe import internal_client
+
+ return await _memory_internal_response(
+ lambda: internal_client.memory_log_unlinked(
+ limit=limit,
+ user_key=user_key,
+ )
+ )
+
+ return await app.dispatch_native_request(starlette_request, handler)
+
@app.get("/api/memory/log/entry", include_in_schema=False)
async def memory_log_entry_get(starlette_request: FastAPIRequest):
async def handler():