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

fix(symphony): Optimise the skill retrieval toolchain

xutuoada4c82e2de2
diff --git a/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py
new file mode 100644
index 0000000000..cf64d789ac
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py
@@ -0,0 +1,149 @@
+"""Prompt rail for agentic installed-skill retrieval."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.prompts import PromptSection
+from openjiuwen.harness.prompts.sections import SectionName
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+from jiuwenswarm.symphony.agent import render_skill_retrieval_prompt
+
+logger = logging.getLogger(__name__)
+
+_LEGACY_LIST_SKILL_TOOL_NAMES = frozenset({"list_skill", "list_skills"})
+
+
+class SkillRetrievalPromptRail(DeepAgentRail):
+ """Inject lightweight skill-tree retrieval guidance into the system prompt."""
+
+ priority = 101
+ SECTION_NAME = "skill_retrieval"
+ SECTION_PRIORITY = 41
+
+ def __init__(self, *, manager: Any | None = None) -> None:
+ super().__init__()
+ self._manager = manager
+ self._agent = None
+ self.system_prompt_builder = None
+ self._hidden_legacy_abilities: dict[str, Any] = {}
+
+ def init(self, agent: Any) -> None:
+ self._agent = agent
+ self.system_prompt_builder = getattr(agent, "system_prompt_builder", None)
+
+ def uninit(self, agent: Any) -> None:
+ self._restore_legacy_list_skill(agent)
+ if self.system_prompt_builder is not None:
+ self.system_prompt_builder.remove_section(self.SECTION_NAME)
+ self.system_prompt_builder = None
+ self._agent = None
+
+ async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ agent = getattr(ctx, "agent", None)
+ if agent is not None:
+ self._agent = agent
+ if self.system_prompt_builder is None:
+ self.system_prompt_builder = getattr(agent, "system_prompt_builder", None)
+
+ self._hide_legacy_list_skill()
+ self._filter_legacy_list_skill_from_model_inputs(ctx)
+
+ if self.system_prompt_builder is None:
+ return
+
+ self.system_prompt_builder.remove_section(SectionName.SKILLS)
+ language = getattr(self.system_prompt_builder, "language", "cn") or "cn"
+ try:
+ content = await asyncio.to_thread(
+ render_skill_retrieval_prompt,
+ self._manager,
+ language=language,
+ )
+ except Exception as exc:
+ logger.warning("[SkillRetrievalPromptRail] render failed: %s", exc)
+ content = ""
+
+ if not content.strip():
+ self.system_prompt_builder.remove_section(self.SECTION_NAME)
+ return
+
+ self.system_prompt_builder.add_section(
+ PromptSection(
+ name=self.SECTION_NAME,
+ content={language: content},
+ priority=self.SECTION_PRIORITY,
+ )
+ )
+
+ async def after_model_call(self, ctx: AgentCallbackContext) -> None:
+ self._restore_legacy_list_skill(getattr(ctx, "agent", None))
+
+ async def on_model_exception(self, ctx: AgentCallbackContext) -> None:
+ self._restore_legacy_list_skill(getattr(ctx, "agent", None))
+
+ def _hide_legacy_list_skill(self) -> None:
+ ability_manager = getattr(self._agent, "ability_manager", None)
+ if ability_manager is None:
+ return
+ get_ability = getattr(ability_manager, "get", None)
+ remove_ability = getattr(ability_manager, "remove", None)
+ if not callable(get_ability) or not callable(remove_ability):
+ return
+
+ for name in _LEGACY_LIST_SKILL_TOOL_NAMES:
+ if name in self._hidden_legacy_abilities:
+ continue
+ card = get_ability(name)
+ if card is None:
+ continue
+ removed = remove_ability(name)
+ if removed is not None:
+ self._hidden_legacy_abilities[name] = removed
+
+ def _restore_legacy_list_skill(self, agent: Any | None = None) -> None:
+ if agent is not None:
+ self._agent = agent
+ ability_manager = getattr(self._agent, "ability_manager", None)
+ if ability_manager is None or not self._hidden_legacy_abilities:
+ return
+ get_ability = getattr(ability_manager, "get", None)
+ add_ability = getattr(ability_manager, "add", None)
+ if not callable(get_ability) or not callable(add_ability):
+ return
+
+ for name, card in list(self._hidden_legacy_abilities.items()):
+ if get_ability(name) is None:
+ add_ability(card)
+ self._hidden_legacy_abilities.pop(name, None)
+
+ @staticmethod
+ def _filter_legacy_list_skill_from_model_inputs(ctx: AgentCallbackContext) -> None:
+ inputs = getattr(ctx, "inputs", None)
+ tools = getattr(inputs, "tools", None)
+ if not tools:
+ return
+
+ filtered = []
+ for tool in tools:
+ name = SkillRetrievalPromptRail._model_tool_name(tool)
+ if name not in _LEGACY_LIST_SKILL_TOOL_NAMES:
+ filtered.append(tool)
+ if len(filtered) != len(tools):
+ inputs.tools = filtered
+
+ @staticmethod
+ def _model_tool_name(tool: Any) -> str:
+ if isinstance(tool, dict):
+ function = tool.get("function")
+ if isinstance(function, dict):
+ return str(function.get("name", "") or "")
+ return str(tool.get("name", "") or "")
+ return str(getattr(tool, "name", "") or "")
+
+
+__all__ = ["SkillRetrievalPromptRail"]
diff --git a/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py b/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
index 9ca100ee0b..9b5d758a1b 100644
--- a/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
@@ -8,19 +8,20 @@ from typing import Any, Callable
from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
-from jiuwenswarm.symphony.skill_retrieval import build_skill_index, retrieve_skills
-from jiuwenswarm.symphony.skill_retrieval.config import load_settings
+from jiuwenswarm.symphony.agent import (
+ build_skill_index,
+ is_agentic_retrieval_enabled,
+ skill_branch_explore,
+ skill_branch_peek,
+)
def is_skill_retrieval_enabled() -> bool:
- try:
- return bool(load_settings().enabled)
- except Exception:
- return False
+ return is_agentic_retrieval_enabled()
class SkillRetrievalToolkit:
- """Expose dispatch-backed installed skill retrieval to agents."""
+ """Expose agentic installed-skill tree retrieval to agents."""
def __init__(self, manager: SkillManager) -> None:
self._manager = manager
@@ -28,8 +29,11 @@ class SkillRetrievalToolkit:
async def skill_index_build(self) -> dict[str, Any]:
return await asyncio.to_thread(build_skill_index, self._manager)
- async def skill_retrieve(self, query: str) -> dict[str, Any]:
- return await asyncio.to_thread(retrieve_skills, query, self._manager)
+ async def skill_branch_peek(self, node_ids: list[str]) -> dict[str, Any]:
+ return await asyncio.to_thread(skill_branch_peek, node_ids, self._manager)
+
+ async def skill_branch_explore(self, node_ids: list[str]) -> dict[str, Any]:
+ return await asyncio.to_thread(skill_branch_explore, node_ids, self._manager)
def get_tools(self) -> list[Tool]:
def make_tool(name: str, description: str, input_params: dict, func: Callable[..., Any]) -> Tool:
@@ -45,10 +49,10 @@ class SkillRetrievalToolkit:
make_tool(
name="skill_index_build",
description=(
- "Build or refresh the local dispatch tree index for installed enabled skills. "
- "Do not call this proactively. First call skill_retrieve with the task query; "
- "call skill_index_build only if skill_retrieve returns a failure result that "
- "explicitly says the index is missing or stale and instructs you to build it."
+ "Build or refresh the local tree index for installed enabled skills. "
+ "Do not call this proactively. First call skill_branch_explore or skill_branch_peek; "
+ "call skill_index_build only if those tools return a failure result that explicitly "
+ "says the index is missing or stale and instructs you to build it."
),
input_params={
"type": "object",
@@ -58,23 +62,60 @@ class SkillRetrievalToolkit:
func=self.skill_index_build,
),
make_tool(
- name="skill_retrieve",
+ name="skill_branch_explore",
+ description=(
+ "Primary skill-directory browsing tool for installed skills. "
+ "Explore one or more branch node ids to disclose the next visible skill-tree boundary. "
+ "Use this directly with first-level category ids already shown in the system prompt, "
+ "or with branch ids returned by previous tool results. Do not call this with ROOT; "
+ "ROOT is already summarized in the system prompt. "
+ "When the result contains a 'skills' section, those entries are installed skills, not branch ids; "
+ "shortlist by Name and Description, then read a returned SKILL.md only after the skill "
+ "looks likely useful. "
+ "Do not read every skill or explore skill names as branch ids. "
+ "This is not an execution tool or a full execution plan. If the index is missing or stale, "
+ "follow the returned instruction to call skill_index_build once, then retry."
+ ),
+ input_params={
+ "type": "object",
+ "properties": {
+ "node_ids": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "Branch node ids to explore. Use first-level category ids from the system "
+ "prompt or branch ids returned by previous retrieval results. Do not use ['ROOT']."
+ ),
+ },
+ },
+ "required": ["node_ids"],
+ },
+ func=self.skill_branch_explore,
+ ),
+ make_tool(
+ name="skill_branch_peek",
description=(
- "Retrieve relevant installed skills for a task query using the local dispatch skill index. "
- "Call this before skill_index_build. If the index is missing or stale, this tool returns "
- "a failure result with instructions to call skill_index_build and then retry retrieval. "
- "This only returns retrieval hints; it does not execute or orchestrate skills."
+ "Lightweight skill-directory preview tool for installed skills. "
+ "Use this only when you are unsure whether a branch is worth exploring. "
+ "It returns child branch summaries and coverage information; it does not return full leaf skill "
+ "details, execute skills, or plan the task. Use skill_branch_explore to disclose actual "
+ "skill entries when a branch looks relevant. If the index is missing or stale, follow the "
+ "returned instruction to call skill_index_build once, then retry."
),
input_params={
"type": "object",
"properties": {
- "query": {
- "type": "string",
- "description": "User task or retrieval query.",
+ "node_ids": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "Branch node ids to preview. Use ['ROOT'] only when you need to rediscover "
+ "top-level branch summaries."
+ ),
},
},
- "required": ["query"],
+ "required": ["node_ids"],
},
- func=self.skill_retrieve,
+ func=self.skill_branch_peek,
),
]
diff --git a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
index adc274e55e..d2925e0a6f 100644
--- a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
+++ b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
@@ -96,7 +96,8 @@ TOOL_WHITELIST = frozenset({
"install_skill",
"uninstall_skill",
"skill_index_build",
- "skill_retrieve",
+ "skill_branch_explore",
+ "skill_branch_peek",
"user_todos",
"get_user_location",
"create_note",
diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.py
index 595801a469..467e2f547d 100644
--- a/jiuwenswarm/agents/swarm/config_specs.py
+++ b/jiuwenswarm/agents/swarm/config_specs.py
@@ -31,6 +31,7 @@ from openjiuwen.agent_teams.schema.deep_agent_spec import (
RailSpec,
SubAgentSpec,
)
+from openjiuwen.agent_teams.rails.builtin_elements import SKILL_USE as CORE_SKILL_USE
from openjiuwen.core.single_agent import AgentCard
from openjiuwen.harness.prompts import resolve_language
from openjiuwen.harness.rails import SkillUseRail
@@ -63,6 +64,7 @@ _COMMON_RAIL_NAMES: tuple[str, ...] = (
registry.TEAM_WORKSPACE_REPORT_PATH,
registry.CONTEXT_PROCESSOR,
registry.PLUGIN_RAILS,
+ registry.SKILL_RETRIEVAL_PROMPT,
)
# Tools common to both roles. Each element self-gates on config, so all are
@@ -108,6 +110,7 @@ _CODE_RAIL_NAMES: tuple[str, ...] = (
registry.USER_HOOKS,
registry.CODE_SKILL_USE,
registry.CODE_WORKTREE,
+ registry.SKILL_RETRIEVAL_PROMPT,
)
# Rails shared with the team profile, appended to the code profile.
@@ -197,12 +200,33 @@ def _evolution_model_config(config: dict[str, Any]) -> dict[str, Any]:
def _skill_mode(config: dict[str, Any]) -> str:
"""Resolve the validated skill-use mode from ``react.skill_mode``."""
+ if _retrieval_enabled(config):
+ return SkillUseRail.SKILL_MODE_AUTO_LIST
react = _config_section(config, "react")
raw = react.get("skill_mode", SkillUseRail.SKILL_MODE_ALL)
valid = {SkillUseRail.SKILL_MODE_AUTO_LIST, SkillUseRail.SKILL_MODE_ALL}
return raw if isinstance(raw, str) and raw in valid else SkillUseRail.SKILL_MODE_ALL
+def _retrieval_enabled(config: dict[str, Any] | None = None) -> bool:
+ """Return whether agentic skill retrieval is enabled for this config."""
+ env_value = os.getenv("SYMPHONY_SKILL_RETRIEVAL_ENABLED")
+ if env_value is not None and env_value.strip():
+ return env_value.strip().lower() in {"1", "true", "yes", "on", "enabled"}
+
+ symphony = _config_section(config or {}, "symphony")
+ retrieval = symphony.get("skill_retrieval")
+ if isinstance(retrieval, dict):
+ return bool(retrieval.get("enabled", False))
+ return False
+
+
+def _remove_skill_use_rails_for_agentic_retrieval(rails: list[RailSpec]) -> list[RailSpec]:
+ """Remove legacy SkillUseRail when agentic retrieval owns discovery."""
+ skill_rail_types = {CORE_SKILL_USE, "skill_use", registry.CODE_SKILL_USE}
+ return [rail for rail in rails if rail.type not in skill_rail_types]
+
+
def _additional_directories(config: dict[str, Any]) -> list[str]:
"""Resolve project-memory additional directories from config + env."""
react = _config_section(config, "react")
@@ -267,7 +291,10 @@ _RAIL_PARAM_BUILDERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
"embed_config": _config_section(c, "embed")
},
registry.USER_HOOKS: lambda c: {"hooks_section": _config_section(c, "hooks")},
- registry.CODE_SKILL_USE: lambda c: {"skill_mode": _skill_mode(c)},
+ registry.CODE_SKILL_USE: lambda c: {
+ "skill_mode": _skill_mode(c),
+ "include_tools": not _retrieval_enabled(c),
+ },
registry.CODE_WORKTREE: lambda c: {"enabled": True},
}
@@ -526,9 +553,13 @@ def build_member_deep_agent_spec(
merged_tools = list(base_spec.tools or [])
merged_tools.extend(tool_specs)
+ retrieval_enabled = _retrieval_enabled(config)
+ if retrieval_enabled:
+ merged_rails = _remove_skill_use_rails_for_agentic_retrieval(merged_rails)
+
update: dict[str, Any] = {"rails": merged_rails, "tools": merged_tools}
if not _is_code_mode(mode):
- update["enable_skill_discovery"] = True
+ update["enable_skill_discovery"] = not retrieval_enabled
subagent_specs = build_member_subagent_specs(config, mode, role)
if subagent_specs:
diff --git a/jiuwenswarm/agents/swarm/providers/code_rails.py b/jiuwenswarm/agents/swarm/providers/code_rails.py
index b46f6e52d5..be1b919d75 100644
--- a/jiuwenswarm/agents/swarm/providers/code_rails.py
+++ b/jiuwenswarm/agents/swarm/providers/code_rails.py
@@ -395,6 +395,10 @@ class CodeSkillUseInput(ConstructionInput):
default=SkillUseRail.SKILL_MODE_ALL,
description="Skill exposure mode (ALL or AUTO_LIST) from react.skill_mode.",
)
+ include_tools: bool = param_field(
+ default=True,
+ description="Whether SkillUseRail should expose regular skill tools.",
+ )
@harness_element(
@@ -406,14 +410,20 @@ class CodeSkillUseInput(ConstructionInput):
def build_code_skill_use(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:
"""Build SkillUseRail from the config source (skill_mode + disabled skills)."""
from jiuwenswarm.common.utils import get_agent_skills_dir
+ from jiuwenswarm.agents.harness.common.tools.skill_retrieval_toolkits import (
+ is_skill_retrieval_enabled,
+ )
from jiuwenswarm.server.runtime.skill import load_execution_disabled_skills
try:
+ if is_skill_retrieval_enabled():
+ logger.info("[swarm.code_skill_use] skipped: agentic skill retrieval is enabled")
+ return None
inp = CodeSkillUseInput.resolve(params, ctx)
return SkillUseRail(
skills_dir=str(get_agent_skills_dir()),
skill_mode=inp.skill_mode,
- include_tools=True,
+ include_tools=inp.include_tools,
disabled_skills=load_execution_disabled_skills(),
)
except Exception as exc:
diff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.py
index 7423c9d47e..d25f9ca19d 100644
--- a/jiuwenswarm/agents/swarm/providers/member_rails.py
+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py
@@ -30,6 +30,9 @@ from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_mana
from jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import (
RuntimePromptRail,
)
+from jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail import (
+ SkillRetrievalPromptRail,
+)
from jiuwenswarm.agents.harness.team.rails.team_skill_storage_policy_rail import (
TeamSkillStoragePolicyRail,
)
@@ -52,6 +55,7 @@ TEAM_SHARED_SKILL_LINK_REFRESH = "swarm.team_shared_skill_link_refresh"
TEAM_WORKSPACE_REPORT_PATH = "swarm.team_workspace_report_path"
CONTEXT_PROCESSOR = "swarm.context_processor"
PLUGIN_RAILS = "swarm.plugin_rails"
+SKILL_RETRIEVAL_PROMPT = "swarm.skill_retrieval_prompt"
def _workspace_root(ctx: SwarmBuildContext) -> str | None:
@@ -60,6 +64,38 @@ def _workspace_root(ctx: SwarmBuildContext) -> str | None:
return getattr(workspace, "root_path", None) if workspace else None
+class SkillRetrievalPromptInput(ConstructionInput):
+ """Construction inputs for the agentic skill retrieval prompt rail."""
+
+ workspace_root: str | None = context_field(
+ resolver=_workspace_root,
+ description="Member workspace root; the SkillManager resolves installed skills from it.",
+ )
+
+
+@harness_element(
+ kind=ElementKind.RAIL,
+ name=SKILL_RETRIEVAL_PROMPT,
+ description="Lightweight prompt guidance for agentic installed-skill tree retrieval.",
+ input_model=SkillRetrievalPromptInput,
+)
+def _build_skill_retrieval_prompt_rail(
+ params: dict[str, Any],
+ context: SwarmBuildContext,
+) -> SkillRetrievalPromptRail | None:
+ """Build the skill retrieval prompt rail when the feature is enabled."""
+ from jiuwenswarm.agents.harness.common.tools.skill_retrieval_toolkits import (
+ is_skill_retrieval_enabled,
+ )
+ from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+
+ if not is_skill_retrieval_enabled():
+ return None
+ inp = SkillRetrievalPromptInput.resolve(params, context)
+ manager = SkillManager(workspace_dir=inp.workspace_root)
+ return SkillRetrievalPromptRail(manager=manager)
+
+
class RuntimePromptInput(ConstructionInput):
"""Construction inputs for the member runtime prompt rail."""
@@ -341,4 +377,5 @@ __all__ = [
"TEAM_WORKSPACE_REPORT_PATH",
"CONTEXT_PROCESSOR",
"PLUGIN_RAILS",
+ "SKILL_RETRIEVAL_PROMPT",
]
diff --git a/jiuwenswarm/agents/swarm/providers/tools.py b/jiuwenswarm/agents/swarm/providers/tools.py
index 2edccfe38e..e1436a6df0 100644
--- a/jiuwenswarm/agents/swarm/providers/tools.py
+++ b/jiuwenswarm/agents/swarm/providers/tools.py
@@ -7,7 +7,7 @@ elements, each self-gated by the config source and filtered against the swarm
``TOOL_WHITELIST``:
* ``swarm.skill_toolkit`` — skill discovery / install / uninstall tools.
-* ``swarm.skill_retrieval`` — dispatch-backed installed skill retrieval tools.
+* ``swarm.skill_retrieval`` — agentic installed skill tree retrieval tools.
* ``swarm.user_todos`` — the personal todo tool.
* ``swarm.video`` — the video-understanding tool (``models.video`` gated).
* ``swarm.image_gen`` — the image-generation tool (``IMAGE_GEN_API_KEY`` gated).
@@ -340,7 +340,7 @@ def build_skill_toolkit(params: dict[str, Any], ctx: SwarmBuildContext) -> list[
@harness_element(
kind=ElementKind.TOOL,
name=SKILL_RETRIEVAL,
- description="Dispatch-backed installed skill retrieval tools bound to the member workspace.",
+ description="Agentic installed skill tree retrieval tools bound to the member workspace.",
input_model=SkillToolkitInput,
)
def build_skill_retrieval(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:
diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.py
index bc511733f9..b92218eec3 100644
--- a/jiuwenswarm/agents/swarm/registry.py
+++ b/jiuwenswarm/agents/swarm/registry.py
@@ -81,6 +81,7 @@ TEAM_SHARED_SKILL_LINK_REFRESH = _member_rails.TEAM_SHARED_SKILL_LINK_REFRESH
TEAM_WORKSPACE_REPORT_PATH = _member_rails.TEAM_WORKSPACE_REPORT_PATH
CONTEXT_PROCESSOR = _member_rails.CONTEXT_PROCESSOR
PLUGIN_RAILS = _member_rails.PLUGIN_RAILS
+SKILL_RETRIEVAL_PROMPT = _member_rails.SKILL_RETRIEVAL_PROMPT
TEAM_SKILL_EVOLUTION = _evolution_rails.TEAM_SKILL_EVOLUTION
TEAM_SKILL_CREATE = _evolution_rails.TEAM_SKILL_CREATE
MEMBER_SKILL_EVOLUTION = _evolution_rails.MEMBER_SKILL_EVOLUTION
@@ -198,6 +199,7 @@ __all__ = [
"TEAM_WORKSPACE_REPORT_PATH",
"CONTEXT_PROCESSOR",
"PLUGIN_RAILS",
+ "SKILL_RETRIEVAL_PROMPT",
"TEAM_SKILL_EVOLUTION",
"TEAM_SKILL_CREATE",
"MEMBER_SKILL_EVOLUTION",
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index 3323fc7ffd..a61f2e760b 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -846,6 +846,7 @@ for (let i = payload.team.length; i < 10; i++) {
success: n.success,
toolCallId: n.toolCallId,
summary: n.summary,
+ skillTree: n.skillTree,
},
{ updatedAt: item.at }
);
@@ -1151,6 +1152,7 @@ for (let i = payload.team.length; i < 10; i++) {
success: n.success,
toolCallId: n.toolCallId,
summary: n.summary,
+ skillTree: n.skillTree,
},
{ updatedAt: item.at }
);
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx
index 793caaec7c..d1cb3f3a16 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx
@@ -1,10 +1,10 @@
/**
* SkillTreePath 组件
*
- * 当 agentic search(symphony 渐进检索)在对话中被触发时,把后端下发的
+ * 当 symphony 技能检索工具在对话中被触发时,把后端下发的
* 「技能树路径」按遍历顺序逐级回放展示,营造路径流转效果,最终落到命中的技能。
*
- * 数据来源:skill_retrieve 工具结果 raw_output.skill_tree(见 types/skillTree.ts)。
+ * 数据来源:工具结果 raw_output.skill_tree(见 types/skillTree.ts)。
* 纯 SVG/DOM 实现,不引入第三方图表库。
*/
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx
index cddf5d2566..6e15b09f25 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx
@@ -218,11 +218,15 @@ function ToolDetailModal({ execution, onClose }: ToolDetailModalProps) {
)}
</span>
</div>
- {result.skillTree ? (
+ {result.skillTree && (
<SkillTreePath tree={result.skillTree} stepIntervalMs={0} />
- ) : (
+ )}
+ {(!result.skillTree || result.result) && (
<pre
- className="p-4 rounded-lg overflow-auto whitespace-pre-wrap break-all"
+ className={clsx(
+ 'p-4 rounded-lg overflow-auto whitespace-pre-wrap break-all',
+ result.skillTree && 'mt-4'
+ )}
style={{
fontFamily: 'var(--mono)',
fontSize: 'var(--font-size-sm)',
@@ -364,7 +368,7 @@ export function ToolGroupDisplay({
const headerLabel = t('chatUi.toolGroup.executed', { totalPairs });
const skillTreeExecutions = visibleExecutions.filter(
- (execution) => execution.toolCall.name === 'skill_retrieve' && execution.result?.skillTree
+ (execution) => execution.result?.skillTree
);
if (visibleExecutions.length === 0) {
return null;
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
index 1100a4632e..4376ebd41b 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
@@ -292,8 +292,13 @@ const SYMPHONY_KEYS = new Set([
]);
const SKILL_RETRIEVAL_BOOLEAN_KEYS = new Set([
"skill_retrieval_enabled",
- "skill_retrieval_compact_codes_enabled",
- "skill_retrieval_flatten_tree",
+ "skill_retrieval_build_postprocess_enabled",
+ "skill_retrieval_build_equivalence_enabled",
+ "skill_retrieval_retrieve_compact_codes_enabled",
+ "skill_retrieval_retrieve_flatten_tree",
+]);
+const MULTILINE_CONFIG_KEYS = new Set([
+ "skill_retrieval_build_root_categories",
]);
const SKILL_RETRIEVAL_KEYS = new Set([
"skill_retrieval_enabled",
@@ -301,14 +306,17 @@ const SKILL_RETRIEVAL_KEYS = new Set([
"skill_retrieval_build_max_depth",
"skill_retrieval_build_root_categories",
"skill_retrieval_build_max_workers",
+ "skill_retrieval_build_max_retries",
"skill_retrieval_build_request_timeout_seconds",
- "skill_retrieval_retrieve_top_k",
- "skill_retrieval_compact_codes_enabled",
- "skill_retrieval_flatten_tree",
+ "skill_retrieval_build_classification_batch_limit",
+ "skill_retrieval_build_discovery_seed",
+ "skill_retrieval_build_postprocess_enabled",
+ "skill_retrieval_build_postprocess_max_passes",
+ "skill_retrieval_build_postprocess_min_skills",
+ "skill_retrieval_build_equivalence_enabled",
+ "skill_retrieval_retrieve_compact_codes_enabled",
+ "skill_retrieval_retrieve_flatten_tree",
"skill_retrieval_retrieve_max_exposure_depth",
- "skill_retrieval_retrieve_max_branch_choices",
- "skill_retrieval_retrieve_max_parallel_branches",
- "skill_retrieval_retrieve_request_timeout_seconds",
]);
function classifyKey(key: string): string {
@@ -511,8 +519,6 @@ function getBooleanKeyLabel(key: string, t: (key: string) => string): string {
a2ui_enabled: t('config.booleanLabels.enabled'),
symphony_enabled: t('config.booleanLabels.enabled'),
skill_retrieval_enabled: t('config.booleanLabels.enabled'),
- skill_retrieval_compact_codes_enabled: t('config.booleanLabels.skillRetrievalCompact'),
- skill_retrieval_flatten_tree: t('config.booleanLabels.skillRetrievalFlat'),
};
return labels[key] ?? key;
}
@@ -528,6 +534,10 @@ function isSensitiveKey(key: string): boolean {
);
}
+function isMultilineConfigKey(key: string): boolean {
+ return MULTILINE_CONFIG_KEYS.has(key);
+}
+
function normalizeConfigValue(value: unknown): string {
if (value === null || value === undefined) return "";
if (typeof value === "string") return value;
@@ -585,14 +595,17 @@ const KEY_DISPLAY_I18N: Record<string, string> = {
skill_retrieval_build_max_depth: "config.keys.skillRetrievalBuildMaxDepth",
skill_retrieval_build_root_categories: "config.keys.skillRetrievalBuildRootCategories",
skill_retrieval_build_max_workers: "config.keys.skillRetrievalBuildMaxWorkers",
+ skill_retrieval_build_max_retries: "config.keys.skillRetrievalBuildMaxRetries",
skill_retrieval_build_request_timeout_seconds: "config.keys.skillRetrievalBuildTimeout",
- skill_retrieval_retrieve_top_k: "config.keys.skillRetrievalTopK",
- skill_retrieval_compact_codes_enabled: "config.keys.skillRetrievalCompactCodes",
- skill_retrieval_flatten_tree: "config.keys.skillRetrievalFlattenTree",
+ skill_retrieval_build_classification_batch_limit: "config.keys.skillRetrievalBuildClassificationBatchLimit",
+ skill_retrieval_build_discovery_seed: "config.keys.skillRetrievalBuildDiscoverySeed",
+ skill_retrieval_build_postprocess_enabled: "config.keys.skillRetrievalBuildPostprocessEnabled",
+ skill_retrieval_build_postprocess_max_passes: "config.keys.skillRetrievalBuildPostprocessMaxPasses",
+ skill_retrieval_build_postprocess_min_skills: "config.keys.skillRetrievalBuildPostprocessMinSkills",
+ skill_retrieval_build_equivalence_enabled: "config.keys.skillRetrievalBuildEquivalenceEnabled",
+ skill_retrieval_retrieve_compact_codes_enabled: "config.keys.skillRetrievalCompactCodes",
+ skill_retrieval_retrieve_flatten_tree: "config.keys.skillRetrievalFlattenTree",
skill_retrieval_retrieve_max_exposure_depth: "config.keys.skillRetrievalMaxExposureDepth",
- skill_retrieval_retrieve_max_branch_choices: "config.keys.skillRetrievalMaxBranchChoices",
- skill_retrieval_retrieve_max_parallel_branches: "config.keys.skillRetrievalMaxParallelBranches",
- skill_retrieval_retrieve_request_timeout_seconds: "config.keys.skillRetrievalRetrieveTimeout",
};
const KEY_PLACEHOLDER_I18N: Record<string, string> = {
memory_forbidden_description: "config.keys.memoryForbiddenDescriptionPlaceholder",
@@ -613,16 +626,19 @@ const KEY_SORT_PRIORITY: Record<string, number> = {
skill_retrieval_enabled: 0,
skill_retrieval_build_branching_factor: 10,
skill_retrieval_build_max_depth: 11,
- skill_retrieval_build_root_categories: 12,
- skill_retrieval_build_max_workers: 13,
+ skill_retrieval_build_max_workers: 12,
+ skill_retrieval_build_max_retries: 13,
skill_retrieval_build_request_timeout_seconds: 14,
- skill_retrieval_retrieve_top_k: 20,
- skill_retrieval_compact_codes_enabled: 21,
- skill_retrieval_flatten_tree: 22,
- skill_retrieval_retrieve_max_exposure_depth: 23,
- skill_retrieval_retrieve_max_branch_choices: 24,
- skill_retrieval_retrieve_max_parallel_branches: 25,
- skill_retrieval_retrieve_request_timeout_seconds: 26,
+ skill_retrieval_build_classification_batch_limit: 15,
+ skill_retrieval_build_discovery_seed: 16,
+ skill_retrieval_build_postprocess_enabled: 17,
+ skill_retrieval_build_postprocess_max_passes: 18,
+ skill_retrieval_build_postprocess_min_skills: 19,
+ skill_retrieval_build_equivalence_enabled: 20,
+ skill_retrieval_build_root_categories: 21,
+ skill_retrieval_retrieve_compact_codes_enabled: 31,
+ skill_retrieval_retrieve_flatten_tree: 32,
+ skill_retrieval_retrieve_max_exposure_depth: 33,
memory_forbidden_enabled: 0,
memory_forbidden_description: 1,
model: 0,
@@ -796,6 +812,25 @@ function GroupSection({
</select>
</div>
</div>
+ ) : isMultilineConfigKey(key) ? (
+ <div className="flex items-start gap-2">
+ <span
+ className={`inline-flex w-3 justify-center shrink-0 font-semibold leading-none select-none pt-2 ${isRequiredModelField(key) ? "text-danger" : "text-transparent"
+ }`}
+ aria-hidden="true"
+ >
+ *
+ </span>
+ <div className="relative flex-1">
+ <textarea
+ value={draftValues[key] ?? value}
+ onChange={(e) => onChange(key, e.target.value)}
+ placeholder={KEY_PLACEHOLDER_I18N[key] ? t(KEY_PLACEHOLDER_I18N[key]) : t('config.enterValue')}
+ className="w-full min-h-[320px] rounded-md border border-border bg-bg px-3 py-2 font-mono text-[12px] leading-5 outline-none focus:border-accent whitespace-pre"
+ spellCheck={false}
+ />
+ </div>
+ </div>
) : (
<div className="flex items-center gap-2">
<span
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
index 82cbbc0ea7..9d749c4063 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
@@ -597,7 +597,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
const data = await webRequest<{ success: boolean; result?: string }>(
"skills.retrieval.index_build",
withSession(),
- { timeoutMs: 10 * 60_000 }
+ { timeoutMs: 31 * 60_000 }
);
setRetrievalResult(data.result || "");
await fetchRetrievalStatus();
diff --git a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts
index 28ed628805..b1551e318c 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts
@@ -109,7 +109,14 @@ export function normalizeToolCallPayload(payload: UnknownPayload): NormalizedToo
export function normalizeToolResultPayload(payload: UnknownPayload): NormalizedToolResult {
const toolResultPayload = asRecord(payload.tool_result) ?? payload;
+ const rawOutputRecord =
+ asRecord(toolResultPayload.raw_output) ?? asRecord(toolResultPayload.rawOutput);
+ const rawOutputResult =
+ typeof rawOutputRecord?.result === 'string'
+ ? rawOutputRecord.result
+ : undefined;
const result =
+ rawOutputResult ||
(typeof toolResultPayload.result === 'string' &&
toolResultPayload.result) ||
(toolResultPayload.data != null ? String(toolResultPayload.data) : '') ||
@@ -138,7 +145,10 @@ export function normalizeToolResultPayload(payload: UnknownPayload): NormalizedT
? toolResultPayload.summary
: success ? undefined : '❌';
const skillTree =
- parseSkillTreePath(toolResultPayload.raw_output) ?? parseSkillTreePath(toolResultPayload);
+ parseSkillTreePath(toolResultPayload.raw_output) ??
+ parseSkillTreePath(toolResultPayload.rawOutput) ??
+ parseSkillTreePath(toolResultPayload) ??
+ parseSkillTreePath(toolResultPayload.result);
return {
toolName,
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 9633e62f53..be32d587a9 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -670,7 +670,7 @@
"memoryForbiddenEnabled": "Enable",
"memoryForbiddenDescription": "Forbidden memory content description",
"memoryForbiddenDescriptionPlaceholder": "e.g. passwords, API keys, secrets, tokens, credit card numbers, ID numbers, phone numbers",
- "skillRetrievalBuildRootCategoriesPlaceholder": "Leave empty for built-in defaults, or enter a JSON/YAML file path",
+ "skillRetrievalBuildRootCategoriesPlaceholder": "Edit the YAML/JSON root taxonomy directly",
"agentSkillsPlaceholder": "Click to select skills",
"agentSkillsEmpty": "No installed skills",
"agentName": "Name",
@@ -692,22 +692,25 @@
"teamMemberAgentKey": "Agent Key",
"symphonyEnabled": "Enable Skill Symphony",
"skillRetrievalEnabled": "Enable skill retrieval",
- "skillRetrievalBuildBranchingFactor": "Tree branching factor",
+ "skillRetrievalBuildBranchingFactor": "Split threshold base",
"skillRetrievalBuildMaxDepth": "Max tree depth",
"skillRetrievalBuildRootCategories": "Root taxonomy config",
"skillRetrievalBuildMaxWorkers": "Build workers",
+ "skillRetrievalBuildMaxRetries": "Build retries",
"skillRetrievalBuildTimeout": "Build request timeout (s)",
- "skillRetrievalTopK": "Retrieved skill count",
- "skillRetrievalCompactCodes": "Compact retrieval",
- "skillRetrievalFlattenTree": "Flat tree retrieval",
- "skillRetrievalMaxExposureDepth": "Max exposure depth",
- "skillRetrievalMaxBranchChoices": "Branch choices per step",
- "skillRetrievalMaxParallelBranches": "Parallel branches",
- "skillRetrievalRetrieveTimeout": "Retrieve request timeout (s)"
+ "skillRetrievalBuildClassificationBatchLimit": "Classification batch limit",
+ "skillRetrievalBuildDiscoverySeed": "Discovery seed",
+ "skillRetrievalBuildPostprocessEnabled": "Enable build postprocess",
+ "skillRetrievalBuildPostprocessMaxPasses": "Postprocess max passes",
+ "skillRetrievalBuildPostprocessMinSkills": "Postprocess min skills",
+ "skillRetrievalBuildEquivalenceEnabled": "Enable equivalent branch merge",
+ "skillRetrievalCompactCodes": "Compact code mode",
+ "skillRetrievalFlattenTree": "Flatten retrieval tree",
+ "skillRetrievalMaxExposureDepth": "Exposure depth per call"
},
"keyHelp": {
"skillCreate": "Install `skill-creator` and `teamskill-creator` before enabling",
- "skillRetrievalBuildRootCategories": "Optional. Leave empty to use the built-in root taxonomy; when set, use a JSON/YAML file containing tree_root_categories or root_categories."
+ "skillRetrievalBuildRootCategories": "Edit YAML/JSON containing tree_root_categories or root_categories directly. The page shows the default taxonomy as a reference; saving writes the config content itself, not an external file path."
},
"hideValue": "Hide value",
"showValue": "Show value",
@@ -807,9 +810,7 @@
"freeSearchDdg": "Enable DuckDuckGo (including DDG via Jina)",
"freeSearchBing": "Enable Bing",
"enabled": "Enable",
- "kvCacheAffinity": "Compute affinity (KV cache release)",
- "skillRetrievalCompact": "Enable compact code",
- "skillRetrievalFlat": "Enable flat tree"
+ "kvCacheAffinity": "Compute affinity (KV cache release)"
},
"permissionsTools": {
"title": "Tool Guardrail (permissions.tools)",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 7e8d3422c0..3f00783549 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -669,7 +669,7 @@
"memoryForbiddenEnabled": "启用",
"memoryForbiddenDescription": "禁止记忆内容描述",
"memoryForbiddenDescriptionPlaceholder": "例如:密码、API密钥、Secret、Token、信用卡号、身份证号、手机号等敏感信息",
- "skillRetrievalBuildRootCategoriesPlaceholder": "留空使用内置默认分层,或填写 JSON/YAML 文件路径",
+ "skillRetrievalBuildRootCategoriesPlaceholder": "直接编辑 YAML/JSON 树根分层配置",
"agentSkillsPlaceholder": "点击选择技能",
"agentSkillsEmpty": "暂无已安装技能",
"agentName": "名称",
@@ -691,22 +691,25 @@
"teamMemberAgentKey": "Agent Key",
"symphonyEnabled": "启用技能交响乐",
"skillRetrievalEnabled": "启用技能检索",
- "skillRetrievalBuildBranchingFactor": "树分支数",
+ "skillRetrievalBuildBranchingFactor": "拆分阈值基数",
"skillRetrievalBuildMaxDepth": "最大树深",
"skillRetrievalBuildRootCategories": "树根分层配置",
"skillRetrievalBuildMaxWorkers": "构建并发数",
+ "skillRetrievalBuildMaxRetries": "构建重试次数",
"skillRetrievalBuildTimeout": "构建请求超时(秒)",
- "skillRetrievalTopK": "检索返回数量",
- "skillRetrievalCompactCodes": "Compact 检索",
- "skillRetrievalFlattenTree": "扁平树检索",
- "skillRetrievalMaxExposureDepth": "最大暴露深度",
- "skillRetrievalMaxBranchChoices": "每层分支选择数",
- "skillRetrievalMaxParallelBranches": "并行分支数",
- "skillRetrievalRetrieveTimeout": "检索请求超时(秒)"
+ "skillRetrievalBuildClassificationBatchLimit": "分类批大小上限",
+ "skillRetrievalBuildDiscoverySeed": "分支发现随机种子",
+ "skillRetrievalBuildPostprocessEnabled": "启用构建后处理",
+ "skillRetrievalBuildPostprocessMaxPasses": "后处理最大轮次",
+ "skillRetrievalBuildPostprocessMinSkills": "后处理最小技能数",
+ "skillRetrievalBuildEquivalenceEnabled": "启用等价分支合并",
+ "skillRetrievalCompactCodes": "紧凑编码模式",
+ "skillRetrievalFlattenTree": "平铺检索树",
+ "skillRetrievalMaxExposureDepth": "单次披露深度"
},
"keyHelp": {
"skillCreate": "建议先安装 `skill-creator` 和 `teamskill-creator`,再开启",
- "skillRetrievalBuildRootCategories": "可选。留空使用内置默认树分层;填写时应为包含 tree_root_categories 或 root_categories 的 JSON/YAML 文件路径。"
+ "skillRetrievalBuildRootCategories": "直接编辑包含 tree_root_categories 或 root_categories 的 YAML/JSON;页面会展示默认分层供参考。保存后会写入配置内容本身,而不是外部文件路径。"
},
"hideValue": "隐藏明文",
"showValue": "显示明文",
@@ -806,9 +809,7 @@
"freeSearchDdg": "启用 DuckDuckGo(含 DDG via Jina)",
"freeSearchBing": "启用 Bing",
"enabled": "启用",
- "kvCacheAffinity": "算力亲和(KV 释放)",
- "skillRetrievalCompact": "启用 compact code",
- "skillRetrievalFlat": "启用 flat tree"
+ "kvCacheAffinity": "算力亲和(KV 释放)"
},
"permissionsTools": {
"title": "工具防护(permissions.tools)",
diff --git a/jiuwenswarm/channels/web/frontend/src/types/skillTree.ts b/jiuwenswarm/channels/web/frontend/src/types/skillTree.ts
index b2ece773eb..316178610e 100644
--- a/jiuwenswarm/channels/web/frontend/src/types/skillTree.ts
+++ b/jiuwenswarm/channels/web/frontend/src/types/skillTree.ts
@@ -1,8 +1,8 @@
/**
* 技能树路径类型定义
*
- * 由后端 agentic search(symphony 渐进检索)在工具结果的 raw_output.skill_tree
- * 中下发,前端用于在对话时间线内联回放「技能树路径流转」。
+ * 由后端 symphony 技能检索工具在工具结果的 raw_output.skill_tree 中下发,
+ * 前端用于在对话时间线内联回放「技能树路径流转」。
*/
export interface SkillTreeNamedId {
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index 27ae944fd2..cecb1c391f 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -20,6 +20,25 @@ logger = logging.getLogger(__name__)
_CONFIG_MODULE_DIR = Path(__file__).parent
CONFIG_YAML_PATH = get_config_file()
+_SKILL_RETRIEVAL_PUBLIC_BUILD_KEYS = {
+ "branching_factor",
+ "max_depth",
+ "root_categories",
+ "max_workers",
+ "max_retries",
+ "request_timeout_seconds",
+ "classification_batch_limit",
+ "discovery_seed",
+ "postprocess_enabled",
+ "postprocess_max_passes",
+ "postprocess_min_skills",
+ "equivalence_enabled",
+}
+_SKILL_RETRIEVAL_PUBLIC_RETRIEVE_KEYS = {
+ "compact_codes_enabled",
+ "flatten_tree",
+ "max_exposure_depth",
+}
# Check if user workspace exists and use it if configured via env
_user_config = os.getenv("JIUWENSWARM_CONFIG_DIR")
@@ -281,7 +300,36 @@ def update_symphony_in_config(updates: dict[str, Any]) -> None:
def update_skill_retrieval_in_config(updates: dict[str, Any]) -> None:
"""更新 symphony.skill_retrieval 配置段并写回。"""
- update_symphony_in_config({"skill_retrieval": updates})
+ data = load_yaml_round_trip(CONFIG_YAML_PATH)
+ if "symphony" not in data or data["symphony"] is None:
+ data["symphony"] = {}
+ symphony = data["symphony"]
+ if "skill_retrieval" not in symphony or symphony["skill_retrieval"] is None:
+ symphony["skill_retrieval"] = {}
+ section = symphony["skill_retrieval"]
+
+ def prune_internal_keys() -> None:
+ build = section.get("build")
+ if isinstance(build, dict):
+ for key in list(build.keys()):
+ if key not in _SKILL_RETRIEVAL_PUBLIC_BUILD_KEYS:
+ build.pop(key, None)
+ if not build:
+ section.pop("build", None)
+ retrieve = section.get("retrieve")
+ if isinstance(retrieve, dict):
+ for key in list(retrieve.keys()):
+ if key not in _SKILL_RETRIEVAL_PUBLIC_RETRIEVE_KEYS:
+ retrieve.pop(key, None)
+ if not retrieve:
+ section.pop("retrieve", None)
+ elif "retrieve" in section:
+ section.pop("retrieve", None)
+
+ prune_internal_keys()
+ _merge_config_dict(section, updates)
+ prune_internal_keys()
+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)
def update_permissions_enabled_in_config(value: bool) -> None:
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index d892e2d361..7a7c0e6b82 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -35,6 +35,7 @@ from jiuwenswarm.common.config import (
update_preferred_language_in_config,
update_context_engine_enabled_in_config,
update_kv_cache_affinity_enabled_in_config,
+ update_skill_retrieval_in_config,
update_symphony_in_config,
update_permissions_enabled_in_config,
update_memory_forbidden_enabled_in_config,
@@ -58,6 +59,10 @@ from jiuwenswarm.common.utils import (
from jiuwenswarm.agents.harness.common.auto_harness import AutoHarnessService
from jiuwenswarm.agents.harness.common.tools.web_file_download import build_file_download_info
from jiuwenswarm.common.version import __version__
+from jiuwenswarm.symphony.skill_retrieval.taxonomy_config import (
+ coerce_root_categories_value,
+ root_categories_to_text,
+)
for _jiuwen_log in LogManager.get_all_loggers().values():
_jiuwen_log.set_level(logging.INFO)
@@ -437,64 +442,27 @@ _CONFIG_YAML_KEYS = frozenset({
_SYMPHONY_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {
"symphony_enabled": (("enabled",), "bool", False),
- "skill_retrieval_enabled": (("skill_retrieval", "enabled"), "bool", False),
- "skill_retrieval_build_branching_factor": (
- ("skill_retrieval", "build", "branching_factor"),
- "int",
- 128,
- ),
- "skill_retrieval_build_max_depth": (("skill_retrieval", "build", "max_depth"), "int", 6),
- "skill_retrieval_build_root_categories": (
- ("skill_retrieval", "build", "root_categories"),
- "str",
- "",
- ),
- "skill_retrieval_build_max_workers": (("skill_retrieval", "build", "max_workers"), "int", 2),
- "skill_retrieval_build_request_timeout_seconds": (
- ("skill_retrieval", "build", "request_timeout_seconds"),
- "float",
- 420.0,
- ),
- "skill_retrieval_retrieve_top_k": (("skill_retrieval", "retrieve", "top_k"), "int", 10),
- "skill_retrieval_compact_codes_enabled": (
- ("skill_retrieval", "retrieve", "compact_codes_enabled"),
- "bool",
- False,
- ),
- "skill_retrieval_flatten_tree": (
- ("skill_retrieval", "retrieve", "flatten_tree"),
- "bool",
- False,
- ),
- "skill_retrieval_retrieve_max_exposure_depth": (
- ("skill_retrieval", "retrieve", "max_exposure_depth"),
- "int",
- 99,
- ),
- "skill_retrieval_retrieve_max_branch_choices": (
- ("skill_retrieval", "retrieve", "max_branch_choices"),
- "int",
- 2,
- ),
- "skill_retrieval_retrieve_max_parallel_branches": (
- ("skill_retrieval", "retrieve", "max_parallel_branches"),
- "int",
- 2,
- ),
- "skill_retrieval_retrieve_request_timeout_seconds": (
- ("skill_retrieval", "retrieve", "request_timeout_seconds"),
- "float",
- 120.0,
- ),
}
_SYMPHONY_CONFIG_KEYS = tuple(_SYMPHONY_CONFIG_SPECS.keys())
-_SKILL_RETRIEVAL_CONFIG_KEYS = frozenset(
- key for key in _SYMPHONY_CONFIG_KEYS if key.startswith("skill_retrieval_")
-)
-_SKILL_RETRIEVAL_CONFIG_SPECS = {
- key: spec for key, spec in _SYMPHONY_CONFIG_SPECS.items()
- if key in _SKILL_RETRIEVAL_CONFIG_KEYS
+_SKILL_RETRIEVAL_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {
+ "skill_retrieval_enabled": (("enabled",), "bool", False),
+ "skill_retrieval_build_branching_factor": (("build", "branching_factor"), "int", 128),
+ "skill_retrieval_build_max_depth": (("build", "max_depth"), "int", 6),
+ "skill_retrieval_build_root_categories": (("build", "root_categories"), "root_categories", ""),
+ "skill_retrieval_build_max_workers": (("build", "max_workers"), "int", 2),
+ "skill_retrieval_build_max_retries": (("build", "max_retries"), "non_negative_int", 2),
+ "skill_retrieval_build_request_timeout_seconds": (("build", "request_timeout_seconds"), "float", 420.0),
+ "skill_retrieval_build_classification_batch_limit": (("build", "classification_batch_limit"), "int", 32),
+ "skill_retrieval_build_discovery_seed": (("build", "discovery_seed"), "raw_int", 42),
+ "skill_retrieval_build_postprocess_enabled": (("build", "postprocess_enabled"), "bool", True),
+ "skill_retrieval_build_postprocess_max_passes": (("build", "postprocess_max_passes"), "non_negative_int", 1),
+ "skill_retrieval_build_postprocess_min_skills": (("build", "postprocess_min_skills"), "int", 6),
+ "skill_retrieval_build_equivalence_enabled": (("build", "equivalence_enabled"), "bool", True),
+ "skill_retrieval_retrieve_compact_codes_enabled": (("retrieve", "compact_codes_enabled"), "bool", False),
+ "skill_retrieval_retrieve_flatten_tree": (("retrieve", "flatten_tree"), "bool", False),
+ "skill_retrieval_retrieve_max_exposure_depth": (("retrieve", "max_exposure_depth"), "int", 99),
}
+_SKILL_RETRIEVAL_CONFIG_KEYS = tuple(_SKILL_RETRIEVAL_CONFIG_SPECS.keys())
def _coerce_config_panel_value(value: Any, value_type: str, default: Any) -> Any:
@@ -505,11 +473,23 @@ def _coerce_config_panel_value(value: Any, value_type: str, default: Any) -> Any
return max(1, int(value))
except (TypeError, ValueError):
return default
+ if value_type == "non_negative_int":
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return default
+ if value_type == "raw_int":
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return default
if value_type == "float":
try:
return max(0.0, float(value))
except (TypeError, ValueError):
return default
+ if value_type == "root_categories":
+ return coerce_root_categories_value(value, allow_path=False) or ""
return str(value if value is not None else default)
@@ -540,14 +520,27 @@ def _flatten_symphony_for_config_panel(raw: dict[str, Any]) -> dict[str, str]:
value = _get_nested_config_value(symphony, path, default)
if value_type == "bool":
flat[key] = "true" if bool(value) else "false"
+ elif value_type == "root_categories":
+ flat[key] = root_categories_to_text(value)
else:
flat[key] = str(value)
+ flat.update(_flatten_skill_retrieval_for_config_panel(raw))
return flat
def _flatten_skill_retrieval_for_config_panel(raw: dict[str, Any]) -> dict[str, str]:
- flat = _flatten_symphony_for_config_panel(raw)
- return {key: value for key, value in flat.items() if key in _SKILL_RETRIEVAL_CONFIG_KEYS}
+ symphony = raw.get("symphony") if isinstance(raw.get("symphony"), dict) else {}
+ section = symphony.get("skill_retrieval") if isinstance(symphony.get("skill_retrieval"), dict) else {}
+ flat: dict[str, str] = {}
+ for key, (path, value_type, default) in _SKILL_RETRIEVAL_CONFIG_SPECS.items():
+ value = _get_nested_config_value(section, path, default)
+ if value_type == "bool":
+ flat[key] = "true" if bool(value) else "false"
+ elif value_type == "root_categories":
+ flat[key] = root_categories_to_text(value)
+ else:
+ flat[key] = str(value)
+ return flat
def _build_symphony_config_update(params: dict[str, Any]) -> dict[str, Any]:
@@ -561,9 +554,13 @@ def _build_symphony_config_update(params: dict[str, Any]) -> dict[str, Any]:
def _build_skill_retrieval_config_update(params: dict[str, Any]) -> dict[str, Any]:
- updates = _build_symphony_config_update(params)
- section = updates.get("skill_retrieval")
- return section if isinstance(section, dict) else {}
+ updates: dict[str, Any] = {}
+ for key, (path, value_type, default) in _SKILL_RETRIEVAL_CONFIG_SPECS.items():
+ if key not in params:
+ continue
+ value = _coerce_config_panel_value(params[key], value_type, default)
+ _set_nested_config_value(updates, path, value)
+ return updates
def _flatten_modes_team_for_config_panel(raw: dict[str, Any]) -> dict[str, str]:
@@ -841,9 +838,14 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
payload.setdefault("memory_forbidden_description", "")
for key, value in get_default_a2ui_config_payload().items():
payload.setdefault(key, value)
- for key, (_, value_type, default) in _SYMPHONY_CONFIG_SPECS.items():
+ for key, (_, value_type, default) in {
+ **_SYMPHONY_CONFIG_SPECS,
+ **_SKILL_RETRIEVAL_CONFIG_SPECS,
+ }.items():
if value_type == "bool":
default_text = "true" if default else "false"
+ elif value_type == "root_categories":
+ default_text = root_categories_to_text(default)
else:
default_text = str(default)
payload.setdefault(key, default_text)
@@ -962,6 +964,17 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
except Exception as e:
logger.warning("[config.set] 写回 symphony 失败: %s", e)
+ try:
+ skill_retrieval_updates = _build_skill_retrieval_config_update(params)
+ except ValueError as exc:
+ raise _ConfigBadRequest(str(exc)) from exc
+ if skill_retrieval_updates:
+ try:
+ update_skill_retrieval_in_config(skill_retrieval_updates)
+ yaml_updated.extend(k for k in _SKILL_RETRIEVAL_CONFIG_KEYS if k in params)
+ except Exception as e:
+ logger.warning("[config.set] 写回 skill_retrieval 失败: %s", e)
+
for env_key, value in env_updates.items():
os.environ[env_key] = value
if env_updates:
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 6d4220aac9..f1f1a2a99c 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -60,14 +60,9 @@ symphony:
postprocess_min_skills: 6
equivalence_enabled: true
retrieve:
- top_k: 10
compact_codes_enabled: false
flatten_tree: false
max_exposure_depth: 99
- max_branch_choices: 2
- max_parallel_branches: 2
- max_tokens: 96
- request_timeout_seconds: 120
# 日志目录:~/.jiuwenswarm/agent/.logs/
# gateway.log / channel.log / agent_server.log 按源码路径分流;full.log 为汇总。
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 747a44488c..8dd18ed461 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -531,6 +531,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
rail_infos = [
_RailBuildInfo("_runtime_prompt_rail", self._build_runtime_prompt_rail),
_RailBuildInfo("_response_prompt_rail", self._build_response_prompt_rail),
+ _RailBuildInfo("_skill_retrieval_prompt_rail", self._build_skill_retrieval_prompt_rail),
_RailBuildInfo("_stream_event_rail", self._build_stream_event_rail),
_RailBuildInfo("_security_rail", self._build_security_rail),
_RailBuildInfo("_lsp_rail", self._build_lsp_rail_via_config),
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index ecb5151f62..3786f3f48f 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -192,6 +192,9 @@ from jiuwenswarm.agents.harness.common.tools import (
is_skill_retrieval_enabled,
SymphonyToolkit,
)
+from jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail import (
+ SkillRetrievalPromptRail,
+)
from jiuwenswarm.agents.harness.common.tools.wiki_tools import wiki_ingest, wiki_query, wiki_lint
from jiuwenswarm.agents.harness.common.tools.acp_output_tools import get_tools as get_acp_output_tools
from jiuwenswarm.agents.harness.common.tools.multi_session_toolkits import MultiSessionToolkit
@@ -1856,6 +1859,8 @@ class JiuWenSwarmDeepAdapter:
@staticmethod
def _resolve_skill_mode(config: dict[str, Any]) -> str:
"""Validate configured skill mode and fallback safely on invalid values."""
+ if is_skill_retrieval_enabled():
+ return SkillUseRail.SKILL_MODE_AUTO_LIST
raw_skill_mode = config.get("skill_mode", SkillUseRail.SKILL_MODE_ALL)
valid_modes = {
SkillUseRail.SKILL_MODE_AUTO_LIST,
@@ -2232,6 +2237,12 @@ class JiuWenSwarmDeepAdapter:
self, config: dict[str, Any], include_tools: bool = False
) -> SkillUseRail | None:
"""Build SkillUseRail."""
+ if is_skill_retrieval_enabled():
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] SkillUseRail skipped: "
+ "agentic skill retrieval is enabled"
+ )
+ return None
try:
skill_mode = self._resolve_skill_mode(config)
logger.info("[JiuWenSwarmDeepAdapter] current skill_mode: %s", skill_mode)
@@ -2440,6 +2451,16 @@ class JiuWenSwarmDeepAdapter:
rail = None
return rail
+ def _build_skill_retrieval_prompt_rail(self) -> SkillRetrievalPromptRail | None:
+ """Build lightweight agentic skill retrieval prompt guidance."""
+ if not is_skill_retrieval_enabled():
+ return None
+ try:
+ return SkillRetrievalPromptRail(manager=self._skill_manager)
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] SkillRetrievalPromptRail create failed: %s", exc)
+ return None
+
def _build_agent_rails(
self, config: dict[str, Any], config_base: dict[str, Any], *, mode: str = "agent.plan"
) -> list[Any]:
@@ -2500,6 +2521,10 @@ class JiuWenSwarmDeepAdapter:
{"config": config, "include_tools": self._skill_include_tools_for_profile()},
),
)
+ rail_infos.insert(
+ 3 if self._filesystem_rail_enabled_for_profile() else 2,
+ _RailBuildInfo("_skill_retrieval_prompt_rail", self._build_skill_retrieval_prompt_rail),
+ )
rails_list = []
for info in rail_infos:
@@ -2655,22 +2680,25 @@ class JiuWenSwarmDeepAdapter:
False,
)
- # Reuse existing SkillUseRail to preserve dynamically loaded skills
- # from activate_package() / load_harness_config()
- if self._skill_rail is None:
- self._skill_rail = self._build_skill_rail(
- config,
- include_tools=self._skill_include_tools_for_profile(),
- )
+ if is_skill_retrieval_enabled():
+ self._skill_rail = None
else:
- # Update existing rail's skill_mode if changed
- new_skill_mode = self._resolve_skill_mode(config)
- if self._skill_rail.skill_mode != new_skill_mode:
- self._skill_rail.skill_mode = new_skill_mode
- # Update disabled_skills
- new_disabled = self._skill_manager.list_execution_disabled_skills()
- if self._skill_rail.disabled_skills != new_disabled:
- self._skill_rail.disabled_skills = new_disabled
+ # Reuse existing SkillUseRail to preserve dynamically loaded skills
+ # from activate_package() / load_harness_config()
+ if self._skill_rail is None:
+ self._skill_rail = self._build_skill_rail(
+ config,
+ include_tools=self._skill_include_tools_for_profile(),
+ )
+ else:
+ # Update existing rail's skill_mode if changed
+ new_skill_mode = self._resolve_skill_mode(config)
+ if self._skill_rail.skill_mode != new_skill_mode:
+ self._skill_rail.skill_mode = new_skill_mode
+ # Update disabled_skills
+ new_disabled = self._skill_manager.list_execution_disabled_skills()
+ if self._skill_rail.disabled_skills != new_disabled:
+ self._skill_rail.disabled_skills = new_disabled
if not self._filesystem_rail_enabled_for_profile():
self._filesystem_rail = None
@@ -5761,6 +5789,18 @@ class JiuWenSwarmDeepAdapter:
raw_output = result_info.get("raw_output")
if raw_output is None:
raw_output = result_info.get("rawOutput")
+ if raw_output is None and "skill_tree" in result_info:
+ raw_output = {}
+ for key, value in result_info.items():
+ if key not in ("tool_name", "name", "tool_call_id", "toolCallId"):
+ raw_output[key] = value
+ result_value = result_info.get("result")
+ if (
+ raw_output is None
+ and isinstance(result_value, dict)
+ and "skill_tree" in result_value
+ ):
+ raw_output = result_value
if raw_output is not None:
result_payload["raw_output"] = raw_output
for key in (
diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.py
index b7a989f935..a570b74947 100644
--- a/jiuwenswarm/server/utils/stream_utils.py
+++ b/jiuwenswarm/server/utils/stream_utils.py
@@ -272,6 +272,18 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any
raw_output = result_info.get("raw_output")
if raw_output is None:
raw_output = result_info.get("rawOutput")
+ if raw_output is None and "skill_tree" in result_info:
+ raw_output = {}
+ for key, value in result_info.items():
+ if key not in ("tool_name", "name", "tool_call_id", "toolCallId"):
+ raw_output[key] = value
+ result_value = result_info.get("result")
+ if (
+ raw_output is None
+ and isinstance(result_value, dict)
+ and "skill_tree" in result_value
+ ):
+ raw_output = result_value
if raw_output is not None:
result_payload["raw_output"] = raw_output
for key in (
diff --git a/jiuwenswarm/symphony/agent/__init__.py b/jiuwenswarm/symphony/agent/__init__.py
new file mode 100644
index 0000000000..764b318d44
--- /dev/null
+++ b/jiuwenswarm/symphony/agent/__init__.py
@@ -0,0 +1,21 @@
+"""Agent-facing retrieval helpers built on top of the symphony skill index."""
+
+from __future__ import annotations
+
+from .agentic_retrieval_toolkit import (
+ AgenticRetrievalToolKit,
+ build_skill_index,
+ is_agentic_retrieval_enabled,
+ render_skill_retrieval_prompt,
+ skill_branch_explore,
+ skill_branch_peek,
+)
+
+__all__ = [
+ "AgenticRetrievalToolKit",
+ "build_skill_index",
+ "is_agentic_retrieval_enabled",
+ "render_skill_retrieval_prompt",
+ "skill_branch_explore",
+ "skill_branch_peek",
+]
diff --git a/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py b/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py
new file mode 100644
index 0000000000..29d90c8710
--- /dev/null
+++ b/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py
@@ -0,0 +1,1118 @@
+"""Agentic skill-tree disclosure toolkit.
+
+This module intentionally builds on the existing symphony/dispatch index and
+disclosure primitives. It does not call an LLM; the calling agent decides which
+tree branches to inspect next.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Sequence
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from threading import RLock
+from time import monotonic
+from typing import Any
+
+from jiuwenswarm.symphony.skill_retrieval.config import RetrieveSettings, load_settings
+from jiuwenswarm.symphony.skill_retrieval.dispatch_imports import dispatch_import_path
+from jiuwenswarm.symphony.skill_retrieval.index_service import SkillIndexService
+from jiuwenswarm.symphony.skill_retrieval.markdown import render_disabled
+
+
+@dataclass(frozen=True)
+class _NodeStats:
+ branch_count: int
+ skill_count: int
+
+
+@dataclass(frozen=True)
+class _DescriptionParts:
+ description: str = ""
+ select_when: str = ""
+ dont_select_when: str = ""
+
+
+@dataclass(frozen=True)
+class _SkillEntry:
+ label: str
+ worker_id: str
+ description: str
+ skill_md_path: str
+
+
+@dataclass(frozen=True)
+class _ToolkitCacheEntry:
+ toolkit: "AgenticRetrievalToolKit"
+
+
+@dataclass(frozen=True)
+class _StatusCacheEntry:
+ created_at: float
+ status: dict[str, Any]
+
+
+@dataclass(frozen=True)
+class _ReadyStatusCacheKey:
+ skills_dir: str
+ artifact_root: str
+ build: tuple[tuple[str, str], ...]
+ llm: tuple[tuple[str, str], ...]
+ index_artifacts: tuple[Any, ...]
+ state_file: tuple[int, int] | None
+
+
+@dataclass(frozen=True)
+class _SettingsCacheEntry:
+ key: tuple[Any, ...]
+ settings: Any
+
+
+_INDEX_FILENAMES = ("tree_index.yaml", "catalog.jsonl", "manifest.json")
+_STATE_FILENAME = "state.json"
+_SETTINGS_ENV_KEYS = (
+ "SYMPHONY_SKILL_RETRIEVAL_ENABLED",
+ "SYMPHONY_SKILL_RETRIEVAL_ROOT",
+ "MODEL_NAME",
+ "API_KEY",
+ "API_BASE",
+)
+_READY_STATUS_TTL_SECONDS = 30.0
+_SETTINGS_CACHE: _SettingsCacheEntry | None = None
+_TOOLKIT_CACHE: dict[tuple[Any, ...], _ToolkitCacheEntry] = {}
+_READY_STATUS_CACHE: dict[_ReadyStatusCacheKey, _StatusCacheEntry] = {}
+_CACHE_LOCK = RLock()
+
+
+class AgenticRetrievalToolKit:
+ """Expose indexed skill-tree disclosure operations for an agent."""
+
+ def __init__(
+ self,
+ *,
+ loaded_index: Any,
+ progressive_config: Any,
+ top_k: int,
+ ) -> None:
+ self._loaded_index = loaded_index
+ self._root = loaded_index.tree_root
+ self._progressive_config = progressive_config
+ self._top_k = max(1, int(top_k))
+ self._node_by_id: dict[str, Any] = {}
+ self._path_by_id: dict[str, tuple[str, ...]] = {}
+ self._stats_by_id: dict[str, _NodeStats] = {}
+ self._leaf_ids: set[str] = set()
+ self._catalog_by_payload: dict[str, Any] = {}
+ for record in tuple(getattr(loaded_index, "catalog_records", ()) or ()):
+ payload = str(getattr(record, "payload", "") or "").strip()
+ if payload:
+ self._catalog_by_payload[payload] = record
+ self._leaf_ids.add(payload)
+ worker_id = str(getattr(record, "worker_id", "") or "").strip()
+ if worker_id:
+ self._leaf_ids.add(worker_id)
+ name = str(getattr(record, "name", "") or "").strip()
+ if name:
+ self._leaf_ids.add(name)
+ self._index_nodes(self._root, ("ROOT",))
+ self._analyze_node(self._root)
+
+ @classmethod
+ def from_index(
+ cls,
+ index_dir: str | Path,
+ *,
+ retrieve_settings: RetrieveSettings | None = None,
+ ) -> "AgenticRetrievalToolKit":
+ """Load an existing symphony skill index from *index_dir*."""
+ with dispatch_import_path():
+ from retrieval.io.loading import load_retriever_index
+
+ loaded_index = load_retriever_index(index_dir)
+ progressive_config, top_k = _progressive_config_from_settings(retrieve_settings)
+ return cls(
+ loaded_index=loaded_index,
+ progressive_config=progressive_config,
+ top_k=top_k,
+ )
+
+ def skill_branch_peek(self, node_ids: Sequence[str]) -> dict[str, Any]:
+ """Return direct child branch summaries for branches that may need inspection."""
+ nodes, error = self._resolve_nodes(node_ids, default_root=True)
+ if error:
+ return _tool_payload(False, error)
+
+ lines = ["# Skill Branch Peek", ""]
+ steps: list[dict[str, Any]] = []
+ for index, node in enumerate(nodes):
+ if index:
+ lines.append("")
+ self._render_peek_node(lines, node)
+ steps.append(self._skill_tree_peek_step(order=len(steps), node=node))
+ return _tool_payload(
+ True,
+ "\n".join(lines).rstrip(),
+ skill_tree=_skill_tree_payload(
+ query=_skill_tree_query("skill_branch_peek", nodes),
+ steps=steps,
+ candidates=[],
+ ),
+ )
+
+ def skill_branch_explore(self, node_ids: Sequence[str]) -> dict[str, Any]:
+ """Return the current disclosure fragment for the requested branch nodes."""
+ nodes, error = self._resolve_nodes(node_ids)
+ if error:
+ return _tool_payload(False, error)
+ root_nodes = [
+ str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
+ for node in nodes
+ if (str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT") == "ROOT"
+ ]
+ if root_nodes:
+ return _tool_payload(
+ False,
+ "# Skill Tree Node Error\n\n"
+ "`ROOT` is already summarized by the first-level categories in the system prompt. "
+ "Choose one or more of those category ids for `skill_branch_explore`. "
+ "Use `skill_branch_peek` with `ROOT` only if the listed categories are insufficient.",
+ )
+
+ with dispatch_import_path():
+ from retrieval.tree.subtree import DefaultCurrentSubtreeProvider
+ from retrieval.tree.types import SearchCursor
+
+ provider = DefaultCurrentSubtreeProvider(
+ config=self._progressive_config,
+ subtree_item_count=lambda current: self._analyze_node(current).skill_count,
+ cache={},
+ cache_lock=None,
+ )
+
+ lines = ["# Skill Branch Explore", ""]
+ steps: list[dict[str, Any]] = []
+ candidates: list[dict[str, Any]] = []
+ for index, node in enumerate(nodes):
+ if index:
+ lines.append("")
+ branch_path = self._path_by_id.get(str(node.node_id), ("ROOT",))
+ subtree = provider.get_current_subtree(
+ cursor=SearchCursor(
+ node=node,
+ depth=max(0, len(branch_path) - 1),
+ branch_path=branch_path,
+ top_k=self._top_k,
+ )
+ )
+ self._render_expand_node(lines, node, subtree.fragment)
+ fragment_steps, fragment_candidates = self._skill_tree_explore_fragment(
+ node=node,
+ fragment=subtree.fragment,
+ start_order=len(steps),
+ start_rank=len(candidates) + 1,
+ )
+ steps.extend(fragment_steps)
+ candidates.extend(fragment_candidates)
+ return _tool_payload(
+ True,
+ "\n".join(lines).rstrip(),
+ skill_tree=_skill_tree_payload(
+ query=_skill_tree_query("skill_branch_explore", nodes),
+ steps=steps,
+ candidates=candidates,
+ ),
+ )
+
+ def root_prompt_markdown(self, *, language: str = "cn", max_children: int = 30) -> str:
+ """Render a compact system-prompt section for first-level categories."""
+ if language == "en":
+ lines = [
+ "# Agentic Skill Retrieval",
+ "",
+ "Agentic retrieval for installed skills is enabled. For tasks that may need skills, avoid "
+ "relying on a full injected skill list.",
+ "",
+ "`skill_branch_explore` and `skill_branch_peek` are skill-directory browsing tools. They "
+ "disclose categories and installed skill entries.",
+ "Use the directory results to shortlist skills; read a returned SKILL.md only after the skill "
+ "looks likely needed.",
+ "For a task that clearly needs installed skills, do not return a final answer with no relevant "
+ "skills before using at least one directory tool.",
+ "",
+ "When using the skill directory, first identify these possible branches from the task:",
+ "1. Main capability branch",
+ "2. Input format branch",
+ "3. Output format branch",
+ "4. Validation/evaluation/test branch",
+ "5. Required execution environment branch",
+ "",
+ "Prioritize exploring the main capability branch. Explore supporting branches only when a task "
+ "constraint would change skill selection, execution strategy, or acceptance criteria.",
+ "Input/output forms, validation requirements, execution constraints, and dependency conditions "
+ "can all be task constraints.",
+ "Do not expand extra branches for background details that do not affect skill selection.",
+ "When terminal skills include both broad overview skills and exact task-specific skills, prefer "
+ "the exact skills.",
+ "Use broad overview skills only as supplements when they add necessary context.",
+ "",
+ "The first-level categories below are already visible. Start by selecting the most relevant "
+ "category id from this list and call `skill_branch_explore` on that category.",
+ "Use the backticked category id as `node_ids`; never use a display number as `node_ids`.",
+ "Do not call `skill_branch_explore` with `ROOT` as the first step.",
+ "When `skill_branch_explore` returns a `skills` section, those entries are installed skills "
+ "rather than branch ids.",
+ "Use Name and Description to shortlist them, and read SKILL.md only after choosing a skill as "
+ "likely useful.",
+ "Use `skill_branch_peek` with `ROOT` only if you cannot decide from the listed categories.",
+ "If either tool says the index is missing or stale, call `skill_index_build` once and retry.",
+ "",
+ "## First-Level Categories",
+ ]
+ else:
+ lines = [
+ "# Agentic 技能检索",
+ "",
+ "已启用适用于较大规模已安装技能场景下的 Agentic 技能检索。处理可能需要技能的任务时,不要依赖全量技能列表注入。",
+ "",
+ "`skill_branch_explore` 和 `skill_branch_peek` 是技能目录查阅工具。"
+ "它们只披露分类和已安装技能条目;请先根据目录结果筛选候选技能,"
+ "只有当某个技能看起来确实需要使用时,才读取其 SKILL.md。",
+ "对于明显需要已安装技能的任务,不要在未使用至少一个目录工具前直接返回“没有相关技能”或空技能结果。",
+ "",
+ "使用技能目录时,先根据任务识别:",
+ "1. 主能力分支",
+ "2. 输入格式分支",
+ "3. 输出格式分支",
+ "4. 验证/评估/测试分支",
+ "5. 必要的执行环境分支",
+ "",
+ "优先探索主能力分支;只有当某个任务约束会改变技能选择、执行方案或验收标准时,才补充探索对应辅助分支。",
+ "输入/输出形式、验证要求、执行约束、依赖条件等都可以作为任务约束;对只提供背景且不影响技能选择的信息,不要额外展开分支。",
+ "当叶子技能中同时出现宽泛概览技能和精确任务技能时,优先选择精确技能;宽泛概览技能只在需要补充必要背景时使用。",
+ "",
+ "下面已经给出第一层分类。请先从这些分类中选择最相关的分类 id,"
+ "并对该分类调用 `skill_branch_explore`。",
+ "调用工具时必须使用反引号中的分类 id,不要把展示序号当作 `node_ids`。",
+ "不要把 `ROOT` 作为首轮 `skill_branch_explore` 的输入。",
+ "当 `skill_branch_explore` 返回 `skills` 小节时,其中条目是已安装技能而不是 branch id。",
+ "先根据 Name 和 Description 筛选,只有当某个技能看起来需要使用时,"
+ "才读取其 SKILL.md,不要继续展开技能名。",
+ "只有当无法根据第一层分类判断方向时,才用 `skill_branch_peek` 查看 `ROOT` 的轻量摘要。",
+ "如果工具提示索引缺失或过期,调用一次 `skill_index_build` 后重试。",
+ "",
+ "## 第一层分类",
+ ]
+
+ children = list(getattr(self._root, "children", ()) or [])
+ if not children:
+ lines.append("No first-level branches are available." if language == "en" else "当前索引树没有第一层分支。")
+ return "\n".join(lines)
+
+ for child in children[:max(1, int(max_children))]:
+ parts = _split_description(str(getattr(child, "description", "") or ""))
+ desc = _compact_branch_text(parts.description or parts.select_when, 180)
+ suffix = f": {desc}" if desc else ""
+ lines.append(f"- `{child.node_id}`{suffix}")
+ if len(children) > max_children:
+ omitted = len(children) - max_children
+ lines.append(f"... {omitted} more first-level branches omitted.")
+ return "\n".join(lines)
+
+ def _resolve_nodes(self, node_ids: Sequence[str], *, default_root: bool = False) -> tuple[list[Any], str]:
+ normalized = [str(item or "").strip() for item in node_ids or [] if str(item or "").strip()]
+ if not normalized:
+ if default_root:
+ normalized = ["ROOT"]
+ else:
+ return [], (
+ "# Skill Tree Node Error\n\n"
+ "`node_ids` is required. Choose one or more branch ids from the first-level categories "
+ "in the system prompt."
+ )
+
+ nodes: list[Any] = []
+ missing: list[str] = []
+ leaf_ids: list[str] = []
+ for node_id in normalized:
+ node = self._node_by_id.get(node_id)
+ if node is None:
+ if node_id in self._leaf_ids:
+ leaf_ids.append(node_id)
+ else:
+ missing.append(node_id)
+ else:
+ nodes.append(node)
+
+ if leaf_ids:
+ return [], (
+ "# Skill Tree Node Error\n\n"
+ f"{', '.join(f'`{item}`' for item in leaf_ids)} "
+ "is a skill id, not a branch id. Explore its parent branch or peek `ROOT`."
+ )
+ if missing:
+ return [], (
+ "# Skill Tree Node Not Found\n\n"
+ f"Unknown branch node id(s): {', '.join(f'`{item}`' for item in missing)}.\n\n"
+ "Peek `ROOT` or a known branch id to inspect valid branch ids."
+ )
+ return nodes, ""
+
+ def _index_nodes(self, node: Any, path: tuple[str, ...]) -> None:
+ node_id = str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
+ self._node_by_id[node_id] = node
+ self._path_by_id[node_id] = path
+ for child in tuple(getattr(node, "children", ()) or ()):
+ child_id = str(getattr(child, "node_id", "") or "").strip()
+ if child_id:
+ self._index_nodes(child, path + (child_id,))
+
+ def _analyze_node(self, node: Any) -> _NodeStats:
+ node_id = str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
+ cached = self._stats_by_id.get(node_id)
+ if cached is not None:
+ return cached
+
+ items = tuple(getattr(node, "items", ()) or ())
+ for item in items:
+ for attr_name in ("payload", "item_id", "label"):
+ value = str(getattr(item, attr_name, "") or "").strip()
+ if value:
+ self._leaf_ids.add(value)
+ branch_count = 1
+ skill_count = len(items)
+ for child in tuple(getattr(node, "children", ()) or ()):
+ child_stats = self._analyze_node(child)
+ branch_count += child_stats.branch_count
+ skill_count += child_stats.skill_count
+ stats = _NodeStats(branch_count=branch_count, skill_count=skill_count)
+ self._stats_by_id[node_id] = stats
+ return stats
+
+ def _render_peek_node(self, lines: list[str], node: Any) -> None:
+ node_id = str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
+ parts = _split_description(str(getattr(node, "description", "") or ""))
+ lines.append(f"## input `{node_id}`")
+ if parts.select_when:
+ lines.append(f"use: {_compact(parts.select_when, 180)}")
+ if parts.dont_select_when:
+ lines.append(f"avoid: {_compact(parts.dont_select_when, 180)}")
+
+ children = list(getattr(node, "children", ()) or [])
+ if not children:
+ lines.append("No child branches.")
+ return
+
+ for index, child in enumerate(children, start=1):
+ child_id = str(getattr(child, "node_id", "") or "").strip()
+ child_parts = _split_description(str(getattr(child, "description", "") or ""))
+ stats = self._analyze_node(child)
+ desc = _compact_branch_text(child_parts.description, 180)
+ suffix = f": {desc}" if desc else ""
+ lines.append(f"{index}. `{child_id}`{suffix}")
+ if child_parts.select_when:
+ lines.append(f" use: {_compact(child_parts.select_when, 160)}")
+ if child_parts.dont_select_when:
+ lines.append(f" avoid: {_compact(child_parts.dont_select_when, 160)}")
+ lines.append(
+ f" covers: {stats.branch_count} {_plural('branch', stats.branch_count)}, "
+ f"{stats.skill_count} {_plural('skill', stats.skill_count)}"
+ )
+ if index < len(children):
+ lines.append("")
+
+ def _render_expand_node(self, lines: list[str], node: Any, fragment: Any) -> None:
+ node_id = str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
+ lines.append(f"## input `{node_id}`")
+ children = tuple(getattr(fragment.root, "children", ()) or ())
+ if not children:
+ lines.append("No exposed branches or skills.")
+ return
+
+ code_to_resolution = getattr(fragment, "code_to_resolution", {}) or {}
+ resolution_by_canonical_id = {
+ str(resolution.canonical_id): resolution
+ for resolution in tuple(code_to_resolution.values())
+ }
+ self._render_exposed_children(
+ lines,
+ children=children,
+ resolution_by_canonical_id=resolution_by_canonical_id,
+ )
+
+ def _render_exposed_children(
+ self,
+ lines: list[str],
+ *,
+ children: Sequence[Any],
+ resolution_by_canonical_id: dict[str, Any],
+ ) -> None:
+ terminal_children, branch_children = _classify_exposed_children(
+ children,
+ resolution_by_canonical_id,
+ )
+
+ if terminal_children:
+ lines.append("")
+ lines.append("### skills")
+ lines.append(
+ "Candidate installed skills, not branch ids. "
+ "Shortlist by Name/Description; read SKILL.md only after choosing a skill as likely useful."
+ )
+ lines.append("")
+ for index, child in enumerate(terminal_children, start=1):
+ resolution = _resolution_for_exposed(child, resolution_by_canonical_id)
+ if resolution is None:
+ continue
+ self._render_terminal_skill(lines, index=index, resolution=resolution)
+
+ for child in branch_children:
+ resolution = _resolution_for_exposed(child, resolution_by_canonical_id)
+ node_id = _exposed_node_id(child, resolution)
+ description = (
+ str(getattr(resolution, "description", "") or "").strip()
+ if resolution is not None
+ else str(getattr(child, "description", "") or "").strip()
+ )
+ parts = _split_description(description)
+ lines.extend(["", f"### branch `{node_id}`"])
+ if parts.description:
+ lines.append(f"desc: {_compact_branch_text(parts.description, 160)}")
+ if parts.select_when:
+ lines.append(f"use: {_compact(parts.select_when, 180)}")
+ if parts.dont_select_when:
+ lines.append(f"avoid: {_compact(parts.dont_select_when, 180)}")
+
+ def _render_terminal_skill(self, lines: list[str], *, index: int, resolution: Any) -> None:
+ entry = self._skill_entry_from_resolution(resolution)
+ if entry is None:
+ return
+
+ desc = _compact(entry.description, 240)
+ lines.append(f"{index}. `{entry.label}`")
+ if desc:
+ lines.append(f" - Description: {desc}")
+ if entry.skill_md_path:
+ lines.append(f" - SKILL.md: `{entry.skill_md_path}`")
+ else:
+ lines.append(" - SKILL.md: unavailable")
+
+ def _skill_tree_peek_step(self, *, order: int, node: Any) -> dict[str, Any]:
+ node_id = str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
+ children = tuple(getattr(node, "children", ()) or ())
+ return {
+ "order": order,
+ "event_type": "fragment_built",
+ "node_id": node_id,
+ "label": _humanize_node_id(node_id),
+ "depth": self._node_depth(node_id),
+ "selectable_count": len(children),
+ "selected": [],
+ "branches": [_named_id(str(getattr(child, "node_id", "") or "")) for child in children],
+ "leaves": [],
+ "candidate_count": 0,
+ }
+
+ def _skill_tree_explore_fragment(
+ self,
+ *,
+ node: Any,
+ fragment: Any,
+ start_order: int,
+ start_rank: int,
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ node_id = str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
+ depth = self._node_depth(node_id)
+ children = tuple(getattr(fragment.root, "children", ()) or ())
+ resolution_by_canonical_id = {
+ str(resolution.canonical_id): resolution
+ for resolution in tuple((getattr(fragment, "code_to_resolution", {}) or {}).values())
+ }
+ terminal_children, branch_children = _classify_exposed_children(
+ children,
+ resolution_by_canonical_id,
+ )
+ branch_ids = [
+ _named_id(_exposed_node_id(child, _resolution_for_exposed(child, resolution_by_canonical_id)))
+ for child in branch_children
+ ]
+ leaf_ids = [
+ _named_id(_terminal_skill_id(_resolution_for_exposed(child, resolution_by_canonical_id)))
+ for child in terminal_children
+ ]
+ candidates = [
+ self._skill_tree_candidate(
+ rank=start_rank + index,
+ resolution=_resolution_for_exposed(child, resolution_by_canonical_id),
+ source_node_id=node_id,
+ )
+ for index, child in enumerate(terminal_children)
+ ]
+ candidates = [candidate for candidate in candidates if candidate is not None]
+
+ steps = [
+ {
+ "order": start_order,
+ "event_type": "fragment_built",
+ "node_id": node_id,
+ "label": _humanize_node_id(node_id),
+ "depth": depth,
+ "selectable_count": len(children),
+ "selected": [],
+ "branches": branch_ids,
+ "leaves": leaf_ids,
+ "candidate_count": len(candidates),
+ }
+ ]
+ if branch_ids or leaf_ids:
+ steps.append(
+ {
+ "order": start_order + 1,
+ "event_type": "fragment_continue",
+ "node_id": node_id,
+ "label": _humanize_node_id(node_id),
+ "depth": depth + 1,
+ "selectable_count": len(children),
+ "selected": branch_ids,
+ "branches": branch_ids,
+ "leaves": leaf_ids,
+ "candidate_count": len(candidates),
+ }
+ )
+ if candidates:
+ steps.append(
+ {
+ "order": start_order + 2,
+ "event_type": "search_complete",
+ "node_id": node_id,
+ "label": _humanize_node_id(node_id),
+ "depth": depth,
+ "selectable_count": len(children),
+ "selected": [],
+ "branches": branch_ids,
+ "leaves": leaf_ids,
+ "candidate_count": len(candidates),
+ }
+ )
+ return steps, candidates
+
+ def _skill_tree_candidate(
+ self,
+ *,
+ rank: int,
+ resolution: Any | None,
+ source_node_id: str,
+ ) -> dict[str, Any] | None:
+ if resolution is None:
+ return None
+ entry = self._skill_entry_from_resolution(resolution)
+ if entry is None or not entry.label:
+ return None
+ return {
+ "rank": rank,
+ "label": entry.label,
+ "worker_id": entry.worker_id or entry.label,
+ "description": _compact(entry.description, 180),
+ "path": list(self._path_by_id.get(source_node_id, ("ROOT",))) + [entry.label],
+ "selected": True,
+ "source": "skill_branch_explore",
+ }
+
+ def _node_depth(self, node_id: str) -> int:
+ return max(0, len(self._path_by_id.get(node_id, ("ROOT",))) - 1)
+
+ def _skill_entry_from_resolution(self, resolution: Any) -> _SkillEntry | None:
+ item = getattr(resolution, "item", None)
+ payload = str(getattr(item, "payload", "") or getattr(resolution, "canonical_id", "") or "").strip()
+ record = self._catalog_by_payload.get(payload)
+ metadata = getattr(record, "metadata", {}) if record is not None else {}
+ metadata = metadata if isinstance(metadata, dict) else {}
+ worker_id = str(
+ getattr(record, "worker_id", "")
+ or metadata.get("worker_id")
+ or getattr(item, "item_id", "")
+ or payload
+ ).strip()
+ name = str(
+ getattr(record, "name", "")
+ or getattr(item, "label", "")
+ or getattr(resolution, "label", "")
+ or worker_id
+ ).strip()
+ description = str(
+ getattr(item, "description", "")
+ or getattr(resolution, "description", "")
+ or getattr(record, "description", "")
+ or ""
+ ).strip()
+ label = name or worker_id or payload
+ if not label:
+ return None
+ return _SkillEntry(
+ label=label,
+ worker_id=worker_id,
+ description=_split_description(description).description,
+ skill_md_path=_skill_md_path(metadata),
+ )
+
+
+def build_skill_index(manager: Any | None = None) -> dict[str, Any]:
+ """Build or reuse the installed-skill retrieval index."""
+ resolved_manager = _resolve_manager(manager)
+ _clear_runtime_caches()
+ payload = SkillIndexService(resolved_manager).build_index()
+ _clear_runtime_caches()
+ return _tool_payload(
+ bool(payload.get("success")),
+ _agentic_build_result(str(payload.get("result") or "")),
+ )
+
+
+def is_agentic_retrieval_enabled() -> bool:
+ """Return whether agentic installed-skill retrieval is enabled."""
+ try:
+ return bool(_cached_settings().enabled)
+ except Exception:
+ return False
+
+
+def skill_branch_peek(node_ids: Sequence[str], manager: Any | None = None) -> dict[str, Any]:
+ """Peek child branch summaries from the current skill tree index."""
+ status, settings, _ = _ready_status(manager)
+ if not status.get("success"):
+ return _tool_payload(False, str(status.get("result") or ""))
+ toolkit = _cached_toolkit(
+ str(status["index_dir"]),
+ retrieve_settings=settings.retrieve,
+ )
+ return toolkit.skill_branch_peek(node_ids)
+
+
+def skill_branch_explore(node_ids: Sequence[str], manager: Any | None = None) -> dict[str, Any]:
+ """Explore branch nodes using the current disclosure settings."""
+ status, settings, _ = _ready_status(manager)
+ if not status.get("success"):
+ return _tool_payload(False, str(status.get("result") or ""))
+ toolkit = _cached_toolkit(
+ str(status["index_dir"]),
+ retrieve_settings=settings.retrieve,
+ )
+ return toolkit.skill_branch_explore(node_ids)
+
+
+def render_skill_retrieval_prompt(manager: Any | None = None, *, language: str = "cn") -> str:
+ """Render the prompt section used by jiuwenswarm when agentic retrieval is enabled."""
+ status, settings, _ = _ready_status(manager, allow_stale=False, prompt_mode=True)
+ if not status.get("enabled", False):
+ return ""
+ if not status.get("success"):
+ if language == "en":
+ return (
+ "# Agentic Skill Retrieval\n\n"
+ "Agentic retrieval for installed skills is enabled, but the skill index is not ready.\n\n"
+ f"{str(status.get('result') or '').strip()}\n\n"
+ "Use `skill_index_build` when you need indexed skill retrieval, or continue with the original "
+ "jiuwenswarm flow."
+ ).strip()
+ return (
+ "# Agentic 技能检索\n\n"
+ "已启用适用于较大规模已安装技能场景下的 Agentic 技能检索,但当前技能索引尚未就绪。\n\n"
+ f"{str(status.get('result') or '').strip()}\n\n"
+ "需要索引化技能检索时调用 `skill_index_build`;也可以继续按 jiuwenswarm 原有流程执行。"
+ ).strip()
+
+ toolkit = _cached_toolkit(
+ str(status["index_dir"]),
+ retrieve_settings=settings.retrieve,
+ )
+ return toolkit.root_prompt_markdown(language=language)
+
+
+def _ready_status(
+ manager: Any | None,
+ *,
+ allow_stale: bool = False,
+ prompt_mode: bool = False,
+) -> tuple[dict[str, Any], Any, Any]:
+ settings = _cached_settings()
+ resolved_manager = _resolve_manager(manager)
+ if not settings.enabled:
+ return {"success": False, "enabled": False, "result": render_disabled()}, settings, resolved_manager
+
+ status = _cached_ready_status(resolved_manager, settings)
+ status["enabled"] = True
+ if not status.get("index_exists"):
+ status["success"] = False
+ status["result"] = _index_not_ready_markdown("missing", prompt_mode=prompt_mode)
+ return status, settings, resolved_manager
+ if not allow_stale and not status.get("fresh"):
+ status["success"] = False
+ status["result"] = _index_not_ready_markdown("stale", prompt_mode=prompt_mode)
+ return status, settings, resolved_manager
+ status["success"] = True
+ status["result"] = ""
+ return status, settings, resolved_manager
+
+
+def _cached_toolkit(
+ index_dir: str | Path,
+ *,
+ retrieve_settings: RetrieveSettings | None,
+) -> AgenticRetrievalToolKit:
+ path = Path(index_dir).expanduser().resolve()
+ key = (
+ str(path),
+ _index_artifact_signature(path),
+ _retrieve_settings_signature(retrieve_settings),
+ )
+ with _CACHE_LOCK:
+ entry = _TOOLKIT_CACHE.get(key)
+ if entry is not None:
+ return entry.toolkit
+ toolkit = AgenticRetrievalToolKit.from_index(path, retrieve_settings=retrieve_settings)
+ _TOOLKIT_CACHE.clear()
+ _TOOLKIT_CACHE[key] = _ToolkitCacheEntry(toolkit=toolkit)
+ return toolkit
+
+
+def _cached_settings() -> Any:
+ global _SETTINGS_CACHE
+
+ key = _settings_cache_key()
+ with _CACHE_LOCK:
+ entry = _SETTINGS_CACHE
+ if entry is not None and entry.key == key:
+ return entry.settings
+
+ settings = load_settings()
+ with _CACHE_LOCK:
+ _SETTINGS_CACHE = _SettingsCacheEntry(key=key, settings=settings)
+ return settings
+
+
+def _settings_cache_key() -> tuple[Any, ...]:
+ return (_config_file_signature(), _settings_env_signature())
+
+
+def _config_file_signature() -> tuple[int, int] | None:
+ try:
+ from jiuwenswarm.common.config import get_config_file
+
+ return _file_signature(get_config_file())
+ except Exception:
+ return None
+
+
+def _settings_env_signature() -> tuple[tuple[str, str | None], ...]:
+ return tuple((key, os.getenv(key)) for key in _SETTINGS_ENV_KEYS)
+
+
+def _cached_ready_status(manager: Any, settings: Any) -> dict[str, Any]:
+ key = _ready_status_cache_key(manager, settings)
+ now = monotonic()
+ with _CACHE_LOCK:
+ entry = _READY_STATUS_CACHE.get(key)
+ if entry is not None and now - entry.created_at <= _READY_STATUS_TTL_SECONDS:
+ return dict(entry.status)
+
+ status = SkillIndexService(manager).status()
+ with _CACHE_LOCK:
+ _READY_STATUS_CACHE.clear()
+ _READY_STATUS_CACHE[key] = _StatusCacheEntry(created_at=now, status=dict(status))
+ return status
+
+
+def _ready_status_cache_key(manager: Any, settings: Any) -> _ReadyStatusCacheKey:
+ skills_dir = str(getattr(manager, "_skills_dir", "") or "")
+ artifact_root = Path(settings.artifact_root).expanduser().resolve()
+ index_dir = artifact_root / "index"
+ state_file = artifact_root / _STATE_FILENAME
+ return _ReadyStatusCacheKey(
+ skills_dir=skills_dir,
+ artifact_root=str(artifact_root),
+ build=_settings_signature(settings.build),
+ llm=_settings_signature(settings.llm),
+ index_artifacts=_index_artifact_signature(index_dir),
+ state_file=_file_signature(state_file),
+ )
+
+
+def _index_artifact_signature(index_dir: Path) -> tuple[Any, ...]:
+ return tuple((filename, _file_signature(index_dir / filename)) for filename in _INDEX_FILENAMES)
+
+
+def _file_signature(path: Path) -> tuple[int, int] | None:
+ try:
+ stat = path.stat()
+ except OSError:
+ return None
+ return stat.st_mtime_ns, stat.st_size
+
+
+def _retrieve_settings_signature(settings: RetrieveSettings | None) -> tuple[Any, ...]:
+ return _settings_signature(settings or RetrieveSettings())
+
+
+def _settings_signature(settings: Any) -> tuple[tuple[str, str], ...]:
+ try:
+ payload = asdict(settings)
+ except TypeError:
+ payload = vars(settings) if hasattr(settings, "__dict__") else {"value": settings}
+ return tuple(sorted((str(key), repr(value)) for key, value in dict(payload).items()))
+
+
+def _clear_runtime_caches() -> None:
+ global _SETTINGS_CACHE
+
+ with _CACHE_LOCK:
+ _SETTINGS_CACHE = None
+ _TOOLKIT_CACHE.clear()
+ _READY_STATUS_CACHE.clear()
+
+
+def _index_not_ready_markdown(reason: str, *, prompt_mode: bool = False) -> str:
+ if reason == "stale":
+ detail = "Skill retrieval index is stale because installed skills or build settings changed."
+ else:
+ detail = "Skill retrieval index does not exist."
+ if prompt_mode:
+ next_step = "Call `skill_index_build` before using `skill_branch_explore` or `skill_branch_peek`."
+ else:
+ next_step = (
+ "Next step: call `skill_index_build`, then call `skill_branch_explore` with known branch node ids "
+ "or `skill_branch_peek` when you need to inspect branch summaries."
+ )
+ return (
+ "# Skill Tree Retrieval Unavailable\n\n"
+ f"{detail}\n\n"
+ f"{next_step}\n\n"
+ "Handling options:\n"
+ "- Ignore this tool result and continue with the original jiuwenswarm flow.\n"
+ "- Build the index once if indexed retrieval is useful for this task."
+ )
+
+
+def _progressive_config_from_settings(settings: RetrieveSettings | None) -> tuple[Any, int]:
+ with dispatch_import_path():
+ from retrieval.service.models import (
+ GenerationConfig,
+ OpenAIClientConfig,
+ RenderConfig,
+ RetrieverConfig,
+ TraversalConfig,
+ runtime_retriever_config_from_config,
+ )
+
+ retrieve = settings or RetrieveSettings()
+ config = RetrieverConfig(
+ top_k=retrieve.top_k,
+ llm_client_config=OpenAIClientConfig(),
+ traversal_config=TraversalConfig(
+ max_branch_choices=retrieve.max_branch_choices,
+ max_parallel_branches=retrieve.max_parallel_branches,
+ enable_parallel_branches=True,
+ ),
+ render_config=RenderConfig(
+ compact_codes_enabled=retrieve.compact_codes_enabled,
+ flatten_tree=retrieve.flatten_tree,
+ max_exposure_depth=retrieve.max_exposure_depth,
+ ),
+ generation_config=GenerationConfig(
+ max_tokens=retrieve.max_tokens,
+ request_timeout_seconds=retrieve.request_timeout_seconds,
+ ),
+ )
+ runtime_config = runtime_retriever_config_from_config(config)
+ return runtime_config.progressive, runtime_config.top_k
+
+
+def _resolve_manager(manager: Any | None) -> Any:
+ if manager is not None:
+ return manager
+ from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+
+ return SkillManager()
+
+
+def _tool_payload(
+ success: bool,
+ result: str,
+ *,
+ skill_tree: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ payload: dict[str, Any] = {"success": bool(success), "result": str(result or "")}
+ if skill_tree is not None:
+ payload["skill_tree"] = skill_tree
+ return payload
+
+
+def _agentic_build_result(result: str) -> str:
+ text = str(result or "")
+ if "Use `skill_retrieve` with a task query to retrieve relevant installed skills." not in text:
+ return text
+ return text.replace(
+ "Use `skill_retrieve` with a task query to retrieve relevant installed skills.",
+ "Use `skill_branch_explore` as the primary branch retrieval tool, "
+ "or use `skill_branch_peek` when you need lightweight branch summaries.",
+ )
+
+
+def _resolution_for_exposed(node: Any, resolution_by_canonical_id: dict[str, Any]) -> Any | None:
+ selectable_id = str(getattr(node, "selectable_canonical_id", "") or "").strip()
+ if selectable_id:
+ resolution = resolution_by_canonical_id.get(selectable_id)
+ if resolution is not None:
+ return resolution
+ canonical_id = str(getattr(node, "canonical_id", "") or "").strip()
+ return resolution_by_canonical_id.get(canonical_id)
+
+
+def _classify_exposed_children(
+ children: Sequence[Any],
+ resolution_by_canonical_id: dict[str, Any],
+) -> tuple[list[Any], list[Any]]:
+ terminal_children: list[Any] = []
+ branch_children: list[Any] = []
+ for child in children:
+ resolution = _resolution_for_exposed(child, resolution_by_canonical_id)
+ if resolution is not None and bool(getattr(resolution, "is_terminal", False)):
+ terminal_children.append(child)
+ else:
+ branch_children.append(child)
+ return terminal_children, branch_children
+
+
+def _skill_tree_payload(
+ *,
+ query: str,
+ steps: list[dict[str, Any]],
+ candidates: list[dict[str, Any]],
+) -> dict[str, Any]:
+ return {
+ "query": query,
+ "elapsed_ms": None,
+ "max_depth": max((int(step.get("depth") or 0) for step in steps), default=0),
+ "candidate_count": len(candidates),
+ "steps": steps,
+ "candidates": candidates,
+ }
+
+
+def _skill_tree_query(tool_name: str, nodes: Sequence[Any]) -> str:
+ node_ids = [
+ str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
+ for node in nodes
+ ]
+ return f"{tool_name}: {', '.join(node_ids)}"
+
+
+def _named_id(identifier: str) -> dict[str, str]:
+ text = str(identifier or "").strip()
+ return {"id": text, "label": _humanize_node_id(text)}
+
+
+def _humanize_node_id(node_id: str) -> str:
+ text = str(node_id or "").strip()
+ if not text:
+ return ""
+ last = text.split(".")[-1]
+ return last.replace("_", " ").replace("-", " ").strip() or text
+
+
+def _terminal_skill_id(resolution: Any | None) -> str:
+ if resolution is None:
+ return ""
+ item = getattr(resolution, "item", None)
+ return str(
+ getattr(item, "payload", "")
+ or getattr(item, "item_id", "")
+ or getattr(item, "label", "")
+ or getattr(resolution, "canonical_id", "")
+ or getattr(resolution, "label", "")
+ or ""
+ ).strip()
+
+
+def _exposed_node_id(node: Any, resolution: Any | None) -> str:
+ if resolution is not None:
+ canonical_id = str(getattr(resolution, "canonical_id", "") or "").strip()
+ if canonical_id:
+ return canonical_id
+ canonical_id = str(getattr(node, "canonical_id", "") or "").strip()
+ if canonical_id.startswith("node::"):
+ return canonical_id.split("::", 1)[1]
+ selectable_id = str(getattr(node, "selectable_canonical_id", "") or "").strip()
+ if selectable_id:
+ return selectable_id
+ return str(getattr(node, "label", "") or canonical_id or "UNKNOWN").strip()
+
+
+def _skill_md_path(metadata: dict[str, Any]) -> str:
+ raw = (
+ metadata.get("skill_md_path")
+ or metadata.get("skill_file")
+ or metadata.get("skill_path")
+ or metadata.get("path")
+ or ""
+ )
+ text = str(raw or "").strip()
+ if not text:
+ return ""
+ path = Path(text)
+ if path.name.lower() == "skill.md":
+ return text
+ return str(path / "SKILL.md")
+
+
+def _split_description(description: str) -> _DescriptionParts:
+ desc_lines: list[str] = []
+ select_lines: list[str] = []
+ dont_lines: list[str] = []
+ current = "description"
+ for raw_line in str(description or "").splitlines():
+ line = raw_line.strip()
+ if not line:
+ continue
+ lowered = line.lower()
+ if lowered.startswith("select when:"):
+ current = "select"
+ select_lines.append(line.split(":", 1)[1].strip())
+ continue
+ if lowered.startswith("don't select when:") or lowered.startswith("dont select when:"):
+ current = "dont"
+ dont_lines.append(line.split(":", 1)[1].strip())
+ continue
+ if current == "select":
+ select_lines.append(line)
+ elif current == "dont":
+ dont_lines.append(line)
+ else:
+ desc_lines.append(line)
+ return _DescriptionParts(
+ description=" ".join(desc_lines).strip(),
+ select_when=" ".join(select_lines).strip(),
+ dont_select_when=" ".join(dont_lines).strip(),
+ )
+
+
+def _compact(text: str, limit: int) -> str:
+ normalized = " ".join(str(text or "").split())
+ if len(normalized) <= limit:
+ return normalized
+ return normalized[: max(0, limit - 3)].rstrip() + "..."
+
+
+def _compact_branch_text(text: str, limit: int) -> str:
+ normalized = " ".join(str(text or "").split())
+ for marker in (" Covers ", " Representative keywords", " Representative descendants"):
+ if marker in normalized:
+ normalized = normalized.split(marker, 1)[0].rstrip(". ")
+ return _compact(normalized, limit)
+
+
+def _plural(word: str, count: int) -> str:
+ if int(count) == 1:
+ return word
+ if word.endswith("ch"):
+ return f"{word}es"
+ return f"{word}s"
diff --git a/jiuwenswarm/symphony/indexing/tree/grouping.py b/jiuwenswarm/symphony/indexing/tree/grouping.py
index ce340cce0f..623a135bb7 100644
--- a/jiuwenswarm/symphony/indexing/tree/grouping.py
+++ b/jiuwenswarm/symphony/indexing/tree/grouping.py
@@ -224,15 +224,11 @@ class TreeGroupingEngine:
def discover_groups(self, skills: list[dict], parent_context: Optional[dict], verbose: bool = False) -> dict:
del verbose
builder = self._builder
- min_groups = max(2, builder.config.branching_factor - 3)
- max_groups = builder.config.branching_factor + 2
context_section = self._render_context(parent_context)
prompt = GROUP_DISCOVERY_PROMPT.format(
count=len(skills),
context_section=context_section,
skills_list=self.format_skills_list(skills),
- min_groups=min_groups,
- max_groups=max_groups,
)
response = _builder_call(builder, "_call_llm_json", prompt)
groups = response.get("groups", {}) if isinstance(response, dict) else {}
@@ -249,15 +245,10 @@ class TreeGroupingEngine:
def merge_group_definitions(self, all_group_defs: list[dict], verbose: bool = False) -> dict:
if verbose:
console.print(f"[cyan] Consolidating {len(all_group_defs)} discovery passes[/cyan]")
- builder = self._builder
- min_groups = max(2, builder.config.branching_factor - 3)
- max_groups = builder.config.branching_factor + 2
prompt = GROUP_MERGE_PROMPT.format(
all_groups=self._render_group_definition_samples(all_group_defs),
- min_groups=min_groups,
- max_groups=max_groups,
)
- response = _builder_call(builder, "_call_llm_json", prompt)
+ response = _builder_call(self._builder, "_call_llm_json", prompt)
canonical_groups = response.get("canonical_groups", {}) if isinstance(response, dict) else {}
merged: dict[str, dict[str, str]] = {}
for group_id, payload in self.iter_group_items(canonical_groups):
diff --git a/jiuwenswarm/symphony/indexing/tree/prompts.py b/jiuwenswarm/symphony/indexing/tree/prompts.py
index 5ee08f113d..dea43c31ab 100644
--- a/jiuwenswarm/symphony/indexing/tree/prompts.py
+++ b/jiuwenswarm/symphony/indexing/tree/prompts.py
@@ -5,13 +5,16 @@ GROUP_DISCOVERY_PROMPT = """Capability tree planning pass.
Scope note:
{context_section}
-Candidate skills:
+Candidate skills ({count} total):
{skills_list}
-Return {min_groups}-{max_groups} proposed groups only. Do not place skills into groups yet.
+Return proposed groups only. Do not place skills into groups yet.
Design guidance:
- optimize for retrieval usefulness rather than implementation taxonomy
+- choose the number of groups from the skill diversity, not from a fixed configured count
+- prefer the smallest set of groups that keeps routing boundaries clear
+- avoid singleton groups unless a skill has genuinely unique routing semantics
- keep groups distinct enough that a router can tell them apart
- prefer names that remain readable as tree labels
- ids should be lowercase and hyphenated
@@ -110,8 +113,8 @@ Candidate group definitions:
{all_groups}
Produce one merged set of canonical groups.
-The final count must stay between {min_groups} and {max_groups}.
-Merge synonyms where possible and keep labels stable enough for reuse in later indexing runs.
+Choose the final count from semantic diversity, not from a fixed configured count.
+Merge synonyms where possible, remove duplicate boundaries, and keep labels stable enough for reuse in later indexing runs.
Respond as JSON:
{{
diff --git a/jiuwenswarm/symphony/indexing/workflows/artifacts.py b/jiuwenswarm/symphony/indexing/workflows/artifacts.py
index 4e2a886be9..c2fece8b02 100644
--- a/jiuwenswarm/symphony/indexing/workflows/artifacts.py
+++ b/jiuwenswarm/symphony/indexing/workflows/artifacts.py
@@ -51,7 +51,7 @@ class TaxonomyBuildConfig:
"""Tree shape and taxonomy refinement settings.
Attributes:
- branching_factor: Target maximum branching factor for discovered groups.
+ branching_factor: Base scale for split thresholds and tree shape controls.
max_depth: Maximum tree depth used by recursive construction.
root_categories: Optional predefined root taxonomy. When omitted,
`FIXED_ROOT_CATEGORIES` is used by the tree schema resolver.
@@ -130,7 +130,7 @@ class ResolvedTaxonomyBuildConfig:
"""Normalized taxonomy build settings used inside workflows.
Attributes:
- branching_factor: Normalized tree branching factor.
+ branching_factor: Normalized split-threshold/tree-shape scale.
max_depth: Normalized maximum tree depth.
root_categories: Root categories after applying schema defaults.
postprocess_enabled: Whether repair passes run.
diff --git a/jiuwenswarm/symphony/skill_retrieval/config.py b/jiuwenswarm/symphony/skill_retrieval/config.py
index e1d9d701b9..de81617217 100644
--- a/jiuwenswarm/symphony/skill_retrieval/config.py
+++ b/jiuwenswarm/symphony/skill_retrieval/config.py
@@ -7,6 +7,7 @@ from typing import Any
from jiuwenswarm.common.config import get_config
from jiuwenswarm.common.utils import get_agent_workspace_dir
+from jiuwenswarm.symphony.skill_retrieval.taxonomy_config import coerce_root_categories_value
@dataclass(frozen=True)
@@ -59,7 +60,7 @@ def load_settings() -> SkillRetrievalSettings:
section = _dict_get(config, "symphony", "skill_retrieval")
artifact_root = _artifact_root(section)
return SkillRetrievalSettings(
- enabled=_as_bool(section.get("enabled"), False),
+ enabled=_enabled(section),
artifact_root=artifact_root,
llm=_load_llm(section, config),
build=_load_build(section.get("build") if isinstance(section.get("build"), dict) else {}),
@@ -83,6 +84,13 @@ def _artifact_root(section: dict[str, Any]) -> Path:
return get_agent_workspace_dir() / "symphony" / "skill_retrieval"
+def _enabled(section: dict[str, Any]) -> bool:
+ env_value = os.getenv("SYMPHONY_SKILL_RETRIEVAL_ENABLED")
+ if env_value is not None and env_value.strip() != "":
+ return _as_bool(env_value, False)
+ return _as_bool(section.get("enabled"), False)
+
+
def _load_llm(section: dict[str, Any], config: dict[str, Any]) -> LLMSettings:
override = section.get("llm") if isinstance(section.get("llm"), dict) else {}
model_cfg = _default_model_client_config(config)
@@ -130,12 +138,12 @@ def _load_build(raw: dict[str, Any]) -> BuildSettings:
max_depth=_as_int(raw.get("max_depth"), 6),
root_categories=_as_optional_root_categories(raw.get("root_categories")),
max_workers=_as_int(raw.get("max_workers"), 2),
- max_retries=_as_int(raw.get("max_retries"), 2),
+ max_retries=_as_non_negative_int(raw.get("max_retries"), 2),
request_timeout_seconds=_as_float(raw.get("request_timeout_seconds"), 420.0),
classification_batch_limit=_as_int(raw.get("classification_batch_limit"), 32),
- discovery_seed=_as_int(raw.get("discovery_seed"), 42),
+ discovery_seed=_as_raw_int(raw.get("discovery_seed"), 42),
postprocess_enabled=_as_bool(raw.get("postprocess_enabled"), True),
- postprocess_max_passes=_as_int(raw.get("postprocess_max_passes"), 1),
+ postprocess_max_passes=_as_non_negative_int(raw.get("postprocess_max_passes"), 1),
postprocess_min_skills=_as_int(raw.get("postprocess_min_skills"), 6),
equivalence_enabled=_as_bool(raw.get("equivalence_enabled"), True),
)
@@ -147,10 +155,6 @@ def _load_retrieve(raw: dict[str, Any]) -> RetrieveSettings:
compact_codes_enabled=_as_bool(raw.get("compact_codes_enabled"), False),
flatten_tree=_as_bool(raw.get("flatten_tree"), False),
max_exposure_depth=_as_int(raw.get("max_exposure_depth"), 99),
- max_branch_choices=_as_int(raw.get("max_branch_choices"), 2),
- max_parallel_branches=_as_int(raw.get("max_parallel_branches"), 2),
- max_tokens=_as_int(raw.get("max_tokens"), 96),
- request_timeout_seconds=_as_float(raw.get("request_timeout_seconds"), 120.0),
)
@@ -166,12 +170,7 @@ def _as_bool(value: Any, default: bool) -> bool:
def _as_optional_root_categories(value: Any) -> Any:
- if value is None:
- return None
- if isinstance(value, str):
- text = value.strip()
- return text or None
- return value
+ return coerce_root_categories_value(value, allow_path=True)
def _as_int(value: Any, default: int) -> int:
@@ -181,13 +180,18 @@ def _as_int(value: Any, default: int) -> int:
return default
-def _as_optional_int(value: Any) -> int | None:
- if value is None or str(value).strip() == "":
- return None
+def _as_non_negative_int(value: Any, default: int) -> int:
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return default
+
+
+def _as_raw_int(value: Any, default: int) -> int:
try:
return int(value)
except (TypeError, ValueError):
- return None
+ return default
def _as_float(value: Any, default: float) -> float:
@@ -195,3 +199,12 @@ def _as_float(value: Any, default: float) -> float:
return float(value)
except (TypeError, ValueError):
return default
+
+
+def _as_optional_int(value: Any) -> int | None:
+ if value is None or str(value).strip() == "":
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
diff --git a/jiuwenswarm/symphony/skill_retrieval/index_service.py b/jiuwenswarm/symphony/skill_retrieval/index_service.py
index ae603e8293..e69c0b3c9a 100644
--- a/jiuwenswarm/symphony/skill_retrieval/index_service.py
+++ b/jiuwenswarm/symphony/skill_retrieval/index_service.py
@@ -46,8 +46,13 @@ class SkillIndexService:
"built_at": str(state.get("built_at") or ""),
"inventory_fingerprint": inventory.fingerprint,
"fingerprint": str(state.get("fingerprint") or ""),
- "default_compact_codes_enabled": settings.retrieve.compact_codes_enabled,
- "default_flatten_tree": settings.retrieve.flatten_tree,
+ "build_branching_factor": settings.build.branching_factor,
+ "build_max_depth": settings.build.max_depth,
+ "build_request_timeout_seconds": settings.build.request_timeout_seconds,
+ "retrieval_top_k": settings.retrieve.top_k,
+ "retrieval_compact_codes_enabled": settings.retrieve.compact_codes_enabled,
+ "retrieval_flatten_tree": settings.retrieve.flatten_tree,
+ "retrieval_max_exposure_depth": settings.retrieve.max_exposure_depth,
}
def build_index(self) -> dict[str, Any]:
diff --git a/jiuwenswarm/symphony/skill_retrieval/taxonomy_config.py b/jiuwenswarm/symphony/skill_retrieval/taxonomy_config.py
new file mode 100644
index 0000000000..3b979d59b5
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/taxonomy_config.py
@@ -0,0 +1,325 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+DEFAULT_ROOT_CATEGORIES_TEXT = """tree_root_categories:
+ - id: external-service-automation
+ name: External service automation and integrations
+ description: Operate a named remote app, SaaS product, API, connector, account or cloud service.
+ select_when: Route here only when the primary action is to read or change state in an external service or connected account.
+ dont_select_when: Do not route local files, source code, datasets, media, science models, security investigations or simulated environments here.
+ children:
+ - id: sales-marketing-and-crm
+ name: Sales, marketing and CRM
+ description: Remote CRM, leads, outreach, campaigns, ads, SEO, social posting, recruiting and customer engagement.
+ - id: communication-productivity-and-education
+ name: Communication, productivity and education
+ description: Remote email, chat, calendar, meetings, notes, LMS, forms, support desks and team workflow tools.
+ - id: commerce-finance-and-operations
+ name: Commerce, finance and operations
+ description: Remote ecommerce, payments, invoices, accounting, certificates, shipping, logistics and back-office systems.
+ - id: cloud-developer-and-data-platforms
+ name: Cloud, developer and data platforms
+ description: Remote cloud, hosting, auth, databases, scraping, analytics, CMS, AI APIs, observability and dev platforms.
+ - id: content-media-and-document-services
+ name: Content, media and document services
+ description: Remote services for generation, conversion, signing, publishing or managing content, documents or media.
+ - id: generic-api-connectors
+ name: Generic API and connector workflows
+ description: Generic MCP/Rube/Composio/API connector skills whose main purpose is tool discovery and remote execution.
+
+ - id: documents-office-and-records
+ name: Documents, office files and records
+ description: Create, read, convert, extract from or edit local document and office-file artifacts.
+ select_when: Route here when the primary object is a PDF, Word, PPT, spreadsheet, CSV, form, contract, report or record file.
+ dont_select_when: Do not route remote service operations, source-code work, raw media tasks, dataset analytics or scientific modeling here.
+ children:
+ - id: pdf-documents-and-ocr
+ name: PDF, documents and OCR
+ description: PDF and document reading, editing, parsing, redaction, page OCR and document-to-text conversion.
+ - id: spreadsheets-csv-and-tables
+ name: Spreadsheets, CSV and tables
+ description: Spreadsheet, CSV and table-file handling, formulas, table extraction and file-level reconciliation.
+ - id: presentations-reports-and-deliverables
+ name: Presentations, reports and deliverables
+ description: PPTX, formatted reports, charts inside documents and business-facing deliverable generation.
+ - id: forms-contracts-and-records
+ name: Forms, contracts and records
+ description: Forms, contracts, certificates, official records, compliance documents and document workflow artifacts.
+
+ - id: data-analytics-and-visualization
+ name: Data analytics, BI and visualization
+ description: Analyze structured data to compute metrics, patterns, features, models, charts or business conclusions.
+ select_when: Route here when the primary object is a dataset or table and the goal is analysis, cleaning, modeling or visualization.
+ dont_select_when: Do not route office-file formatting, remote service operation, source-code implementation, security forensics or physical-science modeling here.
+ children:
+ - id: data-cleaning-and-reconciliation
+ name: Data cleaning and reconciliation
+ description: Data quality, deduplication, fuzzy matching, joins, missing values, normalization and validation.
+ - id: statistics-features-and-modeling
+ name: Statistics, features and modeling
+ description: Statistical analysis, feature engineering, PCA, clustering, regression, causal analysis and GLM.
+ - id: time-series-trends-and-anomalies
+ name: Time series, trends and anomalies
+ description: Time-series detrending, anomaly detection, contribution analysis, seasonality and trend workflows.
+ - id: visualization-and-business-reporting
+ name: Visualization and business reporting
+ description: D3, dashboards, charts, BI narratives and visual explanation of quantitative results.
+ - id: geospatial-and-local-data-analysis
+ name: Geospatial and local data analysis
+ description: Spatial tables, distances, map data, city/place datasets and geospatial analysis.
+
+ - id: software-engineering-devops
+ name: Software engineering and DevOps
+ description: Modify, test, build, migrate, review or operate software projects and developer infrastructure.
+ select_when: Route here when the primary object is source code, a repository, build system, runtime environment, CI job or developer workflow.
+ dont_select_when: Do not route remote business app operations, document processing, media tasks, scientific domain work or security investigations here unless code work is primary.
+ children:
+ - id: language-framework-and-migration
+ name: Languages, frameworks and migrations
+ description: Language, framework and API migrations across Python, Java, Scala, Erlang, React, Spring and similar stacks.
+ - id: build-packaging-and-environments
+ name: Build, packaging and environments
+ description: Build lifecycle, Maven, uv, package managers, dependencies, config files and environment setup.
+ - id: testing-ci-and-quality
+ name: Testing, CI and quality
+ description: Unit tests, browser tests, CI analysis, bug finding, changelogs, validation and code quality.
+ - id: frontend-web-and-interactive-artifacts
+ name: Frontend, web and interactive artifacts
+ description: Web UI implementation, browser testing, Three.js web artifacts and frontend interface work.
+ - id: performance-parallel-and-ml-engineering
+ name: Performance, parallel and ML engineering
+ description: Performance tuning, parallelization, memory optimization, JAX, model-training infrastructure and GPU workflows.
+
+ - id: security-privacy-and-risk
+ name: Security, privacy and risk analysis
+ description: Investigate or reduce security, privacy, vulnerability, network, identity or operational risk.
+ select_when: Route here when the primary goal is security assessment, threat detection, vulnerability handling, forensics, hardening or risk reporting.
+ dont_select_when: Do not route ordinary software testing, generic API automation, normal document redaction, business analytics or scientific signal analysis here.
+ children:
+ - id: network-forensics-and-threat-detection
+ name: Network forensics and threat detection
+ description: PCAP triage, tshark, Suricata, IDS events, malicious traffic, scans, DoS and beaconing.
+ - id: vulnerability-audit-and-pentest
+ name: Vulnerability audit and penetration testing
+ description: Penetration testing, vulnerability scanning, CVSS extraction, Trivy reports and security audit deliverables.
+ - id: secure-coding-and-systems-security
+ name: Secure coding and systems security
+ description: Secure coding, framework hardening, kernel fuzzing, syzkaller and low-level system security.
+ - id: secrets-identity-and-cloud-security
+ name: Secrets, identity and cloud security
+ description: API keys, authentication, secrets management, access controls, cloud security and account risk.
+
+ - id: media-multimodal-and-creative
+ name: Media, multimodal and creative processing
+ description: Transform or understand audio, video, images, graphics, 3D assets or multimodal creative content.
+ select_when: Route here when the primary object is media content rather than a document file, dataset, remote service or codebase.
+ dont_select_when: Do not route office-document OCR, structured data analysis, source-code work, remote SaaS operation or scientific modeling here.
+ children:
+ - id: audio-speech-and-voice
+ name: Audio, speech and voice
+ description: Speech-to-text, Whisper, VAD, speaker clustering, diarization, TTS, audiobooks and audio cleanup.
+ - id: video-and-ffmpeg-workflows
+ name: Video and FFmpeg workflows
+ description: Video editing, filters, format conversion, frame extraction, segmenting, metadata and video understanding.
+ - id: images-ocr-and-computer-vision
+ name: Images, OCR and computer vision
+ description: Image editing, screenshot/photo OCR, object counting, masks and computer-vision analysis.
+ - id: graphics-3d-and-design-assets
+ name: Graphics, 3D and design assets
+ description: Canvas design, brand assets, OBJ export, mesh analysis, graphics pipelines and 3D artifacts.
+ - id: generative-and-multimodal-ai
+ name: Generative and multimodal AI
+ description: AI generation or multimodal model workflows for image, audio, video, voice or mixed media.
+
+ - id: science-engineering-modeling
+ name: Science, engineering and mathematical modeling
+ description: Solve domain equations, simulations or analyses in science, engineering, math or physical systems.
+ select_when: Route here when scientific or engineering domain semantics are primary, even if code or data processing is involved.
+ dont_select_when: Do not route generic software work, business analytics, remote API operations, document processing, media editing or security forensics here.
+ children:
+ - id: control-optimization-simulation
+ name: Control, optimization and simulation
+ description: Control design, MPC, PID, state-space models, vehicle dynamics, CasADi and simulation metrics.
+ - id: power-energy-industrial
+ name: Power, energy and industrial systems
+ description: Power flow, energy markets, locational prices, industrial processes and manufacturing guidance.
+ - id: astronomy-seismology-environment
+ name: Astronomy, seismology and environment
+ description: Astronomy, seismology, hydrology, meteorology, environmental drivers and domain sensor data.
+ - id: chemistry-materials-quantum-math
+ name: Chemistry, materials, quantum and math
+ description: Chemistry, materials, quantum workflows, symbolic math, numerical math and scientific fitting.
+
+ - id: search-research-and-knowledge
+ name: Search, research and knowledge work
+ description: Find, retrieve, verify, cite or organize information from sources or reference datasets.
+ select_when: Route here when the primary goal is evidence gathering, lookup, literature work, knowledge retrieval or information organization.
+ dont_select_when: Do not route execution in a remote account, local file editing, source-code work, media processing, data modeling or security investigation here.
+ children:
+ - id: web-and-browser-research
+ name: Web and browser research
+ description: Web search, browser evidence gathering, page extraction, current lookup and source comparison.
+ - id: academic-citation-and-literature
+ name: Academic, citation and literature work
+ description: Academic search, citations, literature evidence, research summaries and scholarly source organization.
+ - id: enterprise-and-domain-knowledge
+ name: Enterprise and domain knowledge
+ description: Internal artifact search, wiki lookup, documentation search and structured domain references.
+ - id: local-reference-and-travel-datasets
+ name: Local reference and travel datasets
+ description: Lookup-only flights, accommodations, attractions, restaurants, cities, distances and local references.
+ - id: taxonomy-and-information-organization
+ name: Taxonomy and information organization
+ description: Taxonomy building, categorization, indexing, curation and knowledge organization.
+
+ - id: embodied-simulation-and-interactive-tasks
+ name: Embodied, simulated and interactive tasks
+ description: Act inside simulated, embodied, game-like or interactive environments with state and actions.
+ select_when: Route here when the primary task is navigation, object manipulation, environment state change, game-state reasoning or action execution.
+ dont_select_when: Do not route real SaaS APIs, local files, source-code work, media processing, data analysis or physical-system modeling here.
+ children:
+ - id: goal-planning-and-verification
+ name: Goal planning and verification
+ description: Interpret goals, decompose tasks, track progress and verify completion in an interactive environment.
+ - id: navigation-search-and-scanning
+ name: Navigation, search and scanning
+ description: Navigate, inspect surroundings, search likely locations and locate objects, tools or targets.
+ - id: object-manipulation-and-transport
+ name: Object manipulation and transport
+ description: Pick up, retrieve, carry, place, store, dispose, combine or move objects.
+ - id: environment-devices-and-state-changes
+ name: Environment, devices and state changes
+ description: Open/close containers, operate devices, heat, cool, clean or change object/environment state.
+ - id: games-and-domain-simulators
+ name: Games and domain simulators
+ description: Game libraries, state parsers, maps, mechanics and interactive domain-specific simulators.
+
+ - id: skill-agent-meta-workflows
+ name: Agent, skill and workflow meta tasks
+ description: Work on skills, agents, prompts, memory, retrieval, benchmarks, plans or orchestration itself.
+ select_when: Route here only when the task is about building, testing, evaluating or coordinating the agent/skill system.
+ dont_select_when: Do not route normal domain tasks here just because they may use a skill or agent internally.
+ children:
+ - id: skill-authoring-and-packaging
+ name: Skill authoring and packaging
+ description: Create, edit, document, package, vet or improve skills and skill collections.
+ - id: benchmark-and-artifact-evaluation
+ name: Benchmark and artifact evaluation
+ description: SkillsBench, artifact evaluation, reproducibility checks, badges and benchmark harnesses.
+ - id: planning-orchestration-and-workflows
+ name: Planning, orchestration and workflows
+ description: Task decomposition, file-based planning, workload balancing, dialogue graphs, PDDL and workflow coordination.
+ - id: memory-retrieval-and-knowledge-systems
+ name: Memory, retrieval and knowledge systems
+ description: Agent memory, skill retrieval, indexing, ranking and context-management workflows.
+"""
+
+
+def parse_root_categories_text(text: str) -> list[Any]:
+ payload = _parse_json_or_yaml(text)
+ return extract_root_categories(payload, source="root_categories")
+
+
+def coerce_root_categories_value(value: Any, *, allow_path: bool = True) -> Any:
+ if value is None:
+ return None
+ if isinstance(value, list):
+ return value
+ if isinstance(value, dict):
+ return extract_root_categories(value, source="root_categories")
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return None
+ if _looks_like_inline_taxonomy(text):
+ return parse_root_categories_text(text)
+ if allow_path:
+ return text
+ return parse_root_categories_text(text)
+ return value
+
+
+def root_categories_to_text(value: Any) -> str:
+ if value in (None, "", [], ()):
+ return DEFAULT_ROOT_CATEGORIES_TEXT.rstrip()
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return DEFAULT_ROOT_CATEGORIES_TEXT.rstrip()
+ if not _looks_like_inline_taxonomy(text):
+ loaded = _read_path_if_exists(text)
+ if loaded is not None:
+ return loaded.strip()
+ return DEFAULT_ROOT_CATEGORIES_TEXT.rstrip()
+ return text
+ if isinstance(value, list):
+ return _dump_root_categories({"tree_root_categories": value})
+ if isinstance(value, dict):
+ if "tree_root_categories" in value or "root_categories" in value:
+ return _dump_root_categories(value)
+ return _dump_root_categories({"tree_root_categories": extract_root_categories(value, source="root_categories")})
+ return str(value)
+
+
+def extract_root_categories(payload: Any, *, source: str) -> list[Any]:
+ if isinstance(payload, list):
+ return payload
+ if isinstance(payload, dict):
+ for key in ("tree_root_categories", "root_categories"):
+ value = payload.get(key)
+ if value is None:
+ continue
+ if not isinstance(value, list):
+ raise ValueError(f"{source}: field '{key}' must be a list")
+ return value
+ raise ValueError(f"{source}: expected a root category list or object with tree_root_categories/root_categories")
+
+
+def _parse_json_or_yaml(text: str) -> Any:
+ try:
+ return json.loads(text)
+ except json.JSONDecodeError:
+ try:
+ return yaml.safe_load(text)
+ except yaml.YAMLError as exc:
+ raise ValueError(f"Failed to parse root_categories: {exc}") from exc
+
+
+def _dump_root_categories(payload: Any) -> str:
+ return yaml.safe_dump(payload, allow_unicode=True, sort_keys=False).rstrip()
+
+
+def _looks_like_inline_taxonomy(text: str) -> bool:
+ stripped = text.lstrip()
+ return (
+ "\n" in stripped
+ or stripped.startswith("[")
+ or stripped.startswith("{")
+ or stripped.startswith("- ")
+ or stripped.startswith("tree_root_categories:")
+ or stripped.startswith("root_categories:")
+ )
+
+
+def _read_path_if_exists(text: str) -> str | None:
+ try:
+ path = Path(text).expanduser()
+ if path.is_file():
+ return path.read_text(encoding="utf-8")
+ except OSError:
+ return None
+ return None
+
+
+__all__ = [
+ "DEFAULT_ROOT_CATEGORIES_TEXT",
+ "coerce_root_categories_value",
+ "extract_root_categories",
+ "parse_root_categories_text",
+ "root_categories_to_text",
+]
diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.py
index 70bc6d7b15..322d0f96cb 100644
--- a/tests/agents/swarm/test_swarm_assembly.py
+++ b/tests/agents/swarm/test_swarm_assembly.py
@@ -82,6 +82,7 @@ _COMMON_RAIL_NAMES: frozenset[str] = frozenset(
registry.TEAM_WORKSPACE_REPORT_PATH,
registry.CONTEXT_PROCESSOR,
registry.PLUGIN_RAILS,
+ registry.SKILL_RETRIEVAL_PROMPT,
registry.MEMBER_SKILL_TOOLKIT,
}
)
@@ -124,6 +125,10 @@ def _make_team_spec() -> TeamAgentSpec:
)
+def _agentic_retrieval_config(enabled: bool = True) -> dict:
+ return {"symphony": {"skill_retrieval": {"enabled": enabled}}}
+
+
def test_register_swarm_providers_is_idempotent() -> None:
"""Two consecutive registrations must not raise and stay consistent."""
register_swarm_providers()
@@ -312,9 +317,9 @@ def test_build_member_capability_specs_rail_names(
assert _COMMON_RAIL_NAMES <= rail_names
assert extra_rails <= rail_names
- # The common set has exactly 14 entries; the role adds only its evolution
+ # The common set has exactly 15 entries; the role adds only its evolution
# rails on top.
- assert len(_COMMON_RAIL_NAMES) == 14
+ assert len(_COMMON_RAIL_NAMES) == 15
assert rail_names == _COMMON_RAIL_NAMES | extra_rails
# No DeepAgent is involved; every entry is a plain declarative RailSpec.
assert all(isinstance(spec, RailSpec) for spec in rails_specs)
@@ -352,21 +357,45 @@ def test_member_skill_toolkit_carries_selected_skills() -> None:
@pytest.mark.parametrize("role", ["leader", "teammate"])
-def test_team_member_deep_agent_spec_enables_skill_discovery(role: str) -> None:
- """Chat-team members rely on the core default SkillUseRail."""
+def test_team_member_deep_agent_spec_uses_agentic_skill_disclosure(role: str) -> None:
+ """Chat-team members use lightweight skill exposure when retrieval is enabled."""
+ base = DeepAgentSpec(enable_skill_discovery=False)
+
+ spec = build_member_deep_agent_spec(_agentic_retrieval_config(), "team", role, base)
+ rail_names = {rail.type for rail in (spec.rails or [])}
+
+ assert spec.enable_skill_discovery is False
+ assert "core.skill_use" not in rail_names
+
+
[email protected]("role", ["leader", "teammate"])
+def test_team_member_deep_agent_spec_keeps_core_skill_discovery_when_retrieval_disabled(role: str) -> None:
+ """Chat-team members keep the original skill discovery path when retrieval is disabled."""
base = DeepAgentSpec(enable_skill_discovery=False)
- spec = build_member_deep_agent_spec({}, "team", role, base)
+ spec = build_member_deep_agent_spec(_agentic_retrieval_config(False), "team", role, base)
assert spec.enable_skill_discovery is True
@pytest.mark.parametrize("mode", ["code.team", "team.plan"])
-def test_code_member_deep_agent_spec_keeps_explicit_skill_use_rail(mode: str) -> None:
- """Code profiles keep their explicit SkillUseRail provider path."""
+def test_code_member_deep_agent_spec_omits_skill_use_rail_when_retrieval_enabled(mode: str) -> None:
+ """Code profiles also let agentic retrieval own skill discovery."""
base = DeepAgentSpec(enable_skill_discovery=False)
- spec = build_member_deep_agent_spec({}, mode, "leader", base)
+ spec = build_member_deep_agent_spec(_agentic_retrieval_config(), mode, "leader", base)
+ rail_names = {rail.type for rail in (spec.rails or [])}
+
+ assert spec.enable_skill_discovery is False
+ assert registry.CODE_SKILL_USE not in rail_names
+
+
[email protected]("mode", ["code.team", "team.plan"])
+def test_code_member_deep_agent_spec_keeps_skill_use_rail_when_retrieval_disabled(mode: str) -> None:
+ """Code profiles keep their explicit SkillUseRail provider when retrieval is disabled."""
+ base = DeepAgentSpec(enable_skill_discovery=False)
+
+ spec = build_member_deep_agent_spec(_agentic_retrieval_config(False), mode, "leader", base)
rail_names = {rail.type for rail in (spec.rails or [])}
assert spec.enable_skill_discovery is False
@@ -421,8 +450,12 @@ def test_enrich_team_spec_for_swarm_rewrites_spec_in_place() -> None:
assert not hasattr(spec, "agent_customizer")
-def test_enrich_team_spec_appends_after_existing_rails() -> None:
+def test_enrich_team_spec_appends_after_existing_rails(monkeypatch) -> None:
"""Provider rails are appended after a member's pre-existing rails."""
+ monkeypatch.setattr(
+ "jiuwenswarm.agents.swarm.config_specs._retrieval_enabled",
+ lambda config=None: False,
+ )
spec = _make_team_spec()
# Seed the leader with a non-swarm rail to prove ordering is preserved.
spec.agents["leader"].rails = [RailSpec(type="skill_use")]
@@ -721,6 +754,7 @@ _EXPECTED_CODE_RAIL_NAMES: frozenset[str] = frozenset(
registry.USER_HOOKS,
registry.CODE_SKILL_USE,
registry.CODE_WORKTREE,
+ registry.SKILL_RETRIEVAL_PROMPT,
registry.CODE_CONFIRM_INTERRUPT,
registry.MEMBER_SKILL_TOOLKIT,
registry.TEAM_WORKSPACE_REPORT_PATH,
diff --git a/tests/symphony/test_agentic_retrieval_toolkit.py b/tests/symphony/test_agentic_retrieval_toolkit.py
new file mode 100644
index 0000000000..78dd2e9e43
--- /dev/null
+++ b/tests/symphony/test_agentic_retrieval_toolkit.py
@@ -0,0 +1,307 @@
+from __future__ import annotations
+
+import sys
+import types
+from types import SimpleNamespace
+
+from jiuwenswarm.symphony.agent import AgenticRetrievalToolKit
+
+
+def _node(
+ node_id: str,
+ description: str = "",
+ *,
+ children: list[SimpleNamespace] | None = None,
+ items: list[SimpleNamespace] | None = None,
+) -> SimpleNamespace:
+ return SimpleNamespace(
+ node_id=node_id,
+ description=description,
+ children=children or [],
+ items=items or [],
+ )
+
+
+def _toolkit() -> AgenticRetrievalToolKit:
+ pdf_item = SimpleNamespace(
+ payload="pdf-reader",
+ item_id="pdf-reader",
+ label="pdf-reader",
+ description=(
+ "Read, summarize, and extract content from PDF files.\n"
+ "Select when: 用户需要读取、总结或抽取 PDF 内容。\n"
+ "Don't select when: 用户要生成 PPT、Excel 或图片。"
+ ),
+ )
+ pdf_branch = _node(
+ "OfficeDocs.Documents.Pdf",
+ "PDF 阅读、抽取、转换、整理。\nSelect when: 用户处理 PDF。",
+ items=[pdf_item],
+ )
+ docs_branch = _node(
+ "OfficeDocs.Documents",
+ "Word、PDF、TXT、Markdown、格式转换。",
+ children=[pdf_branch],
+ )
+ office_branch = _node(
+ "OfficeDocs",
+ (
+ "办公文件的生成、编辑、转换、提取、排版和结构化处理。\n"
+ "Select when: 用户要处理 Word、PDF、PPT、Excel、Markdown。\n"
+ "Don't select when: 用户只是联网查资料。"
+ ),
+ children=[docs_branch],
+ )
+ research_branch = _node(
+ "SearchResearch",
+ "网页搜索、内容抓取、新闻、论文、深度调研和知识库检索。",
+ )
+ root = _node("ROOT", "Root description must not be rendered.", children=[office_branch, research_branch])
+ record = SimpleNamespace(
+ payload="pdf-reader",
+ worker_id="pdf-reader",
+ name="pdf-reader",
+ description=pdf_item.description,
+ metadata={"skill_path": "/home/doujzc/.openjiuwen/skills/pdf-reader/SKILL.md"},
+ )
+ loaded_index = SimpleNamespace(tree_root=root, catalog_records=[record])
+ return AgenticRetrievalToolKit(loaded_index=loaded_index, progressive_config=object(), top_k=5)
+
+
+def test_skill_branch_peek_returns_branch_summary_only() -> None:
+ result = _toolkit().skill_branch_peek(["ROOT"])
+
+ assert result["success"] is True
+ markdown = result["result"]
+ assert markdown.startswith("# Skill Branch Peek")
+ assert "## input `ROOT`" in markdown
+ assert "Root description must not be rendered" not in markdown
+ assert "1. `OfficeDocs`" in markdown
+ assert "2. `SearchResearch`" in markdown
+ assert "covers: 3 branches, 1 skill" in markdown
+ assert "SKILL.md" not in markdown
+ assert "pdf-reader" not in markdown
+ assert result["skill_tree"]["query"] == "skill_branch_peek: ROOT"
+ assert result["skill_tree"]["candidate_count"] == 0
+ assert result["skill_tree"]["steps"][0]["event_type"] == "fragment_built"
+ assert result["skill_tree"]["steps"][0]["node_id"] == "ROOT"
+ assert result["skill_tree"]["steps"][0]["branches"][0]["id"] == "OfficeDocs"
+
+
+def test_skill_branch_peek_leaf_and_unknown_errors() -> None:
+ toolkit = _toolkit()
+
+ empty_explore = toolkit.skill_branch_explore([])
+ assert empty_explore["success"] is False
+ assert "`node_ids` is required" in empty_explore["result"]
+
+ root_explore = toolkit.skill_branch_explore(["ROOT"])
+ assert root_explore["success"] is False
+ assert "`ROOT` is already summarized" in root_explore["result"]
+
+ leaf_result = toolkit.skill_branch_peek(["pdf-reader"])
+ assert leaf_result["success"] is False
+ assert leaf_result["result"].startswith("# Skill Tree Node Error")
+ assert "`pdf-reader` is a skill id, not a branch id" in leaf_result["result"]
+
+ missing_result = toolkit.skill_branch_explore(["OfficeDocs.Unknown"])
+ assert missing_result["success"] is False
+ assert missing_result["result"].startswith("# Skill Tree Node Not Found")
+ assert "`OfficeDocs.Unknown`" in missing_result["result"]
+
+
+def test_skill_branch_explore_renders_next_boundary(monkeypatch) -> None:
+ terminal = SimpleNamespace(
+ canonical_id="pdf-reader",
+ selectable_canonical_id="pdf-reader",
+ children=[],
+ )
+ pdf_branch = SimpleNamespace(
+ canonical_id="node::OfficeDocs.Documents.Pdf",
+ selectable_canonical_id="",
+ description=(
+ "PDF 阅读、抽取、转换、整理。\n"
+ "Select when: 用户提供 PDF。\n"
+ "Don't select when: 用户主要处理 Excel。"
+ ),
+ children=[terminal],
+ )
+ resolution = SimpleNamespace(
+ canonical_id="pdf-reader",
+ is_terminal=True,
+ item=SimpleNamespace(
+ payload="pdf-reader",
+ item_id="pdf-reader",
+ label="pdf-reader",
+ description=(
+ "Read, summarize, and extract content from PDF files.\n"
+ "Select when: 用户需要读取、总结或抽取 PDF 内容。\n"
+ "Don't select when: 用户要生成 PPT、Excel 或图片。"
+ ),
+ ),
+ label="pdf-reader",
+ description="",
+ )
+ fragment = SimpleNamespace(
+ root=SimpleNamespace(children=[pdf_branch]),
+ code_to_resolution={"A": resolution},
+ )
+
+ class FakeCurrentSubtreeProvider:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ @staticmethod
+ def get_current_subtree(cursor):
+ assert cursor.node.node_id == "OfficeDocs.Documents"
+ assert cursor.branch_path == ("ROOT", "OfficeDocs", "OfficeDocs.Documents")
+ return SimpleNamespace(fragment=fragment)
+
+ class FakeSearchCursor:
+ def __init__(self, **kwargs):
+ self.__dict__.update(kwargs)
+
+ retrieval_module = types.ModuleType("retrieval")
+ tree_module = types.ModuleType("retrieval.tree")
+ subtree_module = types.ModuleType("retrieval.tree.subtree")
+ subtree_module.DefaultCurrentSubtreeProvider = FakeCurrentSubtreeProvider
+ types_module = types.ModuleType("retrieval.tree.types")
+ types_module.SearchCursor = FakeSearchCursor
+
+ monkeypatch.setitem(sys.modules, "retrieval", retrieval_module)
+ monkeypatch.setitem(sys.modules, "retrieval.tree", tree_module)
+ monkeypatch.setitem(sys.modules, "retrieval.tree.subtree", subtree_module)
+ monkeypatch.setitem(sys.modules, "retrieval.tree.types", types_module)
+
+ result = _toolkit().skill_branch_explore(["OfficeDocs.Documents"])
+
+ assert result["success"] is True
+ markdown = result["result"]
+ assert markdown.startswith("# Skill Branch Explore")
+ assert "## input `OfficeDocs.Documents`" in markdown
+ assert "### branch `OfficeDocs.Documents.Pdf`" in markdown
+ assert "pdf-reader" not in markdown
+ assert "Worker id" not in markdown
+ assert "SKILL.md" not in markdown
+ assert "Terminal Skill Candidates" not in markdown
+ assert "Covers:" not in markdown
+ tree = result["skill_tree"]
+ assert tree["query"] == "skill_branch_explore: OfficeDocs.Documents"
+ assert tree["candidate_count"] == 0
+ assert [step["event_type"] for step in tree["steps"]] == ["fragment_built", "fragment_continue"]
+ assert tree["steps"][1]["selected"][0]["id"] == "OfficeDocs.Documents.Pdf"
+
+
+def test_skill_branch_explore_renders_terminal_skills_with_read_info(monkeypatch) -> None:
+ terminal = SimpleNamespace(
+ canonical_id="pdf-reader",
+ selectable_canonical_id="pdf-reader",
+ children=[],
+ )
+ resolution = SimpleNamespace(
+ canonical_id="pdf-reader",
+ is_terminal=True,
+ item=SimpleNamespace(
+ payload="pdf-reader",
+ item_id="pdf-reader",
+ label="pdf-reader",
+ description=(
+ "Read, summarize, and extract content from PDF files.\n"
+ "Select when: 用户需要读取、总结或抽取 PDF 内容。\n"
+ "Don't select when: 用户要生成 PPT、Excel 或图片。"
+ ),
+ ),
+ label="pdf-reader",
+ description="",
+ )
+ fragment = SimpleNamespace(
+ root=SimpleNamespace(children=[terminal]),
+ code_to_resolution={"A": resolution},
+ )
+
+ class FakeCurrentSubtreeProvider:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ @staticmethod
+ def get_current_subtree(cursor):
+ assert cursor.node.node_id == "OfficeDocs.Documents.Pdf"
+ return SimpleNamespace(fragment=fragment)
+
+ class FakeSearchCursor:
+ def __init__(self, **kwargs):
+ self.__dict__.update(kwargs)
+
+ retrieval_module = types.ModuleType("retrieval")
+ tree_module = types.ModuleType("retrieval.tree")
+ subtree_module = types.ModuleType("retrieval.tree.subtree")
+ subtree_module.DefaultCurrentSubtreeProvider = FakeCurrentSubtreeProvider
+ types_module = types.ModuleType("retrieval.tree.types")
+ types_module.SearchCursor = FakeSearchCursor
+
+ monkeypatch.setitem(sys.modules, "retrieval", retrieval_module)
+ monkeypatch.setitem(sys.modules, "retrieval.tree", tree_module)
+ monkeypatch.setitem(sys.modules, "retrieval.tree.subtree", subtree_module)
+ monkeypatch.setitem(sys.modules, "retrieval.tree.types", types_module)
+
+ result = _toolkit().skill_branch_explore(["OfficeDocs.Documents.Pdf"])
+
+ assert result["success"] is True
+ markdown = result["result"]
+ assert "### skills" in markdown
+ assert "Candidate installed skills, not branch ids." in markdown
+ assert "Shortlist by Name/Description" in markdown
+ assert "read SKILL.md only after choosing a skill as likely useful" in markdown
+ assert "1. `pdf-reader`" in markdown
+ assert "- Description: Read, summarize, and extract content from PDF files." in markdown
+ assert "- SKILL.md: `/home/doujzc/.openjiuwen/skills/pdf-reader/SKILL.md`" in markdown
+ assert "Worker id" not in markdown
+ assert "- Select when:" not in markdown
+ assert "- Don't select when:" not in markdown
+ assert "- Read:" not in markdown
+ tree = result["skill_tree"]
+ assert tree["query"] == "skill_branch_explore: OfficeDocs.Documents.Pdf"
+ assert tree["candidate_count"] == 1
+ assert [step["event_type"] for step in tree["steps"]] == [
+ "fragment_built",
+ "fragment_continue",
+ "search_complete",
+ ]
+ assert tree["steps"][1]["leaves"][0]["id"] == "pdf-reader"
+ assert tree["candidates"][0]["label"] == "pdf-reader"
+ assert tree["candidates"][0]["worker_id"] == "pdf-reader"
+
+
+def test_root_prompt_contains_first_level_categories_only() -> None:
+ markdown = _toolkit().root_prompt_markdown(language="cn")
+
+ assert markdown.startswith("# Agentic 技能检索")
+ assert "技能目录查阅工具" in markdown
+ assert "请先根据目录结果筛选候选技能" in markdown
+ assert "只有当某个技能看起来确实需要使用时,才读取其 SKILL.md" in markdown
+ assert "不要在未使用至少一个目录工具前直接返回" in markdown
+ assert "使用技能目录时,先根据任务识别" in markdown
+ assert "主能力分支" in markdown
+ assert "输入格式分支" in markdown
+ assert "输出格式分支" in markdown
+ assert "验证/评估/测试分支" in markdown
+ assert "必要的执行环境分支" in markdown
+ assert "优先探索主能力分支" in markdown
+ assert "任务约束会改变技能选择、执行方案或验收标准" in markdown
+ assert "输入/输出形式、验证要求、执行约束、依赖条件" in markdown
+ assert "只提供背景且不影响技能选择" in markdown
+ assert "任务明确点名框架、平台、库、运行时或云服务" not in markdown
+ assert "SaaS API" not in markdown
+ assert "优先选择精确技能" in markdown
+ assert "宽泛概览技能只在需要补充必要背景时使用" in markdown
+ assert "## 第一层分类" in markdown
+ assert "不要把展示序号当作 `node_ids`" in markdown
+ assert "不要把 `ROOT` 作为首轮 `skill_branch_explore` 的输入" in markdown
+ assert "不要继续展开技能名" in markdown
+ assert "只有当某个技能看起来需要使用时,才读取其 SKILL.md" in markdown
+ assert "- `OfficeDocs`" in markdown
+ assert "1. `OfficeDocs`" not in markdown
+ assert "`OfficeDocs`" in markdown
+ assert "`SearchResearch`" in markdown
+ assert "`OfficeDocs.Documents`" not in markdown
+ assert "pdf-reader" not in markdown
diff --git a/tests/symphony/test_skill_retrieval_config.py b/tests/symphony/test_skill_retrieval_config.py
new file mode 100644
index 0000000000..420e9b384e
--- /dev/null
+++ b/tests/symphony/test_skill_retrieval_config.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from jiuwenswarm.symphony.skill_retrieval.config import load_settings
+from jiuwenswarm.symphony.skill_retrieval.taxonomy_config import root_categories_to_text
+
+
+def test_load_settings_reads_public_retrieve_config(monkeypatch) -> None:
+ monkeypatch.delenv("SYMPHONY_SKILL_RETRIEVAL_ENABLED", raising=False)
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.config.get_agent_workspace_dir",
+ lambda: Path("/tmp/jiuwenswarm-test-workspace"),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.config.get_config",
+ lambda: {
+ "symphony": {
+ "skill_retrieval": {
+ "enabled": True,
+ "build": {
+ "branching_factor": 64,
+ "root_categories": "taxonomy.yaml",
+ "max_depth": 12,
+ "request_timeout_seconds": 240,
+ "max_workers": 9,
+ "max_retries": 4,
+ "classification_batch_limit": 16,
+ "discovery_seed": 123,
+ "postprocess_enabled": False,
+ "postprocess_max_passes": 3,
+ "postprocess_min_skills": 9,
+ "equivalence_enabled": False,
+ },
+ "retrieve": {
+ "top_k": 7,
+ "compact_codes_enabled": True,
+ "flatten_tree": True,
+ "max_exposure_depth": 5,
+ "max_branch_choices": 8,
+ },
+ }
+ }
+ },
+ )
+
+ settings = load_settings()
+
+ assert settings.enabled is True
+ assert settings.build.root_categories == "taxonomy.yaml"
+ assert settings.build.branching_factor == 64
+ assert settings.build.max_depth == 12
+ assert settings.build.request_timeout_seconds == 240
+ assert settings.build.max_workers == 9
+ assert settings.build.max_retries == 4
+ assert settings.build.classification_batch_limit == 16
+ assert settings.build.discovery_seed == 123
+ assert settings.build.postprocess_enabled is False
+ assert settings.build.postprocess_max_passes == 3
+ assert settings.build.postprocess_min_skills == 9
+ assert settings.build.equivalence_enabled is False
+ assert settings.retrieve.top_k == 7
+ assert settings.retrieve.compact_codes_enabled is True
+ assert settings.retrieve.flatten_tree is True
+ assert settings.retrieve.max_exposure_depth == 5
+ assert settings.retrieve.max_branch_choices == 2
+
+
+def test_root_categories_panel_text_falls_back_from_unreadable_path() -> None:
+ text = root_categories_to_text("missing-root-categories.yaml")
+
+ assert text.startswith("tree_root_categories:")
+ assert "external-service-automation" in text
diff --git a/tests/symphony/test_tree_grouping_prompts.py b/tests/symphony/test_tree_grouping_prompts.py
new file mode 100644
index 0000000000..9d1a5a243f
--- /dev/null
+++ b/tests/symphony/test_tree_grouping_prompts.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jiuwenswarm.symphony.skill_retrieval.dispatch_imports import dispatch_import_path
+
+
+def test_dynamic_grouping_prompts_do_not_use_fixed_group_count() -> None:
+ with dispatch_import_path():
+ from indexing.tree.grouping import TreeGroupingEngine
+
+ class FakeBuilder:
+ def __init__(self) -> None:
+ self.config = SimpleNamespace(branching_factor=999)
+ self.prompts: list[str] = []
+
+ def _call_llm_json(self, prompt: str) -> dict:
+ self.prompts.append(prompt)
+ if "Canonicalization pass" in prompt:
+ return {"canonical_groups": {"alpha": {"name": "Alpha", "description": "Alpha group"}}}
+ return {"groups": {"alpha": {"name": "Alpha", "description": "Alpha group"}}}
+
+ builder = FakeBuilder()
+ engine = TreeGroupingEngine(builder)
+
+ groups = engine.discover_groups(
+ [{"id": "skill-a", "name": "Skill A", "description": "A skill."}],
+ parent_context={"name": "Parent", "description": "Parent scope."},
+ )
+ merged = engine.merge_group_definitions([groups, groups])
+
+ expected_group = {
+ "alpha": {
+ "name": "Alpha",
+ "description": "Alpha group",
+ "select_when": "",
+ "dont_select_when": "",
+ }
+ }
+ assert groups == expected_group
+ assert merged == expected_group
+ assert len(builder.prompts) == 2
+ assert "996" not in builder.prompts[0]
+ assert "1001" not in builder.prompts[0]
+ assert "996" not in builder.prompts[1]
+ assert "1001" not in builder.prompts[1]
+ assert "fixed configured count" in builder.prompts[0]
+ assert "fixed configured count" in builder.prompts[1]
diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.py
index 7b1cdee4e3..9d83e01491 100644
--- a/tests/unit_tests/agentserver/test_agentserver_acp.py
+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py
@@ -230,6 +230,65 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_result_status():
}
+def test_parse_stream_chunk_uses_skill_tree_result_as_raw_output():
+ raw_output = {
+ "success": True,
+ "result": "# Skill Branch Explore",
+ "skill_tree": {
+ "query": "skill_branch_explore: SoftwareEngineering",
+ "steps": [{"order": 0, "node_id": "SoftwareEngineering"}],
+ "candidates": [],
+ },
+ }
+ parsed = parse_stream_chunk(
+ types.SimpleNamespace(
+ type="tool_result",
+ payload={
+ "tool_result": {
+ "tool_call_id": "call-1",
+ "tool_name": "skill_branch_explore",
+ **raw_output,
+ }
+ },
+ )
+ )
+
+ assert parsed["event_type"] == "chat.tool_result"
+ assert parsed["tool_name"] == "skill_branch_explore"
+ assert parsed["tool_call_id"] == "call-1"
+ assert parsed["raw_output"] == raw_output
+
+
+def test_interface_deep_parse_stream_chunk_uses_skill_tree_result_as_raw_output():
+ parse_chunk = getattr(interface_deep_module.JiuWenSwarmDeepAdapter, "_parse_stream_chunk")
+ raw_output = {
+ "success": True,
+ "result": "# Skill Branch Explore",
+ "skill_tree": {
+ "query": "skill_branch_explore: SoftwareEngineering",
+ "steps": [{"order": 0, "node_id": "SoftwareEngineering"}],
+ "candidates": [],
+ },
+ }
+ parsed = parse_chunk(
+ types.SimpleNamespace(
+ type="tool_result",
+ payload={
+ "tool_result": {
+ "tool_call_id": "call-1",
+ "tool_name": "skill_branch_explore",
+ **raw_output,
+ }
+ },
+ )
+ )
+
+ assert parsed["event_type"] == "chat.tool_result"
+ assert parsed["tool_name"] == "skill_branch_explore"
+ assert parsed["tool_call_id"] == "call-1"
+ assert parsed["raw_output"] == raw_output
+
+
def test_parse_stream_chunk_preserves_symphony_status_payload():
parsed = parse_stream_chunk(
types.SimpleNamespace(
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index 07a1a5195c..94af17cd9a 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -13,7 +13,9 @@ from openjiuwen.harness.prompts import PromptSection, SystemPromptBuilder
from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
from jiuwenswarm.agents.harness.common.prompt.prompt_builder import build_agent_identity_prompt
from jiuwenswarm.agents.harness.common.rails import runtime_prompt_rail as _runtime_mod
+from jiuwenswarm.agents.harness.common.rails import skill_retrieval_prompt_rail as _skill_retrieval_prompt_mod
from jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import RuntimePromptRail
+from jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail import SkillRetrievalPromptRail
class _TestableJiuWenSwarmDeepAdapter(JiuWenSwarmDeepAdapter):
@@ -40,6 +42,29 @@ class _FakeAgent:
self.prompt_attachment_manager = PromptAttachmentManager()
+class _FakeAbilityManager:
+ def __init__(self) -> None:
+ self._items = {
+ "list_skill": SimpleNamespace(name="list_skill"),
+ "search_skill": SimpleNamespace(name="search_skill"),
+ }
+
+ def get(self, name: str):
+ return self._items.get(name)
+
+ def remove(self, name: str):
+ return self._items.pop(name, None)
+
+ def add(self, ability):
+ self._items[ability.name] = ability
+
+
+class _FakeToolAgent(_FakeAgent):
+ def __init__(self, builder: SystemPromptBuilder) -> None:
+ super().__init__(builder)
+ self.ability_manager = _FakeAbilityManager()
+
+
def test_build_agent_identity_prompt_contains_identity_section_only(monkeypatch):
monkeypatch.setattr(
"jiuwenswarm.symphony.config.load_symphony_config",
@@ -242,11 +267,59 @@ async def test_runtime_prompt_language_output_prefers_rail_language_over_runtime
assert "当前语言:cn" in rendered
-def test_resolve_skill_mode_accepts_all_and_auto_list():
+async def test_skill_retrieval_prompt_hides_legacy_list_skill(monkeypatch):
+ monkeypatch.setattr(
+ _skill_retrieval_prompt_mod,
+ "render_skill_retrieval_prompt",
+ lambda manager, language: "# Agentic 技能检索\n使用 skill_branch_explore。",
+ )
+ builder = SystemPromptBuilder(language="cn")
+ builder.add_section(PromptSection(name="skills", content={"cn": "旧 list_skill 提示"}, priority=40))
+ agent = _FakeToolAgent(builder)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=SimpleNamespace(
+ tools=[
+ SimpleNamespace(name="list_skill"),
+ SimpleNamespace(name="list_skills"),
+ SimpleNamespace(name="skill_branch_explore"),
+ ],
+ ),
+ session=_FakeSession(),
+ extra={},
+ )
+
+ rail = SkillRetrievalPromptRail()
+ rail.init(agent)
+ await rail.before_model_call(ctx)
+
+ assert [tool.name for tool in ctx.inputs.tools] == ["skill_branch_explore"]
+ assert agent.ability_manager.get("list_skill") is None
+ prompt = builder.build()
+ assert "旧 list_skill 提示" not in prompt
+ assert "Agentic 技能检索" in prompt
+
+ await rail.after_model_call(ctx)
+
+ assert agent.ability_manager.get("list_skill") is not None
+
+
+def test_resolve_skill_mode_accepts_all_and_auto_list(monkeypatch):
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.is_skill_retrieval_enabled",
+ lambda: False,
+ )
assert JiuWenSwarmDeepAdapter._resolve_skill_mode({"skill_mode": "all"}) == "all"
assert JiuWenSwarmDeepAdapter._resolve_skill_mode({"skill_mode": "auto_list"}) == "auto_list"
assert JiuWenSwarmDeepAdapter._resolve_skill_mode({"skill_mode": "invalid"}) == "all"
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.is_skill_retrieval_enabled",
+ lambda: True,
+ )
+ assert JiuWenSwarmDeepAdapter._resolve_skill_mode({"skill_mode": "all"}) == "auto_list"
+
def test_resolve_enable_task_loop_can_be_called_on_class(monkeypatch):
monkeypatch.delenv("SKILL_CREATE", raising=False)
diff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.py
index 572d2d20b0..94c97919b9 100644
--- a/tests/unit_tests/test_app_web_handlers.py
+++ b/tests/unit_tests/test_app_web_handlers.py
@@ -151,14 +151,15 @@ def test_config_panel_flatten_reads_symphony_enabled_and_skill_retrieval():
assert "symphony_orchestration_mode" not in flat
assert flat["skill_retrieval_enabled"] == "true"
assert flat["skill_retrieval_build_branching_factor"] == "64"
- assert flat["skill_retrieval_retrieve_top_k"] == "5"
- assert flat["skill_retrieval_flatten_tree"] == "true"
+ assert "skill_retrieval_retrieve_top_k" not in flat
+ assert flat["skill_retrieval_retrieve_flatten_tree"] == "true"
@pytest.mark.asyncio
async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):
channel = FakeWebChannel()
- recorded: list[dict] = []
+ recorded_symphony: list[dict] = []
+ recorded_skill_retrieval: list[dict] = []
_register_web_handlers(WebHandlersBindParams(channel=channel))
@@ -172,7 +173,11 @@ async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):
)
monkeypatch.setattr(
"jiuwenswarm.gateway.channel_manager.web.app_web_handlers.update_symphony_in_config",
- lambda updates: recorded.append(updates),
+ lambda updates: recorded_symphony.append(updates),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.update_skill_retrieval_in_config",
+ lambda updates: recorded_skill_retrieval.append(updates),
)
await channel.methods["config.set"](
@@ -181,17 +186,13 @@ async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):
{
"symphony_enabled": "true",
"skill_retrieval_enabled": "false",
- "skill_retrieval_retrieve_top_k": "7",
+ "skill_retrieval_retrieve_flatten_tree": "true",
},
"sess-3",
)
- assert recorded == [
- {
- "enabled": True,
- "skill_retrieval": {"enabled": False, "retrieve": {"top_k": 7}},
- }
- ]
+ assert recorded_symphony == [{"enabled": True}]
+ assert recorded_skill_retrieval == [{"enabled": False, "retrieve": {"flatten_tree": True}}]
assert channel.responses[-1] == {
"id": "req-3",
"ok": True,
@@ -199,7 +200,7 @@ async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):
"updated": [
"symphony_enabled",
"skill_retrieval_enabled",
- "skill_retrieval_retrieve_top_k",
+ "skill_retrieval_retrieve_flatten_tree",
],
"applied_without_restart": True,
},
diff --git a/tests/unit_tests/test_config.py b/tests/unit_tests/test_config.py
index 38992af78a..0dedf50ea9 100644
--- a/tests/unit_tests/test_config.py
+++ b/tests/unit_tests/test_config.py
@@ -13,6 +13,7 @@ from jiuwenswarm.common.config import (
migrate_config_from_template,
replace_teams_in_config,
resolve_env_vars,
+ update_skill_retrieval_in_config,
)
@@ -169,6 +170,84 @@ symphony:
assert migrated["symphony"]["fingerprint"]["extraction"]["batch_size"] == 1
assert migrated["symphony"]["fingerprint"]["normalization"]["workers"] == 1
+ @staticmethod
+ def test_update_skill_retrieval_keeps_public_build_and_retrieve_config(
+ monkeypatch: pytest.MonkeyPatch,
+ temp_config_file: Path,
+ ):
+ temp_config_file.write_text(
+ """
+symphony:
+ skill_retrieval:
+ enabled: false
+ build:
+ branching_factor: 96
+ root_categories: old
+ max_depth: 7
+ request_timeout_seconds: 300
+ max_workers: 4
+ max_retries: 2
+ classification_batch_limit: 24
+ discovery_seed: 42
+ postprocess_enabled: true
+ postprocess_max_passes: 1
+ postprocess_min_skills: 6
+ equivalence_enabled: true
+ retrieve:
+ top_k: 8
+ compact_codes_enabled: true
+ flatten_tree: true
+ max_exposure_depth: 12
+ max_branch_choices: 3
+ max_parallel_branches: 4
+""",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)
+
+ update_skill_retrieval_in_config(
+ {
+ "build": {
+ "root_categories": "new",
+ "max_depth": 9,
+ "max_workers": 8,
+ "max_retries": 3,
+ "classification_batch_limit": 12,
+ "discovery_seed": 7,
+ "postprocess_enabled": False,
+ "postprocess_max_passes": 4,
+ "postprocess_min_skills": 10,
+ "equivalence_enabled": False,
+ },
+ "retrieve": {
+ "top_k": 6,
+ "max_branch_choices": 5,
+ },
+ }
+ )
+
+ raw = yaml.safe_load(temp_config_file.read_text(encoding="utf-8"))
+ section = raw["symphony"]["skill_retrieval"]
+ assert section["build"] == {
+ "branching_factor": 96,
+ "root_categories": "new",
+ "max_depth": 9,
+ "request_timeout_seconds": 300,
+ "max_workers": 8,
+ "max_retries": 3,
+ "classification_batch_limit": 12,
+ "discovery_seed": 7,
+ "postprocess_enabled": False,
+ "postprocess_max_passes": 4,
+ "postprocess_min_skills": 10,
+ "equivalence_enabled": False,
+ }
+ assert section["retrieve"] == {
+ "compact_codes_enabled": True,
+ "flatten_tree": True,
+ "max_exposure_depth": 12,
+ }
+
class TestTeamModesConfig:
"""Test team config persistence under modes.team."""