Skip to content

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

refactor: remove dead code paths (#2545)

Qin Haojie80ce2df0b814
diff --git a/crates/ov_cli/src/commands/chat.rs b/crates/ov_cli/src/commands/chat.rs
index bb7336cf5..904fc26c5 100644
--- a/crates/ov_cli/src/commands/chat.rs
+++ b/crates/ov_cli/src/commands/chat.rs
@@ -677,35 +677,6 @@ impl ChatCommand {
}
}
-#[allow(dead_code)]
-impl ChatCommand {
- /// Create a new ChatCommand with the given parameters
- #[allow(clippy::too_many_arguments)]
- pub fn new(
- endpoint: String,
- api_key: Option<String>,
- session: Option<String>,
- sender: String,
- message: Option<String>,
- stream: bool,
- no_format: bool,
- no_history: bool,
- ) -> Self {
- Self {
- endpoint,
- api_key,
- account: None,
- user: None,
- session,
- sender,
- message,
- stream,
- no_format,
- no_history,
- }
- }
-}
-
/// Render markdown to terminal using termimad
fn render_markdown(text: &str) {
let skin = MadSkin::default();
diff --git a/crates/ov_cli/src/config_agent.rs b/crates/ov_cli/src/config_agent.rs
index 463de434f..a61c9c224 100644
--- a/crates/ov_cli/src/config_agent.rs
+++ b/crates/ov_cli/src/config_agent.rs
@@ -12,7 +12,7 @@ use uuid::Uuid;
use crate::{
CliContext, ConfigAddCustomArgs, ConfigAddOvServiceArgs, ConfigAddTarget, ConfigDeleteArgs,
ConfigEditArgs,
- config::{Config, DEFAULT_CUSTOM_URL, display_config_home},
+ config::{Config, DEFAULT_CUSTOM_URL},
config_wizard::{
ApiKeyRole, ConfigKind, ConfigStore, OPENVIKING_SERVICE_URL, configs_equivalent,
custom_allows_empty_api_key, custom_requires_api_key, normalize_custom_url,
@@ -920,11 +920,6 @@ fn path_string(path: impl Into<PathBuf>) -> String {
path.into().display().to_string()
}
-#[allow(dead_code)]
-fn config_home_string() -> String {
- display_config_home()
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ov_cli/src/output.rs b/crates/ov_cli/src/output.rs
index b609acaa9..aea4eb0b9 100644
--- a/crates/ov_cli/src/output.rs
+++ b/crates/ov_cli/src/output.rs
@@ -60,29 +60,6 @@ fn compact_success_value<T: Serialize>(result: T) -> Value {
json!({ "status": "ok", "result": result, "profile": profile })
}
-#[allow(dead_code)]
-pub fn output_error(code: &str, message: &str, format: OutputFormat, compact: bool) {
- if matches!(format, OutputFormat::Json) && compact {
- eprintln!(
- "{}",
- json!({
- "ok": false,
- "error": {
- "code": code,
- "message": message
- }
- })
- );
- } else {
- eprintln!(
- "{}[{}]: {}",
- theme::error("ERROR").bold(),
- theme::error(code),
- theme::body(message)
- );
- }
-}
-
fn print_table<T: Serialize>(result: T, compact: bool) {
// Convert to json Value for processing
let value = match serde_json::to_value(&result) {
diff --git a/openviking/core/path_variables.py b/openviking/core/path_variables.py
index e9bca53b1..2240f6a47 100644
--- a/openviking/core/path_variables.py
+++ b/openviking/core/path_variables.py
@@ -9,7 +9,7 @@ Provides URI template resolution with support for variables like {calendar:today
import re
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
-from typing import Dict, Optional, Set
+from typing import Dict, Optional
from openviking_cli.utils import get_logger
@@ -132,14 +132,6 @@ class PathVariableResolver:
"""Check if a URI template contains variables."""
return VARIABLE_PATTERN.search(uri_template) is not None
- def extract_variables(self, uri_template: str) -> Set[str]:
- """Extract all variables from a URI template."""
- variables = set()
- matches = VARIABLE_PATTERN.findall(uri_template)
- for namespace, key in matches:
- variables.add(f"{namespace}:{key}")
- return variables
-
def resolve(self, uri_template: str, dt: Optional[datetime] = None) -> str:
"""
Resolve variables in a URI template.
@@ -224,17 +216,3 @@ def resolve_path_variables(uri_template: str, dt: Optional[datetime] = None) ->
"""
resolver = get_path_variable_resolver()
return resolver.resolve(uri_template, dt=dt)
-
-
-def has_path_variables(uri_template: str) -> bool:
- """
- Convenience function to check if a URI template contains variables.
-
- Args:
- uri_template: URI template to check
-
- Returns:
- True if the template contains variables
- """
- resolver = get_path_variable_resolver()
- return resolver.has_variables(uri_template)
diff --git a/openviking/models/vlm/base.py b/openviking/models/vlm/base.py
index 1aab3231e..c05510cf1 100644
--- a/openviking/models/vlm/base.py
+++ b/openviking/models/vlm/base.py
@@ -95,7 +95,6 @@ class VLMBase(ABC):
Returns:
str if no tools provided, VLMResponse if tools provided
"""
- effective_thinking = self.thinking if thinking is None else thinking
pass
@abstractmethod
@@ -119,7 +118,6 @@ class VLMBase(ABC):
Returns:
str if no tools provided, VLMResponse if tools provided
"""
- effective_thinking = self.thinking if thinking is None else thinking
pass
@abstractmethod
@@ -145,7 +143,6 @@ class VLMBase(ABC):
Returns:
str if no tools provided, VLMResponse if tools provided
"""
- effective_thinking = self.thinking if thinking is None else thinking
pass
@abstractmethod
@@ -171,7 +168,6 @@ class VLMBase(ABC):
Returns:
str if no tools provided, VLMResponse if tools provided
"""
- effective_thinking = self.thinking if thinking is None else thinking
pass
def _clean_response(self, content: str) -> str:
diff --git a/openviking/parse/image_rewrite.py b/openviking/parse/image_rewrite.py
index 018fc974b..02c24d441 100644
--- a/openviking/parse/image_rewrite.py
+++ b/openviking/parse/image_rewrite.py
@@ -9,7 +9,6 @@ directory.
import json
import re
-from pathlib import PurePath
from typing import TYPE_CHECKING, Dict, Optional, Set
from openviking.server.identity import RequestContext
diff --git a/openviking/session/__init__.py b/openviking/session/__init__.py
index 4c9fefd0f..877638b8f 100644
--- a/openviking/session/__init__.py
+++ b/openviking/session/__init__.py
@@ -3,11 +3,7 @@
"""Session management module."""
from typing import TYPE_CHECKING, Optional
-from openviking.session.memory_archiver import (
- ArchivalCandidate,
- ArchivalResult,
- MemoryArchiver,
-)
+
from openviking.session.session import Session, SessionCompression, SessionMeta, SessionStats
from openviking.storage import VikingDBManager
from openviking_cli.utils import get_logger
@@ -50,8 +46,4 @@ __all__ = [
"SessionStats",
# Compressor
"create_session_compressor",
- # Memory Archiver
- "MemoryArchiver",
- "ArchivalCandidate",
- "ArchivalResult",
]
diff --git a/openviking/session/memory/core.py b/openviking/session/memory/core.py
index b18c7eb04..ba22734bd 100644
--- a/openviking/session/memory/core.py
+++ b/openviking/session/memory/core.py
@@ -12,7 +12,6 @@ from abc import ABC, abstractmethod
from typing import Any, Dict, List
from openviking.server.identity import RequestContext
-from openviking.storage.viking_fs import VikingFS
class ExtractContextProvider(ABC):
diff --git a/openviking/session/memory/tools.py b/openviking/session/memory/tools.py
index 84ee418a7..74a159c7d 100644
--- a/openviking/session/memory/tools.py
+++ b/openviking/session/memory/tools.py
@@ -10,7 +10,6 @@ import json
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
-from openviking.session.memory.dataclass import MemoryFile
from openviking.session.memory.utils import add_line_numbers, line_count, slice_content_lines
from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
from openviking.telemetry import tracer
diff --git a/openviking/session/memory/utils/link_renderer.py b/openviking/session/memory/utils/link_renderer.py
index ce2695083..d0d64c567 100644
--- a/openviking/session/memory/utils/link_renderer.py
+++ b/openviking/session/memory/utils/link_renderer.py
@@ -2,7 +2,6 @@ import re
from typing import Dict, List, Optional
from openviking.core.namespace import uri_parts
-from openviking.session.memory.dataclass import StoredLink
class LinkRenderer:
diff --git a/openviking/session/memory_archiver.py b/openviking/session/memory_archiver.py
deleted file mode 100644
index d4ac08fb0..000000000
--- a/openviking/session/memory_archiver.py
+++ /dev/null
@@ -1,336 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-"""Cold-storage archival for stale memories based on hotness scoring.
-
-Moves memories with low hotness scores to an archive directory,
-reducing token consumption from stale abstracts and overviews during
-retrieval. Archived memories can be restored to their original location.
-"""
-
-from dataclasses import dataclass, field
-from datetime import datetime, timezone
-from typing import Any, List, Optional
-
-from openviking.retrieve.memory_lifecycle import hotness_score
-from openviking.server.identity import RequestContext
-from openviking.storage.expr import And, Eq
-from openviking.utils.time_utils import parse_iso_datetime
-from openviking_cli.utils.logger import get_logger
-from openviking_cli.utils.uri import VikingURI
-
-logger = get_logger(__name__)
-
-# Directory name for archived memories within each scope.
-ARCHIVE_DIR = "_archive"
-
-
-@dataclass
-class ArchivalCandidate:
- """A memory that qualifies for archival."""
-
- uri: str
- active_count: int
- updated_at: Optional[datetime]
- score: float
- context_type: str = ""
- parent_uri: str = ""
-
-
-@dataclass
-class ArchivalResult:
- """Summary of an archival operation."""
-
- scanned: int = 0
- archived: int = 0
- skipped: int = 0
- errors: int = 0
- candidates: List[ArchivalCandidate] = field(default_factory=list)
-
-
-class MemoryArchiver:
- """Archives cold memories based on hotness scoring.
-
- Uses ``hotness_score()`` from ``memory_lifecycle`` to identify memories
- whose access frequency and recency have fallen below a threshold.
- Moves them to ``{scope}/_archive/`` using ``viking_fs.mv()`` so
- they remain recoverable but are excluded from default retrieval.
- """
-
- DEFAULT_THRESHOLD: float = 0.1
- DEFAULT_MIN_AGE_DAYS: int = 7
- DEFAULT_BATCH_SIZE: int = 100
-
- def __init__(
- self,
- viking_fs: Any,
- storage: Any,
- threshold: float = DEFAULT_THRESHOLD,
- min_age_days: int = DEFAULT_MIN_AGE_DAYS,
- ):
- """Initialize the archiver.
-
- Args:
- viking_fs: VikingFS instance for filesystem operations.
- storage: VikingDBManagerProxy for vector index queries.
- threshold: Hotness score below which memories are archived.
- min_age_days: Skip memories updated within this many days.
- """
- self.viking_fs = viking_fs
- self.storage = storage
- self.threshold = threshold
- self.min_age_days = min_age_days
-
- @staticmethod
- def _derive_parent_uri(uri: str) -> str:
- try:
- parent = VikingURI(uri).parent
- except Exception:
- return ""
- return parent.uri if parent else ""
-
- async def scan(
- self,
- scope_uri: str,
- ctx: Optional[RequestContext] = None,
- now: Optional[datetime] = None,
- ) -> List[ArchivalCandidate]:
- """Scan a scope for cold memories.
-
- Queries the vector index for all L2 memories under *scope_uri*,
- computes their hotness score, and returns those below the threshold
- that are older than ``min_age_days``.
-
- Args:
- scope_uri: Root URI to scan (e.g. ``viking://memories/``).
- ctx: Request context for tenant isolation.
- now: Override current time (for deterministic tests).
-
- Returns:
- List of candidates eligible for archival, sorted by score
- ascending (coldest first).
- """
- if now is None:
- now = datetime.now(timezone.utc)
-
- candidates: List[ArchivalCandidate] = []
-
- # Only scan L2 content -- never archive L0 abstracts or L1 overviews.
- filter_expr = And(conds=[Eq("level", 2)])
-
- cursor: Optional[str] = None
- total_scanned = 0
-
- while True:
- records, next_cursor = await self.storage.scroll(
- filter=filter_expr,
- limit=self.DEFAULT_BATCH_SIZE,
- cursor=cursor,
- output_fields=[
- "uri",
- "active_count",
- "updated_at",
- "context_type",
- ],
- )
-
- if not records:
- break
-
- for record in records:
- uri = record.get("uri", "")
-
- # Skip entries already in an archive directory.
- if f"/{ARCHIVE_DIR}/" in uri:
- continue
-
- # Skip entries outside the requested scope.
- if not uri.startswith(scope_uri):
- continue
-
- total_scanned += 1
-
- active_count = int(record.get("active_count", 0) or 0)
- updated_at_raw = record.get("updated_at")
- updated_at = _parse_datetime(updated_at_raw)
-
- # Respect minimum age.
- if updated_at is not None:
- age_days = (now - updated_at).total_seconds() / 86400.0
- if age_days < self.min_age_days:
- continue
-
- score = hotness_score(
- active_count=active_count,
- updated_at=updated_at,
- now=now,
- )
-
- if score < self.threshold:
- candidates.append(
- ArchivalCandidate(
- uri=uri,
- active_count=active_count,
- updated_at=updated_at,
- score=score,
- context_type=record.get("context_type", ""),
- parent_uri=self._derive_parent_uri(uri),
- )
- )
-
- cursor = next_cursor
- if cursor is None:
- break
-
- # Coldest first.
- candidates.sort(key=lambda c: c.score)
-
- logger.info(
- f"[MemoryArchiver] Scanned {total_scanned} memories under {scope_uri}, "
- f"found {len(candidates)} archival candidates (threshold={self.threshold})"
- )
- return candidates
-
- async def archive(
- self,
- candidates: List[ArchivalCandidate],
- ctx: Optional[RequestContext] = None,
- dry_run: bool = False,
- ) -> ArchivalResult:
- """Archive the given candidates.
-
- Moves each candidate to ``{parent}/_archive/{filename}`` using
- ``viking_fs.mv()``, which atomically updates the vector index.
-
- Args:
- candidates: Output of ``scan()``.
- ctx: Request context for tenant isolation.
- dry_run: If True, log what would happen without moving files.
-
- Returns:
- Summary of the operation.
- """
- result = ArchivalResult(scanned=len(candidates), candidates=candidates)
-
- for candidate in candidates:
- archive_uri = _build_archive_uri(candidate.uri)
-
- if dry_run:
- logger.info(
- f"[MemoryArchiver] DRY-RUN would archive {candidate.uri} "
- f"(score={candidate.score:.4f}) -> {archive_uri}"
- )
- result.skipped += 1
- continue
-
- try:
- await self.viking_fs.mv(candidate.uri, archive_uri, ctx=ctx)
- result.archived += 1
- logger.info(
- f"[MemoryArchiver] Archived {candidate.uri} "
- f"(score={candidate.score:.4f}) -> {archive_uri}"
- )
- except Exception:
- logger.exception(f"[MemoryArchiver] Failed to archive {candidate.uri}")
- result.errors += 1
-
- logger.info(
- f"[MemoryArchiver] Archive complete: "
- f"{result.archived} archived, {result.skipped} skipped, "
- f"{result.errors} errors"
- )
- return result
-
- async def restore(
- self,
- archived_uri: str,
- ctx: Optional[RequestContext] = None,
- ) -> bool:
- """Restore an archived memory to its original location.
-
- The original location is derived by removing the ``_archive/``
- path segment from the URI.
-
- Args:
- archived_uri: URI of the archived memory.
- ctx: Request context for tenant isolation.
-
- Returns:
- True if the memory was restored successfully.
- """
- original_uri = _build_restore_uri(archived_uri)
- if original_uri is None:
- logger.warning(
- f"[MemoryArchiver] Cannot restore {archived_uri}: not in an archive directory"
- )
- return False
-
- try:
- await self.viking_fs.mv(archived_uri, original_uri, ctx=ctx)
- logger.info(f"[MemoryArchiver] Restored {archived_uri} -> {original_uri}")
- return True
- except Exception:
- logger.exception(f"[MemoryArchiver] Failed to restore {archived_uri}")
- return False
-
- async def scan_and_archive(
- self,
- scope_uri: str,
- ctx: Optional[RequestContext] = None,
- dry_run: bool = False,
- now: Optional[datetime] = None,
- ) -> ArchivalResult:
- """Convenience method: scan then archive in one call."""
- candidates = await self.scan(scope_uri, ctx=ctx, now=now)
- return await self.archive(candidates, ctx=ctx, dry_run=dry_run)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _build_archive_uri(uri: str) -> str:
- """Insert ``_archive/`` before the filename in a URI.
-
- ``viking://memories/facts/greeting.md``
- -> ``viking://memories/facts/_archive/greeting.md``
- """
- last_slash = uri.rfind("/")
- if last_slash == -1:
- return f"{ARCHIVE_DIR}/{uri}"
- parent = uri[:last_slash]
- filename = uri[last_slash + 1 :]
- return f"{parent}/{ARCHIVE_DIR}/{filename}"
-
-
-def _build_restore_uri(archived_uri: str) -> Optional[str]:
- """Remove the ``_archive/`` segment to recover the original URI.
-
- ``viking://memories/facts/_archive/greeting.md``
- -> ``viking://memories/facts/greeting.md``
-
- Returns None if the URI does not contain ``_archive/``.
- """
- marker = f"/{ARCHIVE_DIR}/"
- idx = archived_uri.find(marker)
- if idx == -1:
- return None
- parent = archived_uri[:idx]
- filename = archived_uri[idx + len(marker) :]
- return f"{parent}/{filename}"
-
-
-def _parse_datetime(value: Any) -> Optional[datetime]:
- """Best-effort parse of a datetime value from the vector store."""
- if value is None:
- return None
- if isinstance(value, datetime):
- if value.tzinfo is None:
- return value.replace(tzinfo=timezone.utc)
- return value
- if isinstance(value, str):
- try:
- return parse_iso_datetime(value)
- except Exception:
- return None
- return None
diff --git a/openviking/storage/observers/filesystem_observer.py b/openviking/storage/observers/filesystem_observer.py
index 2ca97ec84..ba392dbcd 100644
--- a/openviking/storage/observers/filesystem_observer.py
+++ b/openviking/storage/observers/filesystem_observer.py
@@ -4,7 +4,7 @@ FilesystemObserver: Filesystem observability tool.
Provides methods to observe and report filesystem operation statistics.
"""
-from typing import Dict, Optional
+from typing import Optional
from openviking.storage.observers.base_observer import BaseObserver
from openviking_cli.utils import run_async
diff --git a/openviking/utils/model_retry.py b/openviking/utils/model_retry.py
index 56bea7e2e..0566269b4 100644
--- a/openviking/utils/model_retry.py
+++ b/openviking/utils/model_retry.py
@@ -145,11 +145,6 @@ def classify_api_error(error: Exception) -> str:
return ERROR_CLASS_UNKNOWN
-def is_quota_exceeded_api_error(error: Exception) -> bool:
- """Return True if the error indicates an account quota has been exceeded."""
- return classify_api_error(error) == ERROR_CLASS_QUOTA_EXCEEDED
-
-
def is_retryable_api_error(error: Exception) -> bool:
"""Return True if the error should be retried."""
return classify_api_error(error) == ERROR_CLASS_TRANSIENT
diff --git a/openviking/utils/search_filters.py b/openviking/utils/search_filters.py
index 5a8ce3611..d2c04e32d 100644
--- a/openviking/utils/search_filters.py
+++ b/openviking/utils/search_filters.py
@@ -44,24 +44,6 @@ def merge_time_filter(
return {"op": "and", "conds": [existing_filter, time_filter]}
-def merge_level_filter(
- existing_filter: Optional[Dict[str, Any]],
- level: Optional[Union[int, str, List[int]]] = None,
-) -> Optional[Dict[str, Any]]:
- """Merge level filter into an existing metadata filter tree."""
- levels = _resolve_levels(level)
- if not levels:
- return existing_filter
-
- level_filter: Dict[str, Any] = {"op": "must", "field": "level", "conds": levels}
-
- if not existing_filter:
- return level_filter
- # Preserve any caller-supplied metadata predicates by AND-ing the level filter
- # into the existing filter tree instead of replacing it.
- return {"op": "and", "conds": [existing_filter, level_filter]}
-
-
def _resolve_levels(level: Optional[Union[int, str, List[int], List[str]]]) -> List[int]:
"""Resolve level parameter into a list of integers."""
if level is None:
diff --git a/tests/unit/session/test_memory_archiver.py b/tests/unit/session/test_memory_archiver.py
deleted file mode 100644
index b33d6b7da..000000000
--- a/tests/unit/session/test_memory_archiver.py
+++ /dev/null
@@ -1,442 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-"""Unit tests for memory cold-storage archival."""
-
-from datetime import datetime, timedelta, timezone
-from unittest.mock import AsyncMock
-
-import pytest
-
-from openviking.session.memory_archiver import (
- ArchivalCandidate,
- MemoryArchiver,
- _build_archive_uri,
- _build_restore_uri,
- _parse_datetime,
-)
-
-# ---------------------------------------------------------------------------
-# Helper URI functions
-# ---------------------------------------------------------------------------
-
-
-class TestBuildArchiveUri:
- def test_simple_file(self):
- assert (
- _build_archive_uri("viking://memories/facts/greeting.md")
- == "viking://memories/facts/_archive/greeting.md"
- )
-
- def test_nested_path(self):
- assert (
- _build_archive_uri("viking://memories/user/prefs/theme.md")
- == "viking://memories/user/prefs/_archive/theme.md"
- )
-
- def test_root_level_file(self):
- assert (
- _build_archive_uri("viking://memories/note.md") == "viking://memories/_archive/note.md"
- )
-
- def test_no_slash(self):
- assert _build_archive_uri("note.md") == "_archive/note.md"
-
-
-class TestBuildRestoreUri:
- def test_simple_restore(self):
- assert (
- _build_restore_uri("viking://memories/facts/_archive/greeting.md")
- == "viking://memories/facts/greeting.md"
- )
-
- def test_nested_restore(self):
- assert (
- _build_restore_uri("viking://memories/user/_archive/pref.md")
- == "viking://memories/user/pref.md"
- )
-
- def test_not_archived_returns_none(self):
- assert _build_restore_uri("viking://memories/facts/greeting.md") is None
-
- def test_roundtrip(self):
- original = "viking://memories/deep/path/to/file.md"
- archived = _build_archive_uri(original)
- restored = _build_restore_uri(archived)
- assert restored == original
-
-
-# ---------------------------------------------------------------------------
-# Datetime parsing
-# ---------------------------------------------------------------------------
-
-
-class TestParseDatetime:
- def test_none(self):
- assert _parse_datetime(None) is None
-
- def test_datetime_object(self):
- dt = datetime(2026, 1, 1, tzinfo=timezone.utc)
- assert _parse_datetime(dt) == dt
-
- def test_naive_datetime_gets_utc(self):
- dt = datetime(2026, 1, 1)
- result = _parse_datetime(dt)
- assert result is not None
- assert result.tzinfo == timezone.utc
-
- def test_iso_string(self):
- result = _parse_datetime("2026-01-01T00:00:00+00:00")
- assert result is not None
- assert result.year == 2026
-
- def test_invalid_string(self):
- assert _parse_datetime("not-a-date") is None
-
- def test_integer_returns_none(self):
- assert _parse_datetime(12345) is None
-
-
-# ---------------------------------------------------------------------------
-# MemoryArchiver.scan
-# ---------------------------------------------------------------------------
-
-
-def _make_storage(records):
- """Create a mock storage that returns records from scroll()."""
- storage = AsyncMock()
- storage.scroll = AsyncMock(return_value=(records, None))
- return storage
-
-
-def _make_viking_fs():
- """Create a mock VikingFS."""
- vfs = AsyncMock()
- vfs.mv = AsyncMock(return_value={"status": "ok"})
- return vfs
-
-
-NOW = datetime(2026, 3, 14, 12, 0, 0, tzinfo=timezone.utc)
-OLD_DATE = NOW - timedelta(days=30)
-RECENT_DATE = NOW - timedelta(days=2)
-
-
-class TestScan:
- @pytest.mark.asyncio
- async def test_scan_requests_no_parent_uri_field(self):
- storage = _make_storage([])
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=storage,
- threshold=0.5,
- min_age_days=7,
- )
-
- await archiver.scan("viking://memories/", now=NOW)
-
- assert storage.scroll.await_count == 1
- assert storage.scroll.await_args.kwargs["output_fields"] == [
- "uri",
- "active_count",
- "updated_at",
- "context_type",
- ]
-
- @pytest.mark.asyncio
- async def test_scan_finds_cold_memories(self):
- records = [
- {
- "uri": "viking://memories/fact1.md",
- "active_count": 0,
- "updated_at": OLD_DATE,
- "context_type": "memory",
- },
- ]
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=_make_storage(records),
- threshold=0.5,
- min_age_days=7,
- )
- candidates = await archiver.scan("viking://memories/", now=NOW)
- assert len(candidates) == 1
- assert candidates[0].uri == "viking://memories/fact1.md"
- assert candidates[0].score < 0.5
-
- @pytest.mark.asyncio
- async def test_scan_skips_recent_memories(self):
- records = [
- {
- "uri": "viking://memories/recent.md",
- "active_count": 0,
- "updated_at": RECENT_DATE,
- "context_type": "memory",
- "parent_uri": "viking://memories/",
- },
- ]
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=_make_storage(records),
- threshold=0.5,
- min_age_days=7,
- )
- candidates = await archiver.scan("viking://memories/", now=NOW)
- assert len(candidates) == 0
-
- @pytest.mark.asyncio
- async def test_scan_skips_already_archived(self):
- records = [
- {
- "uri": "viking://memories/_archive/old.md",
- "active_count": 0,
- "updated_at": OLD_DATE,
- "context_type": "memory",
- "parent_uri": "viking://memories/_archive/",
- },
- ]
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=_make_storage(records),
- threshold=0.5,
- min_age_days=7,
- )
- candidates = await archiver.scan("viking://memories/", now=NOW)
- assert len(candidates) == 0
-
- @pytest.mark.asyncio
- async def test_scan_skips_out_of_scope(self):
- records = [
- {
- "uri": "viking://resources/doc.md",
- "active_count": 0,
- "updated_at": OLD_DATE,
- "context_type": "resource",
- "parent_uri": "viking://resources/",
- },
- ]
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=_make_storage(records),
- threshold=0.5,
- min_age_days=7,
- )
- candidates = await archiver.scan("viking://memories/", now=NOW)
- assert len(candidates) == 0
-
- @pytest.mark.asyncio
- async def test_scan_keeps_hot_memories(self):
- records = [
- {
- "uri": "viking://memories/hot.md",
- "active_count": 100,
- "updated_at": NOW - timedelta(days=1),
- "context_type": "memory",
- "parent_uri": "viking://memories/",
- },
- ]
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=_make_storage(records),
- threshold=0.5,
- min_age_days=0,
- )
- candidates = await archiver.scan("viking://memories/", now=NOW)
- # High active_count + recent = hot, should not be a candidate
- assert len(candidates) == 0
-
- @pytest.mark.asyncio
- async def test_scan_sorts_coldest_first(self):
- records = [
- {
- "uri": "viking://memories/warm.md",
- "active_count": 5,
- "updated_at": OLD_DATE,
- "context_type": "memory",
- "parent_uri": "viking://memories/",
- },
- {
- "uri": "viking://memories/cold.md",
- "active_count": 0,
- "updated_at": OLD_DATE - timedelta(days=60),
- "context_type": "memory",
- "parent_uri": "viking://memories/",
- },
- ]
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=_make_storage(records),
- threshold=0.5,
- min_age_days=7,
- )
- candidates = await archiver.scan("viking://memories/", now=NOW)
- assert len(candidates) == 2
- assert candidates[0].uri == "viking://memories/cold.md"
- assert candidates[0].score <= candidates[1].score
-
- @pytest.mark.asyncio
- async def test_scan_empty_store(self):
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=_make_storage([]),
- threshold=0.5,
- min_age_days=7,
- )
- candidates = await archiver.scan("viking://memories/", now=NOW)
- assert candidates == []
-
-
-# ---------------------------------------------------------------------------
-# MemoryArchiver.archive
-# ---------------------------------------------------------------------------
-
-
-class TestArchive:
- @pytest.mark.asyncio
- async def test_archive_moves_files(self):
- vfs = _make_viking_fs()
- archiver = MemoryArchiver(viking_fs=vfs, storage=_make_storage([]))
- candidates = [
- ArchivalCandidate(
- uri="viking://memories/fact1.md",
- active_count=0,
- updated_at=OLD_DATE,
- score=0.01,
- ),
- ]
- result = await archiver.archive(candidates)
- assert result.archived == 1
- assert result.errors == 0
- vfs.mv.assert_called_once_with(
- "viking://memories/fact1.md",
- "viking://memories/_archive/fact1.md",
- ctx=None,
- )
-
- @pytest.mark.asyncio
- async def test_archive_dry_run(self):
- vfs = _make_viking_fs()
- archiver = MemoryArchiver(viking_fs=vfs, storage=_make_storage([]))
- candidates = [
- ArchivalCandidate(
- uri="viking://memories/fact1.md",
- active_count=0,
- updated_at=OLD_DATE,
- score=0.01,
- ),
- ]
- result = await archiver.archive(candidates, dry_run=True)
- assert result.archived == 0
- assert result.skipped == 1
- vfs.mv.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_archive_handles_mv_error(self):
- vfs = _make_viking_fs()
- vfs.mv = AsyncMock(side_effect=RuntimeError("AGFS error"))
- archiver = MemoryArchiver(viking_fs=vfs, storage=_make_storage([]))
- candidates = [
- ArchivalCandidate(
- uri="viking://memories/fact1.md",
- active_count=0,
- updated_at=OLD_DATE,
- score=0.01,
- ),
- ]
- result = await archiver.archive(candidates)
- assert result.archived == 0
- assert result.errors == 1
-
- @pytest.mark.asyncio
- async def test_archive_empty_candidates(self):
- archiver = MemoryArchiver(
- viking_fs=_make_viking_fs(),
- storage=_make_storage([]),
- )
- result = await archiver.archive([])
- assert result.archived == 0
- assert result.scanned == 0
-
-
-# ---------------------------------------------------------------------------
-# MemoryArchiver.restore
-# ---------------------------------------------------------------------------
-
-
-class TestRestore:
- @pytest.mark.asyncio
- async def test_restore_moves_back(self):
- vfs = _make_viking_fs()
- archiver = MemoryArchiver(viking_fs=vfs, storage=_make_storage([]))
- ok = await archiver.restore("viking://memories/_archive/fact1.md")
- assert ok is True
- vfs.mv.assert_called_once_with(
- "viking://memories/_archive/fact1.md",
- "viking://memories/fact1.md",
- ctx=None,
- )
-
- @pytest.mark.asyncio
- async def test_restore_non_archived_uri(self):
- vfs = _make_viking_fs()
- archiver = MemoryArchiver(viking_fs=vfs, storage=_make_storage([]))
- ok = await archiver.restore("viking://memories/fact1.md")
- assert ok is False
- vfs.mv.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_restore_handles_error(self):
- vfs = _make_viking_fs()
- vfs.mv = AsyncMock(side_effect=RuntimeError("AGFS error"))
- archiver = MemoryArchiver(viking_fs=vfs, storage=_make_storage([]))
- ok = await archiver.restore("viking://memories/_archive/fact1.md")
- assert ok is False
-
-
-# ---------------------------------------------------------------------------
-# scan_and_archive convenience
-# ---------------------------------------------------------------------------
-
-
-class TestScanAndArchive:
- @pytest.mark.asyncio
- async def test_scan_and_archive(self):
- records = [
- {
- "uri": "viking://memories/cold.md",
- "active_count": 0,
- "updated_at": OLD_DATE,
- "context_type": "memory",
- "parent_uri": "viking://memories/",
- },
- ]
- vfs = _make_viking_fs()
- archiver = MemoryArchiver(
- viking_fs=vfs,
- storage=_make_storage(records),
- threshold=0.5,
- min_age_days=7,
- )
- result = await archiver.scan_and_archive("viking://memories/", now=NOW)
- assert result.archived == 1
-
- @pytest.mark.asyncio
- async def test_scan_and_archive_dry_run(self):
- records = [
- {
- "uri": "viking://memories/cold.md",
- "active_count": 0,
- "updated_at": OLD_DATE,
- "context_type": "memory",
- "parent_uri": "viking://memories/",
- },
- ]
- vfs = _make_viking_fs()
- archiver = MemoryArchiver(
- viking_fs=vfs,
- storage=_make_storage(records),
- threshold=0.5,
- min_age_days=7,
- )
- result = await archiver.scan_and_archive("viking://memories/", dry_run=True, now=NOW)
- assert result.archived == 0
- assert result.skipped == 1
- vfs.mv.assert_not_called()
diff --git a/tests/unit/test_model_retry.py b/tests/unit/test_model_retry.py
index 3bc02aac7..536d57992 100644
--- a/tests/unit/test_model_retry.py
+++ b/tests/unit/test_model_retry.py
@@ -10,7 +10,6 @@ from openviking.utils.model_retry import (
ERROR_CLASS_QUOTA_EXCEEDED,
ERROR_CLASS_TRANSIENT,
classify_api_error,
- is_quota_exceeded_api_error,
retry_async,
retry_sync,
)
@@ -87,11 +86,6 @@ def test_permanent_still_takes_precedence_over_quota():
assert classify_api_error(RuntimeError("403 AccountQuotaExceeded")) == ERROR_CLASS_PERMANENT
-def test_is_quota_exceeded_api_error():
- assert is_quota_exceeded_api_error(RuntimeError("AccountQuotaExceeded")) is True
- assert is_quota_exceeded_api_error(RuntimeError("429 TooManyRequests")) is False
-
-
def test_retry_sync_does_not_retry_quota_exceeded():
"""Quota-exceeded errors should NOT be retried."""
attempts = {"count": 0}
diff --git a/tests/unit/test_path_variables.py b/tests/unit/test_path_variables.py
index 3248df28a..4ce2afe89 100644
--- a/tests/unit/test_path_variables.py
+++ b/tests/unit/test_path_variables.py
@@ -10,7 +10,6 @@ import pytest
from openviking.core.path_variables import (
CalendarVariableProvider,
PathVariableResolver,
- has_path_variables,
resolve_path_variables,
)
@@ -260,18 +259,6 @@ class TestPathVariableResolver:
assert resolver.has_variables("") is False
assert resolver.has_variables("no variables here") is False
- def test_extract_variables(self, resolver):
- uri = "viking://resources/{calendar:year}/{calendar:month}/{calendar:day}"
- variables = resolver.extract_variables(uri)
-
- assert variables == {"calendar:year", "calendar:month", "calendar:day"}
-
- def test_extract_variables_none(self, resolver):
- uri = "viking://resources/docs/api.md"
- variables = resolver.extract_variables(uri)
-
- assert variables == set()
-
def test_multiple_occurrences_same_variable(self, resolver, sample_datetime):
uri = "viking://resources/{calendar:year}/backup/{calendar:year}/data"
resolved = resolver.resolve(uri, dt=sample_datetime)
@@ -293,12 +280,6 @@ class TestConvenienceFunctions:
assert resolved == "viking://resources/emails/2026/05/07/inbox"
- def test_has_path_variables_true(self):
- assert has_path_variables("viking://resources/{calendar:year}/docs") is True
-
- def test_has_path_variables_false(self):
- assert has_path_variables("viking://resources/docs") is False
-
class TestRealWorldExamples:
"""Tests for real-world usage patterns."""
diff --git a/tests/unit/test_search_filters.py b/tests/unit/test_search_filters.py
index 999a817b8..32fd239b0 100644
--- a/tests/unit/test_search_filters.py
+++ b/tests/unit/test_search_filters.py
@@ -5,7 +5,7 @@ from datetime import datetime, timezone
import pytest
-from openviking.utils.search_filters import merge_time_filter, merge_level_filter
+from openviking.utils.search_filters import merge_time_filter
from openviking.utils.time_utils import parse_iso_datetime
@@ -119,70 +119,3 @@ def test_merge_time_filter_date_only_uses_now_timezone():
assert result["gte"].endswith("Z")
assert result["lte"].endswith("Z")
-
-
-def test_merge_level_filter_with_single_level():
- result = merge_level_filter(None, level=0)
- assert result == {"op": "must", "field": "level", "conds": [0]}
-
-
-def test_merge_level_filter_with_multiple_levels():
- result = merge_level_filter(None, level=[0, 1])
- assert result == {"op": "must", "field": "level", "conds": [0, 1]}
-
-
-def test_merge_level_filter_with_comma_separated_string():
- result = merge_level_filter(None, level="0,1,2")
- assert result == {"op": "must", "field": "level", "conds": [0, 1, 2]}
-
-
-def test_merge_level_filter_with_single_string():
- result = merge_level_filter(None, level="0")
- assert result == {"op": "must", "field": "level", "conds": [0]}
-
-
-def test_merge_level_filter_merges_with_existing_filter():
- existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}
-
- result = merge_level_filter(existing_filter, level=2)
-
- assert result == {
- "op": "and",
- "conds": [
- existing_filter,
- {"op": "must", "field": "level", "conds": [2]},
- ],
- }
-
-
-def test_merge_level_filter_with_none_returns_existing():
- existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}
- result = merge_level_filter(existing_filter, level=None)
- assert result == existing_filter
-
-
-def test_merge_level_filter_with_empty_string_returns_existing():
- existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}
- result = merge_level_filter(existing_filter, level="")
- assert result == existing_filter
-
-
-def test_merge_level_filter_with_empty_list_returns_existing():
- existing_filter = {"op": "must", "field": "kind", "conds": ["email"]}
- result = merge_level_filter(existing_filter, level=[])
- assert result == existing_filter
-
-
-def test_merge_level_filter_with_mixed_types_list():
- result = merge_level_filter(None, level=[0, "1", 2])
- assert result == {"op": "must", "field": "level", "conds": [0, 1, 2]}
-
-
-def test_merge_level_filter_with_spaces_in_comma_string():
- result = merge_level_filter(None, level="0, 1, 2")
- assert result == {"op": "must", "field": "level", "conds": [0, 1, 2]}
-
-
-def test_merge_level_filter_skips_invalid_values():
- result = merge_level_filter(None, level="0,invalid,2")
- assert result == {"op": "must", "field": "level", "conds": [0, 2]}