Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(agent-evolution): aggregate outcomes and refine experience snapshots (#3742)

agent73a70195b133
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts
index 5a0d49be0..fee05c9b8 100644
--- a/docs/.vitepress/config.ts
+++ b/docs/.vitepress/config.ts
@@ -200,7 +200,8 @@ const apiReferenceSidebar = {
['03-filesystem.md', 'File System'],
['04-skills.md', 'Skills'],
['05-sessions.md', 'Sessions'],
- ['16-memory.md', 'Memory']
+ ['16-memory.md', 'Memory'],
+ ['19-agent-evolution.md', 'Agent Evolution']
]
},
{
@@ -259,7 +260,8 @@ const apiReferenceSidebar = {
['03-filesystem.md', '文件系统'],
['04-skills.md', '技能'],
['05-sessions.md', '会话'],
- ['16-memory.md', '记忆']
+ ['16-memory.md', '记忆'],
+ ['19-agent-evolution.md', 'Agent 进化']
]
},
{
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index 9abc81ce5..d1bbeef6f 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -452,7 +452,7 @@ This catalog follows the routes actually mounted by the server. Each group headi
| PUT | `/api/v1/skills/{skill_name}` | Update a skill |
| DELETE | `/api/v1/skills/{skill_name}` | Delete a skill |
-### [Sessions](05-sessions.md) and [Memory](16-memory.md)
+### [Sessions](05-sessions.md), [Memory](16-memory.md), and [Agent Evolution](19-agent-evolution.md)
| Method | Path | Description |
|--------|------|-------------|
@@ -471,6 +471,8 @@ This catalog follows the routes actually mounted by the server. Each group headi
| POST | `/api/v1/sessions/{session_id}/messages/batch` | Add messages in a batch |
| POST | `/api/v1/sessions/{session_id}/used` | Record context or skills actually used |
| POST | `/api/v1/search/recall` | Deprecated: thin preset over the search endpoint with `mode="context"` |
+| GET | `/api/v1/agent-evolution/experiences/trajectories` | List trajectories that consumed an Experience |
+| GET | `/api/v1/agent-evolution/experiences/outcomes` | Aggregate outcomes of trajectories that consumed an Experience |
### [Retrieval](06-retrieval.md) and [Relations](13-relations.md)
diff --git a/docs/en/api/19-agent-evolution.md b/docs/en/api/19-agent-evolution.md
new file mode 100644
index 000000000..0478adc3d
--- /dev/null
+++ b/docs/en/api/19-agent-evolution.md
@@ -0,0 +1,114 @@
+# Agent Evolution
+
+The Agent Evolution API reports trajectories that consumed a specific Experience and their outcome distribution. These operations are currently available through HTTP only.
+
+## API Reference
+
+### List Experience application trajectories
+
+Return a paginated list of trajectories that successfully read the specified Experience. The query is restricted to Experiences and trajectories owned by the current user.
+
+**Code Entry Points**:
+
+- `openviking/server/routers/agent_evolution.py:list_experience_trajectories` - HTTP route
+- `openviking/service/agent_evolution_service.py:AgentEvolutionService.list_trajectories_by_experience` - Core implementation
+
+**Parameters**
+
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| experience_uri | string | Yes | - | Experience file URI in the current user space |
+| limit | integer | No | 50 | Page size from 1 through 1000 |
+| offset | integer | No | 0 | Zero-based result offset |
+
+**HTTP API**
+
+```
+GET /api/v1/agent-evolution/experiences/trajectories?experience_uri={experience_uri}&limit=50&offset=0
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/trajectories?experience_uri=viking://user/default/memories/experiences/exchange.md&limit=50&offset=0" \
+ -H "X-API-Key: your-key"
+```
+
+**Response Example**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "experience_uri": "viking://user/default/memories/experiences/exchange.md",
+ "items": [
+ {
+ "uri": "viking://user/default/memories/trajectories/exchange_20260805020000.md",
+ "name": "exchange_20260805020000.md",
+ "description": "Handle an exchange request",
+ "created_at": "2026-08-05T02:00:00Z",
+ "updated_at": "2026-08-05T02:00:00Z"
+ }
+ ],
+ "total": 1,
+ "limit": 50,
+ "offset": 0,
+ "has_more": false
+ },
+ "time": 0.01
+}
+```
+
+Each item contains only the indexed fields that are present among `uri`, `name`, `description`, `created_at`, and `updated_at`.
+
+---
+
+### Get Experience outcome distribution
+
+Count trajectories that consumed the specified Experience across the five supported outcomes. The query uses exact scalar-tag aggregation and does not load every trajectory file.
+
+**Code Entry Points**:
+
+- `openviking/server/routers/agent_evolution.py:get_experience_outcome_distribution` - HTTP route
+- `openviking/service/agent_evolution_service.py:AgentEvolutionService.get_experience_outcome_distribution` - Core implementation
+
+**Parameters**
+
+| Parameter | Type | Required | Default | Description |
+|-----------|------|----------|---------|-------------|
+| experience_uri | string | Yes | - | Experience file URI in the current user space |
+
+**HTTP API**
+
+```
+GET /api/v1/agent-evolution/experiences/outcomes?experience_uri={experience_uri}
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/outcomes?experience_uri=viking://user/default/memories/experiences/exchange.md" \
+ -H "X-API-Key: your-key"
+```
+
+**Response Example**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "experience_uri": "viking://user/default/memories/experiences/exchange.md",
+ "outcome_distribution": [
+ {"outcome": "success", "count": 4},
+ {"outcome": "failure", "count": 1},
+ {"outcome": "partial", "count": 0},
+ {"outcome": "unknown", "count": 0},
+ {"outcome": "unfinished", "count": 0}
+ ]
+ },
+ "time": 0.01
+}
+```
+
+The response always includes `success`, `failure`, `partial`, `unknown`, and `unfinished`. Trajectories created by older versions and not yet re-indexed do not carry outcome tags and are therefore excluded.
+
+## Related Documentation
+
+- [Sessions](05-sessions.md) - Commit sessions and generate Agent Evolution memories
+- [Memory](16-memory.md) - Read and recall memories
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 33c3d2901..432433e31 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -447,7 +447,7 @@ JSON 输出 - 错误:
| PUT | `/api/v1/skills/{skill_name}` | 更新技能 |
| DELETE | `/api/v1/skills/{skill_name}` | 删除技能 |
-### [会话](05-sessions.md)与[记忆](16-memory.md)
+### [会话](05-sessions.md)、[记忆](16-memory.md)与 [Agent 进化](19-agent-evolution.md)
| 方法 | 路径 | 说明 |
|------|------|------|
@@ -466,6 +466,8 @@ JSON 输出 - 错误:
| POST | `/api/v1/sessions/{session_id}/messages/batch` | 批量添加消息 |
| POST | `/api/v1/sessions/{session_id}/used` | 记录实际使用的上下文或技能 |
| POST | `/api/v1/search/recall` | 已弃用:search 接口 `mode="context"` 之上的轻量预设 |
+| GET | `/api/v1/agent-evolution/experiences/trajectories` | 分页查询应用过指定 Experience 的 Trajectory |
+| GET | `/api/v1/agent-evolution/experiences/outcomes` | 聚合应用过指定 Experience 的 Trajectory 结果分布 |
### [检索](06-retrieval.md)与[关系](13-relations.md)
diff --git a/docs/zh/api/19-agent-evolution.md b/docs/zh/api/19-agent-evolution.md
new file mode 100644
index 000000000..c2f923329
--- /dev/null
+++ b/docs/zh/api/19-agent-evolution.md
@@ -0,0 +1,114 @@
+# Agent 进化
+
+Agent Evolution API 用于查询某条 Experience 被实际应用后的 Trajectory 记录及结果分布。当前仅提供 HTTP API。
+
+## API 参考
+
+### 查询 Experience 应用轨迹
+
+分页返回成功读取过指定 Experience 的 Trajectory。查询仅匹配当前调用用户空间内的 Experience 和 Trajectory。
+
+**代码入口**:
+
+- `openviking/server/routers/agent_evolution.py:list_experience_trajectories` - HTTP 路由
+- `openviking/service/agent_evolution_service.py:AgentEvolutionService.list_trajectories_by_experience` - 核心实现
+
+**参数**
+
+| 参数 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| experience_uri | string | 是 | - | 当前用户空间内的 Experience 文件 URI |
+| limit | integer | 否 | 50 | 单页数量,范围为 1~1000 |
+| offset | integer | 否 | 0 | 从零开始的结果偏移量 |
+
+**HTTP API**
+
+```
+GET /api/v1/agent-evolution/experiences/trajectories?experience_uri={experience_uri}&limit=50&offset=0
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/trajectories?experience_uri=viking://user/default/memories/experiences/exchange.md&limit=50&offset=0" \
+ -H "X-API-Key: your-key"
+```
+
+**响应示例**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "experience_uri": "viking://user/default/memories/experiences/exchange.md",
+ "items": [
+ {
+ "uri": "viking://user/default/memories/trajectories/exchange_20260805020000.md",
+ "name": "exchange_20260805020000.md",
+ "description": "处理换货请求",
+ "created_at": "2026-08-05T02:00:00Z",
+ "updated_at": "2026-08-05T02:00:00Z"
+ }
+ ],
+ "total": 1,
+ "limit": 50,
+ "offset": 0,
+ "has_more": false
+ },
+ "time": 0.01
+}
+```
+
+`items` 中仅返回索引记录实际存在的 `uri`、`name`、`description`、`created_at` 和 `updated_at` 字段。
+
+---
+
+### 查询 Experience 应用结果分布
+
+统计应用过指定 Experience 的 Trajectory 在五种结果状态下的数量。该查询使用精确标量标签聚合,不读取全部 Trajectory 文件。
+
+**代码入口**:
+
+- `openviking/server/routers/agent_evolution.py:get_experience_outcome_distribution` - HTTP 路由
+- `openviking/service/agent_evolution_service.py:AgentEvolutionService.get_experience_outcome_distribution` - 核心实现
+
+**参数**
+
+| 参数 | 类型 | 必填 | 默认值 | 说明 |
+|------|------|------|--------|------|
+| experience_uri | string | 是 | - | 当前用户空间内的 Experience 文件 URI |
+
+**HTTP API**
+
+```
+GET /api/v1/agent-evolution/experiences/outcomes?experience_uri={experience_uri}
+```
+
+```bash
+curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/outcomes?experience_uri=viking://user/default/memories/experiences/exchange.md" \
+ -H "X-API-Key: your-key"
+```
+
+**响应示例**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "experience_uri": "viking://user/default/memories/experiences/exchange.md",
+ "outcome_distribution": [
+ {"outcome": "success", "count": 4},
+ {"outcome": "failure", "count": 1},
+ {"outcome": "partial", "count": 0},
+ {"outcome": "unknown", "count": 0},
+ {"outcome": "unfinished", "count": 0}
+ ]
+ },
+ "time": 0.01
+}
+```
+
+结果固定包含 `success`、`failure`、`partial`、`unknown` 和 `unfinished`。旧版创建且尚未重新索引的 Trajectory 没有 outcome 标签,因此不会计入分布。
+
+## 相关文档
+
+- [会话](05-sessions.md) - 提交会话并生成 Agent Evolution 记忆
+- [记忆](16-memory.md) - 记忆读取与召回
diff --git a/openviking/server/routers/agent_evolution.py b/openviking/server/routers/agent_evolution.py
index 0652e0d0d..824554bb3 100644
--- a/openviking/server/routers/agent_evolution.py
+++ b/openviking/server/routers/agent_evolution.py
@@ -36,3 +36,17 @@ async def list_experience_trajectories(
offset=offset,
)
return Response(status="ok", result=result)
+
+
[email protected]("/experiences/outcomes")
+async def get_experience_outcome_distribution(
+ experience_uri: str = Query(..., description="Experience file URI"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Count application trajectories by outcome for an Experience."""
+ service = get_service()
+ result = await service.agent_evolution.get_experience_outcome_distribution(
+ experience_uri=experience_uri,
+ ctx=_ctx,
+ )
+ return Response(status="ok", result=result)
diff --git a/openviking/service/agent_evolution_service.py b/openviking/service/agent_evolution_service.py
index 06844c9d7..8ea5206b9 100644
--- a/openviking/service/agent_evolution_service.py
+++ b/openviking/service/agent_evolution_service.py
@@ -10,8 +10,10 @@ from typing import TYPE_CHECKING, Any, Optional
from openviking.core.namespace import canonicalize_uri
from openviking.server.identity import RequestContext
from openviking.session.memory.experience_lineage import (
+ TRAJECTORY_OUTCOMES,
canonical_experience_uri,
experience_source_tag,
+ trajectory_outcome_tag,
)
from openviking.storage.expr import And, Eq, PathScope
from openviking.storage.viking_fs import VikingFS
@@ -52,20 +54,12 @@ class AgentEvolutionService:
raise NotInitializedError("VikingFS")
return self._viking_fs
- async def list_trajectories_by_experience(
+ async def _prepare_experience_query(
self,
*,
experience_uri: str,
ctx: RequestContext,
- limit: int = DEFAULT_TRAJECTORY_PAGE_LIMIT,
- offset: int = 0,
- ) -> dict[str, Any]:
- """List trajectories produced by commits that read an Experience."""
- if limit < 1 or limit > MAX_TRAJECTORY_PAGE_LIMIT:
- raise InvalidArgumentError(f"limit must be between 1 and {MAX_TRAJECTORY_PAGE_LIMIT}")
- if offset < 0:
- raise InvalidArgumentError("offset must be greater than or equal to 0")
-
+ ) -> tuple[str, str, VikingDBManager]:
canonical_uri = canonical_experience_uri(experience_uri, ctx)
if canonical_uri is None:
raise InvalidArgumentError(
@@ -84,6 +78,26 @@ class AgentEvolutionService:
f"viking://user/{ctx.user.user_id}/memories/trajectories",
ctx,
)
+ return canonical_uri, trajectory_root, self._vikingdb
+
+ async def list_trajectories_by_experience(
+ self,
+ *,
+ experience_uri: str,
+ ctx: RequestContext,
+ limit: int = DEFAULT_TRAJECTORY_PAGE_LIMIT,
+ offset: int = 0,
+ ) -> dict[str, Any]:
+ """List trajectories produced by commits that read an Experience."""
+ if limit < 1 or limit > MAX_TRAJECTORY_PAGE_LIMIT:
+ raise InvalidArgumentError(f"limit must be between 1 and {MAX_TRAJECTORY_PAGE_LIMIT}")
+ if offset < 0:
+ raise InvalidArgumentError("offset must be greater than or equal to 0")
+
+ canonical_uri, trajectory_root, vikingdb = await self._prepare_experience_query(
+ experience_uri=experience_uri,
+ ctx=ctx,
+ )
lineage_filter = And(
[
PathScope("uri", trajectory_root, depth=1),
@@ -93,7 +107,7 @@ class AgentEvolutionService:
]
)
records, total = await asyncio.gather(
- self._vikingdb.filter(
+ vikingdb.filter(
filter=lineage_filter,
limit=limit,
offset=offset,
@@ -102,7 +116,7 @@ class AgentEvolutionService:
order_desc=True,
ctx=ctx,
),
- self._vikingdb.count(filter=lineage_filter, ctx=ctx),
+ vikingdb.count(filter=lineage_filter, ctx=ctx),
)
items = [
{field: record.get(field) for field in _TRAJECTORY_OUTPUT_FIELDS if field in record}
@@ -116,3 +130,42 @@ class AgentEvolutionService:
"offset": offset,
"has_more": offset + len(items) < total,
}
+
+ async def get_experience_outcome_distribution(
+ self,
+ *,
+ experience_uri: str,
+ ctx: RequestContext,
+ ) -> dict[str, Any]:
+ """Count application trajectories by outcome for an Experience."""
+ canonical_uri, trajectory_root, vikingdb = await self._prepare_experience_query(
+ experience_uri=experience_uri,
+ ctx=ctx,
+ )
+ base_conditions = [
+ PathScope("uri", trajectory_root, depth=1),
+ Eq("context_type", "memory"),
+ Eq("level", 2),
+ Eq("search_tags", experience_source_tag(canonical_uri)),
+ ]
+ counts = await asyncio.gather(
+ *[
+ vikingdb.count(
+ filter=And(
+ [
+ *base_conditions,
+ Eq("search_tags", trajectory_outcome_tag(outcome)),
+ ]
+ ),
+ ctx=ctx,
+ )
+ for outcome in TRAJECTORY_OUTCOMES
+ ]
+ )
+ return {
+ "experience_uri": canonical_uri,
+ "outcome_distribution": [
+ {"outcome": outcome, "count": count}
+ for outcome, count in zip(TRAJECTORY_OUTCOMES, counts, strict=True)
+ ],
+ }
diff --git a/openviking/session/compressor_v3.py b/openviking/session/compressor_v3.py
index 8fe0c0431..0e1581a87 100644
--- a/openviking/session/compressor_v3.py
+++ b/openviking/session/compressor_v3.py
@@ -106,15 +106,15 @@ async def _commit_experience_snapshot(
commit = getattr(viking_fs, "commit", None)
if not callable(commit):
return
- has_experience_changes = any(
- "/memories/experiences/" in uri and uri.endswith(".md")
+ paths = [
+ uri
for uri in dict.fromkeys(str(uri or "") for uri in experience_uris)
- )
- if not has_experience_changes:
+ if "/memories/experiences/" in uri and uri.endswith(".md")
+ ]
+ if not paths:
return
- paths = [_experience_root_uri(ctx)]
archive_ref = archive_uri.rstrip("/") if archive_uri else "unknown"
- changed_experience_uris = set(dict.fromkeys(str(uri or "") for uri in experience_uris))
+ changed_experience_uris = set(paths)
trajectory_map = {
experience_uri: list(dict.fromkeys(trajectory_uris))
for experience_uri, trajectory_uris in (experience_trajectory_map or {}).items()
@@ -898,6 +898,9 @@ class SessionCompressorV3:
*,
_fallback_trajectory_uris: set[str] = fallback_trajectory_uris,
) -> None:
+ persisted_result = (
+ getattr(batch_result, "batch_result", None) or batch_result
+ )
snapshot_apply_result, experience_trajectory_map = (
_experience_snapshot_provenance(
batch_result,
@@ -907,10 +910,10 @@ class SessionCompressorV3:
await _commit_experience_snapshot(
viking_fs,
ctx=ctx,
- experience_uris=[
- *list(getattr(snapshot_apply_result, "written_uris", []) or []),
- *list(getattr(snapshot_apply_result, "deleted_uris", []) or []),
- ],
+ experience_uris=_visible_experience_snapshot_uris(
+ plan=persisted_result.plan,
+ apply_result=snapshot_apply_result,
+ ),
archive_uri=archive_uri,
experience_trajectory_map=experience_trajectory_map,
)
@@ -1767,6 +1770,42 @@ def _experience_trajectory_map(
return result
+def _visible_experience_snapshot_uris(
+ *,
+ plan: PolicyUpdatePlan,
+ apply_result: PolicyApplyResult,
+) -> list[str]:
+ """Return successfully applied Experience paths whose visible content changed."""
+ root_uri = getattr(getattr(apply_result, "updated_policy_set", None), "root_uri", "")
+ written_uris = set(getattr(apply_result, "written_uris", []) or [])
+ deleted_uris = set(getattr(apply_result, "deleted_uris", []) or [])
+ result: list[str] = []
+ seen: set[str] = set()
+
+ for item in getattr(plan, "items", []) or []:
+ if item.memory_type != _EXPERIENCES_MEMORY_TYPE:
+ continue
+ if item.before_content == item.after_content:
+ continue
+
+ uri = _experience_plan_item_uri(item, root_uri)
+ if not uri or uri in seen:
+ continue
+ if item.kind == "upsert":
+ applied = uri in written_uris
+ elif item.kind == "delete":
+ applied = uri in deleted_uris
+ else:
+ applied = False
+ if not applied:
+ continue
+
+ seen.add(uri)
+ result.append(uri)
+
+ return result
+
+
def _experience_snapshot_provenance(
training_result: Any,
*,
diff --git a/openviking/session/memory/experience_lineage.py b/openviking/session/memory/experience_lineage.py
index 118a15f8e..1241fdf36 100644
--- a/openviking/session/memory/experience_lineage.py
+++ b/openviking/session/memory/experience_lineage.py
@@ -13,6 +13,7 @@ from openviking.server.identity import RequestContext
from openviking.utils.tags import normalize_search_tag
_EXPERIENCE_SIDECAR_FILENAMES = {".abstract.md", ".overview.md", ".relations.json"}
+TRAJECTORY_OUTCOMES = ("success", "failure", "partial", "unknown", "unfinished")
def is_experience_uri_for_user(uri: str, user_id: str) -> bool:
@@ -74,6 +75,19 @@ def experience_source_tags(experience_uris: Iterable[str] | None) -> list[str]:
return tags
+def normalize_trajectory_outcome(outcome: Any) -> str:
+ """Normalize trajectory outcome values used by scalar lineage aggregation."""
+ normalized = str(outcome or "").strip().lower()
+ if normalized not in TRAJECTORY_OUTCOMES:
+ return "unknown"
+ return normalized
+
+
+def trajectory_outcome_tag(outcome: Any) -> str:
+ """Build the exact scalar tag used for trajectory outcome aggregation."""
+ return normalize_search_tag(f"trajectory_outcome={normalize_trajectory_outcome(outcome)}")
+
+
def collect_read_experience_uris(
messages: Iterable[Message] | None,
*,
diff --git a/openviking/session/train/components/trajectory_analyzer.py b/openviking/session/train/components/trajectory_analyzer.py
index 300d7d305..073ac2aad 100644
--- a/openviking/session/train/components/trajectory_analyzer.py
+++ b/openviking/session/train/components/trajectory_analyzer.py
@@ -22,6 +22,7 @@ from openviking.session.memory.dataclass import (
from openviking.session.memory.experience_lineage import (
collect_read_experience_uris,
experience_source_tags,
+ trajectory_outcome_tag,
)
from openviking.session.memory.memory_isolation_handler import MemoryIsolationHandler
from openviking.session.memory.memory_updater import ExtractContext, MemoryUpdateResult
@@ -427,13 +428,14 @@ def _trajectory_search_tags_by_uri(
operations: ResolvedOperations,
consumed_experience_uris: list[str] | None,
) -> dict[str, list[str]]:
- tags = experience_source_tags(consumed_experience_uris)
- if not tags:
- return {}
+ source_tags = experience_source_tags(consumed_experience_uris)
result: dict[str, list[str]] = {}
for op in getattr(operations, "upsert_operations", []) or []:
if getattr(op, "memory_type", None) != _TRAJECTORY_MEMORY_TYPE:
continue
+ fields = getattr(op, "memory_fields", None)
+ outcome = fields.get("outcome") if isinstance(fields, dict) else None
+ tags = [*source_tags, trajectory_outcome_tag(outcome)]
for uri in getattr(op, "uris", []) or []:
if uri:
result[uri] = list(tags)
diff --git a/tests/server/test_api_agent_evolution.py b/tests/server/test_api_agent_evolution.py
index 8e2a8a5e8..8120269e9 100644
--- a/tests/server/test_api_agent_evolution.py
+++ b/tests/server/test_api_agent_evolution.py
@@ -58,3 +58,37 @@ async def test_list_experience_trajectories_rejects_limit_above_1000(
)
assert response.status_code == 400
+
+
+async def test_get_experience_outcome_distribution(
+ client: httpx.AsyncClient,
+ service,
+ monkeypatch,
+):
+ captured = {}
+
+ async def fake_get(*, experience_uri, ctx):
+ captured.update(experience_uri=experience_uri, ctx=ctx)
+ return {
+ "experience_uri": experience_uri,
+ "outcome_distribution": [{"outcome": "success", "count": 2}],
+ }
+
+ monkeypatch.setattr(
+ service.agent_evolution,
+ "get_experience_outcome_distribution",
+ fake_get,
+ )
+ uri = "viking://user/default/memories/experiences/exchange.md"
+
+ response = await client.get(
+ "/api/v1/agent-evolution/experiences/outcomes",
+ params={"experience_uri": uri},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["result"] == {
+ "experience_uri": uri,
+ "outcome_distribution": [{"outcome": "success", "count": 2}],
+ }
+ assert captured["experience_uri"] == uri
diff --git a/tests/service/test_agent_evolution_service.py b/tests/service/test_agent_evolution_service.py
index 9aefc288d..e8a82b2d7 100644
--- a/tests/service/test_agent_evolution_service.py
+++ b/tests/service/test_agent_evolution_service.py
@@ -7,7 +7,11 @@ import pytest
from openviking.server.identity import RequestContext, Role
from openviking.service.agent_evolution_service import AgentEvolutionService
-from openviking.session.memory.experience_lineage import experience_source_tag
+from openviking.session.memory.experience_lineage import (
+ TRAJECTORY_OUTCOMES,
+ experience_source_tag,
+ trajectory_outcome_tag,
+)
from openviking.storage.expr import And, Eq, PathScope
from openviking_cli.exceptions import InvalidArgumentError
from openviking_cli.session.user_id import UserIdentifier
@@ -135,3 +139,55 @@ async def test_list_trajectories_by_experience_accepts_1000_and_paginates_all_re
assert second_page["items"] == [{"uri": "viking://user/alice/memories/trajectories/1000.md"}]
assert second_page["has_more"] is False
assert [call.kwargs["offset"] for call in vikingdb.filter.await_args_list] == [0, 1000]
+
+
+async def test_get_experience_outcome_distribution_counts_two_tags_on_same_list_field():
+ experience_uri = "viking://user/alice/memories/experiences/exchange.md"
+ viking_fs = Mock()
+ viking_fs.stat = AsyncMock(return_value={"isDir": False})
+ vikingdb = Mock()
+ vikingdb.count = AsyncMock(side_effect=[4, 2, 1, 0, 3])
+ service = AgentEvolutionService(viking_fs=viking_fs, vikingdb=vikingdb)
+
+ result = await service.get_experience_outcome_distribution(
+ experience_uri=experience_uri,
+ ctx=_ctx(),
+ )
+
+ assert result == {
+ "experience_uri": experience_uri,
+ "outcome_distribution": [
+ {"outcome": "success", "count": 4},
+ {"outcome": "failure", "count": 2},
+ {"outcome": "partial", "count": 1},
+ {"outcome": "unknown", "count": 0},
+ {"outcome": "unfinished", "count": 3},
+ ],
+ }
+ assert vikingdb.count.await_count == len(TRAJECTORY_OUTCOMES)
+ for call, outcome in zip(vikingdb.count.await_args_list, TRAJECTORY_OUTCOMES, strict=True):
+ assert call.kwargs["filter"] == And(
+ [
+ PathScope(
+ "uri",
+ "viking://user/alice/memories/trajectories",
+ depth=1,
+ ),
+ Eq("context_type", "memory"),
+ Eq("level", 2),
+ Eq("search_tags", experience_source_tag(experience_uri)),
+ Eq("search_tags", trajectory_outcome_tag(outcome)),
+ ]
+ )
+
+
+async def test_get_experience_outcome_distribution_rejects_other_user_uri():
+ service = AgentEvolutionService(viking_fs=Mock(), vikingdb=Mock())
+
+ with pytest.raises(InvalidArgumentError):
+ await service.get_experience_outcome_distribution(
+ experience_uri="viking://user/bob/memories/experiences/exchange.md",
+ ctx=_ctx(),
+ )
diff --git a/tests/session/test_compressor_v3.py b/tests/session/test_compressor_v3.py
index 157fbe237..be59bdb4c 100644
--- a/tests/session/test_compressor_v3.py
+++ b/tests/session/test_compressor_v3.py
@@ -13,9 +13,11 @@ from openviking.server.identity import RequestContext, Role
from openviking.session import create_session_compressor
from openviking.session.compressor_v3 import (
SessionCompressorV3,
+ _commit_experience_snapshot,
_experience_root_uri,
_experience_snapshot_provenance,
_experience_trajectory_map,
+ _visible_experience_snapshot_uris,
)
from openviking.session.memory.dataclass import (
MemoryFile,
@@ -1403,6 +1405,75 @@ def test_v3_snapshot_provenance_uses_complete_shared_batch_result():
}
+def test_visible_experience_snapshot_uris_only_returns_applied_body_changes():
+ root = "viking://user/u/memories/experiences"
+ changed_uri = f"{root}/changed.md"
+ metadata_only_uri = f"{root}/metadata_only.md"
+ failed_uri = f"{root}/failed.md"
+ deleted_uri = f"{root}/deleted.md"
+ content_write_uri = f"{root}/content_write.md"
+ plan = PolicyUpdatePlan(
+ items=[
+ PolicyPlanItem(
+ kind="upsert",
+ memory_type="experiences",
+ target_name="changed",
+ target_uri=changed_uri,
+ before_content="before",
+ after_content="after",
+ ),
+ PolicyPlanItem(
+ kind="upsert",
+ memory_type="experiences",
+ target_name="metadata_only",
+ target_uri=metadata_only_uri,
+ before_content="unchanged",
+ after_content="unchanged",
+ ),
+ PolicyPlanItem(
+ kind="upsert",
+ memory_type="experiences",
+ target_name="failed",
+ target_uri=failed_uri,
+ before_content="before",
+ after_content="after",
+ ),
+ PolicyPlanItem(
+ kind="delete",
+ memory_type="experiences",
+ target_name="deleted",
+ target_uri=deleted_uri,
+ before_content="old content",
+ after_content=None,
+ ),
+ ]
+ )
+ apply_result = PolicyApplyResult(
+ updated_policy_set=ExperienceSet(root_uri=root, policies=[]),
+ written_uris=[changed_uri, metadata_only_uri, content_write_uri],
+ deleted_uris=[deleted_uri],
+ )
+
+ assert _visible_experience_snapshot_uris(
+ plan=plan,
+ apply_result=apply_result,
+ ) == [changed_uri, deleted_uri]
+
+
+async def test_commit_experience_snapshot_skips_when_no_visible_content_changed():
+ viking_fs = SimpleNamespace(commit=AsyncMock())
+
+ await _commit_experience_snapshot(
+ viking_fs,
+ ctx=_ctx(),
+ experience_uris=[],
+ archive_uri="viking://user/u/sessions/session-1/history/archive_001",
+ )
+
+ viking_fs.commit.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_v3_training_links_case_to_trajectory_and_experience_via_trajectory(monkeypatch):
case_uri = "viking://user/u/memories/cases/duplicate_booking.md"
@@ -1512,7 +1583,15 @@ async def test_v3_training_links_case_to_trajectory_and_experience_via_trajector
description="",
)
],
- )
+ ),
+ PolicyPlanItem(
+ kind="delete",
+ memory_type="experiences",
+ target_name="legacy_booking_handling",
+ target_uri=deleted_exp_uri,
+ before_content="legacy exp content",
+ after_content=None,
+ ),
]
)
result = RolloutTrainingResult(
@@ -1631,7 +1710,7 @@ async def test_v3_training_links_case_to_trajectory_and_experience_via_trajector
'{"viking://user/u/memories/experiences/booking_duplicate_handling.md":'
'["viking://user/u/memories/trajectories/duplicate_booking.md"]}'
),
- "paths": ["viking://user/u/memories/experiences"],
+ "paths": [exp_uri, deleted_exp_uri],
"ctx": _ctx(),
}
]
diff --git a/tests/unit/session/memory/test_experience_lineage.py b/tests/unit/session/memory/test_experience_lineage.py
index e72373fa8..f569cf3eb 100644
--- a/tests/unit/session/memory/test_experience_lineage.py
+++ b/tests/unit/session/memory/test_experience_lineage.py
@@ -7,6 +7,8 @@ from openviking.session.memory.dataclass import ResolvedOperation, ResolvedOpera
from openviking.session.memory.experience_lineage import (
collect_read_experience_uris,
experience_source_tag,
+ normalize_trajectory_outcome,
+ trajectory_outcome_tag,
)
from openviking.session.train.components.trajectory_analyzer import (
_trajectory_search_tags_by_uri,
@@ -85,9 +87,7 @@ def test_experience_source_tag_preserves_case_and_escapes_equals_without_collisi
uppercase_tag = experience_source_tag(uppercase_uri)
lowercase_tag = experience_source_tag(lowercase_uri)
- assert uppercase_tag == (
- "viking://user/%41lice/memories/experiences/%45xchange%3d%46low.md=1"
- )
+ assert uppercase_tag == ("viking://user/%41lice/memories/experiences/%45xchange%3d%46low.md=1")
assert lowercase_tag == "viking://user/alice/memories/experiences/exchange%3dflow.md=1"
assert uppercase_tag != lowercase_tag
assert uppercase_tag.count("=") == 1
@@ -100,12 +100,12 @@ def test_source_experiences_create_transient_tags_for_every_generated_trajectory
operations = ResolvedOperations(
upsert_operations=[
ResolvedOperation(
- memory_fields={"trajectory_name": "exchange"},
+ memory_fields={"trajectory_name": "exchange", "outcome": "success"},
memory_type="trajectories",
uris=["viking://user/alice/memories/trajectories/exchange.md"],
),
ResolvedOperation(
- memory_fields={"trajectory_name": "refund"},
+ memory_fields={"trajectory_name": "refund", "outcome": "failure"},
memory_type="trajectories",
uris=["viking://user/alice/memories/trajectories/refund.md"],
),
@@ -119,10 +119,23 @@ def test_source_experiences_create_transient_tags_for_every_generated_trajectory
[first_uri, second_uri, first_uri],
)
- expected_tags = [experience_source_tag(first_uri), experience_source_tag(second_uri)]
assert tags_by_uri == {
- "viking://user/alice/memories/trajectories/exchange.md": expected_tags,
- "viking://user/alice/memories/trajectories/refund.md": expected_tags,
+ "viking://user/alice/memories/trajectories/exchange.md": [
+ experience_source_tag(first_uri),
+ experience_source_tag(second_uri),
+ "trajectory_outcome=success",
+ ],
+ "viking://user/alice/memories/trajectories/refund.md": [
+ experience_source_tag(first_uri),
+ experience_source_tag(second_uri),
+ "trajectory_outcome=failure",
+ ],
}
for operation in operations.upsert_operations:
assert "source_experience_uris" not in operation.memory_fields
+
+
+def test_trajectory_outcome_tag_normalizes_unknown_values():
+ assert trajectory_outcome_tag(" SUCCESS ") == "trajectory_outcome=success"
+ assert trajectory_outcome_tag("unexpected") == "trajectory_outcome=unknown"
+ assert normalize_trajectory_outcome(None) == "unknown"