Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat (symphony): 支持依赖感知检索

xutuo60d73ac53944
diff --git a/jiuwenswarm/symphony/indexing/catalog/records.py b/jiuwenswarm/symphony/indexing/catalog/records.py
index 4a4e33ce9d..4c1dc278c2 100644
--- a/jiuwenswarm/symphony/indexing/catalog/records.py
+++ b/jiuwenswarm/symphony/indexing/catalog/records.py
@@ -15,6 +15,7 @@ class CatalogRecord:
category: str
retrieval_text: str
metadata: Dict[str, object]
+ tags: tuple[str, ...] = ()
__all__ = ["CatalogRecord"]
diff --git a/jiuwenswarm/symphony/indexing/doc.md b/jiuwenswarm/symphony/indexing/doc.md
index 8fdb96ef6a..adab230ddc 100644
--- a/jiuwenswarm/symphony/indexing/doc.md
+++ b/jiuwenswarm/symphony/indexing/doc.md
@@ -12,6 +12,11 @@ Given skill/plugin material directories or pre-scanned JSONL, it builds the tree
- `catalog.jsonl`
- `manifest.json`
+Each candidate can carry normalized tags. Directory builds read `tags` from
+`SKILL.md` frontmatter, while pre-scanned JSONL builds read `tags` from
+`contentExtendParam`. Tags are written to each `catalog.jsonl` row, while
+`manifest.json.tag_counts` summarizes the available filter values.
+
## Main Components
### `indexing/tree/`
diff --git a/jiuwenswarm/symphony/indexing/io/catalog.py b/jiuwenswarm/symphony/indexing/io/catalog.py
index 8cb4aa95fe..504e8879e0 100644
--- a/jiuwenswarm/symphony/indexing/io/catalog.py
+++ b/jiuwenswarm/symphony/indexing/io/catalog.py
@@ -5,6 +5,7 @@ from pathlib import Path
from typing import List
from indexing.catalog.records import CatalogRecord
+from shared.tags import normalize_tags
def load_catalog_records(path: Path) -> List[CatalogRecord]:
@@ -16,6 +17,7 @@ def load_catalog_records(path: Path) -> List[CatalogRecord]:
continue
payload = json.loads(line)
worker_id = str(payload.get("worker_id") or payload.get("skill_id") or "")
+ metadata = dict(payload.get("metadata") or {})
records.append(
CatalogRecord(
worker_id=worker_id,
@@ -26,7 +28,8 @@ def load_catalog_records(path: Path) -> List[CatalogRecord]:
branch_path=tuple(str(item) for item in payload.get("branch_path") or ()),
category=str(payload.get("category") or ""),
retrieval_text=str(payload.get("retrieval_text") or ""),
- metadata=dict(payload.get("metadata") or {}),
+ metadata=metadata,
+ tags=normalize_tags(payload.get("tags"), metadata.get("tags")),
)
)
return records
diff --git a/jiuwenswarm/symphony/indexing/io/items_jsonl.py b/jiuwenswarm/symphony/indexing/io/items_jsonl.py
index b5466a7e0e..df7f30fce3 100644
--- a/jiuwenswarm/symphony/indexing/io/items_jsonl.py
+++ b/jiuwenswarm/symphony/indexing/io/items_jsonl.py
@@ -7,6 +7,7 @@ from urllib.parse import urlparse
from urllib.request import urlopen
from shared.storage import is_s3_uri, read_s3_text
+from shared.tags import normalize_tags
LOGGER = logging.getLogger("index_builder")
@@ -113,6 +114,7 @@ def parse_jsonl_scanned_items(jsonl_content: str) -> tuple[dict[str, dict], list
"stars": stars,
"is_official": bool(content_extend.get("isOfficial", content_extend.get("is_official", False))),
"author": str(content_extend.get("author") or ""),
+ "tags": list(normalize_tags(content_extend.get("tags"))),
"content_extend_param": dict(content_extend),
}
if source_path not in seen_paths:
diff --git a/jiuwenswarm/symphony/indexing/io/manifest.py b/jiuwenswarm/symphony/indexing/io/manifest.py
index e22f4db4aa..6aedb00fc3 100644
--- a/jiuwenswarm/symphony/indexing/io/manifest.py
+++ b/jiuwenswarm/symphony/indexing/io/manifest.py
@@ -1,11 +1,13 @@
from __future__ import annotations
import json
+from collections import Counter
from pathlib import Path
from typing import Dict, Sequence
from indexing.catalog.records import CatalogRecord
from indexing.io.items_jsonl import is_passthrough_item_uri
+from shared.tags import normalize_tags
def write_manifest(
@@ -21,6 +23,15 @@ def write_manifest(
"count": len(records),
"item_paths": [_serialize_item_path(path) for path in item_paths],
"worker_ids": [record.worker_id for record in records],
+ "tag_counts": dict(
+ sorted(
+ Counter(
+ tag
+ for record in records
+ for tag in normalize_tags(record.tags, record.metadata.get("tags"))
+ ).items()
+ )
+ ),
}
if item_type:
manifest["item_type"] = str(item_type)
diff --git a/jiuwenswarm/symphony/indexing/scanners/base.py b/jiuwenswarm/symphony/indexing/scanners/base.py
index 1c76d1b1e9..32b0ec7762 100644
--- a/jiuwenswarm/symphony/indexing/scanners/base.py
+++ b/jiuwenswarm/symphony/indexing/scanners/base.py
@@ -5,6 +5,7 @@ from dataclasses import dataclass
from pathlib import Path
from shared.rich_compat import BarColumn, Console, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
+from shared.tags import normalize_tags
console = Console()
@@ -23,6 +24,7 @@ class ScannedItem:
stars: int = 0
is_official: bool = False
author: str = ""
+ tags: tuple[str, ...] = ()
def to_dict(self) -> dict[str, object]:
return {
@@ -36,6 +38,7 @@ class ScannedItem:
"stars": self.stars,
"is_official": self.is_official,
"author": self.author,
+ "tags": list(normalize_tags(self.tags)),
}
diff --git a/jiuwenswarm/symphony/indexing/scanners/skill.py b/jiuwenswarm/symphony/indexing/scanners/skill.py
index 039bffbdc2..b493501898 100644
--- a/jiuwenswarm/symphony/indexing/scanners/skill.py
+++ b/jiuwenswarm/symphony/indexing/scanners/skill.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import json
from pathlib import Path
+from shared.tags import normalize_tags
+
from .base import BaseScanner, ScannedItem, console
from .common import clean_first_paragraph, parse_frontmatter
@@ -33,6 +35,7 @@ class SkillScanner(BaseScanner):
"stars": item.get("stars", 0),
"is_official": item.get("is_official", False),
"author": item.get("author", ""),
+ "tags": normalize_tags(item.get("tags")),
}
@classmethod
@@ -77,4 +80,8 @@ class SkillScanner(BaseScanner):
stars=int(meta.get("stars") or 0),
is_official=bool(meta.get("is_official")),
author=str(meta.get("author") or ""),
+ tags=normalize_tags(
+ frontmatter.get("tags"),
+ meta.get("tags"),
+ ),
)
diff --git a/jiuwenswarm/symphony/indexing/workflows/artifacts.py b/jiuwenswarm/symphony/indexing/workflows/artifacts.py
index c2fece8b02..4790d031b8 100644
--- a/jiuwenswarm/symphony/indexing/workflows/artifacts.py
+++ b/jiuwenswarm/symphony/indexing/workflows/artifacts.py
@@ -13,6 +13,7 @@ except Exception:
from indexing.catalog.records import CatalogRecord
from indexing.tree.root_categories import RootCategoryInput, resolve_tree_root_categories
+from shared.tags import normalize_tags
class BuildMethod(IntFlag):
@@ -252,6 +253,10 @@ def build_catalog_records_from_nodes(
select_when = str(raw_node.get("select_when") or "").strip()
dont_select_when = str(raw_node.get("dont_select_when") or "").strip()
skill_path = str(scanned.get("path") or "")
+ # Scanner outputs expose one canonical, normalized tag field. In
+ # particular, the JSONL scanner has already merged top-level and
+ # contentExtendParam tag/device fields into this value.
+ tags = normalize_tags(scanned.get("tags"))
records.append(
CatalogRecord(
worker_id=worker_id,
@@ -273,7 +278,9 @@ def build_catalog_records_from_nodes(
"source_description": source_description,
"select_when": select_when,
"dont_select_when": dont_select_when,
+ "tags": list(tags),
},
+ tags=tags,
)
)
return sorted(records, key=lambda item: item.cid)
@@ -299,6 +306,7 @@ def write_catalog(records: Sequence[CatalogRecord], path: Path) -> None:
"category": record.category,
"retrieval_text": record.retrieval_text,
"metadata": record.metadata,
+ "tags": list(normalize_tags(record.tags, record.metadata.get("tags"))),
},
ensure_ascii=False,
)
diff --git a/jiuwenswarm/symphony/indexing/workflows/tree_ops.py b/jiuwenswarm/symphony/indexing/workflows/tree_ops.py
index 11e4bd9229..ef0cee9f7c 100644
--- a/jiuwenswarm/symphony/indexing/workflows/tree_ops.py
+++ b/jiuwenswarm/symphony/indexing/workflows/tree_ops.py
@@ -133,6 +133,7 @@ def build_catalog_records_from_existing(
category=record.category,
retrieval_text=record.retrieval_text,
metadata=dict(record.metadata),
+ tags=tuple(record.tags),
)
)
return sorted(records, key=lambda item: item.cid)
diff --git a/jiuwenswarm/symphony/retrieval/algorithm.md b/jiuwenswarm/symphony/retrieval/algorithm.md
index 970ba7de2f..698cbe6ef6 100644
--- a/jiuwenswarm/symphony/retrieval/algorithm.md
+++ b/jiuwenswarm/symphony/retrieval/algorithm.md
@@ -32,11 +32,12 @@ Input:
Process:
-1. start from the current visible subtree
-2. if the structure is trivial, use deterministic shortcuts
-3. otherwise ask the LLM to choose among the current visible boundary nodes
-4. recurse into selected branches or terminate on selected items
-5. reduce branch results to the requested `top_k`
+1. apply request tag filters to catalog leaves and prune empty tree branches
+2. start from the resulting visible subtree
+3. if the structure is trivial, use deterministic shortcuts
+4. otherwise ask the LLM to choose among the current visible boundary nodes
+5. recurse into selected branches or terminate on selected items
+6. reduce branch results to the requested `top_k`
Important rules:
diff --git a/jiuwenswarm/symphony/retrieval/doc.md b/jiuwenswarm/symphony/retrieval/doc.md
index fa406e004b..a803972423 100644
--- a/jiuwenswarm/symphony/retrieval/doc.md
+++ b/jiuwenswarm/symphony/retrieval/doc.md
@@ -45,12 +45,22 @@ The canonical route uses the progressive tree index:
Typical usage:
```python
-from retrieval.service.retriever import Retriever
+from retrieval.service import RequestConfig, Retriever
retriever = Retriever.from_index("/abs/path/to/index")
-payloads = retriever.search("find tools for browser automation", top_k=5)
+payloads = retriever.search(
+ "find tools for browser automation",
+ search_config=RequestConfig(top_k=5, tags=("mobile",)),
+)
```
+Tag filtering is a deterministic pre-filter: disallowed leaves and their empty
+ancestor branches are removed before the first LLM routing call. With an empty
+`tags` tuple, retrieval uses the complete tree. With a non-empty tuple,
+untagged candidates are excluded and candidates tagged `all` remain eligible by
+default. A candidate must contain every requested tag unless it carries the
+reserved wildcard tag `all`.
+
## Dependency Boundary
`retrieval/` does not import orchestration core runtime. Orchestration consumes retrieval through canonical retrieval modules and the retrieval adapter layer under `orchestration/`.
diff --git a/jiuwenswarm/symphony/retrieval/io/loading.py b/jiuwenswarm/symphony/retrieval/io/loading.py
index fb45ebbfe8..593c16227a 100644
--- a/jiuwenswarm/symphony/retrieval/io/loading.py
+++ b/jiuwenswarm/symphony/retrieval/io/loading.py
@@ -7,6 +7,7 @@ from typing import Dict, List, Sequence
from models.retrieval import RetrieverItem, RetrieverNode, RetrieverChoice
from shared.storage import is_s3_uri, materialize_s3_dir
+from shared.tags import normalize_tags
@dataclass(frozen=True)
@@ -19,6 +20,7 @@ class CatalogRecord:
retrieval_text: str = ""
branch_path: tuple[str, ...] = ()
metadata: Dict[str, object] = field(default_factory=dict)
+ tags: tuple[str, ...] = ()
@dataclass(frozen=True)
@@ -69,6 +71,9 @@ def load_catalog_records(path: str | Path) -> List[CatalogRecord]:
if not text:
continue
payload = json.loads(text)
+ metadata = payload.get("metadata")
+ if not isinstance(metadata, dict):
+ metadata = {}
choice_id = str(payload.get("name") or payload.get("choice_id") or "").strip()
candidate_payload = str(payload.get("cid") or payload.get("payload") or "").strip()
if not choice_id or not candidate_payload:
@@ -88,7 +93,9 @@ def load_catalog_records(path: str | Path) -> List[CatalogRecord]:
"skill_path": str(payload.get("skill_path") or "").strip(),
"category": str(payload.get("category") or "").strip(),
"worker_id": str(payload.get("worker_id") or "").strip(),
+ "tags": list(normalize_tags(payload.get("tags"), metadata.get("tags"))),
},
+ tags=normalize_tags(payload.get("tags"), metadata.get("tags")),
)
)
records.sort(key=lambda item: (item.payload, item.choice_id))
diff --git a/jiuwenswarm/symphony/retrieval/service/models.py b/jiuwenswarm/symphony/retrieval/service/models.py
index 5fc7acadf1..3ca4dc7e7d 100644
--- a/jiuwenswarm/symphony/retrieval/service/models.py
+++ b/jiuwenswarm/symphony/retrieval/service/models.py
@@ -113,6 +113,9 @@ class RequestConfig:
# Requested result count. None means using RetrieverConfig.top_k.
top_k: int | None = None
+ # Candidate tags required before tree traversal. Empty means no filtering.
+ tags: tuple[str, ...] = ()
+
@dataclass(frozen=True)
class _RuntimeRetrieverConfig:
diff --git a/jiuwenswarm/symphony/retrieval/service/retriever.py b/jiuwenswarm/symphony/retrieval/service/retriever.py
index dff1d81576..1282326827 100644
--- a/jiuwenswarm/symphony/retrieval/service/retriever.py
+++ b/jiuwenswarm/symphony/retrieval/service/retriever.py
@@ -4,6 +4,9 @@ import logging
from pathlib import Path
from typing import Any, Callable, Dict, List, Sequence
+from shared.tags import normalize_tags
+
+from ..io.loading import LoadedRetrieverIndex, load_retriever_index
from ..llm import (
LLMClientCapabilities,
LLMClientConfig,
@@ -17,6 +20,7 @@ from ..llm import (
progressive_client_cache_key,
)
from ..llm.transformers_prefix_cached_generation import warmup_progressive_prefix_cache
+from ..tree.filtering import candidate_tags_match, count_retriever_items, filter_retriever_tree
from ..tree.progressive import ProgressiveRetriever
from .defaults import serialize_trace_event
@@ -28,8 +32,6 @@ from .models import (
runtime_retriever_config_from_config,
)
-from ..io.loading import LoadedRetrieverIndex, load_retriever_index
-
LOGGER = logging.getLogger("retriever")
@@ -68,12 +70,16 @@ class Retriever:
self._before_llm_call_hook = before_llm_call_hook
self._progressive_runtime_cache: dict[tuple[object, ...], ProgressiveLLMClient] = {}
self._progressive_retriever_cache: dict[tuple[object, ...], ProgressiveRetriever] = {}
+ self._filtered_tree_cache: dict[tuple[str, ...], tuple[object, int]] = {}
+ self._prefix_warmed_roots: set[tuple[int, int, int]] = set()
self._public_name_by_payload: dict[str, str] = {}
self._public_name_by_choice_id: dict[str, str] = {}
self._description_by_payload: dict[str, str] = {}
self._description_by_choice_id: dict[str, str] = {}
self._worker_id_by_payload: dict[str, str] = {}
self._worker_id_by_choice_id: dict[str, str] = {}
+ self._tags_by_payload: dict[str, tuple[str, ...]] = {}
+ self._tags_by_choice_id: dict[str, tuple[str, ...]] = {}
for record in self._loaded_index.catalog_records:
payload = str(getattr(record, "payload", "") or getattr(record, "cid", "") or "").strip()
choice_id = str(
@@ -88,16 +94,22 @@ class Retriever:
worker_id = str(metadata.get("worker_id") or "").strip()
public_name = str(getattr(record, "name", "") or choice_id or payload).strip()
description = str(getattr(record, "description", "") or "").strip()
+ tags = normalize_tags(
+ getattr(record, "tags", ()),
+ metadata.get("tags") if isinstance(metadata, dict) else (),
+ )
if payload:
self._public_name_by_payload[payload] = public_name or payload
self._worker_id_by_payload[payload] = worker_id or payload
if description:
self._description_by_payload[payload] = description
+ self._tags_by_payload[payload] = tags
if choice_id:
self._public_name_by_choice_id[choice_id] = public_name or choice_id
self._worker_id_by_choice_id[choice_id] = worker_id or choice_id
if description:
self._description_by_choice_id[choice_id] = description
+ self._tags_by_choice_id[choice_id] = tags
def _record_debug_event(self, event: Dict[str, object]) -> None:
if self._debug_event_hook is None:
@@ -176,6 +188,16 @@ class Retriever:
def search(self, query: str, *, search_config: RequestConfig | None = None) -> List[str]:
return list(self.search_details(query, search_config=search_config).payloads)
+ @property
+ def available_tags(self) -> tuple[str, ...]:
+ """Return the normalized tags present in the loaded offline catalog."""
+
+ available: set[str] = set()
+ for tags_by_key in (self._tags_by_payload, self._tags_by_choice_id):
+ for tags in tags_by_key.values():
+ available.update(tags)
+ return tuple(sorted(available))
+
def close(self) -> None:
clients: list[object] = list(self._progressive_runtime_cache.values())
if self._llm is not None:
@@ -195,6 +217,8 @@ class Retriever:
LOGGER.exception("failed to close retriever llm client")
self._progressive_runtime_cache.clear()
self._progressive_retriever_cache.clear()
+ self._filtered_tree_cache.clear()
+ self._prefix_warmed_roots.clear()
def search_details(
self,
@@ -204,14 +228,71 @@ class Retriever:
) -> SearchResult:
runtime_config = self._config
request_top_k = _resolve_request_top_k(runtime_config=runtime_config, search_config=search_config)
- _validate_search_request_config(runtime_config=runtime_config, request_top_k=request_top_k)
+ requested_tags = _resolve_request_tags(search_config)
+ _validate_search_request_config(
+ runtime_config=runtime_config,
+ request_top_k=request_top_k,
+ )
+ root, tag_filter_trace = self._root_for_tag_filter(
+ requested_tags=requested_tags,
+ )
+ if tag_filter_trace is not None and count_retriever_items(root) == 0:
+ return SearchResult(
+ method="progressive",
+ payloads=[],
+ candidate_records=[],
+ summary_lines=[],
+ selected_payload=None,
+ selected_rank=-1,
+ trace_events=[tag_filter_trace],
+ )
result = self._search_progressive(
query=query,
top_k=request_top_k,
runtime_config=runtime_config,
+ root=root,
)
+ if tag_filter_trace is not None:
+ result.trace_events.insert(0, tag_filter_trace)
return self._trim_public_search_result(self._publicize_search_result(result), top_k=request_top_k)
+ def _root_for_tag_filter(
+ self,
+ *,
+ requested_tags: tuple[str, ...],
+ ) -> tuple[object, Dict[str, object] | None]:
+ if not requested_tags:
+ return self._loaded_index.tree_root, None
+
+ cached = self._filtered_tree_cache.get(requested_tags)
+ if cached is None:
+ allowed_payloads: set[str] = set()
+ for record in self._loaded_index.catalog_records:
+ metadata = getattr(record, "metadata", {}) or {}
+ metadata_tags = metadata.get("tags") if isinstance(metadata, dict) else ()
+ candidate_tags = normalize_tags(getattr(record, "tags", ()), metadata_tags)
+ if candidate_tags_match(candidate_tags, requested_tags):
+ allowed_payloads.add(str(record.payload))
+ filtered_root = filter_retriever_tree(
+ self._loaded_index.tree_root,
+ allowed_payloads=allowed_payloads,
+ )
+ cached = (filtered_root, count_retriever_items(filtered_root))
+ self._filtered_tree_cache[requested_tags] = cached
+
+ root, retained_count = cached
+ trace = {
+ "event_type": "tag_filter",
+ "node_id": "ROOT",
+ "depth": 0,
+ "detail": {
+ "requested_tags": list(requested_tags),
+ "catalog_count": len(self._loaded_index.catalog_records),
+ "retained_count": retained_count,
+ },
+ }
+ return root, trace
+
def _can_run_progressive(self, runtime_config: _RuntimeRetrieverConfig | None = None) -> bool:
return self._progressive_unavailable_reason(runtime_config) is None
@@ -258,6 +339,7 @@ class Retriever:
query: str | Sequence[Dict[str, str]],
top_k: int,
runtime_config: _RuntimeRetrieverConfig,
+ root: object,
) -> SearchResult:
backend_name = _progressive_search_backend_name(runtime_config.progressive)
LOGGER.info(
@@ -287,15 +369,20 @@ class Retriever:
raise RuntimeError(f"progressive runtime initialization failed: {exc}") from exc
if progressive_client is None:
progressive_client = _UnavailableProgressiveLLMClient()
+ self._ensure_prefix_cache_warmup(
+ progressive_client=progressive_client,
+ runtime_config=runtime_config,
+ root=root,
+ )
retriever = self._get_progressive_retriever(
progressive_client=progressive_client,
runtime_config=runtime_config,
- root=self._loaded_index.tree_root,
+ root=root,
)
result = retriever.search(
model=_progressive_model_name(self._llm_model, runtime_config.progressive),
query=query,
- root=self._loaded_index.tree_root,
+ root=root,
top_k=top_k,
before_llm_call_hook=self._before_llm_call_hook,
)
@@ -351,6 +438,25 @@ class Retriever:
self._progressive_retriever_cache[cache_key] = retriever
return retriever
+ def _ensure_prefix_cache_warmup(
+ self,
+ *,
+ progressive_client: ProgressiveLLMClient,
+ runtime_config: _RuntimeRetrieverConfig,
+ root: object,
+ ) -> None:
+ if not bool(progressive_client.capabilities.progressive_prefix_kv_cache):
+ return
+ cache_key = (id(progressive_client), id(root), int(runtime_config.progressive.top_k))
+ if cache_key in self._prefix_warmed_roots:
+ return
+ warmup_progressive_prefix_cache(
+ client=progressive_client,
+ root=root,
+ config=runtime_config.progressive,
+ )
+ self._prefix_warmed_roots.add(cache_key)
+
def _get_progressive_client(self, runtime_config: _RuntimeRetrieverConfig) -> ProgressiveLLMClient | None:
progressive = runtime_config.progressive
cache_key = progressive_client_cache_key(progressive)
@@ -383,6 +489,7 @@ class Retriever:
root=self._loaded_index.tree_root,
config=progressive,
)
+ self._prefix_warmed_roots.add((id(client), id(self._loaded_index.tree_root), int(progressive.top_k)))
self._emit_runtime_event(
phase="prefix_cache_warmup_completed",
attempted=int(warmup_result.attempted),
@@ -443,6 +550,10 @@ class Retriever:
or str(self._description_by_choice_id.get(choice_id, "")).strip()
or str(record.get("description") or "").strip()
)
+ tags = normalize_tags(
+ self._tags_by_payload.get(resolved_payload, ()),
+ self._tags_by_choice_id.get(choice_id, ()),
+ )
if resolved_payload:
public_record["resolved_cid"] = resolved_payload
public_record["resolved_payload"] = worker_id
@@ -457,6 +568,7 @@ class Retriever:
public_record["worker_id"] = worker_id
if description:
public_record["description"] = description
+ public_record["tags"] = list(tags)
return public_record
@staticmethod
@@ -598,7 +710,17 @@ def _resolve_request_top_k(*, runtime_config: _RuntimeRetrieverConfig, search_co
return max(1, int(search_config.top_k))
-def _validate_search_request_config(*, runtime_config: _RuntimeRetrieverConfig, request_top_k: int) -> None:
+def _resolve_request_tags(search_config: RequestConfig | None) -> tuple[str, ...]:
+ if search_config is None:
+ return ()
+ return normalize_tags(search_config.tags)
+
+
+def _validate_search_request_config(
+ *,
+ runtime_config: _RuntimeRetrieverConfig,
+ request_top_k: int,
+) -> None:
initialized_top_k = max(1, int(runtime_config.top_k))
if request_top_k == initialized_top_k:
return
diff --git a/jiuwenswarm/symphony/retrieval/tree/__init__.py b/jiuwenswarm/symphony/retrieval/tree/__init__.py
index c5b8bf8635..834e5192d7 100644
--- a/jiuwenswarm/symphony/retrieval/tree/__init__.py
+++ b/jiuwenswarm/symphony/retrieval/tree/__init__.py
@@ -7,11 +7,15 @@ from models.retrieval import (
RetrieverChoice,
)
from .flat import FlatRetriever
+from .filtering import candidate_tags_match, count_retriever_items, filter_retriever_tree
from .progressive import ProgressiveRetriever
from .types import ProgressiveRetrieverConfig, ProgressiveRetrieverResult
__all__ = [
"FlatRetriever",
+ "candidate_tags_match",
+ "count_retriever_items",
+ "filter_retriever_tree",
"RetrieverCandidate",
"RetrieverItem",
"RetrieverNode",
diff --git a/jiuwenswarm/symphony/retrieval/tree/filtering.py b/jiuwenswarm/symphony/retrieval/tree/filtering.py
new file mode 100644
index 0000000000..8212ac93f4
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/filtering.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+from typing import Iterable
+
+from models.retrieval import RetrieverNode
+from shared.tags import normalize_tags
+
+
+def candidate_tags_match(
+ candidate_tags: Iterable[str],
+ requested_tags: Iterable[str],
+) -> bool:
+ requested = set(normalize_tags(requested_tags))
+ if not requested:
+ return True
+ candidate = set(normalize_tags(candidate_tags))
+ if not candidate:
+ return False
+ if "all" in candidate:
+ return True
+ return requested.issubset(candidate)
+
+
+def filter_retriever_tree(root: RetrieverNode, *, allowed_payloads: set[str]) -> RetrieverNode:
+ """Prune disallowed leaves and empty ancestors while retaining the root node."""
+
+ filtered = _filter_node(root, allowed_payloads=allowed_payloads, is_root=True)
+ return filtered or RetrieverNode(node_id=root.node_id, label=root.label, description=root.description)
+
+
+def count_retriever_items(root: RetrieverNode) -> int:
+ return len(root.items) + sum(count_retriever_items(child) for child in root.children)
+
+
+def _filter_node(
+ node: RetrieverNode,
+ *,
+ allowed_payloads: set[str],
+ is_root: bool,
+) -> RetrieverNode | None:
+ items = tuple(item for item in node.items if str(item.payload) in allowed_payloads)
+ retained_children: list[RetrieverNode] = []
+ for current in node.children:
+ child = _filter_node(current, allowed_payloads=allowed_payloads, is_root=False)
+ if child is not None:
+ retained_children.append(child)
+ children = tuple(retained_children)
+ if not is_root and not items and not children:
+ return None
+ return RetrieverNode(
+ node_id=node.node_id,
+ label=node.label,
+ description=node.description,
+ children=children,
+ items=items,
+ )
+
+
+__all__ = [
+ "candidate_tags_match",
+ "count_retriever_items",
+ "filter_retriever_tree",
+]
diff --git a/jiuwenswarm/symphony/shared/tags.py b/jiuwenswarm/symphony/shared/tags.py
new file mode 100644
index 0000000000..acb471f4ed
--- /dev/null
+++ b/jiuwenswarm/symphony/shared/tags.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping, Set
+from typing import Any
+
+
+def normalize_tags(*values: Any) -> tuple[str, ...]:
+ """Normalize candidate tags for stable indexing and case-insensitive matching."""
+
+ normalized: list[str] = []
+ seen: set[str] = set()
+ for value in values:
+ for item in _iter_tag_values(value):
+ tag = str(item if item is not None else "").strip().casefold()
+ if not tag or tag in seen:
+ continue
+ seen.add(tag)
+ normalized.append(tag)
+ return tuple(normalized)
+
+
+def _iter_tag_values(value: Any, *, _seen: set[int] | None = None) -> Iterable[str]:
+ if value is None:
+ return ()
+ if isinstance(value, (bytes, bytearray, memoryview)):
+ return _iter_tag_values(bytes(value).decode("utf-8", errors="replace"), _seen=_seen)
+ if isinstance(value, str):
+ return _parse_tag_text(value)
+ if isinstance(value, Mapping):
+ return ()
+ if isinstance(value, Iterable):
+ return _flatten_tag_values(value, seen=_seen)
+ return (str(value),)
+
+
+def _parse_tag_text(value: str) -> tuple[str, ...]:
+ text = value.strip()
+ if not text:
+ return ()
+ if text.startswith("[") and text.endswith("]"):
+ text = text[1:-1].strip()
+ if not text:
+ return ()
+ if "," in text:
+ return tuple(part.strip().strip("\"'") for part in text.split(","))
+ return (text.strip("\"'"),)
+
+
+def _flatten_tag_values(values: Iterable[Any], *, seen: set[int] | None) -> tuple[str, ...]:
+ active_containers = seen if seen is not None else set()
+ container_id = id(values)
+ if container_id in active_containers:
+ return ()
+
+ active_containers.add(container_id)
+ flattened: list[str] = []
+ try:
+ items = sorted(values, key=repr) if isinstance(values, Set) else values
+ for item in items:
+ flattened.extend(_iter_tag_values(item, _seen=active_containers))
+ return tuple(flattened)
+ finally:
+ active_containers.remove(container_id)
+
+
+__all__ = ["normalize_tags"]
diff --git a/tests/symphony/test_retrieval_tag_filter.py b/tests/symphony/test_retrieval_tag_filter.py
new file mode 100644
index 0000000000..c81da70dc5
--- /dev/null
+++ b/tests/symphony/test_retrieval_tag_filter.py
@@ -0,0 +1,305 @@
+from __future__ import annotations
+
+import json
+from collections import UserDict
+from pathlib import Path
+from types import SimpleNamespace
+
+from jiuwenswarm.symphony.skill_retrieval.dispatch_imports import dispatch_import_path
+
+
+def test_offline_build_records_skill_tags(tmp_path: Path) -> None:
+ skill_dir = tmp_path / "skills" / "phone-control"
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text(
+ """---
+name: Phone Control
+description: Controls a phone application.
+tags: [automation, Mobile, ALL]
+---
+
+Use the phone.
+""",
+ encoding="utf-8",
+ )
+
+ with dispatch_import_path():
+ from indexing.io.manifest import write_manifest
+ from indexing.scanners.skill import SkillScanner
+ from indexing.workflows.artifacts import build_catalog_records_from_nodes, write_catalog
+ from retrieval.io.loading import load_catalog_records
+
+ scanned = SkillScanner(tmp_path / "skills").to_dict_list()
+ assert scanned[0]["tags"] == ["automation", "mobile", "all"]
+
+ records = build_catalog_records_from_nodes(
+ nodes=[
+ {
+ "cid": "automation.phone.phone_control",
+ "type": "leaf",
+ "worker_id": "phone-control",
+ }
+ ],
+ scanned_skills={"phone-control": scanned[0]},
+ )
+ catalog_path = tmp_path / "catalog.jsonl"
+ write_catalog(records, catalog_path)
+ write_manifest(tmp_path, [skill_dir], records, mode="full", item_type="skill")
+ assert load_catalog_records(catalog_path)[0].tags == ("automation", "mobile", "all")
+
+ catalog_row = json.loads(catalog_path.read_text(encoding="utf-8"))
+ manifest = json.loads((tmp_path / "manifest.json").read_text(encoding="utf-8"))
+ assert catalog_row["tags"] == ["automation", "mobile", "all"]
+ assert catalog_row["metadata"]["tags"] == ["automation", "mobile", "all"]
+ assert manifest["tag_counts"] == {"all": 1, "automation": 1, "mobile": 1}
+
+
+def test_jsonl_tags_are_read_from_content_extend_param() -> None:
+ payload = {
+ "tags": ["top-level-tag"],
+ "contentExtendParam": {
+ "skillId": "sms",
+ "skillName": "SMS",
+ "skillDesc": "Read messages.",
+ "tags": ["Messaging", "Mobile"],
+ }
+ }
+
+ with dispatch_import_path():
+ from indexing.io.items_jsonl import parse_jsonl_scanned_items
+
+ scanned, _paths = parse_jsonl_scanned_items(json.dumps(payload))
+
+ assert scanned["sms"]["tags"] == ["messaging", "mobile"]
+
+
+def test_catalog_build_uses_canonical_scanned_tags_once(monkeypatch) -> None:
+ with dispatch_import_path():
+ from indexing.workflows import artifacts
+
+ calls = []
+ original_normalize_tags = artifacts.normalize_tags
+
+ def capture_normalize_tags(*values):
+ calls.append(values)
+ return original_normalize_tags(*values)
+
+ monkeypatch.setattr(artifacts, "normalize_tags", capture_normalize_tags)
+ records = artifacts.build_catalog_records_from_nodes(
+ nodes=[{"cid": "messaging.sms", "type": "leaf", "worker_id": "sms"}],
+ scanned_skills={
+ "sms": {
+ "name": "SMS",
+ "description": "Read messages.",
+ "path": "jsonl://skill/sms",
+ "tags": ["messaging", "mobile"],
+ "content_extend_param": {
+ "tags": ["messaging"],
+ },
+ }
+ },
+ )
+
+ assert records[0].tags == ("messaging", "mobile")
+ assert calls == [(["messaging", "mobile"],)]
+
+
+def test_request_config_filters_tree_before_retrieval(monkeypatch, tmp_path: Path) -> None:
+ with dispatch_import_path():
+ from models.retrieval import RetrieverItem, RetrieverNode
+ from retrieval.io.loading import CatalogRecord, LoadedRetrieverIndex
+ from retrieval.service import RequestConfig, Retriever, RetrieverConfig, SearchResult
+
+ records = (
+ CatalogRecord(
+ choice_id="Phone Control",
+ payload="automation.phone",
+ worker_id="phone-control",
+ tags=("mobile", "automation"),
+ ),
+ CatalogRecord(
+ choice_id="Desktop Control",
+ payload="automation.desktop",
+ worker_id="desktop-control",
+ tags=("pc", "automation"),
+ ),
+ CatalogRecord(
+ choice_id="Cloud Storage",
+ payload="storage.cloud",
+ worker_id="cloud-storage",
+ tags=("all",),
+ ),
+ CatalogRecord(
+ choice_id="Unknown Compatibility",
+ payload="misc.unknown",
+ worker_id="unknown",
+ ),
+ )
+ root = RetrieverNode(
+ node_id="ROOT",
+ label="ROOT",
+ children=(
+ RetrieverNode(
+ node_id="capabilities",
+ label="Capabilities",
+ items=tuple(
+ RetrieverItem(item_id=record.choice_id, payload=record.payload)
+ for record in records
+ ),
+ ),
+ ),
+ )
+ loaded = LoadedRetrieverIndex(
+ index_dir=tmp_path,
+ tree_root=root,
+ choices=(),
+ catalog_records=records,
+ )
+ retriever = Retriever(loaded_index=loaded, config=RetrieverConfig(top_k=10))
+ calls: list[list[str]] = []
+
+ def fake_search_progressive(*, query, top_k, runtime_config, root):
+ del query, top_k, runtime_config
+
+ def payloads(node):
+ return [item.payload for item in node.items] + [
+ payload
+ for child in node.children
+ for payload in payloads(child)
+ ]
+
+ visible = payloads(root)
+ calls.append(visible)
+ by_payload = {record.payload: record for record in records}
+ return SearchResult(
+ method="progressive",
+ payloads=visible,
+ candidate_records=[
+ {
+ "rank": index,
+ "raw_output": by_payload[payload].choice_id,
+ "resolved_payload": payload,
+ "choice_id": by_payload[payload].choice_id,
+ "valid": True,
+ "selected": index == 1,
+ "source": "test",
+ }
+ for index, payload in enumerate(visible, start=1)
+ ],
+ summary_lines=[],
+ selected_payload=visible[0] if visible else None,
+ selected_rank=1 if visible else -1,
+ )
+
+ monkeypatch.setattr(retriever, "_search_progressive", fake_search_progressive)
+
+ result = retriever.search_details(
+ "control my device",
+ search_config=RequestConfig(tags=("mobile",)),
+ )
+ assert calls == [["automation.phone", "storage.cloud"]]
+ assert result.payloads == ["phone-control", "cloud-storage"]
+ assert result.candidate_records[0]["tags"] == ["mobile", "automation"]
+ assert result.trace_events[0]["event_type"] == "tag_filter"
+ assert result.trace_events[0]["detail"]["retained_count"] == 2
+ assert set(result.trace_events[0]["detail"]) == {
+ "requested_tags",
+ "catalog_count",
+ "retained_count",
+ }
+ assert retriever.available_tags == ("all", "automation", "mobile", "pc")
+
+ unfiltered = retriever.search_details("anything")
+ assert len(unfiltered.payloads) == 4
+ assert calls[-1] == [
+ "automation.phone",
+ "automation.desktop",
+ "storage.cloud",
+ "misc.unknown",
+ ]
+
+ non_wildcard_records = records[:2]
+ non_wildcard_root = RetrieverNode(
+ node_id="ROOT",
+ label="ROOT",
+ items=tuple(
+ RetrieverItem(item_id=record.choice_id, payload=record.payload)
+ for record in non_wildcard_records
+ ),
+ )
+ no_match_retriever = Retriever(
+ loaded_index=LoadedRetrieverIndex(
+ index_dir=tmp_path,
+ tree_root=non_wildcard_root,
+ choices=(),
+ catalog_records=non_wildcard_records,
+ ),
+ config=RetrieverConfig(top_k=10),
+ )
+
+ def fail_search_progressive(**kwargs):
+ del kwargs
+ raise AssertionError("empty filtered trees must not invoke retrieval")
+
+ monkeypatch.setattr(no_match_retriever, "_search_progressive", fail_search_progressive)
+ no_match = no_match_retriever.search_details(
+ "use a watch",
+ search_config=RequestConfig(tags=("watch",)),
+ )
+ assert no_match.payloads == []
+
+
+def test_tag_filter_requires_all_tags_and_supports_reserved_wildcard() -> None:
+ with dispatch_import_path():
+ from retrieval.tree.filtering import candidate_tags_match
+
+ assert candidate_tags_match(("mobile", "automation"), ("mobile", "automation"))
+ assert not candidate_tags_match(("mobile",), ("mobile", "automation"))
+ assert candidate_tags_match(("all",), ("mobile", "automation"))
+ assert not candidate_tags_match((), ("mobile",))
+
+
+def test_request_config_exposes_only_tags_for_filtering() -> None:
+ with dispatch_import_path():
+ from retrieval.service import RequestConfig
+
+ assert tuple(RequestConfig.__dataclass_fields__) == ("top_k", "tags")
+
+
+def test_normalize_tags_handles_boundary_values_deterministically() -> None:
+ with dispatch_import_path():
+ from shared.tags import normalize_tags
+
+ cyclic = ["cycle"]
+ cyclic.append(cyclic)
+
+ assert normalize_tags(None, "", "[]", [], UserDict({"ignored": "mobile"})) == ()
+ assert normalize_tags(b"Mobile,PC", bytearray(b"ALL"), memoryview(b"Watch")) == (
+ "mobile",
+ "pc",
+ "all",
+ "watch",
+ )
+ assert normalize_tags({"pc", "mobile"}) == ("mobile", "pc")
+ assert normalize_tags(["outer", ["inner"]], cyclic) == ("outer", "inner", "cycle")
+ assert normalize_tags(0, False) == ("0", "false")
+
+
+def test_available_tags_includes_choice_only_catalog_records(tmp_path: Path) -> None:
+ with dispatch_import_path():
+ from models.retrieval import RetrieverNode
+ from retrieval.io.loading import LoadedRetrieverIndex
+ from retrieval.service import Retriever
+
+ retriever = Retriever(
+ loaded_index=LoadedRetrieverIndex(
+ index_dir=tmp_path,
+ tree_root=RetrieverNode(node_id="ROOT", label="ROOT"),
+ choices=(),
+ catalog_records=(
+ SimpleNamespace(choice_id="choice-only", tags=("choice-tag",)),
+ ),
+ )
+ )
+
+ assert retriever.available_tags == ("choice-tag",)