Skip to content

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

fix(retrieve): return one entry per Skill package from context assembly (#5255)

t0saki49fbec30cc0c
diff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.md
index 59bf36563..71f58aa83 100644
--- a/docs/en/api/06-retrieval.md
+++ b/docs/en/api/06-retrieval.md
@@ -662,10 +662,11 @@ Injecting context every turn used to mean searching per type, reading each hit b
|----------|--------------|---------------------------|-----|
| `events` | overview | full | The one memory type whose body is long enough for `# Summary` extraction to be a real compression |
| `entities` / `preferences` / `experiences` | abstract | abstract | Short bodies, and the writer stores the whole body in the abstract scalar, so abstract already is the complete file |
- | `resources` / `skills` | abstract | abstract | The 256-char abstract from semantic processing; bodies can be large or carry credentials, so deepening is opt-in |
+ | `resources` / `skills` | abstract | abstract | A resource shows the 256-char abstract from semantic processing, a skill the name/description generated from its `SKILL.md` frontmatter; bodies can be large or carry credentials, so deepening is opt-in |
| `memories` | abstract | abstract | Built-in memory types outside the four named ones — `cases`, `patterns`, `tools`, `trajectories`, skill-usage memories. Only quota-free retrieval reaches them; they own no bucket, so `quotas` cannot name them, but `detail` and `other_peer_penalty` can |
- | Directory hits | overview | overview | A directory has no abstract, so it reads the `.overview.md` sidecar; a full tier is meaningless for a subtree |
+ | Directory hits | overview | overview | A directory has no abstract, so it reads the `.overview.md` sidecar; a full tier is meaningless for a subtree. Skill package hits are the exception: they normalize onto `<package root>/SKILL.md` and follow the file rules above |
+- **Skill packages**: a package stores one vector per file and per directory level, and they all collapse into a single entry before the quotas apply — one entry per package, one quota slot, whichever file inside it matched. That entry's `uri` is `<package root>/SKILL.md`, the same path `/skills/find` reports as `skill_md_uri`, and its text is the package's own abstract; a package whose abstract has not been generated yet degrades to a bare `uri` rather than borrowing the summary of the file that matched. `dedup_turns` therefore cools a whole package: once one is served at `abstract` or deeper, a hit on any file inside it is skipped for the rest of the window
- **Floor**: every result carries at least its `uri`. When a memory abstract is unavailable or busts the per-entry cap, the entry falls back to overview: the memory writer stores the whole body in that scalar, so for memory categories overview sits *below* abstract on the content ladder and the substitute discloses less. A `resources` or `skills` abstract is the short generated summary instead, so the same substitution would read a body the caller never asked for — those two degrade to a bare `uri` rather than deepen
- **Explicit `detail`**: sets that tier as both the requested start and ceiling; entries that do not fit still step down a tier rather than being truncated. The memory overview substitute above is the one case where the served `detail` can outrank the pin, and only because it carries less content than the pinned tier would
- **Overview by source type**: memory files use the leading `# Summary` section, code files use class and function signatures (reusing `code_outline`), long documents use the heading tree plus first paragraph
diff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.md
index 864d1c345..1dbecb960 100644
--- a/docs/zh/api/06-retrieval.md
+++ b/docs/zh/api/06-retrieval.md
@@ -664,10 +664,11 @@ Agent 插件每轮注入上下文时,过去需要按类型逐个检索、再
|------|--------|------------------|------|
| `events` | 概览档 | 全文档 | 唯一正文足够长、`# Summary` 抽取能真正压缩的类型 |
| `entities` / `preferences` / `experiences` | 摘要档 | 摘要档 | 正文本身很短,且写入侧把整篇正文存进了摘要标量,摘要档即完整内容 |
- | `resources` / `skills` | 摘要档 | 摘要档 | 语义处理生成的 256 字符摘要;正文可能很大或含凭据,加深需显式指定 |
+ | `resources` / `skills` | 摘要档 | 摘要档 | 资源取语义处理生成的 256 字符摘要,skill 取 `SKILL.md` frontmatter 生成的 name/description;正文可能很大或含凭据,加深需显式指定 |
| `memories` | 摘要档 | 摘要档 | 四个具名类型之外的内置记忆类型——`cases`、`patterns`、`tools`、`trajectories`、技能使用记忆。只有 quota-free 检索会命中它们;它们没有自己的检索桶,`quotas` 不能指定,但 `detail` 和 `other_peer_penalty` 可以 |
- | 目录命中 | 概览档 | 概览档 | 目录没有摘要,读 `.overview.md` 侧车;全文档对目录无意义 |
+ | 目录命中 | 概览档 | 概览档 | 目录没有摘要,读 `.overview.md` 侧车;全文档对目录无意义。skill 包命中除外:它们归一到 `<包根>/SKILL.md`,按上面的文件档位处理 |
+- **Skill 包**:一个包的每个文件、每层目录各存一条向量记录,它们在配额生效之前先合并成一条——不管命中的是包里哪个文件,每个包只出一条 entry、只占一个名额。这条 entry 的 `uri` 是 `<包根>/SKILL.md`,和 `/skills/find` 返回的 `skill_md_uri` 是同一条路径,正文是包自己的摘要;包的摘要还没生成时退成裸 `uri`,不拿命中的那个文件的摘要顶替。因此 `dedup_turns` 是按包冷却的:某个包以摘要档或更深的档位注入过之后,冷却窗口内命中包里任何文件都会被排除
- **保底**:每条结果至少给出 `uri`。记忆类摘要缺失或超出单条上限时回落到概览档:写入侧把整篇正文存进了摘要标量,所以对记忆类别而言概览档在内容阶梯上位于摘要档*之下*,这次替换披露得更少。而 `resources` / `skills` 的摘要是语义处理生成的短摘要,同样的替换会去读调用方没有请求的正文,因此这两类直接退成裸 `uri`,不向上加深
- **显式 `detail`**:把该档作为全部结果请求的起点和上限;装不下的条目仍逐档退档而不截断。上述记忆类概览档替换是实际档位唯一可能高于指定档的情况,且仅因为它比指定档携带的内容更少
- **概览档按来源取骨架**:记忆文件取开头的 `# Summary` 段,代码文件取函数与类签名(复用 `code_outline`),长文档取标题树加首段
diff --git a/openviking/retrieve/context_assembler/gather.py b/openviking/retrieve/context_assembler/gather.py
index 5d293e33e..ece42605a 100644
--- a/openviking/retrieve/context_assembler/gather.py
+++ b/openviking/retrieve/context_assembler/gather.py
@@ -19,8 +19,10 @@ from openviking.retrieve.context_assembler.params import (
ORIGIN_ORDER,
OTHER_MEMORY_CATEGORY,
OTHER_PEER_OVERFETCH,
+ READ_CONCURRENCY,
REPORTED_CATEGORY_KEYS,
)
+from openviking.retrieve.skill_results import package_abstract, skill_root_uri
from openviking.server.identity import RequestContext
from openviking.utils.search_filters import merge_context_type_filter
from openviking_cli.exceptions import InvalidArgumentError
@@ -179,7 +181,7 @@ def dedupe_keep_best(items: Sequence[Any]) -> List[Any]:
return out
-async def _safe_find(service: Any, errors: List[str], **kwargs: Any) -> Any:
+async def _safe_find(service: Any, errors: List[str], method: str, **kwargs: Any) -> Any:
"""Retrieval must never fail the whole assembly for one scope.
Failures are counted into stats rather than swallowed silently, so an empty
@@ -190,7 +192,7 @@ async def _safe_find(service: Any, errors: List[str], **kwargs: Any) -> Any:
the same 400 ``mode="list"`` returns.
"""
try:
- return await service.search.find(**kwargs)
+ return await getattr(service.search, method)(**kwargs)
except InvalidArgumentError:
raise
except Exception as exc:
@@ -234,10 +236,23 @@ async def gather_candidates(
base_uri, is_directory = strip_level_suffix(uri)
if base_uri.endswith("/profile.md"):
continue
+ category = category_for(item, bucket)
+ abstract = _abstract(item)
+ if category == "skills":
+ # Every file and directory level of a package carries its own
+ # vector, so a hit anywhere inside one stands for the package:
+ # it becomes the package's SKILL.md before exclusion is checked,
+ # which is what lets the ledger cool a whole package for a turn.
+ root = skill_root_uri(uri)
+ if not root:
+ continue
+ if uri != f"{root}/.abstract.md":
+ abstract = ""
+ uri = base_uri = f"{root}/SKILL.md"
+ is_directory = False
if uri in excluded or base_uri in excluded:
excluded_count += 1
continue
- category = category_for(item, bucket)
origin = origin_for_uri(base_uri, ctx.actor_peer_id, user_root)
score = _score(item)
penalty = penalties.get(category, 0.0) if origin == "other_peer" else 0.0
@@ -249,7 +264,7 @@ async def gather_candidates(
score=score,
ranked_score=score - penalty,
level=_level(item),
- abstract=_abstract(item),
+ abstract=abstract,
origin=origin,
is_directory=is_directory,
read_ctx=open_ctx if origin == "other_peer" else ctx,
@@ -277,6 +292,7 @@ async def gather_candidates(
return _safe_find(
service,
retrieval_errors,
+ "find",
query=query,
ctx=find_ctx,
target_uri=target_uri,
@@ -294,17 +310,52 @@ async def gather_candidates(
"skills": ContextType.SKILL,
}.get(bucket, ContextType.MEMORY)
bucket_filter = merge_context_type_filter(filter, context_type)
- searches = [
- _find(
- query=query,
- find_ctx=ctx,
- target_uri=target,
- find_limit=_overfetch(quota),
- find_filter=bucket_filter,
- )
- for query in planned
- for target in targets
- ]
+ if bucket == "skills":
+ # Package retrieval pages until it holds `limit` distinct packages
+ # and spans every root in one call, so one search per query is
+ # enough. It is a vector search though, so it needs query text. A
+ # filter-only request stays on the generic path, which answers it
+ # by scanning scalars rather than embedding an empty string, and an
+ # image-only one has nothing either path can use for this bucket.
+ searches = []
+ for query in planned:
+ if query.strip():
+ searches.append(
+ _safe_find(
+ service,
+ retrieval_errors,
+ "find_skills",
+ query=query,
+ ctx=ctx,
+ target_uri=targets,
+ limit=_overfetch(quota),
+ score_threshold=score_threshold,
+ filter=bucket_filter,
+ )
+ )
+ elif filter:
+ searches.extend(
+ _find(
+ query=query,
+ find_ctx=ctx,
+ target_uri=target,
+ find_limit=_overfetch(quota),
+ find_filter=bucket_filter,
+ )
+ for target in targets
+ )
+ else:
+ searches = [
+ _find(
+ query=query,
+ find_ctx=ctx,
+ target_uri=target,
+ find_limit=_overfetch(quota),
+ find_filter=bucket_filter,
+ )
+ for query in planned
+ for target in targets
+ ]
peer_offset = len(searches)
if peer_scope == "all" and bucket in MEMORY_CATEGORIES:
searches.extend(
@@ -332,6 +383,8 @@ async def gather_candidates(
found = dedupe_keep_best(found)
searched[bucket] = len(found)
candidates = _build([(item, bucket) for item in found])
+ if bucket == "skills":
+ candidates = _dedupe_candidates(candidates)
candidates.sort(key=_rank_key, reverse=True)
return candidates[: max(0, quota)]
@@ -376,6 +429,12 @@ async def gather_candidates(
found = dedupe_keep_best(found)
searched["all"] = len(found)
candidates = _build([(item, buckets.get(_uri(item))) for item in found])
+ # Only skills collapse here. Merging the other categories before the cut
+ # would hand them quota they never had in this mode.
+ skills = [c for c in candidates if c.category == "skills"]
+ if skills:
+ candidates = [c for c in candidates if c.category != "skills"]
+ candidates.extend(_dedupe_candidates(skills))
candidates.sort(key=_rank_key, reverse=True)
return candidates[: max(0, limit)]
@@ -388,6 +447,8 @@ async def gather_candidates(
candidates = _dedupe_candidates(candidates)
candidates.sort(key=_rank_key, reverse=True)
+ candidates = await _fill_skill_abstracts(service, candidates)
+
origins = dict.fromkeys(ORIGIN_ORDER, 0)
for candidate in candidates:
origins[candidate.origin] = origins.get(candidate.origin, 0) + 1
@@ -405,6 +466,31 @@ async def gather_candidates(
return candidates, stats
+async def _fill_skill_abstracts(service: Any, candidates: List[Candidate]) -> List[Candidate]:
+ """Describe each skill entry with its package abstract rather than the file that matched."""
+ wanted = [
+ index
+ for index, candidate in enumerate(candidates)
+ if candidate.category == "skills" and not candidate.abstract.strip()
+ ]
+ if not wanted:
+ return candidates
+ semaphore = asyncio.Semaphore(READ_CONCURRENCY)
+
+ async def read_one(index: int) -> Tuple[int, str]:
+ candidate = candidates[index]
+ async with semaphore:
+ abstract = await package_abstract(
+ service.fs, candidate.read_ctx, skill_root_uri(candidate.base_uri)
+ )
+ return index, abstract
+
+ for index, abstract in await asyncio.gather(*(read_one(index) for index in wanted)):
+ if abstract:
+ candidates[index] = replace(candidates[index], abstract=abstract)
+ return candidates
+
+
def _rank_key(candidate: Candidate) -> Tuple[float, int]:
origin_rank = {origin: index for index, origin in enumerate(ORIGIN_ORDER)}
return (candidate.ranked_score, -origin_rank.get(candidate.origin, len(origin_rank)))
diff --git a/openviking/retrieve/skill_results.py b/openviking/retrieve/skill_results.py
index f8ed5e9e7..932cb4b64 100644
--- a/openviking/retrieve/skill_results.py
+++ b/openviking/retrieve/skill_results.py
@@ -11,6 +11,9 @@ from openviking_cli.exceptions import PermissionDeniedError
from openviking_cli.retrieve.types import ContextType, MatchedContext
LEVEL_SUFFIXES = ("/.abstract.md", "/.overview.md")
+# Tail of the placeholder VikingFS returns for a directory whose .abstract.md
+# has not been generated yet.
+ABSTRACT_NOT_READY = "[Directory abstract is not ready]"
def skill_root_uri(uri: str) -> str:
@@ -36,6 +39,17 @@ def skill_root_uri(uri: str) -> str:
return "viking://" + "/".join(shape.parts[: index + 2])
+async def package_abstract(fs: Any, ctx: RequestContext, root: str) -> str:
+ """Return a Skill package's own abstract, or "" when it has none yet."""
+ try:
+ text = str(await fs.abstract(root, ctx=ctx) or "").strip()
+ except Exception:
+ return ""
+ if text.endswith(ABSTRACT_NOT_READY):
+ return ""
+ return text
+
+
def candidate_key(candidate: Dict[str, Any]) -> Any:
"""Keep Skill directory levels distinct until their final scores are known."""
uri = candidate.get("uri", "")
diff --git a/openviking/service/search_service.py b/openviking/service/search_service.py
index 790201fe4..4dabb67cd 100644
--- a/openviking/service/search_service.py
+++ b/openviking/service/search_service.py
@@ -183,8 +183,9 @@ class SearchService:
limit: int = 10,
score_threshold: Optional[float] = None,
level: Optional[List[int]] = None,
+ filter: Optional[Dict] = None,
) -> Any:
- """Find distinct packages for /skills/find; general find/search stay item-based."""
+ """Find distinct packages; general find/search stay item-based."""
from openviking.core.retrieval_targets import resolve_retrieval_targets
from openviking.retrieve.skill_package_retriever import SkillPackageRetriever
from openviking.retrieve.skill_results import SkillResultResolver
@@ -201,7 +202,10 @@ class SearchService:
if not embedder:
raise RuntimeError("Embedder not configured.")
retriever = SkillPackageRetriever(
- storage=storage, embedder=embedder, retrieval_config=fs.retrieval_config
+ storage=storage,
+ embedder=embedder,
+ rerank_config=fs.rerank_config,
+ retrieval_config=fs.retrieval_config,
)
result = await retriever.retrieve_skills(
TypedQuery(query, ContextType.SKILL, "", target_directories=targets),
@@ -210,5 +214,6 @@ class SearchService:
limit=limit,
score_threshold=score_threshold,
level=level,
+ scope_dsl=filter,
)
return FindResult(memories=[], resources=[], skills=result.matched_contexts)
diff --git a/tests/retrieve/test_context_assembler_pipeline.py b/tests/retrieve/test_context_assembler_pipeline.py
index 7c852e954..8012788a9 100644
--- a/tests/retrieve/test_context_assembler_pipeline.py
+++ b/tests/retrieve/test_context_assembler_pipeline.py
@@ -27,6 +27,10 @@ from openviking.server.identity import RequestContext, Role
from openviking_cli.session.user_id import UserIdentifier
USER_ROOT = "viking://user/test_user"
+SKILLS_ROOT = f"{USER_ROOT}/skills"
+DEPLOY = f"{SKILLS_ROOT}/deploy"
+REVIEW = f"{SKILLS_ROOT}/review"
+NOT_READY = "# {uri} [Directory abstract is not ready]"
def _ctx():
@@ -44,7 +48,9 @@ class _FakeFindResult:
self.skills = skills or []
-def _service(*, hits, bodies, session=None):
+def _service(*, hits, bodies, session=None, abstracts=None):
+ abstracts = abstracts or {}
+
async def fake_find(**kwargs):
del kwargs
return _FakeFindResult(list(hits))
@@ -55,6 +61,10 @@ def _service(*, hits, bodies, session=None):
raise FileNotFoundError(uri)
return bodies[uri]
+ async def fake_abstract(uri, **kwargs):
+ del kwargs
+ return abstracts.get(uri, NOT_READY.format(uri=uri))
+
async def fake_get(session_id, ctx, *, auto_create=False):
del session_id, ctx
assert auto_create is True
@@ -62,7 +72,7 @@ def _service(*, hits, bodies, session=None):
return SimpleNamespace(
search=SimpleNamespace(find=fake_find),
- fs=SimpleNamespace(read=fake_read),
+ fs=SimpleNamespace(read=fake_read, abstract=fake_abstract),
sessions=SimpleNamespace(get=fake_get),
viking_fs=None,
)
@@ -286,27 +296,33 @@ async def test_purpose_quotas_are_not_truncated_by_global_limit():
}
]
)
- if target_uri.endswith("/skills"):
- scope = "agent" if target_uri.startswith("viking://agent/") else "user"
- return _FakeFindResult(
- skills=[
- {
- "uri": f"{target_uri}/{scope}.md",
- "score": 0.86,
- "abstract": f"{scope} skill",
- "level": 2,
- }
- ]
- )
return _FakeFindResult()
+ async def fake_find_skills(**kwargs):
+ skills = []
+ for root in kwargs["target_uri"]:
+ scope = "agent" if root.startswith("viking://agent/") else "user"
+ skills.append(
+ {
+ "uri": f"{root}/{scope}-skill/scripts/run.py",
+ "score": 0.86,
+ "abstract": f"{scope} script",
+ "level": 2,
+ }
+ )
+ return _FakeFindResult(skills=skills)
+
async def fake_read(uri, **kwargs):
del kwargs
return f"# Summary\n{uri}"
+ async def fake_abstract(uri, **kwargs):
+ del kwargs
+ return f"name: {uri.rsplit('/', 1)[-1]}"
+
service = SimpleNamespace(
- search=SimpleNamespace(find=fake_find),
- fs=SimpleNamespace(read=fake_read),
+ search=SimpleNamespace(find=fake_find, find_skills=fake_find_skills),
+ fs=SimpleNamespace(read=fake_read, abstract=fake_abstract),
sessions=SimpleNamespace(),
viking_fs=None,
)
@@ -323,6 +339,10 @@ async def test_purpose_quotas_are_not_truncated_by_global_limit():
)
assert len(result.entries) == 10
+ assert [entry.uri for entry in result.entries if entry.category == "skills"] == [
+ f"{USER_ROOT}/skills/user-skill/SKILL.md",
+ "viking://agent/skills/agent-skill/SKILL.md",
+ ]
assert result.stats["quotas"] == {
"events": 1,
"entities": 2,
@@ -597,3 +617,292 @@ async def test_no_relevant_digest_keeps_uris_out_of_the_dedup_ledger(monkeypatch
assert result.rendered == ""
assert len(result.entries) == 1
assert recorded == []
+
+
+def _skill_hit(uri, score, abstract="hit abstract", level=2):
+ return {"uri": uri, "score": score, "abstract": abstract, "level": level}
+
+
+def _skill_service(hits, abstracts=None, *, finds=None, reads=None, bodies=None):
+ """A service whose every package search answers with the same skill hits."""
+ abstracts = abstracts or {}
+
+ async def fake_find_skills(**kwargs):
+ if finds is not None:
+ finds.append(kwargs)
+ return _FakeFindResult(skills=list(hits))
+
+ async def fake_abstract(uri, **kwargs):
+ del kwargs
+ if reads is not None:
+ reads.append(uri)
+ return abstracts.get(uri, NOT_READY.format(uri=uri))
+
+ async def fake_read(uri, **kwargs):
+ del kwargs
+ if bodies is None or uri not in bodies:
+ raise AssertionError(f"a skill entry must not read a body: {uri}")
+ return bodies[uri]
+
+ return SimpleNamespace(
+ search=SimpleNamespace(find_skills=fake_find_skills),
+ fs=SimpleNamespace(read=fake_read, abstract=fake_abstract),
+ sessions=SimpleNamespace(),
+ viking_fs=None,
+ )
+
+
+async def _assemble_skills(service, **overrides):
+ params = {"query": "how do I deploy", "quotas": {"skills": 2}, "peer_scope": "actor"}
+ params.update(overrides)
+ return await assemble_context(service=service, ctx=_ctx(), params=AssembleParams(**params))
+
+
+async def test_every_hit_in_a_package_collapses_into_one_skill_entry():
+ reads = []
+ service = _skill_service(
+ [
+ _skill_hit(f"{DEPLOY}/.abstract.md", 0.6, "stale package abstract", level=0),
+ _skill_hit(f"{DEPLOY}/SKILL.md", 0.7, "skill file abstract"),
+ _skill_hit(f"{DEPLOY}/scripts/run.py", 0.8, "run script"),
+ _skill_hit(f"{REVIEW}/SKILL.md", 0.5, "review file abstract"),
+ ],
+ {
+ DEPLOY: "name: deploy\ndescription: ship the service",
+ REVIEW: "name: review\ndescription: read diffs",
+ },
+ reads=reads,
+ )
+
+ result = await _assemble_skills(service)
+
+ assert [(entry.uri, entry.score, entry.detail, entry.text) for entry in result.entries] == [
+ (f"{DEPLOY}/SKILL.md", 0.8, "abstract", "name: deploy\ndescription: ship the service"),
+ (f"{REVIEW}/SKILL.md", 0.5, "abstract", "name: review\ndescription: read diffs"),
+ ]
+ assert sorted(reads) == [DEPLOY, REVIEW]
+
+
+async def test_a_hit_on_the_package_abstract_needs_no_extra_read():
+ reads = []
+ service = _skill_service(
+ [_skill_hit(f"{DEPLOY}/.abstract.md", 0.6, "name: deploy", level=0)],
+ reads=reads,
+ )
+
+ result = await _assemble_skills(service)
+
+ assert [(entry.uri, entry.detail, entry.text) for entry in result.entries] == [
+ (f"{DEPLOY}/SKILL.md", "abstract", "name: deploy")
+ ]
+ assert reads == []
+
+
+async def test_package_without_a_generated_abstract_degrades_to_a_bare_uri():
+ """The matched file's own summary never stands in for the package's."""
+ service = _skill_service([_skill_hit(f"{DEPLOY}/scripts/run.py", 0.8, "run script")])
+
+ result = await _assemble_skills(service)
+
+ assert [(entry.uri, entry.detail, entry.text) for entry in result.entries] == [
+ (f"{DEPLOY}/SKILL.md", "uri", "")
+ ]
+
+
+async def test_skills_root_and_backup_hits_produce_no_entry():
+ service = _skill_service(
+ [
+ _skill_hit(f"{SKILLS_ROOT}/.abstract.md", 0.9, "every skill", level=0),
+ _skill_hit(f"{SKILLS_ROOT}/.backup-20260101/SKILL.md", 0.8, "replaced copy"),
+ ]
+ )
+
+ result = await _assemble_skills(service)
+
+ assert result.entries == []
+
+
+async def test_excluding_a_package_drops_a_hit_on_any_file_inside_it():
+ service = _skill_service([_skill_hit(f"{DEPLOY}/references/a.md", 0.8, "reference")])
+
+ result = await _assemble_skills(service, exclude_uris=[f"{DEPLOY}/SKILL.md"])
+
+ assert result.entries == []
+ assert result.stats["excluded"] == 1
+
+
+async def test_a_pinned_detail_reads_the_package_skill_md():
+ """A package entry is a file, not a directory: `detail` reaches its SKILL.md."""
+ service = _skill_service(
+ # The package's own overview record, the one hit shape that would
+ # otherwise stay a directory and pin every skill entry to overview.
+ [_skill_hit(f"{DEPLOY}/.overview.md", 0.8, "package overview", level=1)],
+ {DEPLOY: "name: deploy"},
+ bodies={f"{DEPLOY}/SKILL.md": "# Deploy\n\nRun the pipeline, then verify."},
+ )
+
+ result = await _assemble_skills(service, detail={"skills": "full"})
+
+ assert [(entry.uri, entry.detail, entry.text) for entry in result.entries] == [
+ (f"{DEPLOY}/SKILL.md", "full", "# Deploy\n\nRun the pipeline, then verify."),
+ ]
+
+
+async def test_skills_bucket_searches_both_roots_once_per_query():
+ """One package search spans both roots and stops at `limit` distinct packages."""
+ finds = []
+ service = _skill_service([], finds=finds)
+
+ await _assemble_skills(service)
+
+ assert len(finds) == 1
+ assert finds[0]["target_uri"] == [SKILLS_ROOT, "viking://agent/skills"]
+ assert finds[0]["limit"] == 2
+
+
+async def test_skills_bucket_forwards_the_caller_filter():
+ finds = []
+ service = _skill_service([], finds=finds)
+
+ await _assemble_skills(service, filter={"op": "must", "field": "tags", "conds": ["ops"]})
+
+ assert {"op": "must", "field": "tags", "conds": ["ops"]} in finds[0]["filter"]["conds"]
+
+
+async def test_a_filter_only_query_stays_on_the_generic_path():
+ """Package retrieval embeds its query; a filter-only lookup has none to embed."""
+ calls = []
+
+ async def fake_find(**kwargs):
+ calls.append(("find", kwargs["target_uri"]))
+ return _FakeFindResult(skills=[_skill_hit(f"{DEPLOY}/scripts/run.py", 0.8, "run script")])
+
+ async def fake_find_skills(**kwargs):
+ calls.append(("find_skills", kwargs["target_uri"]))
+ return _FakeFindResult()
+
+ async def fake_abstract(uri, **kwargs):
+ del kwargs
+ return "name: deploy" if uri == DEPLOY else NOT_READY.format(uri=uri)
+
+ service = SimpleNamespace(
+ search=SimpleNamespace(find=fake_find, find_skills=fake_find_skills),
+ fs=SimpleNamespace(read=None, abstract=fake_abstract),
+ sessions=SimpleNamespace(),
+ viking_fs=None,
+ )
+
+ result = await _assemble_skills(
+ service, query="", filter={"op": "must", "field": "tags", "conds": ["ops"]}
+ )
+
+ assert [name for name, _ in calls] == ["find", "find"]
+ assert [target for _, target in calls] == [f"{USER_ROOT}/skills", "viking://agent/skills"]
+ assert [(entry.uri, entry.text) for entry in result.entries] == [
+ (f"{DEPLOY}/SKILL.md", "name: deploy"),
+ ]
+
+
+async def test_a_failed_skills_search_leaves_the_request_standing():
+ async def fake_find_skills(**kwargs):
+ del kwargs
+ raise RuntimeError("embedder unavailable")
+
+ service = SimpleNamespace(
+ search=SimpleNamespace(find_skills=fake_find_skills),
+ fs=SimpleNamespace(read=None, abstract=None),
+ sessions=SimpleNamespace(),
+ viking_fs=None,
+ )
+
+ result = await _assemble_skills(service)
+
+ assert result.entries == []
+ assert result.stats["retrieval_errors"] == ["RuntimeError: embedder unavailable"]
+
+
+async def test_an_image_only_query_skips_the_skills_bucket():
+ """find_skills rejects a query with nothing to search on; the bucket stays empty instead."""
+ finds = []
+ service = _skill_service([_skill_hit(f"{DEPLOY}/SKILL.md", 0.8, "name: deploy")], finds=finds)
+
+ result = await _assemble_skills(
+ service, query="", image_url="https://example.com/screenshot.png"
+ )
+
+ assert finds == []
+ assert result.entries == []
+
+
+async def test_skills_and_memories_share_one_score_threshold():
+ calls = []
+
+ async def fake_find(**kwargs):
+ calls.append(("find", kwargs))
+ return _FakeFindResult()
+
+ async def fake_find_skills(**kwargs):
+ calls.append(("find_skills", kwargs))
+ return _FakeFindResult()
+
+ service = SimpleNamespace(
+ search=SimpleNamespace(find=fake_find, find_skills=fake_find_skills),
+ fs=SimpleNamespace(),
+ sessions=SimpleNamespace(),
+ viking_fs=None,
+ )
+ await assemble_context(
+ service=service,
+ ctx=_ctx(),
+ params=AssembleParams(
+ query="how do I deploy",
+ quotas={"skills": 1, "events": 1},
+ peer_scope="actor",
+ ),
+ )
+
+ thresholds = {name: kwargs["score_threshold"] for name, kwargs in calls}
+ assert thresholds == {"find": None, "find_skills": None}
+
+
+async def test_flat_retrieval_collapses_skills_and_leaves_other_hits_alone():
+ events_dir = f"{USER_ROOT}/memories/events/2026-09"
+ memories = [
+ {"uri": f"{events_dir}/.abstract.md", "score": 0.55, "abstract": "month abstract"},
+ {"uri": f"{events_dir}/.overview.md", "score": 0.5, "abstract": "month overview"},
+ ]
+ skills = [
+ _skill_hit(f"{DEPLOY}/.abstract.md", 0.6, "name: deploy", level=0),
+ _skill_hit(f"{DEPLOY}/SKILL.md", 0.7, "skill file abstract"),
+ _skill_hit(f"{DEPLOY}/scripts/run.py", 0.8, "run script"),
+ ]
+
+ async def fake_find(**kwargs):
+ del kwargs
+ return _FakeFindResult(memories=list(memories), skills=list(skills))
+
+ async def fake_read(uri, **kwargs):
+ del kwargs
+ return "September, in outline."
+
+ async def fake_abstract(uri, **kwargs):
+ del kwargs
+ return "name: deploy\ndescription: ship the service" if uri == DEPLOY else ""
+
+ service = SimpleNamespace(
+ search=SimpleNamespace(find=fake_find),
+ fs=SimpleNamespace(read=fake_read, abstract=fake_abstract),
+ sessions=SimpleNamespace(),
+ viking_fs=None,
+ )
+ result = await assemble_context(
+ service=service,
+ ctx=_ctx(),
+ params=AssembleParams(query="what happened", limit=10, peer_scope="actor"),
+ )
+
+ # Three skill records became one candidate; the two memory sidecars still
+ # take a candidate slot each and only meet the existing body-level dedup.
+ assert result.stats["candidates"] == 3
+ assert [entry.uri for entry in result.entries] == [f"{DEPLOY}/SKILL.md", events_dir]
+ assert result.stats["deduped"] == 1
diff --git a/tests/retrieve/test_skill_package_results.py b/tests/retrieve/test_skill_package_results.py
index 0b2305fff..67dba4dfb 100644
--- a/tests/retrieve/test_skill_package_results.py
+++ b/tests/retrieve/test_skill_package_results.py
@@ -7,6 +7,7 @@ import pytest
from openviking.retrieve.skill_package_retriever import SkillPackageRetriever
from openviking.retrieve.skill_results import (
SkillResultResolver,
+ package_abstract,
skill_root_uri,
)
from openviking.server.identity import RequestContext, Role
@@ -184,3 +185,36 @@ async def test_scoped_hits_preserve_requested_level_and_do_not_use_outside_score
assert matched.score == score
assert matched.abstract == abstract
assert store.calls[0]["extra_filter"] is filters
+
+
+class _AbstractFs:
+ """Only the accessor `package_abstract` uses, so a stray read is a failure."""
+
+ def __init__(self, answer):
+ self.answer = answer
+ self.calls = []
+
+ async def abstract(self, uri, ctx=None):
+ self.calls.append((uri, ctx))
+ if isinstance(self.answer, Exception):
+ raise self.answer
+ return self.answer
+
+
+ ("answer", "expected"),
+ [
+ ("name: demo\ndescription: do things", "name: demo\ndescription: do things"),
+ (f"# {SKILLS}/demo [Directory abstract is not ready]", ""),
+ ("", ""),
+ (NotFoundError(f"{SKILLS}/demo"), ""),
+ (PermissionDeniedError("denied", resource=f"{SKILLS}/demo"), ""),
+ ],
+)
+async def test_package_abstract_reports_only_a_generated_abstract(answer, expected):
+ fs = _AbstractFs(answer)
+ request_ctx = ctx()
+
+ assert await package_abstract(fs, request_ctx, f"{SKILLS}/demo") == expected
+ assert fs.calls == [(f"{SKILLS}/demo", request_ctx)]
diff --git a/tests/server/test_api_search_context.py b/tests/server/test_api_search_context.py
index fb1653d6f..e5f7670fa 100644
--- a/tests/server/test_api_search_context.py
+++ b/tests/server/test_api_search_context.py
@@ -68,12 +68,18 @@ async def test_context_mode_quotas_use_category_ownership_roots(
monkeypatch,
):
targets = []
+ skill_targets = []
async def fake_find(**kwargs):
targets.append(kwargs["target_uri"])
return _FakeFindResult()
+ async def fake_find_skills(**kwargs):
+ skill_targets.append(kwargs["target_uri"])
+ return _FakeFindResult()
+
monkeypatch.setattr(service.search, "find", fake_find)
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
response = await client.post(
"/api/v1/search/search",
json={
@@ -86,8 +92,7 @@ async def test_context_mode_quotas_use_category_ownership_roots(
assert response.status_code == 200
assert any(target.endswith("/memories/events") for target in targets)
- assert any(target.endswith("/user/default/skills") for target in targets)
- assert "viking://agent/skills" in targets
+ assert skill_targets == [["viking://user/default/skills", "viking://agent/skills"]]
async def test_coding_purpose_searches_all_domains_and_actor_resource(
@@ -96,12 +101,18 @@ async def test_coding_purpose_searches_all_domains_and_actor_resource(
monkeypatch,
):
calls = []
+ skill_targets = []
async def fake_find(**kwargs):
calls.append(kwargs)
return _FakeFindResult()
+ async def fake_find_skills(**kwargs):
+ skill_targets.append(kwargs["target_uri"])
+ return _FakeFindResult()
+
monkeypatch.setattr(service.search, "find", fake_find)
+ monkeypatch.setattr(service.search, "find_skills", fake_find_skills)
response = await client.post(
"/api/v1/search/search",
headers={"X-OpenViking-Actor-Peer": "current"},
@@ -122,7 +133,7 @@ async def test_coding_purpose_searches_all_domains_and_actor_resource(
assert any(target.endswith("/memories/experiences") for target in targets)
assert "viking://resources" in targets
assert any(target.endswith("/peers/current/resources") for target in targets)
- assert any(target.endswith("/skills") for target in targets)
+ assert skill_targets == [["viking://user/default/skills", "viking://agent/skills"]]
assert response.json()["result"]["stats"]["quotas"] == {
"events": 1,
"entities": 2,
diff --git a/tests/unit/test_find_skills_entrypoint.py b/tests/unit/test_find_skills_entrypoint.py
new file mode 100644
index 000000000..bc7936106
--- /dev/null
+++ b/tests/unit/test_find_skills_entrypoint.py
@@ -0,0 +1,78 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""What SearchService.find_skills hands the package retriever."""
+
+from types import SimpleNamespace
+
+import pytest
+
+from openviking.retrieve import skill_package_retriever
+from openviking.server.identity import RequestContext, Role
+from openviking.service.search_service import SearchService
+from openviking_cli.exceptions import InvalidArgumentError
+from openviking_cli.session.user_id import UserIdentifier
+
+SKILLS = "viking://agent/skills"
+TAG_FILTER = {"op": "must", "field": "search_tags", "conds": ["team=infra"]}
+
+
+def _ctx():
+ return RequestContext(user=UserIdentifier.the_default_user("test_user"), role=Role.USER)
+
+
+def seen(monkeypatch):
+ captured = {}
+
+ class _Retriever:
+ def __init__(self, **kwargs):
+ captured["init"] = kwargs
+
+ async def retrieve_skills(self, query, ctx, **kwargs):
+ captured["retrieve"] = kwargs
+ return SimpleNamespace(matched_contexts=[])
+
+ monkeypatch.setattr(skill_package_retriever, "SkillPackageRetriever", _Retriever)
+ return captured
+
+
+def _service(rerank_config):
+ async def ensure_scope(target, ctx):
+ return None
+
+ fs = SimpleNamespace(
+ _ensure_retrieval_scope=ensure_scope,
+ _get_vector_store=lambda: object(),
+ _get_embedder=lambda: object(),
+ rerank_config=rerank_config,
+ retrieval_config=None,
+ )
+ return SearchService(fs)
+
+
+async def test_find_skills_applies_the_configured_rerank_threshold(seen):
+ """Without the rerank config the package floor is 0 while general find sits at 0.1."""
+ rerank_config = SimpleNamespace(threshold=0.1)
+
+ await _service(rerank_config).find_skills(query="deploy", ctx=_ctx(), target_uri=SKILLS)
+
+ assert seen["init"]["rerank_config"] is rerank_config
+
+
+async def test_find_skills_forwards_the_filter_as_the_retrieval_scope(seen):
+ await _service(None).find_skills(
+ query="deploy", ctx=_ctx(), target_uri=SKILLS, filter=TAG_FILTER
+ )
+
+ assert seen["retrieve"]["scope_dsl"] == TAG_FILTER
+
+
[email protected]("query", ["", " "])
+async def test_find_skills_needs_a_query_even_with_a_filter(seen, query):
+ """It embeds the query, so a filter cannot stand in the way it can on find."""
+ with pytest.raises(InvalidArgumentError):
+ await _service(None).find_skills(
+ query=query, ctx=_ctx(), target_uri=SKILLS, filter=TAG_FILTER
+ )
+
+ assert seen == {}