Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(agent-evolution): add trajectory date filters (#3915)
agenta779c62a0f35
diff --git a/docs/en/api/19-agent-evolution.md b/docs/en/api/19-agent-evolution.mdindex 0478adc3d..20c7d7412 100644--- a/docs/en/api/19-agent-evolution.md+++ b/docs/en/api/19-agent-evolution.md@@ -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"```@@ -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"```diff --git a/docs/zh/api/19-agent-evolution.md b/docs/zh/api/19-agent-evolution.mdindex c2f923329..e156cc664 100644--- a/docs/zh/api/19-agent-evolution.md+++ b/docs/zh/api/19-agent-evolution.md@@ -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"```@@ -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"```diff --git a/openviking/server/routers/agent_evolution.py b/openviking/server/routers/agent_evolution.pyindex 824554bb3..ea1d8f83f 100644--- a/openviking/server/routers/agent_evolution.py+++ b/openviking/server/routers/agent_evolution.py@@ -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."""@@ -34,6 +36,8 @@ 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)@@ -41,6 +45,8 @@ async def list_experience_trajectories(@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."""@@ -48,5 +54,7 @@ async def get_experience_outcome_distribution(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)diff --git a/openviking/service/agent_evolution_service.py b/openviking/service/agent_evolution_service.pyindex 8ea5206b9..9cce530bb 100644--- a/openviking/service/agent_evolution_service.py+++ b/openviking/service/agent_evolution_service.py@@ -5,6 +5,7 @@from __future__ import annotationsimport asyncio+from datetime import date, datetime, time, timedelta, timezonefrom typing import TYPE_CHECKING, Any, Optionalfrom openviking.core.namespace import canonicalize_uri@@ -15,7 +16,7 @@ from openviking.session.memory.experience_lineage import (experience_source_tag,trajectory_outcome_tag,)-from openviking.storage.expr import And, Eq, PathScope+from openviking.storage.expr import And, Eq, PathScope, TimeRangefrom openviking.storage.viking_fs import VikingFSfrom openviking_cli.exceptions import InvalidArgumentError, NotInitializedError@@ -34,6 +35,61 @@ _TRAJECTORY_OUTPUT_FIELDS = []+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."""@@ -87,24 +143,26 @@ class AgentEvolutionService: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(@@ -136,18 +194,20 @@ class AgentEvolutionService:*,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(diff --git a/tests/server/test_api_agent_evolution.py b/tests/server/test_api_agent_evolution.pyindex 8120269e9..a51f6276a 100644--- a/tests/server/test_api_agent_evolution.py+++ b/tests/server/test_api_agent_evolution.py@@ -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,@@ -44,6 +46,41 @@ async def test_list_experience_trajectories_uses_default_pagination(assert captured["experience_uri"] == uriassert captured["limit"] == 50assert 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(@@ -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}],@@ -92,3 +134,38 @@ async def test_get_experience_outcome_distribution("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"diff --git a/tests/service/test_agent_evolution_service.py b/tests/service/test_agent_evolution_service.pyindex e8a82b2d7..5cc4b04c0 100644--- a/tests/service/test_agent_evolution_service.py+++ b/tests/service/test_agent_evolution_service.py@@ -12,7 +12,7 @@ from openviking.session.memory.experience_lineage import (experience_source_tag,trajectory_outcome_tag,)-from openviking.storage.expr import And, Eq, PathScope+from openviking.storage.expr import And, Eq, PathScope, TimeRangefrom openviking_cli.exceptions import InvalidArgumentErrorfrom openviking_cli.session.user_id import UserIdentifier@@ -92,6 +92,53 @@ async def test_list_trajectories_by_experience_rejects_other_user_uri():)+async def test_list_trajectories_by_experience_filters_created_at_by_utc_date():+ experience_uri = "viking://user/alice/memories/experiences/exchange.md"+ viking_fs = Mock()+ viking_fs.stat = AsyncMock(return_value={"isDir": False})+ vikingdb = Mock()+ vikingdb.filter = AsyncMock(return_value=[])+ vikingdb.count = AsyncMock(return_value=0)+ service = AgentEvolutionService(viking_fs=viking_fs, vikingdb=vikingdb)++ await service.list_trajectories_by_experience(+ experience_uri=experience_uri,+ ctx=_ctx(),+ start_date="2026-08-01",+ end_date="2026-08-10",+ )++ expected_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)),+ TimeRange(+ "created_at",+ start="2026-08-01T00:00:00+00:00",+ end="2026-08-11T00:00:00+00:00",+ ),+ ]+ )+ assert vikingdb.filter.await_args.kwargs["filter"] == expected_filter+ assert vikingdb.count.await_args.kwargs["filter"] == expected_filter+++async def test_list_trajectories_by_experience_rejects_invalid_date_range():+ service = AgentEvolutionService(viking_fs=Mock(), vikingdb=Mock())++ with pytest.raises(InvalidArgumentError, match="start_date must be earlier"):+ await service.list_trajectories_by_experience(+ experience_uri="viking://user/alice/memories/experiences/exchange.md",+ ctx=_ctx(),+ start_date="2026-08-11",+ end_date="2026-08-10",+ )++@pytest.mark.asyncioasync def test_list_trajectories_by_experience_rejects_limit_above_1000():service = AgentEvolutionService(viking_fs=Mock(), vikingdb=Mock())@@ -182,6 +229,39 @@ async def test_get_experience_outcome_distribution_counts_two_tags_on_same_list_)+async def test_get_experience_outcome_distribution_filters_created_at_by_utc_date():+ 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(return_value=0)+ service = AgentEvolutionService(viking_fs=viking_fs, vikingdb=vikingdb)++ await service.get_experience_outcome_distribution(+ experience_uri=experience_uri,+ ctx=_ctx(),+ start_date="2026-08-10",+ end_date="2026-08-10",+ )++ 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)),+ TimeRange(+ "created_at",+ start="2026-08-10T00:00:00+00:00",+ end="2026-08-11T00:00:00+00:00",+ ),+ Eq("search_tags", trajectory_outcome_tag(outcome)),+ ]+ )++@pytest.mark.asyncioasync def test_get_experience_outcome_distribution_rejects_other_user_uri():service = AgentEvolutionService(viking_fs=Mock(), vikingdb=Mock())