Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions docs/en/api/19-agent-evolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,17 @@ Return a paginated list of trajectories that successfully read the specified Exp
| 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 |
| start_date | string | No | - | Earliest trajectory creation date, inclusive, as a UTC `YYYY-MM-DD` date |
| end_date | string | No | - | Latest trajectory creation date, inclusive, as a UTC `YYYY-MM-DD` date |

**HTTP API**

```
GET /api/v1/agent-evolution/experiences/trajectories?experience_uri={experience_uri}&limit=50&offset=0
GET /api/v1/agent-evolution/experiences/trajectories?experience_uri={experience_uri}&limit=50&offset=0&start_date=2026-08-01&end_date=2026-08-10
```

```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" \
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&start_date=2026-08-01&end_date=2026-08-10" \
-H "X-API-Key: your-key"
```

Expand Down Expand Up @@ -75,15 +77,17 @@ Count trajectories that consumed the specified Experience across the five suppor
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| experience_uri | string | Yes | - | Experience file URI in the current user space |
| start_date | string | No | - | Earliest trajectory creation date, inclusive, as a UTC `YYYY-MM-DD` date |
| end_date | string | No | - | Latest trajectory creation date, inclusive, as a UTC `YYYY-MM-DD` date |

**HTTP API**

```
GET /api/v1/agent-evolution/experiences/outcomes?experience_uri={experience_uri}
GET /api/v1/agent-evolution/experiences/outcomes?experience_uri={experience_uri}&start_date=2026-08-01&end_date=2026-08-10
```

```bash
curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/outcomes?experience_uri=viking://user/default/memories/experiences/exchange.md" \
curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/outcomes?experience_uri=viking://user/default/memories/experiences/exchange.md&start_date=2026-08-01&end_date=2026-08-10" \
-H "X-API-Key: your-key"
```

Expand Down
12 changes: 8 additions & 4 deletions docs/zh/api/19-agent-evolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,17 @@ Agent Evolution API 用于查询某条 Experience 被实际应用后的 Trajecto
| experience_uri | string | 是 | - | 当前用户空间内的 Experience 文件 URI |
| limit | integer | 否 | 50 | 单页数量,范围为 1~1000 |
| offset | integer | 否 | 0 | 从零开始的结果偏移量 |
| start_date | string | 否 | - | Trajectory 创建日期下界(包含),UTC `YYYY-MM-DD` |
| end_date | string | 否 | - | Trajectory 创建日期上界(包含),UTC `YYYY-MM-DD` |

**HTTP API**

```
GET /api/v1/agent-evolution/experiences/trajectories?experience_uri={experience_uri}&limit=50&offset=0
GET /api/v1/agent-evolution/experiences/trajectories?experience_uri={experience_uri}&limit=50&offset=0&start_date=2026-08-01&end_date=2026-08-10
```

```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" \
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&start_date=2026-08-01&end_date=2026-08-10" \
-H "X-API-Key: your-key"
```

Expand Down Expand Up @@ -75,15 +77,17 @@ curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/trajectori
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| experience_uri | string | 是 | - | 当前用户空间内的 Experience 文件 URI |
| start_date | string | 否 | - | Trajectory 创建日期下界(包含),UTC `YYYY-MM-DD` |
| end_date | string | 否 | - | Trajectory 创建日期上界(包含),UTC `YYYY-MM-DD` |

**HTTP API**

```
GET /api/v1/agent-evolution/experiences/outcomes?experience_uri={experience_uri}
GET /api/v1/agent-evolution/experiences/outcomes?experience_uri={experience_uri}&start_date=2026-08-01&end_date=2026-08-10
```

```bash
curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/outcomes?experience_uri=viking://user/default/memories/experiences/exchange.md" \
curl -X GET "http://localhost:1933/api/v1/agent-evolution/experiences/outcomes?experience_uri=viking://user/default/memories/experiences/exchange.md&start_date=2026-08-01&end_date=2026-08-10" \
-H "X-API-Key: your-key"
```

Expand Down
8 changes: 8 additions & 0 deletions openviking/server/routers/agent_evolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ async def list_experience_trajectories(
le=MAX_TRAJECTORY_PAGE_LIMIT,
),
offset: int = Query(0, ge=0),
start_date: str | None = Query(None, description="UTC start date, inclusive (YYYY-MM-DD)"),
end_date: str | None = Query(None, description="UTC end date, inclusive (YYYY-MM-DD)"),
_ctx: RequestContext = Depends(get_request_context),
):
"""List trajectories produced by commits that read an Experience."""
Expand All @@ -34,19 +36,25 @@ async def list_experience_trajectories(
ctx=_ctx,
limit=limit,
offset=offset,
start_date=start_date,
end_date=end_date,
)
return Response(status="ok", result=result)


@router.get("/experiences/outcomes")
async def get_experience_outcome_distribution(
experience_uri: str = Query(..., description="Experience file URI"),
start_date: str | None = Query(None, description="UTC start date, inclusive (YYYY-MM-DD)"),
end_date: str | None = Query(None, description="UTC end date, inclusive (YYYY-MM-DD)"),
_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,
start_date=start_date,
end_date=end_date,
)
return Response(status="ok", result=result)
86 changes: 73 additions & 13 deletions openviking/service/agent_evolution_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from __future__ import annotations

import asyncio
from datetime import date, datetime, time, timedelta, timezone
from typing import TYPE_CHECKING, Any, Optional

from openviking.core.namespace import canonicalize_uri
Expand All @@ -15,7 +16,7 @@
experience_source_tag,
trajectory_outcome_tag,
)
from openviking.storage.expr import And, Eq, PathScope
from openviking.storage.expr import And, Eq, PathScope, TimeRange
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import InvalidArgumentError, NotInitializedError

Expand All @@ -34,6 +35,61 @@
]


def _trajectory_created_at_range(
start_date: Optional[str],
end_date: Optional[str],
) -> Optional[TimeRange]:
"""Build a UTC, end-date-inclusive filter over trajectory creation time."""
normalized_start = (start_date or "").strip()
normalized_end = (end_date or "").strip()
if not normalized_start and not normalized_end:
return None

def parse_date(value: str, field: str) -> date:
try:
parsed = date.fromisoformat(value)
except ValueError as exc:
raise InvalidArgumentError(f"{field} must be a valid YYYY-MM-DD date") from exc
if parsed.isoformat() != value:
raise InvalidArgumentError(f"{field} must use YYYY-MM-DD format")
return parsed

start = parse_date(normalized_start, "start_date") if normalized_start else None
end = parse_date(normalized_end, "end_date") if normalized_end else None
if start is not None and end is not None and start > end:
raise InvalidArgumentError("start_date must be earlier than or equal to end_date")

start_time = (
datetime.combine(start, time.min, tzinfo=timezone.utc).isoformat()
if start is not None
else None
)
# TimeRange uses an exclusive upper bound. Advancing one day keeps end_date inclusive.
end_time = (
datetime.combine(end + timedelta(days=1), time.min, tzinfo=timezone.utc).isoformat()
if end is not None
else None
)
return TimeRange("created_at", start=start_time, end=end_time)


def _experience_trajectory_conditions(
*,
trajectory_root: str,
experience_uri: str,
created_at_range: Optional[TimeRange],
) -> list[Any]:
conditions: list[Any] = [
PathScope("uri", trajectory_root, depth=1),
Eq("context_type", "memory"),
Eq("level", 2),
Eq("search_tags", experience_source_tag(experience_uri)),
]
if created_at_range is not None:
conditions.append(created_at_range)
return conditions


class AgentEvolutionService:
"""Serve exact, non-semantic Agent Evolution lineage queries."""

Expand Down Expand Up @@ -87,24 +143,26 @@ async def list_trajectories_by_experience(
ctx: RequestContext,
limit: int = DEFAULT_TRAJECTORY_PAGE_LIMIT,
offset: int = 0,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
) -> 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")
created_at_range = _trajectory_created_at_range(start_date, end_date)

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),
Eq("context_type", "memory"),
Eq("level", 2),
Eq("search_tags", experience_source_tag(canonical_uri)),
]
_experience_trajectory_conditions(
trajectory_root=trajectory_root,
experience_uri=canonical_uri,
created_at_range=created_at_range,
)
)
records, total = await asyncio.gather(
vikingdb.filter(
Expand Down Expand Up @@ -136,18 +194,20 @@ async def get_experience_outcome_distribution(
*,
experience_uri: str,
ctx: RequestContext,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
) -> dict[str, Any]:
"""Count application trajectories by outcome for an Experience."""
created_at_range = _trajectory_created_at_range(start_date, end_date)
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)),
]
base_conditions = _experience_trajectory_conditions(
trajectory_root=trajectory_root,
experience_uri=canonical_uri,
created_at_range=created_at_range,
)
counts = await asyncio.gather(
*[
vikingdb.count(
Expand Down
83 changes: 80 additions & 3 deletions tests/server/test_api_agent_evolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ async def test_list_experience_trajectories_uses_default_pagination(
):
captured = {}

async def fake_list(*, experience_uri, ctx, limit, offset):
async def fake_list(*, experience_uri, ctx, limit, offset, start_date, end_date):
captured.update(
experience_uri=experience_uri,
ctx=ctx,
limit=limit,
offset=offset,
start_date=start_date,
end_date=end_date,
)
return {
"experience_uri": experience_uri,
Expand Down Expand Up @@ -44,6 +46,41 @@ async def fake_list(*, experience_uri, ctx, limit, offset):
assert captured["experience_uri"] == uri
assert captured["limit"] == 50
assert captured["offset"] == 0
assert captured["start_date"] is None
assert captured["end_date"] is None


async def test_list_experience_trajectories_passes_date_range(
client: httpx.AsyncClient,
service,
monkeypatch,
):
captured = {}

async def fake_list(**kwargs):
captured.update(kwargs)
return {
"experience_uri": kwargs["experience_uri"],
"items": [],
"total": 0,
"limit": kwargs["limit"],
"offset": kwargs["offset"],
"has_more": False,
}

monkeypatch.setattr(service.agent_evolution, "list_trajectories_by_experience", fake_list)
response = await client.get(
"/api/v1/agent-evolution/experiences/trajectories",
params={
"experience_uri": "viking://user/default/memories/experiences/exchange.md",
"start_date": "2026-08-01",
"end_date": "2026-08-10",
},
)

assert response.status_code == 200
assert captured["start_date"] == "2026-08-01"
assert captured["end_date"] == "2026-08-10"


async def test_list_experience_trajectories_rejects_limit_above_1000(
Expand All @@ -67,8 +104,13 @@ async def test_get_experience_outcome_distribution(
):
captured = {}

async def fake_get(*, experience_uri, ctx):
captured.update(experience_uri=experience_uri, ctx=ctx)
async def fake_get(*, experience_uri, ctx, start_date, end_date):
captured.update(
experience_uri=experience_uri,
ctx=ctx,
start_date=start_date,
end_date=end_date,
)
return {
"experience_uri": experience_uri,
"outcome_distribution": [{"outcome": "success", "count": 2}],
Expand All @@ -92,3 +134,38 @@ async def fake_get(*, experience_uri, ctx):
"outcome_distribution": [{"outcome": "success", "count": 2}],
}
assert captured["experience_uri"] == uri
assert captured["start_date"] is None
assert captured["end_date"] is None


async def test_get_experience_outcome_distribution_passes_date_range(
client: httpx.AsyncClient,
service,
monkeypatch,
):
captured = {}

async def fake_get(**kwargs):
captured.update(kwargs)
return {
"experience_uri": kwargs["experience_uri"],
"outcome_distribution": [],
}

monkeypatch.setattr(
service.agent_evolution,
"get_experience_outcome_distribution",
fake_get,
)
response = await client.get(
"/api/v1/agent-evolution/experiences/outcomes",
params={
"experience_uri": "viking://user/default/memories/experiences/exchange.md",
"start_date": "2026-08-01",
"end_date": "2026-08-10",
},
)

assert response.status_code == 200
assert captured["start_date"] == "2026-08-01"
assert captured["end_date"] == "2026-08-10"
Loading
Loading