Skip to content

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

Python

feat (symphony-retrieval): 引入本地skill的Agentic检索能力

xutuoa89c994c1d97
diff --git a/jiuwenswarm/agents/harness/common/tools/__init__.py b/jiuwenswarm/agents/harness/common/tools/__init__.py
index a8903d31c0..c6244fa18e 100644
--- a/jiuwenswarm/agents/harness/common/tools/__init__.py
+++ b/jiuwenswarm/agents/harness/common/tools/__init__.py
@@ -21,6 +21,10 @@ from .send_file_to_user import (
from .skill_toolkits import (
SkillToolkit,
)
+from .skill_retrieval_toolkits import (
+ is_skill_retrieval_enabled,
+ SkillRetrievalToolkit,
+)
# Re-export deep openjiuwen symbols at ≤3-layer depth so task_tools.py can comply
# with the G.IMP import-depth lint rule without creating additional files.
@@ -57,6 +61,8 @@ __all__ = [
"is_group_chat_mode",
"SendFileToolkit",
"SkillToolkit",
+ "is_skill_retrieval_enabled",
+ "SkillRetrievalToolkit",
# openjiuwen re-exports
"tool",
"ce_config",
diff --git a/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py b/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
new file mode 100644
index 0000000000..9ca100ee0b
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
@@ -0,0 +1,80 @@
+"""Agent-facing toolkit for installed skill retrieval."""
+
+from __future__ import annotations
+
+import asyncio
+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
+
+
+def is_skill_retrieval_enabled() -> bool:
+ try:
+ return bool(load_settings().enabled)
+ except Exception:
+ return False
+
+
+class SkillRetrievalToolkit:
+ """Expose dispatch-backed installed skill retrieval to agents."""
+
+ def __init__(self, manager: SkillManager) -> None:
+ self._manager = manager
+
+ 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)
+
+ def get_tools(self) -> list[Tool]:
+ def make_tool(name: str, description: str, input_params: dict, func: Callable[..., Any]) -> Tool:
+ card = ToolCard(
+ id=name,
+ name=name,
+ description=description,
+ input_params=input_params,
+ )
+ return LocalFunction(card=card, func=func)
+
+ return [
+ 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."
+ ),
+ input_params={
+ "type": "object",
+ "properties": {},
+ "required": [],
+ },
+ func=self.skill_index_build,
+ ),
+ make_tool(
+ name="skill_retrieve",
+ 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."
+ ),
+ input_params={
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "User task or retrieval query.",
+ },
+ },
+ "required": ["query"],
+ },
+ func=self.skill_retrieve,
+ ),
+ ]
diff --git a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
index 221bf8d342..4c63a9bb4c 100644
--- a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
+++ b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
@@ -95,6 +95,8 @@ TOOL_WHITELIST = frozenset({
"search_skill",
"install_skill",
"uninstall_skill",
+ "skill_index_build",
+ "skill_retrieve",
"user_todos",
"get_user_location",
"create_note",
diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.py
index e319892452..595801a469 100644
--- a/jiuwenswarm/agents/swarm/config_specs.py
+++ b/jiuwenswarm/agents/swarm/config_specs.py
@@ -78,6 +78,7 @@ _COMMON_TOOL_NAMES: tuple[str, ...] = (
# link-refresh callback. Declaring SKILL_TOOLKIT here too only double-
# registers the same-named tools, logging a refresh + duplicate-ability
# warning per tool every build; the rail is the sole registrar.
+ registry.SKILL_RETRIEVAL,
registry.USER_TODOS,
registry.VIDEO,
registry.IMAGE_GEN,
@@ -124,6 +125,7 @@ _CODE_TOOL_NAMES: tuple[str, ...] = (
registry.AUDIO,
# See _COMMON_TOOL_NAMES: skill tools come from the MEMBER_SKILL_TOOLKIT
# rail; declaring SKILL_TOOLKIT here too would double-register them.
+ registry.SKILL_RETRIEVAL,
registry.USER_TODOS,
registry.VIDEO,
registry.IMAGE_GEN,
diff --git a/jiuwenswarm/agents/swarm/providers/tools.py b/jiuwenswarm/agents/swarm/providers/tools.py
index 8be18e54c1..2edccfe38e 100644
--- a/jiuwenswarm/agents/swarm/providers/tools.py
+++ b/jiuwenswarm/agents/swarm/providers/tools.py
@@ -7,6 +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.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).
@@ -43,6 +44,10 @@ from jiuwenswarm.agents.harness.common.tools.multimodal_config import (
apply_vision_model_config_from_yaml,
dedicated_multimodal_model_configured,
)
+from jiuwenswarm.agents.harness.common.tools.skill_retrieval_toolkits import (
+ SkillRetrievalToolkit,
+ is_skill_retrieval_enabled,
+)
from jiuwenswarm.agents.harness.common.tools.skill_toolkits import SkillToolkit
from jiuwenswarm.agents.harness.common.tools.user_todo_tool import get_decorated_tools
from jiuwenswarm.agents.harness.common.tools.video_tools import video_understanding
@@ -83,6 +88,7 @@ logger = logging.getLogger(__name__)
# Provider name constants; namespaced under the shared "swarm." prefix.
SKILL_TOOLKIT = "swarm.skill_toolkit"
+SKILL_RETRIEVAL = "swarm.skill_retrieval"
USER_TODOS = "swarm.user_todos"
VIDEO = "swarm.video"
IMAGE_GEN = "swarm.image_gen"
@@ -257,6 +263,20 @@ def _build_skill_toolkit_tools(workspace_root: str | None) -> list[Any]:
return []
+def _build_skill_retrieval_tools(workspace_root: str | None) -> list[Any]:
+ """Build the installed-skill retrieval tools bound to the member workspace."""
+ if not is_skill_retrieval_enabled():
+ logger.info("[swarm.skill_retrieval] skipped: disabled")
+ return []
+ try:
+ manager = SkillManager(workspace_dir=workspace_root)
+ toolkit = SkillRetrievalToolkit(manager=manager)
+ return list(toolkit.get_tools())
+ except Exception as exc:
+ logger.warning("[swarm.skill_retrieval] construction failed: %s", exc)
+ return []
+
+
def _build_user_todo_tools() -> list[Any]:
"""Build the user's personal todo tool."""
try:
@@ -317,6 +337,18 @@ def build_skill_toolkit(params: dict[str, Any], ctx: SwarmBuildContext) -> list[
return _filter_whitelist(_build_skill_toolkit_tools(inp.workspace_root))
+@harness_element(
+ kind=ElementKind.TOOL,
+ name=SKILL_RETRIEVAL,
+ description="Dispatch-backed installed skill retrieval tools bound to the member workspace.",
+ input_model=SkillToolkitInput,
+)
+def build_skill_retrieval(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:
+ """Build the whitelist-filtered installed-skill retrieval tools."""
+ inp = SkillToolkitInput.resolve(params, ctx)
+ return _filter_whitelist(_build_skill_retrieval_tools(inp.workspace_root))
+
+
@harness_element(
kind=ElementKind.TOOL,
name=USER_TODOS,
@@ -388,6 +420,7 @@ def build_code_extra_tools(params: dict[str, Any], ctx: SwarmBuildContext) -> li
__all__ = [
"SKILL_TOOLKIT",
+ "SKILL_RETRIEVAL",
"USER_TODOS",
"VIDEO",
"IMAGE_GEN",
diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.py
index 780fc17173..bc511733f9 100644
--- a/jiuwenswarm/agents/swarm/registry.py
+++ b/jiuwenswarm/agents/swarm/registry.py
@@ -61,6 +61,7 @@ from jiuwenswarm.common.config import get_config
# Re-exported provider name constants for config_specs to reference by symbol.
# Swarm-owned tools (each self-gated by config + whitelist-filtered).
SKILL_TOOLKIT = _tools.SKILL_TOOLKIT
+SKILL_RETRIEVAL = _tools.SKILL_RETRIEVAL
USER_TODOS = _tools.USER_TODOS
VIDEO = _tools.VIDEO
IMAGE_GEN = _tools.IMAGE_GEN
@@ -178,6 +179,7 @@ def register_swarm_providers() -> None:
__all__ = [
"register_swarm_providers",
"SKILL_TOOLKIT",
+ "SKILL_RETRIEVAL",
"USER_TODOS",
"VIDEO",
"IMAGE_GEN",
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
index 82e0f944e4..c5c60615e3 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
@@ -286,6 +286,26 @@ const FREE_SEARCH_KEYS = new Set([...FREE_SEARCH_BOOLEAN_KEYS]);
const HIDDEN_CONFIG_KEYS = new Set(["free_search_proxy_url"]);
const MEMORY_KEYS = new Set(["memory_forbidden_enabled", "memory_forbidden_description"]);
const A2UI_KEYS = new Set(["a2ui_enabled"]);
+const SKILL_RETRIEVAL_BOOLEAN_KEYS = new Set([
+ "skill_retrieval_enabled",
+ "skill_retrieval_compact_codes_enabled",
+ "skill_retrieval_flatten_tree",
+]);
+const SKILL_RETRIEVAL_KEYS = new Set([
+ "skill_retrieval_enabled",
+ "skill_retrieval_build_branching_factor",
+ "skill_retrieval_build_max_depth",
+ "skill_retrieval_build_root_categories",
+ "skill_retrieval_build_max_workers",
+ "skill_retrieval_build_request_timeout_seconds",
+ "skill_retrieval_retrieve_top_k",
+ "skill_retrieval_compact_codes_enabled",
+ "skill_retrieval_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 {
if (MODEL_DEFAULT_KEYS.has(key)) return "model_default";
@@ -301,6 +321,7 @@ function classifyKey(key: string): string {
if (FREE_SEARCH_KEYS.has(key)) return "free_search";
if (MEMORY_KEYS.has(key)) return "memory";
if (A2UI_KEYS.has(key)) return "a2ui";
+ if (SKILL_RETRIEVAL_KEYS.has(key)) return "skill_retrieval";
if (key === "context_engine_enabled" || key === "kv_cache_affinity_enabled") return "context_engine";
if (key === "permissions_enabled") return "permissions";
if (key.startsWith("feishu")) return "feishu";
@@ -400,6 +421,14 @@ function getGroupIcon(tag: string) {
</svg>
);
}
+ if (tag === "skill_retrieval") {
+ return (
+ <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.8}>
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 5.25h16.5M6 5.25v13.5m0 0h12.75M6 18.75l3.75-4.5 3 3 4.5-6" />
+ <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 8.25h3M15.75 11.25h3" />
+ </svg>
+ );
+ }
return (
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.8}>
<path strokeLinecap="round" strokeLinejoin="round" d="M11.25 6h9m-9 6h9m-9 6h9M3.75 6h.008v.008H3.75V6zm0 6h.008v.008H3.75V12zm0 6h.008v.008H3.75V18z" />
@@ -422,6 +451,7 @@ function getGroupToneClass(tag: string): string {
if (tag === "context_engine") return "text-sky-500 bg-sky-500/10 border-sky-500/20";
if (tag === "permissions") return "text-rose-500 bg-rose-500/10 border-rose-500/20";
if (tag === "a2ui") return "text-fuchsia-500 bg-fuchsia-500/10 border-fuchsia-500/20";
+ if (tag === "skill_retrieval") return "text-emerald-500 bg-emerald-500/10 border-emerald-500/20";
if (tag === "email") return "text-emerald-500 bg-emerald-500/10 border-emerald-500/20";
return "text-text-muted bg-secondary/70 border-border";
}
@@ -445,7 +475,8 @@ function isBooleanKey(key: string): boolean {
key === "kv_cache_affinity_enabled" ||
key === "permissions_enabled" ||
key === "memory_forbidden_enabled" ||
- key === "a2ui_enabled"
+ key === "a2ui_enabled" ||
+ SKILL_RETRIEVAL_BOOLEAN_KEYS.has(key)
);
}
@@ -464,6 +495,9 @@ function getBooleanKeyLabel(key: string, t: (key: string) => string): string {
permissions_enabled: t('config.booleanLabels.enabled'),
memory_forbidden_enabled: t('config.booleanLabels.enabled'),
a2ui_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;
}
@@ -506,6 +540,7 @@ function getGroupMeta(t: (key: string) => string): Record<string, { label: strin
context_engine: { label: t('config.groups.contextEngine.label'), order: 8, hint: t('config.groups.contextEngine.hint') },
permissions: { label: t('config.groups.permissions.label'), order: 9, hint: t('config.groups.permissions.hint') },
a2ui: { label: t('config.groups.a2ui.label'), order: 10, hint: t('config.groups.a2ui.hint') },
+ skill_retrieval: { label: t('config.groups.skillRetrieval.label'), order: 10.5, hint: t('config.groups.skillRetrieval.hint') },
memory: { label: t('config.groups.memory.label'), order: 11, hint: t('config.groups.memory.hint') },
email: { label: t('config.groups.email.label'), order: 12, hint: t('config.groups.email.hint') },
other: { label: t('config.groups.other.label'), order: 13, hint: t('config.groups.other.hint') },
@@ -528,12 +563,27 @@ const KEY_DISPLAY_I18N: Record<string, string> = {
name: "config.keys.agentName",
model: "config.keys.agentModel",
skills: "config.keys.agentSkills",
+ skill_retrieval_enabled: "config.keys.skillRetrievalEnabled",
+ skill_retrieval_build_branching_factor: "config.keys.skillRetrievalBuildBranchingFactor",
+ 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_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_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",
+ skill_retrieval_build_root_categories: "config.keys.skillRetrievalBuildRootCategoriesPlaceholder",
};
const KEY_LABEL_HINT_I18N: Record<string, string> = {
skill_create: "config.keyHelp.skillCreate",
+ skill_retrieval_build_root_categories: "config.keyHelp.skillRetrievalBuildRootCategories",
};
/** 组内字段排序优先级,数字越小越靠前 */
@@ -542,6 +592,19 @@ const KEY_SORT_PRIORITY: Record<string, number> = {
skill_create: 1,
free_search_ddg_enabled: 0,
free_search_bing_enabled: 1,
+ 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_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,
memory_forbidden_enabled: 0,
memory_forbidden_description: 1,
model: 0,
@@ -3477,4 +3540,4 @@ export function ConfigPanel({
</div >
);
-}
\ No newline at end of file
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
index 50cd36cec5..2fde48b91d 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
@@ -3,8 +3,9 @@
*
* Skills 管理面板
*/
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useTranslation } from 'react-i18next';
+import { ChevronRight } from 'lucide-react';
import { webRequest } from "../../services/webClient";
import { SourceManagerModal } from "../../features/SourceManagerModal";
import { SkillNetSearchModal } from "../../features/SkillNetSearchModal";
@@ -63,6 +64,44 @@ type SkillDetail = SkillItem & {
type LoadState = "idle" | "loading" | "success" | "error";
+type SkillRetrievalStatus = {
+ enabled?: boolean;
+ index_exists?: boolean;
+ fresh?: boolean;
+ installed_enabled_count?: number;
+ indexed_count?: number;
+ built_at?: string;
+ index_dir?: string;
+};
+
+type SkillRetrievalTreeResponse = {
+ success?: boolean;
+ result?: string;
+ nodes?: SkillIndexNode[];
+ branch_count?: number;
+ leaf_count?: number;
+ index_dir?: string;
+};
+
+type SkillIndexNode = {
+ cid: string;
+ parent_cid?: string;
+ type?: "branch" | "leaf" | string;
+ label?: string;
+ description?: string;
+ select_when?: string;
+ dont_select_when?: string;
+ source_description?: string;
+ worker_id?: string;
+ category?: string;
+ keywords?: string[];
+ examples?: string[];
+};
+
+type SkillIndexTreeNode = SkillIndexNode & {
+ children: SkillIndexTreeNode[];
+};
+
interface SkillPanelProps {
sessionId: string;
onNavigateToConfig?: () => void;
@@ -100,9 +139,154 @@ function normalizeSkillItem<T extends SkillItem>(raw: T): T {
};
}
+function buildSkillIndexTree(nodes: SkillIndexNode[]): SkillIndexTreeNode[] {
+ const map = new Map<string, SkillIndexTreeNode>();
+ nodes.forEach((node) => {
+ const cid = String(node.cid || "").trim();
+ if (!cid) return;
+ map.set(cid, { ...node, cid, children: [] });
+ });
+
+ const roots: SkillIndexTreeNode[] = [];
+ map.forEach((node) => {
+ const parentCid = String(node.parent_cid || "").trim();
+ const parent = parentCid ? map.get(parentCid) : undefined;
+ if (parent) {
+ parent.children.push(node);
+ } else {
+ roots.push(node);
+ }
+ });
+
+ const sortNodes = (items: SkillIndexTreeNode[]) => {
+ items.sort((a, b) => {
+ const aType = a.type === "leaf" ? 1 : 0;
+ const bType = b.type === "leaf" ? 1 : 0;
+ if (aType !== bType) return aType - bType;
+ return getSkillIndexNodeLabel(a).localeCompare(getSkillIndexNodeLabel(b));
+ });
+ items.forEach((item) => sortNodes(item.children));
+ };
+ sortNodes(roots);
+ return roots;
+}
+
+function getSkillIndexNodeLabel(node: SkillIndexNode): string {
+ return String(node.label || node.worker_id || node.cid || "").trim() || "node";
+}
+
+function findSkillIndexNode(nodes: SkillIndexNode[], cid: string | null): SkillIndexNode | null {
+ if (!cid) return null;
+ return nodes.find((node) => node.cid === cid) || null;
+}
+
+function SkillIndexTreeView({
+ roots,
+ selectedCid,
+ onSelect,
+ emptyText,
+ branchLabel,
+ skillLabel,
+}: {
+ roots: SkillIndexTreeNode[];
+ selectedCid: string | null;
+ onSelect: (cid: string) => void;
+ emptyText: string;
+ branchLabel: string;
+ skillLabel: string;
+}) {
+ const [expanded, setExpanded] = useState<Record<string, boolean>>({});
+
+ useEffect(() => {
+ const next: Record<string, boolean> = {};
+ const walk = (items: SkillIndexTreeNode[], depth: number) => {
+ items.forEach((item) => {
+ if (item.children.length > 0 && depth < 2) {
+ next[item.cid] = true;
+ }
+ walk(item.children, depth + 1);
+ });
+ };
+ walk(roots, 0);
+ setExpanded(next);
+ }, [roots]);
+
+ const renderNode = (node: SkillIndexTreeNode, depth: number): ReactNode => {
+ const hasChildren = node.children.length > 0;
+ const isExpanded = expanded[node.cid] ?? false;
+ const selected = selectedCid === node.cid;
+ const isLeaf = node.type === "leaf";
+ return (
+ <div key={node.cid}>
+ <div
+ role="treeitem"
+ aria-selected={selected}
+ aria-expanded={hasChildren ? isExpanded : undefined}
+ className={`flex items-center gap-1 rounded-md border text-xs transition-colors ${
+ selected
+ ? "border-accent/40 bg-accent/10 text-accent"
+ : "border-transparent text-text hover:bg-secondary/60"
+ }`}
+ style={{ paddingLeft: `${8 + depth * 14}px` }}
+ >
+ <button
+ type="button"
+ onClick={() => {
+ if (hasChildren) {
+ setExpanded((prev) => ({ ...prev, [node.cid]: !isExpanded }));
+ }
+ }}
+ className={`h-7 w-5 shrink-0 flex items-center justify-center rounded ${
+ hasChildren ? "text-text-muted hover:text-text" : "text-text-muted/50 cursor-default"
+ }`}
+ aria-label={hasChildren ? (isExpanded ? "Collapse" : "Expand") : undefined}
+ >
+ {hasChildren ? (
+ <ChevronRight
+ className={`h-3 w-3 transition-transform ${isExpanded ? "rotate-90" : ""}`}
+ strokeWidth={2}
+ />
+ ) : (
+ <span className="h-1.5 w-1.5 rounded-full bg-current opacity-50" />
+ )}
+ </button>
+ <button
+ type="button"
+ onClick={() => onSelect(node.cid)}
+ className="min-w-0 flex-1 h-7 flex items-center gap-2 text-left"
+ title={getSkillIndexNodeLabel(node)}
+ >
+ <span
+ className={`shrink-0 rounded border px-1.5 py-0.5 text-[10px] leading-none ${
+ isLeaf
+ ? "border-emerald-500/25 bg-emerald-500/10 text-emerald-600"
+ : "border-sky-500/25 bg-sky-500/10 text-sky-600"
+ }`}
+ >
+ {isLeaf ? skillLabel : branchLabel}
+ </span>
+ <span className="truncate">{getSkillIndexNodeLabel(node)}</span>
+ </button>
+ </div>
+ {hasChildren && isExpanded ? (
+ <div className="mt-1 space-y-1">
+ {node.children.map((child) => renderNode(child, depth + 1))}
+ </div>
+ ) : null}
+ </div>
+ );
+ };
+
+ if (roots.length === 0) {
+ return <div className="text-sm text-text-muted">{emptyText}</div>;
+ }
+
+ return <div className="space-y-1" role="tree">{roots.map((node) => renderNode(node, 0))}</div>;
+}
+
export function SkillPanel({ sessionId, onNavigateToConfig }: SkillPanelProps) {
const { t } = useTranslation();
- const [activeTab, setActiveTab] = useState<"my" | "marketplace">("my");
+ const [activeTab, setActiveTab] = useState<"my" | "marketplace" | "index">("my");
const [mySkillsSubTab, setMySkillsSubTab] = useState<"all" | "enabled" | "disabled">("all");
const [marketplaceSubTab, setMarketplaceSubTab] = useState<"builtin" | "swarmskills" | "online">("builtin");
const [onlineSource, setOnlineSource] = useState<"skillnet" | "clawhub">("skillnet");
@@ -121,6 +305,14 @@ export function SkillPanel({ sessionId, onNavigateToConfig }: SkillPanelProps) {
const [messageType, setMessageType] = useState<"success" | "error" | "loading" | null>(null);
const messageTimerRef = useRef<number | null>(null);
const [viewMode, setViewMode] = useState<"list" | "grid">("list");
+ const [retrievalStatus, setRetrievalStatus] = useState<SkillRetrievalStatus | null>(null);
+ const [retrievalQuery, setRetrievalQuery] = useState("");
+ const [retrievalResult, setRetrievalResult] = useState("");
+ const [retrievalTree, setRetrievalTree] = useState("");
+ const [retrievalTreeNodes, setRetrievalTreeNodes] = useState<SkillIndexNode[]>([]);
+ const [retrievalTreeCounts, setRetrievalTreeCounts] = useState({ branches: 0, skills: 0 });
+ const [selectedTreeNodeCid, setSelectedTreeNodeCid] = useState<string | null>(null);
+ const [retrievalLoading, setRetrievalLoading] = useState<"idle" | "status" | "tree" | "build" | "search">("idle");
useEffect(() => {
return () => {
@@ -316,10 +508,111 @@ export function SkillPanel({ sessionId, onNavigateToConfig }: SkillPanelProps) {
[withSession]
);
+ const fetchRetrievalStatus = useCallback(async () => {
+ setRetrievalLoading((current) => (current === "idle" ? "status" : current));
+ try {
+ const data = await webRequest<SkillRetrievalStatus>(
+ "skills.retrieval.status",
+ withSession()
+ );
+ setRetrievalStatus(data);
+ } catch (error) {
+ console.error('Failed to load skill retrieval status:', error);
+ } finally {
+ setRetrievalLoading((current) => (current === "status" ? "idle" : current));
+ }
+ }, [withSession]);
+
+ const fetchRetrievalTree = useCallback(async () => {
+ setRetrievalLoading((current) => (current === "idle" ? "tree" : current));
+ try {
+ const data = await webRequest<SkillRetrievalTreeResponse>(
+ "skills.retrieval.tree",
+ withSession()
+ );
+ const nodes = Array.isArray(data.nodes) ? data.nodes : [];
+ setRetrievalTree(data.result || "");
+ setRetrievalTreeNodes(nodes);
+ setRetrievalTreeCounts({
+ branches: typeof data.branch_count === "number"
+ ? data.branch_count
+ : nodes.filter((node) => node.type !== "leaf").length,
+ skills: typeof data.leaf_count === "number"
+ ? data.leaf_count
+ : nodes.filter((node) => node.type === "leaf").length,
+ });
+ setSelectedTreeNodeCid((current) => {
+ if (current && nodes.some((node) => node.cid === current)) {
+ return current;
+ }
+ return nodes[0]?.cid || null;
+ });
+ } catch (error) {
+ console.error('Failed to load skill retrieval tree:', error);
+ setRetrievalTree(error instanceof Error ? error.message : String(error));
+ setRetrievalTreeNodes([]);
+ setRetrievalTreeCounts({ branches: 0, skills: 0 });
+ setSelectedTreeNodeCid(null);
+ } finally {
+ setRetrievalLoading((current) => (current === "tree" ? "idle" : current));
+ }
+ }, [withSession]);
+
useEffect(() => {
fetchSkills();
}, [fetchSkills]);
+ useEffect(() => {
+ fetchRetrievalStatus();
+ }, [fetchRetrievalStatus]);
+
+ useEffect(() => {
+ if (activeTab !== "index") return;
+ void fetchRetrievalStatus();
+ void fetchRetrievalTree();
+ }, [activeTab, fetchRetrievalStatus, fetchRetrievalTree]);
+
+ const handleBuildRetrievalIndex = useCallback(async () => {
+ setRetrievalLoading("build");
+ setRetrievalResult("");
+ try {
+ const data = await webRequest<{ success: boolean; result?: string }>(
+ "skills.retrieval.index_build",
+ withSession(),
+ { timeoutMs: 10 * 60_000 }
+ );
+ setRetrievalResult(data.result || "");
+ await fetchRetrievalStatus();
+ await fetchRetrievalTree();
+ } catch (error) {
+ console.error(error);
+ setRetrievalResult(error instanceof Error ? error.message : String(error));
+ } finally {
+ setRetrievalLoading("idle");
+ }
+ }, [fetchRetrievalStatus, fetchRetrievalTree, withSession]);
+
+ const handleSkillRetrieve = useCallback(async () => {
+ const query = retrievalQuery.trim();
+ if (!query) return;
+ setRetrievalLoading("search");
+ setRetrievalResult("");
+ try {
+ const data = await webRequest<{ success: boolean; result?: string }>(
+ "skills.retrieval.search",
+ withSession({ query }),
+ { timeoutMs: 120_000 }
+ );
+ setRetrievalResult(data.result || "");
+ await fetchRetrievalStatus();
+ } catch (error) {
+ console.error(error);
+ setRetrievalResult(error instanceof Error ? error.message : String(error));
+ } finally {
+ setRetrievalLoading("idle");
+ }
+ }, [fetchRetrievalStatus, retrievalQuery, withSession]);
+
const handleOpenSkill = useCallback(
(skillName: string) => {
fetchSkillDetail(skillName);
@@ -728,6 +1021,23 @@ export function SkillPanel({ sessionId, onNavigateToConfig }: SkillPanelProps) {
};
const cleanMessage = message?.replace("√", "") || "";
+ const retrievalTreeRoots = useMemo(
+ () => buildSkillIndexTree(retrievalTreeNodes),
+ [retrievalTreeNodes]
+ );
+ const selectedTreeNode = useMemo(
+ () => findSkillIndexNode(retrievalTreeNodes, selectedTreeNodeCid),
+ [retrievalTreeNodes, selectedTreeNodeCid]
+ );
+ const retrievalStatusText = retrievalStatus
+ ? retrievalStatus.enabled === false
+ ? t('skills.retrieval.disabled')
+ : retrievalStatus.index_exists
+ ? retrievalStatus.fresh
+ ? t('skills.retrieval.ready')
+ : t('skills.retrieval.stale')
+ : t('skills.retrieval.missing')
+ : t('common.loading');
return (
<>
{message && messageType === "success" && (
@@ -772,7 +1082,10 @@ export function SkillPanel({ sessionId, onNavigateToConfig }: SkillPanelProps) {
</button>
<button
onClick={() => {
- if (activeTab === "my" || (activeTab === "marketplace" && marketplaceSubTab === "builtin")) {
+ if (activeTab === "index") {
+ void fetchRetrievalStatus();
+ void fetchRetrievalTree();
+ } else if (activeTab === "my" || (activeTab === "marketplace" && marketplaceSubTab === "builtin")) {
setSearch("");
fetchSkills(true);
} else {
@@ -826,37 +1139,257 @@ export function SkillPanel({ sessionId, onNavigateToConfig }: SkillPanelProps) {
>
{t('skills.tabs.marketplace')}
</button>
- </div>
- <div className="flex items-center gap-1 border border-border rounded-lg p-1">
- <button
- onClick={() => setViewMode("list")}
- className={`p-1.5 rounded-md transition-colors ${
- viewMode === "list"
- ? "bg-secondary text-text"
- : "text-text-muted hover:text-text"
- }`}
- title={t('skills.viewMode.list')}
- >
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>
- <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
- </svg>
- </button>
<button
- onClick={() => setViewMode("grid")}
- className={`p-1.5 rounded-md transition-colors ${
- viewMode === "grid"
- ? "bg-secondary text-text"
+ onClick={() => setActiveTab("index")}
+ className={`px-4 text-sm font-medium transition-colors ${
+ activeTab === "index"
+ ? "rounded-[8px] bg-secondary h-8 text-text"
: "text-text-muted hover:text-text"
}`}
- title={t('skills.viewMode.grid')}
>
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>
- <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z" />
- </svg>
+ {t('skills.tabs.skillIndex')}
</button>
</div>
+ {activeTab !== "index" ? (
+ <div className="flex items-center gap-1 border border-border rounded-lg p-1">
+ <button
+ onClick={() => setViewMode("list")}
+ className={`p-1.5 rounded-md transition-colors ${
+ viewMode === "list"
+ ? "bg-secondary text-text"
+ : "text-text-muted hover:text-text"
+ }`}
+ title={t('skills.viewMode.list')}
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
+ </svg>
+ </button>
+ <button
+ onClick={() => setViewMode("grid")}
+ className={`p-1.5 rounded-md transition-colors ${
+ viewMode === "grid"
+ ? "bg-secondary text-text"
+ : "text-text-muted hover:text-text"
+ }`}
+ title={t('skills.viewMode.grid')}
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z" />
+ </svg>
+ </button>
+ </div>
+ ) : null}
</div>
+ {activeTab === "index" ? (
+ <div className="mt-4 flex flex-col flex-1 min-h-0 gap-4">
+ <div className="rounded-lg border border-border bg-panel p-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="min-w-[220px]">
+ <div className="text-sm font-medium text-text-strong">
+ {t('skills.retrieval.title')}
+ </div>
+ <div className="text-xs text-text-muted mt-1">
+ {retrievalStatusText}
+ {retrievalStatus?.indexed_count != null
+ ? ` · ${t('skills.retrieval.indexedCount', { count: retrievalStatus.indexed_count })}`
+ : ""}
+ {retrievalStatus?.installed_enabled_count != null
+ ? ` · ${t('skills.retrieval.enabledCount', { count: retrievalStatus.installed_enabled_count })}`
+ : ""}
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={handleBuildRetrievalIndex}
+ className="px-3 py-1.5 rounded-lg text-sm border border-border hover:bg-secondary transition-colors disabled:opacity-60"
+ disabled={retrievalLoading === "build" || retrievalStatus?.enabled === false}
+ >
+ {retrievalLoading === "build"
+ ? t('skills.retrieval.building')
+ : t('skills.retrieval.build')}
+ </button>
+ <button
+ onClick={() => {
+ void fetchRetrievalStatus();
+ void fetchRetrievalTree();
+ }}
+ className="px-3 py-1.5 rounded-lg text-sm border border-border hover:bg-secondary transition-colors disabled:opacity-60"
+ disabled={retrievalLoading === "tree" || retrievalLoading === "status"}
+ >
+ {retrievalLoading === "tree" || retrievalLoading === "status"
+ ? t('common.refreshing')
+ : t('common.refresh')}
+ </button>
+ </div>
+ </div>
+ <div className="mt-4 flex items-center gap-2">
+ <input
+ type="text"
+ value={retrievalQuery}
+ onChange={(event) => setRetrievalQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ handleSkillRetrieve();
+ }
+ }}
+ placeholder={t('skills.retrieval.queryPlaceholder')}
+ className="w-full px-3 py-1.5 rounded-lg text-sm bg-secondary border border-border text-text placeholder:text-text-muted"
+ />
+ <button
+ onClick={handleSkillRetrieve}
+ className="px-3 py-1.5 rounded-lg text-sm border border-border hover:bg-secondary transition-colors disabled:opacity-60"
+ disabled={retrievalLoading === "search" || !retrievalQuery.trim() || retrievalStatus?.enabled === false}
+ >
+ {retrievalLoading === "search"
+ ? t('skills.retrieval.searching')
+ : t('skills.retrieval.search')}
+ </button>
+ </div>
+ {retrievalResult && (
+ <pre className="mt-3 max-h-64 overflow-auto whitespace-pre-wrap rounded-md bg-secondary p-3 text-xs text-text">
+ {retrievalResult}
+ </pre>
+ )}
+ </div>
+ <div className="grid flex-1 min-h-0 grid-cols-1 gap-4 lg:grid-cols-[minmax(320px,1fr)_minmax(320px,0.9fr)]">
+ <div className="rounded-lg border border-border bg-panel p-4 min-h-0 flex flex-col">
+ <div className="mb-3 flex items-center justify-between gap-2">
+ <div>
+ <div className="text-sm font-medium text-text-strong">
+ {t('skills.retrieval.treeTitle')}
+ </div>
+ <div className="text-xs text-text-muted mt-1">
+ {retrievalTreeNodes.length > 0
+ ? t('skills.retrieval.treeCount', {
+ branches: retrievalTreeCounts.branches,
+ skills: retrievalTreeCounts.skills,
+ })
+ : retrievalLoading === "tree"
+ ? t('common.loading')
+ : t('skills.retrieval.noTree')}
+ </div>
+ </div>
+ </div>
+ <div className="flex-1 min-h-[320px] overflow-auto rounded-md border border-border bg-secondary/40 p-2">
+ {retrievalTreeNodes.length > 0 ? (
+ <SkillIndexTreeView
+ roots={retrievalTreeRoots}
+ selectedCid={selectedTreeNodeCid}
+ onSelect={setSelectedTreeNodeCid}
+ emptyText={t('skills.retrieval.noTree')}
+ branchLabel={t('skills.retrieval.nodeTypes.branch')}
+ skillLabel={t('skills.retrieval.nodeTypes.skill')}
+ />
+ ) : (
+ <div className="whitespace-pre-wrap text-xs text-text-muted">
+ {retrievalTree || (retrievalLoading === "tree" ? t('common.loading') : t('skills.retrieval.noTree'))}
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="rounded-lg border border-border bg-panel p-4 min-h-0 flex flex-col">
+ <div className="text-sm font-medium text-text-strong mb-3">
+ {t('skills.retrieval.nodeDetails')}
+ </div>
+ {selectedTreeNode ? (
+ <div className="flex-1 min-h-0 overflow-auto">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="text-base font-semibold text-text-strong break-words">
+ {getSkillIndexNodeLabel(selectedTreeNode)}
+ </div>
+ <div className="mt-1 text-xs text-text-muted break-all">
+ {selectedTreeNode.cid}
+ </div>
+ </div>
+ <span
+ className={`shrink-0 rounded border px-2 py-1 text-xs ${
+ selectedTreeNode.type === "leaf"
+ ? "border-emerald-500/25 bg-emerald-500/10 text-emerald-600"
+ : "border-sky-500/25 bg-sky-500/10 text-sky-600"
+ }`}
+ >
+ {selectedTreeNode.type === "leaf"
+ ? t('skills.retrieval.nodeTypes.skill')
+ : t('skills.retrieval.nodeTypes.branch')}
+ </span>
+ </div>
+
+ <dl className="mt-4 space-y-3 text-sm">
+ <div>
+ <dt className="text-xs text-text-muted">{t('skills.retrieval.nodeDescription')}</dt>
+ <dd className="mt-1 whitespace-pre-wrap text-text">
+ {selectedTreeNode.description || t('skills.noDescription')}
+ </dd>
+ </div>
+ {selectedTreeNode.select_when ? (
+ <div>
+ <dt className="text-xs text-text-muted">{t('skills.retrieval.nodeSelectWhen')}</dt>
+ <dd className="mt-1 whitespace-pre-wrap text-text">{selectedTreeNode.select_when}</dd>
+ </div>
+ ) : null}
+ {selectedTreeNode.dont_select_when ? (
+ <div>
+ <dt className="text-xs text-text-muted">{t('skills.retrieval.nodeDontSelectWhen')}</dt>
+ <dd className="mt-1 whitespace-pre-wrap text-text">{selectedTreeNode.dont_select_when}</dd>
+ </div>
+ ) : null}
+ {selectedTreeNode.source_description ? (
+ <div>
+ <dt className="text-xs text-text-muted">{t('skills.retrieval.nodeSourceDescription')}</dt>
+ <dd className="mt-1 whitespace-pre-wrap text-text">{selectedTreeNode.source_description}</dd>
+ </div>
+ ) : null}
+ {selectedTreeNode.worker_id ? (
+ <div>
+ <dt className="text-xs text-text-muted">{t('skills.retrieval.nodeWorkerId')}</dt>
+ <dd className="mt-1 break-all font-mono text-xs text-text">{selectedTreeNode.worker_id}</dd>
+ </div>
+ ) : null}
+ {selectedTreeNode.category ? (
+ <div>
+ <dt className="text-xs text-text-muted">{t('skills.retrieval.nodeCategory')}</dt>
+ <dd className="mt-1 whitespace-pre-wrap text-text">{selectedTreeNode.category}</dd>
+ </div>
+ ) : null}
+ {selectedTreeNode.keywords?.length ? (
+ <div>
+ <dt className="text-xs text-text-muted">{t('skills.retrieval.nodeKeywords')}</dt>
+ <dd className="mt-2 flex flex-wrap gap-1.5">
+ {selectedTreeNode.keywords.slice(0, 24).map((keyword) => (
+ <span key={keyword} className="rounded border border-border bg-secondary px-2 py-0.5 text-xs text-text-muted">
+ {keyword}
+ </span>
+ ))}
+ </dd>
+ </div>
+ ) : null}
+ {selectedTreeNode.examples?.length ? (
+ <div>
+ <dt className="text-xs text-text-muted">{t('skills.retrieval.nodeExamples')}</dt>
+ <dd className="mt-1 space-y-1">
+ {selectedTreeNode.examples.slice(0, 5).map((example) => (
+ <div key={example} className="whitespace-pre-wrap rounded border border-border bg-secondary px-2 py-1 text-xs text-text">
+ {example}
+ </div>
+ ))}
+ </dd>
+ </div>
+ ) : null}
+ </dl>
+ </div>
+ ) : (
+ <div className="flex-1 min-h-[220px] rounded-md border border-dashed border-border bg-secondary/30 p-4 text-sm text-text-muted">
+ {t('skills.retrieval.selectNodeHint')}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ ) : null}
+
{activeTab === "marketplace" ? (
<>
<div className="mt-4 flex items-center justify-between gap-4">
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 101cd00d64..fa7251646b 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -670,6 +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",
"agentSkillsPlaceholder": "Click to select skills",
"agentSkillsEmpty": "No installed skills",
"agentName": "Name",
@@ -688,10 +689,24 @@
"teamMemberRoleType": "Role Type",
"teamMemberPersona": "Persona",
"teamMemberPromptHint": "Prompt Hint",
- "teamMemberAgentKey": "Agent Key"
+ "teamMemberAgentKey": "Agent Key",
+ "skillRetrievalEnabled": "Enable skill retrieval",
+ "skillRetrievalBuildBranchingFactor": "Tree branching factor",
+ "skillRetrievalBuildMaxDepth": "Max tree depth",
+ "skillRetrievalBuildRootCategories": "Root taxonomy config",
+ "skillRetrievalBuildMaxWorkers": "Build workers",
+ "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)"
},
"keyHelp": {
- "skillCreate": "Install `skill-creator` and `teamskill-creator` before enabling"
+ "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."
},
"hideValue": "Hide value",
"showValue": "Show value",
@@ -779,6 +794,7 @@
"contextEngine": { "label": "Context Compression", "hint": "Enable or disable dialogue context compression" },
"permissions": { "label": "Tool Safety Guardrail", "hint": "Enable or disable permission checks for tool calls" },
"a2ui": { "label": "A2UI", "hint": "Enable or disable generated UI rendering and A2UI runtime prompts." },
+ "skillRetrieval": { "label": "Agentic Skill Retrieval", "hint": "Agentic skill retrieval for larger sets of installed skills" },
"memory": { "label": "Memory Sensitive Info Filter", "hint": "Configure sensitive content types forbidden from memory" },
"email": { "label": "Email Settings", "hint": "Email account and token settings" },
"other": { "label": "Other Settings", "hint": "Unclassified extended parameters" }
@@ -789,7 +805,9 @@
"freeSearchDdg": "Enable DuckDuckGo (including DDG via Jina)",
"freeSearchBing": "Enable Bing",
"enabled": "Enable",
- "kvCacheAffinity": "Compute affinity (KV cache release)"
+ "kvCacheAffinity": "Compute affinity (KV cache release)",
+ "skillRetrievalCompact": "Enable compact code",
+ "skillRetrievalFlat": "Enable flat tree"
},
"permissionsTools": {
"title": "Tool Guardrail (permissions.tools)",
@@ -957,7 +975,8 @@
"subtitle": "Manage and install skills available to the agent.",
"tabs": {
"mySkills": "My Skills",
- "marketplace": "Marketplace"
+ "marketplace": "Marketplace",
+ "skillIndex": "Skill Index"
},
"mySkillsTabs": {
"all": "All",
@@ -1022,6 +1041,37 @@
},
"detailLoading": "Loading details...",
"detailError": "Failed to load details",
+ "retrieval": {
+ "title": "Local Skill Retrieval",
+ "disabled": "Retrieval disabled",
+ "ready": "Index ready",
+ "stale": "Index needs update",
+ "missing": "Index not built",
+ "indexedCount": "{{count}} indexed",
+ "enabledCount": "{{count}} enabled",
+ "build": "Build Index",
+ "building": "Building...",
+ "search": "Retrieve",
+ "searching": "Retrieving...",
+ "queryPlaceholder": "Enter a task to retrieve installed skills",
+ "treeTitle": "Index Tree",
+ "treeCount": "{{branches}} branches · {{skills}} skills",
+ "noTree": "No index tree",
+ "nodeDetails": "Node Details",
+ "selectNodeHint": "Select a node in the tree to view its description.",
+ "nodeDescription": "Description",
+ "nodeSelectWhen": "Select When",
+ "nodeDontSelectWhen": "Do Not Select When",
+ "nodeSourceDescription": "Source Description",
+ "nodeWorkerId": "Skill ID",
+ "nodeCategory": "Category",
+ "nodeKeywords": "Keywords",
+ "nodeExamples": "Examples",
+ "nodeTypes": {
+ "branch": "Branch",
+ "skill": "Skill"
+ }
+ },
"evolution": {
"closeAria": "Close skill experience dialog",
"title": "Skill Experience: {{name}}",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index d2ce5da554..42ee21eb69 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -669,6 +669,7 @@
"memoryForbiddenEnabled": "启用",
"memoryForbiddenDescription": "禁止记忆内容描述",
"memoryForbiddenDescriptionPlaceholder": "例如:密码、API密钥、Secret、Token、信用卡号、身份证号、手机号等敏感信息",
+ "skillRetrievalBuildRootCategoriesPlaceholder": "留空使用内置默认分层,或填写 JSON/YAML 文件路径",
"agentSkillsPlaceholder": "点击选择技能",
"agentSkillsEmpty": "暂无已安装技能",
"agentName": "名称",
@@ -687,10 +688,24 @@
"teamMemberRoleType": "角色类型",
"teamMemberPersona": "人设",
"teamMemberPromptHint": "提示词",
- "teamMemberAgentKey": "Agent Key"
+ "teamMemberAgentKey": "Agent Key",
+ "skillRetrievalEnabled": "启用技能检索",
+ "skillRetrievalBuildBranchingFactor": "树分支数",
+ "skillRetrievalBuildMaxDepth": "最大树深",
+ "skillRetrievalBuildRootCategories": "树根分层配置",
+ "skillRetrievalBuildMaxWorkers": "构建并发数",
+ "skillRetrievalBuildTimeout": "构建请求超时(秒)",
+ "skillRetrievalTopK": "检索返回数量",
+ "skillRetrievalCompactCodes": "Compact 检索",
+ "skillRetrievalFlattenTree": "扁平树检索",
+ "skillRetrievalMaxExposureDepth": "最大暴露深度",
+ "skillRetrievalMaxBranchChoices": "每层分支选择数",
+ "skillRetrievalMaxParallelBranches": "并行分支数",
+ "skillRetrievalRetrieveTimeout": "检索请求超时(秒)"
},
"keyHelp": {
- "skillCreate": "建议先安装 `skill-creator` 和 `teamskill-creator`,再开启"
+ "skillCreate": "建议先安装 `skill-creator` 和 `teamskill-creator`,再开启",
+ "skillRetrievalBuildRootCategories": "可选。留空使用内置默认树分层;填写时应为包含 tree_root_categories 或 root_categories 的 JSON/YAML 文件路径。"
},
"hideValue": "隐藏明文",
"showValue": "显示明文",
@@ -778,6 +793,7 @@
"contextEngine": { "label": "上下文压缩", "hint": "控制对话上下文是否启用压缩" },
"permissions": { "label": "工具安全护栏", "hint": "控制工具调用时的权限检查" },
"a2ui": { "label": "A2UI", "hint": "开启或关闭生成式界面渲染与 A2UI 运行时提示词" },
+ "skillRetrieval": { "label": "Agentic技能检索", "hint": "适用于较大规模已安装技能场景下的 Agentic 技能检索" },
"memory": { "label": "记忆系统敏感信息过滤", "hint": "配置禁止写入记忆的敏感信息类型" },
"email": { "label": "邮箱配置", "hint": "邮件账号与令牌参数" },
"other": { "label": "其他配置", "hint": "未归类的扩展参数" }
@@ -788,7 +804,9 @@
"freeSearchDdg": "启用 DuckDuckGo(含 DDG via Jina)",
"freeSearchBing": "启用 Bing",
"enabled": "启用",
- "kvCacheAffinity": "算力亲和(KV 释放)"
+ "kvCacheAffinity": "算力亲和(KV 释放)",
+ "skillRetrievalCompact": "启用 compact code",
+ "skillRetrievalFlat": "启用 flat tree"
},
"permissionsTools": {
"title": "工具防护(permissions.tools)",
@@ -956,7 +974,8 @@
"subtitle": "管理并安装智能体可用的技能。",
"tabs": {
"mySkills": "我的技能",
- "marketplace": "技能广场"
+ "marketplace": "技能广场",
+ "skillIndex": "技能索引"
},
"mySkillsTabs": {
"all": "全部",
@@ -1021,6 +1040,37 @@
},
"detailLoading": "加载详情中...",
"detailError": "加载详情失败",
+ "retrieval": {
+ "title": "本地技能检索",
+ "disabled": "检索已关闭",
+ "ready": "索引就绪",
+ "stale": "索引需要更新",
+ "missing": "索引未构建",
+ "indexedCount": "已索引 {{count}} 个",
+ "enabledCount": "启用 {{count}} 个",
+ "build": "构建索引",
+ "building": "构建中...",
+ "search": "检索",
+ "searching": "检索中...",
+ "queryPlaceholder": "输入任务需求,检索已安装技能",
+ "treeTitle": "索引树",
+ "treeCount": "{{branches}} 个分支 · {{skills}} 个技能",
+ "noTree": "暂无索引树",
+ "nodeDetails": "节点详情",
+ "selectNodeHint": "请选择左侧树节点查看描述。",
+ "nodeDescription": "描述",
+ "nodeSelectWhen": "选择条件",
+ "nodeDontSelectWhen": "排除条件",
+ "nodeSourceDescription": "来源描述",
+ "nodeWorkerId": "Skill ID",
+ "nodeCategory": "分类",
+ "nodeKeywords": "关键词",
+ "nodeExamples": "示例",
+ "nodeTypes": {
+ "branch": "分支",
+ "skill": "技能"
+ }
+ },
"evolution": {
"closeAria": "关闭技能经验弹窗",
"title": "技能经验:{{name}}",
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index 8f8b970839..2c2594ac17 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -257,6 +257,30 @@ def update_kv_cache_affinity_enabled_in_config(value: bool) -> None:
dump_yaml_round_trip(CONFIG_YAML_PATH, data)
+def update_skill_retrieval_in_config(updates: dict[str, Any]) -> None:
+ """更新 symphony.skill_retrieval 配置段并写回。"""
+ 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"] = {}
+
+ def merge_dict(target: dict[str, Any], patch: dict[str, Any]) -> None:
+ for key, value in patch.items():
+ if isinstance(value, dict):
+ child = target.get(key)
+ if not isinstance(child, dict):
+ child = {}
+ target[key] = child
+ merge_dict(child, value)
+ else:
+ target[key] = value
+
+ merge_dict(symphony["skill_retrieval"], updates)
+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)
+
+
def update_permissions_enabled_in_config(value: bool) -> None:
"""更新 permissions.enabled(工具安全护栏开关)并写回。"""
data = load_yaml_round_trip(CONFIG_YAML_PATH)
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index 81b2b538e8..d4147b4d72 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -98,6 +98,10 @@ class ReqMethod(Enum):
SKILLS_TEAMSKILLS_HUB_INSTALL = "skills.teamskillshub.install"
SKILLS_TEAMSKILLS_HUB_PUBLISH = "skills.teamskillshub.publish"
SKILLS_TEAMSKILLS_HUB_DELETE = "skills.teamskillshub.delete"
+ SKILLS_RETRIEVAL_STATUS = "skills.retrieval.status"
+ SKILLS_RETRIEVAL_INDEX_BUILD = "skills.retrieval.index_build"
+ SKILLS_RETRIEVAL_SEARCH = "skills.retrieval.search"
+ SKILLS_RETRIEVAL_TREE = "skills.retrieval.tree"
SKILLS_EVOLUTION_STATUS = "skills.evolution.status"
SKILLS_EVOLUTION_GET = "skills.evolution.get"
SKILLS_EVOLUTION_SAVE = "skills.evolution.save"
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 6b174008b2..da45acaa06 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_permissions_enabled_in_config,
update_memory_forbidden_enabled_in_config,
update_memory_forbidden_description_in_config,
@@ -250,6 +251,10 @@ _FORWARD_REQ_METHODS = frozenset({
"skills.teamskillshub.install",
"skills.teamskillshub.publish",
"skills.teamskillshub.delete",
+ "skills.retrieval.status",
+ "skills.retrieval.index_build",
+ "skills.retrieval.search",
+ "skills.retrieval.tree",
"skills.evolution.status",
"skills.evolution.get",
"skills.evolution.save",
@@ -322,6 +327,10 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
"skills.teamskillshub.install",
"skills.teamskillshub.publish",
"skills.teamskillshub.delete",
+ "skills.retrieval.status",
+ "skills.retrieval.index_build",
+ "skills.retrieval.search",
+ "skills.retrieval.tree",
"skills.evolution.status",
"skills.evolution.get",
"skills.evolution.save",
@@ -418,6 +427,82 @@ _CONFIG_YAML_KEYS = frozenset({
"a2ui_enabled",
})
+_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"), "str", ""),
+ "skill_retrieval_build_max_workers": (("build", "max_workers"), "int", 2),
+ "skill_retrieval_build_request_timeout_seconds": (("build", "request_timeout_seconds"), "float", 420.0),
+ "skill_retrieval_retrieve_top_k": (("retrieve", "top_k"), "int", 10),
+ "skill_retrieval_compact_codes_enabled": (("retrieve", "compact_codes_enabled"), "bool", False),
+ "skill_retrieval_flatten_tree": (("retrieve", "flatten_tree"), "bool", False),
+ "skill_retrieval_retrieve_max_exposure_depth": (("retrieve", "max_exposure_depth"), "int", 99),
+ "skill_retrieval_retrieve_max_branch_choices": (("retrieve", "max_branch_choices"), "int", 2),
+ "skill_retrieval_retrieve_max_parallel_branches": (("retrieve", "max_parallel_branches"), "int", 2),
+ "skill_retrieval_retrieve_request_timeout_seconds": (("retrieve", "request_timeout_seconds"), "float", 120.0),
+}
+_SKILL_RETRIEVAL_CONFIG_KEYS = frozenset(_SKILL_RETRIEVAL_CONFIG_SPECS.keys())
+
+
+def _coerce_config_panel_value(value: Any, value_type: str, default: Any) -> Any:
+ if value_type == "bool":
+ return str(value).strip().lower() in ("true", "1", "yes", "on", "enabled")
+ if value_type == "int":
+ try:
+ return max(1, int(value))
+ except (TypeError, ValueError):
+ return default
+ if value_type == "float":
+ try:
+ return max(0.0, float(value))
+ except (TypeError, ValueError):
+ return default
+ return str(value if value is not None else default)
+
+
+def _set_nested_config_value(target: dict[str, Any], path: tuple[str, ...], value: Any) -> None:
+ current = target
+ for segment in path[:-1]:
+ child = current.get(segment)
+ if not isinstance(child, dict):
+ child = {}
+ current[segment] = child
+ current = child
+ current[path[-1]] = value
+
+
+def _get_nested_config_value(source: dict[str, Any], path: tuple[str, ...], default: Any) -> Any:
+ current: Any = source
+ for segment in path:
+ if not isinstance(current, dict) or segment not in current:
+ return default
+ current = current.get(segment)
+ return default if current is None else current
+
+
+def _flatten_skill_retrieval_for_config_panel(raw: dict[str, Any]) -> dict[str, str]:
+ 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"
+ else:
+ flat[key] = str(value)
+ return flat
+
+
+def _build_skill_retrieval_config_update(params: dict[str, Any]) -> dict[str, Any]:
+ 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]:
"""Return the legacy flat fields consumed by the web config panel."""
@@ -678,6 +763,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
memory_desc = memory_cfg.get("description") or {}
payload["memory_forbidden_description"] = memory_desc
payload.update(get_a2ui_config_payload(raw))
+ payload.update(_flatten_skill_retrieval_for_config_panel(raw))
if not payload.get("free_search_ddg_enabled"):
payload["free_search_ddg_enabled"] = "false"
if not payload.get("free_search_bing_enabled"):
@@ -693,6 +779,12 @@ 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 _SKILL_RETRIEVAL_CONFIG_SPECS.items():
+ if value_type == "bool":
+ default_text = "true" if default else "false"
+ else:
+ default_text = str(default)
+ payload.setdefault(key, default_text)
payload.setdefault("free_search_ddg_enabled", "false")
payload.setdefault("free_search_bing_enabled", "false")
await channel.send_response(ws, req_id, ok=True, payload=payload)
@@ -800,6 +892,14 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
except Exception as e: # noqa: BLE001
logger.warning("[config.set] 写回 config.yaml 失败 %s: %s", param_key, e)
+ skill_retrieval_updates = _build_skill_retrieval_config_update(params)
+ 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/agent/workspace/agent-data.json b/jiuwenswarm/resources/agent/workspace/agent-data.json
index 35a782fe9d..ab4ce3918a 100644
--- a/jiuwenswarm/resources/agent/workspace/agent-data.json
+++ b/jiuwenswarm/resources/agent/workspace/agent-data.json
@@ -600,6 +600,13 @@
"isMarkdown": false
}
],
+ "workspace/skills/skill-retrieval": [
+ {
+ "name": "SKILL.md",
+ "path": "agent/workspace/skills/skill-retrieval/SKILL.md",
+ "isMarkdown": true
+ }
+ ],
"workspace/skills/skvm-general": [
{
"name": "SKILL.md",
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 067c4daa4a..e9da558f58 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -178,6 +178,33 @@ models:
model_config_obj:
temperature: 0.95
+symphony:
+ skill_retrieval:
+ enabled: false
+ artifact_root: ${SYMPHONY_SKILL_RETRIEVAL_ROOT:-}
+ build:
+ branching_factor: 128
+ max_depth: 6
+ root_categories: ""
+ max_workers: 2
+ max_retries: 2
+ request_timeout_seconds: 420
+ classification_batch_limit: 32
+ discovery_seed: 42
+ postprocess_enabled: true
+ postprocess_max_passes: 1
+ 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
+
# 外接 ACP Agent(stdio),供工具 acp_chat 使用。按需取消注释并填写;command/args 可指向任意兼容 ACP 的包(与 VS Code formulahendry.acp-client 预置列表一致)。
acp_agents:
codex:
@@ -879,6 +906,7 @@ modes:
- web_paid_search
- user_todos
- skill_toolkit
+ - skill_retrieval
embedding_config:
model_name: null
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index cddc8b58b8..addaee78b2 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -125,6 +125,10 @@ _SKILL_ROUTES: dict[ReqMethod, str] = {
ReqMethod.SKILLS_TEAMSKILLS_HUB_INSTALL: "handle_skills_team_skills_hub_install",
ReqMethod.SKILLS_TEAMSKILLS_HUB_PUBLISH: "handle_skills_team_skills_hub_publish",
ReqMethod.SKILLS_TEAMSKILLS_HUB_DELETE: "handle_skills_team_skills_hub_delete",
+ ReqMethod.SKILLS_RETRIEVAL_STATUS: "handle_skills_retrieval_status",
+ ReqMethod.SKILLS_RETRIEVAL_INDEX_BUILD: "handle_skills_retrieval_index_build",
+ ReqMethod.SKILLS_RETRIEVAL_SEARCH: "handle_skills_retrieval_search",
+ ReqMethod.SKILLS_RETRIEVAL_TREE: "handle_skills_retrieval_tree",
ReqMethod.SKILLS_EVOLUTION_STATUS: "handle_skills_evolution_status",
ReqMethod.SKILLS_EVOLUTION_GET: "handle_skills_evolution_get",
ReqMethod.SKILLS_EVOLUTION_SAVE: "handle_skills_evolution_save",
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index c660a538b3..747a44488c 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -62,7 +62,11 @@ from jiuwenswarm.agents.harness.common.rails import (
StructuredAskUserRail,
)
from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode
-from jiuwenswarm.agents.harness.common.tools import SkillToolkit
+from jiuwenswarm.agents.harness.common.tools import (
+ SkillRetrievalToolkit,
+ SkillToolkit,
+ is_skill_retrieval_enabled,
+)
from jiuwenswarm.agents.harness.common.tools.acp_chat import acp_chat
from jiuwenswarm.common.config import get_config
from jiuwenswarm.common.coding_memory_paths import resolve_project_coding_memory_dir
@@ -200,6 +204,7 @@ _TOOL_BUILD_NAMES: dict[str, str] = {
"web_paid_search": "_build_paid_search_tool",
"user_todos": "_build_user_todos_tool",
"skill_toolkit": "_build_skill_toolkit",
+ "skill_retrieval": "_build_skill_retrieval_toolkit",
"acp_chat": "_build_acp_chat_tool",
}
@@ -1248,6 +1253,22 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
logger.warning("[JiuwenSwarmCodeAdapter] skill_toolkit build failed: %s", exc)
return None
+ def _build_skill_retrieval_toolkit(self, agent_id: str) -> list[Any] | None:
+ """构建 SkillRetrievalToolkit 工具(不注册到 Runner,由 _get_tool_cards 统一注册)."""
+ if not is_skill_retrieval_enabled():
+ logger.info("[JiuwenClawCodeAdapter] SkillRetrievalToolkit skipped: disabled")
+ return None
+ try:
+ skill_retrieval_toolkit = SkillRetrievalToolkit(manager=self._skill_manager)
+ logger.info(
+ "[JiuwenClawCodeAdapter] SkillRetrievalToolkit built: tools=%s",
+ [t.card.name for t in skill_retrieval_toolkit.get_tools()],
+ )
+ return skill_retrieval_toolkit.get_tools()
+ except Exception as exc:
+ logger.warning("[JiuwenClawCodeAdapter] skill_retrieval build failed: %s", exc)
+ return None
+
def _build_acp_chat_tool(self, agent_id: str) -> Any | None:
"""Register acp_chat when at least one external ACP profile is configured."""
acp_cfg = get_config().get("acp_agents")
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index bc1bc933c1..cf45102d51 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -186,7 +186,12 @@ from jiuwenswarm.agents.harness.common.tools.multimodal_config import (
from jiuwenswarm.agents.harness.common.tools.video_tools import video_understanding
from jiuwenswarm.agents.harness.common.tools.image_tools import generate_image
-from jiuwenswarm.agents.harness.common.tools import SendFileToolkit, SkillToolkit
+from jiuwenswarm.agents.harness.common.tools import (
+ SendFileToolkit,
+ SkillRetrievalToolkit,
+ SkillToolkit,
+ is_skill_retrieval_enabled,
+)
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
@@ -2824,6 +2829,24 @@ class JiuWenSwarmDeepAdapter:
except Exception as exc:
logger.warning("[JiuWenSwarmDeepAdapter] skill tools registration failed: %s", exc)
+ if is_skill_retrieval_enabled():
+ try:
+ skill_retrieval_toolkit = SkillRetrievalToolkit(manager=self._skill_manager)
+ skill_retrieval_tool_names: list[str] = []
+ for tool in skill_retrieval_toolkit.get_tools():
+ if not Runner.resource_mgr.get_tool(tool.card.id):
+ Runner.resource_mgr.add_tool(tool)
+ tool_cards.append(tool.card)
+ skill_retrieval_tool_names.append(tool.card.name)
+ logger.info(
+ "[JiuWenClawDeepAdapter] SkillRetrievalToolkit registered: tools=%s",
+ skill_retrieval_tool_names,
+ )
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] skill retrieval tools registration failed: %s", exc)
+ else:
+ logger.info("[JiuWenClawDeepAdapter] SkillRetrievalToolkit skipped: disabled")
+
# acp_chat: forward prompts to external stdio ACP agents (see acp_agents in config.yaml)
try:
acp_cfg = get_config().get("acp_agents")
diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.py
index d81a4d0fb2..3bea953166 100644
--- a/jiuwenswarm/server/runtime/skill/skill_manager.py
+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py
@@ -527,6 +527,31 @@ class SkillManager:
"detail": "配置已更新;下次 reload / rebuild / 新会话后执行面生效。",
}
+ async def handle_skills_retrieval_status(self, params: dict) -> dict:
+ """返回本地 skill retrieval 索引状态."""
+ from jiuwenswarm.symphony.skill_retrieval import get_skill_retrieval_status
+
+ return await asyncio.to_thread(get_skill_retrieval_status, self)
+
+ async def handle_skills_retrieval_index_build(self, params: dict) -> dict:
+ """构建或复用本地 skill retrieval 索引."""
+ from jiuwenswarm.symphony.skill_retrieval import build_skill_index
+
+ return await asyncio.to_thread(build_skill_index, self)
+
+ async def handle_skills_retrieval_search(self, params: dict) -> dict:
+ """基于本地索引检索已安装 skills."""
+ from jiuwenswarm.symphony.skill_retrieval import retrieve_skills
+
+ query = str((params or {}).get("query") or "").strip()
+ return await asyncio.to_thread(retrieve_skills, query, self)
+
+ async def handle_skills_retrieval_tree(self, params: dict) -> dict:
+ """返回本地 skill retrieval 树索引概览."""
+ from jiuwenswarm.symphony.skill_retrieval import get_skill_retrieval_tree
+
+ return await asyncio.to_thread(get_skill_retrieval_tree, self)
+
async def handle_skills_evolution_status(self, params: dict) -> dict:
"""检查某个 skill 是否存在 evolutions.json."""
name = str(params.get("name") or "").strip()
diff --git a/jiuwenswarm/symphony/.gitignore b/jiuwenswarm/symphony/.gitignore
new file mode 100644
index 0000000000..8c0513927e
--- /dev/null
+++ b/jiuwenswarm/symphony/.gitignore
@@ -0,0 +1,232 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[codz]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py.cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+# Pipfile.lock
+
+# UV
+# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# uv.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+# poetry.lock
+# poetry.toml
+
+# pdm
+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
+# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
+# pdm.lock
+# pdm.toml
+.pdm-python
+.pdm-build/
+
+# pixi
+# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
+# pixi.lock
+# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
+# in the .venv directory. It is recommended not to include this directory in version control.
+.pixi
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# Redis
+*.rdb
+*.aof
+*.pid
+
+# RabbitMQ
+mnesia/
+rabbitmq/
+rabbitmq-data/
+
+# ActiveMQ
+activemq-data/
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.envrc
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+# .idea/
+
+# Abstra
+# Abstra is an AI-powered process automation framework.
+# Ignore directories containing user credentials, local state, and settings.
+# Learn more at https://abstra.io/docs
+.abstra/
+
+# Visual Studio Code
+# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
+# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
+# and can be added to the global gitignore or merged into this file. However, if you prefer,
+# you could uncomment the following to ignore the entire vscode folder
+# .vscode/
+
+# Ruff stuff:
+.ruff_cache/
+
+# PyPI configuration file
+.pypirc
+
+# Marimo
+marimo/_static/
+marimo/_lsp/
+__marimo__/
+
+# Streamlit
+.streamlit/secrets.toml
+
+.vscode
+
+__pycache__/
+*.pyc
+
+logs/
+*.log
+
+orchestration/output
+training/output
+.codex
+.tmp
+.clinerules
+output
+records
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/README.md b/jiuwenswarm/symphony/README.md
new file mode 100644
index 0000000000..7bbdb328c8
--- /dev/null
+++ b/jiuwenswarm/symphony/README.md
@@ -0,0 +1,81 @@
+# openjiuwen-skillsdispatch
+
+`openjiuwen-skillsdispatch` 是 openJiuwen 的技能分发能力包,用于基于 skill/plugin 目录构建 Capability Tree 索引。
+
+## 目录结构
+
+```text
+dispatch/
+├── build.py
+├── indexing/
+│ ├── catalog/
+│ ├── io/
+│ ├── scanners/
+│ ├── tree/
+│ └── workflows/
+├── shared/
+├── pyproject.toml
+└── README.md
+```
+
+## 核心能力
+
+- `indexing.scanners`:扫描 skill/plugin 目录。
+- `indexing.tree`:基于 LLM 或 fallback 逻辑构建 Capability Tree。
+- `indexing.workflows`:封装索引构建工作流,输出 tree、catalog、manifest 等产物。
+- `shared`:提供 Rich 兼容层和 S3/OBS 存储工具。
+
+## 安装
+
+本地开发验证:
+
+```bash
+cd marketplace/dispatch
+python -m pip install -e .
+```
+
+发布到 pip 源后安装:
+
+```bash
+python -m pip install openjiuwen-skillsdispatch
+```
+
+## SDK 使用
+
+```python
+from indexing.workflows.artifacts import BuildConfig, BuildMethod
+from indexing.workflows.index_builder import IndexBuilder
+
+config = BuildConfig(
+ method=BuildMethod.TREE,
+ llm_model="your-model",
+ llm_api_key="your-api-key",
+ llm_base_url="your-base-url",
+)
+
+IndexBuilder.build(
+ item_paths=["/path/to/skill-or-plugin"],
+ output_dir="/path/to/output-index",
+ item_type="skill",
+ config=config,
+)
+```
+
+如果没有配置 LLM,默认允许走 fallback tree,用于本地 smoke test 和基础构建链路验证。真实树构建效果仍建议配置 LLM。
+
+## 构建产物
+
+构建完成后,输出目录通常包含:
+
+- `manifest.json`
+- `tree_index.yaml`
+- `tree_index.html`
+- `catalog.jsonl`
+
+## 构建 wheel
+
+在 `marketplace/dispatch` 目录下执行:
+
+```bash
+python -m pip wheel . --no-deps --no-build-isolation -w dist
+```
diff --git a/jiuwenswarm/symphony/config/config_template.json b/jiuwenswarm/symphony/config/config_template.json
new file mode 100644
index 0000000000..774cc7dacd
--- /dev/null
+++ b/jiuwenswarm/symphony/config/config_template.json
@@ -0,0 +1,66 @@
+{
+ "query": "extract tables from websites",
+
+ "top_k": 2,
+ "method": "PROGRESSIVE",
+ "llm_top_k": 2,
+
+ "progressive_batch_size": 5,
+ "progressive_max_tokens": 96,
+ "progressive_request_timeout": null,
+
+ "trie_constrained_decoding_enabled": true,
+ "trie_constraint_allow_user_nodes": false,
+ "trie_constraint_max_candidates": 512,
+ "trie_constraint_fallback_payload": "User.Chat",
+
+ "progressive_max_branch_choices": 6,
+ "progressive_auto_expand_child_threshold": 3,
+ "progressive_collapse_single_chain": true,
+ "progressive_max_collapse_steps": 8,
+ "progressive_max_parallel_branches": 3,
+ "progressive_enable_parallel_branches": true,
+ "progressive_auto_terminal_item_threshold": 12,
+ "progressive_branch_choice_slack": 2,
+ "progressive_branch_candidate_slack": 1,
+ "progressive_round_robin_branch_reduce": true,
+ "progressive_branch_max_tokens": 96,
+ "progressive_item_max_tokens": 128,
+
+ "progressive_compact_boundary_codes_enabled": true,
+ "progressive_flatten_full_tree_in_prompt": true,
+ "progressive_max_exposure_depth_per_call": 99,
+ "progressive_exposure_threshold": 1000000000,
+ "progressive_force_expand_single_child": true,
+ "progressive_single_forward_logit_selection_enabled": false,
+ "progressive_selection_mode": "generate",
+
+ "progressive_scoring_backend": "vllm",
+ "progressive_scoring_backend_model_path": "/data/xt/codes/FineTune/models/qwen3_30b_a3b_instruct",
+ "progressive_scoring_backend_tokenizer_path": "/data/xt/codes/FineTune/models/qwen3_30b_a3b_instruct",
+ "progressive_scoring_backend_device": "auto",
+ "progressive_scoring_backend_dtype": "auto",
+ "progressive_scoring_backend_enable_prefix_caching": true,
+ "progressive_scoring_backend_vllm_kwargs": {
+ "tensor_parallel_size": 2,
+ "gpu_memory_utilization": 0.8,
+ "base_url": "http://10.50.91.126:37000/v1",
+ "api_key": "haha",
+ "request_model": "qwen3.5_35b_a3b_instruct"
+ },
+ "progressive_scoring_backend_batching_enabled": true,
+ "progressive_scoring_require_single_token_codes": true,
+ "progressive_scoring_return_probabilities": true,
+ "progressive_scoring_fallback_mode": "abstain",
+ "progressive_scoring_max_candidates": 512,
+ "progressive_scoring_min_probability": null,
+ "progressive_scoring_trace_top_n": 10,
+
+ "_method_options": ["PROGRESSIVE"],
+ "_description": {
+ "query": "搜索查询文本",
+ "top_k": "返回结果数量",
+ "llm_top_k": "LLM 重排序的 top_k 数量",
+ "method": "检索方法,可选值见 _method_options"
+ }
+}
diff --git a/jiuwenswarm/symphony/environment.yml b/jiuwenswarm/symphony/environment.yml
new file mode 100644
index 0000000000..711f7dcb92
--- /dev/null
+++ b/jiuwenswarm/symphony/environment.yml
@@ -0,0 +1,11 @@
+name: demo
+channels:
+ - conda-forge
+dependencies:
+ - python=3.9
+ - pip
+ - numpy
+ - pyyaml
+ - pip:
+ - openai
+ - rich
diff --git a/jiuwenswarm/symphony/indexing/__init__.py b/jiuwenswarm/symphony/indexing/__init__.py
new file mode 100644
index 0000000000..0cc4da67cf
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/__init__.py
@@ -0,0 +1,17 @@
+"""Canonical offline indexing package."""
+
+from .catalog.records import CatalogRecord
+from .models import (
+ CATALOG_FILENAME,
+ INDEX_MANIFEST_FILENAME,
+ TREE_HTML_FILENAME,
+ TREE_INDEX_FILENAME,
+)
+
+__all__ = [
+ "CATALOG_FILENAME",
+ "CatalogRecord",
+ "INDEX_MANIFEST_FILENAME",
+ "TREE_HTML_FILENAME",
+ "TREE_INDEX_FILENAME",
+]
diff --git a/jiuwenswarm/symphony/indexing/catalog/__init__.py b/jiuwenswarm/symphony/indexing/catalog/__init__.py
new file mode 100644
index 0000000000..71578fdeb3
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/catalog/__init__.py
@@ -0,0 +1,3 @@
+from .records import CatalogRecord
+
+__all__ = ["CatalogRecord"]
diff --git a/jiuwenswarm/symphony/indexing/catalog/records.py b/jiuwenswarm/symphony/indexing/catalog/records.py
new file mode 100644
index 0000000000..4a4e33ce9d
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/catalog/records.py
@@ -0,0 +1,20 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Dict
+
+
+@dataclass(frozen=True)
+class CatalogRecord:
+ worker_id: str
+ cid: str
+ name: str
+ description: str
+ skill_path: str
+ branch_path: tuple[str, ...]
+ category: str
+ retrieval_text: str
+ metadata: Dict[str, object]
+
+
+__all__ = ["CatalogRecord"]
diff --git a/jiuwenswarm/symphony/indexing/doc.md b/jiuwenswarm/symphony/indexing/doc.md
new file mode 100644
index 0000000000..8fdb96ef6a
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/doc.md
@@ -0,0 +1,54 @@
+# Indexing
+
+## Purpose
+
+`indexing/` owns offline progressive tree index construction.
+
+Given skill/plugin material directories or pre-scanned JSONL, it builds the tree, catalog, and manifest artifacts consumed later by `retrieval/` and orchestration.
+
+## Main Outputs
+
+- `tree_index.yaml`
+- `catalog.jsonl`
+- `manifest.json`
+
+## Main Components
+
+### `indexing/tree/`
+
+- scans skills
+- builds the capability tree
+- supports LLM-driven tree construction and fallback tree generation
+
+### `indexing/catalog/`
+
+- defines catalog records
+- builds the leaf catalog used by online progressive retrieval
+
+### `indexing/io/`
+
+- reads and writes tree, catalog, and manifest artifacts
+
+### `indexing/workflows/`
+
+- coordinates full builds and incremental add/delete rebuilds
+- writes only the progressive tree artifacts listed above
+
+## Main Entry Point
+
+- `indexing/workflows/index_builder.py`
+
+Typical usage:
+
+```python
+from indexing.workflows.index_builder import IndexBuilder
+
+IndexBuilder.build(
+ item_paths=["/abs/path/to/skills"],
+ output_dir="/abs/path/to/index",
+)
+```
+
+## Dependency Boundary
+
+`indexing/` does not depend on `retrieval.service` or orchestration runtime code. It produces artifacts; it does not execute online retrieval.
diff --git a/jiuwenswarm/symphony/indexing/io/__init__.py b/jiuwenswarm/symphony/indexing/io/__init__.py
new file mode 100644
index 0000000000..d5724353ab
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/io/__init__.py
@@ -0,0 +1,14 @@
+from .catalog import load_catalog_records
+from .manifest import load_manifest, write_manifest
+from .tree import load_tree_preset, normalize_item_paths, parse_simple_nodes_yaml, sort_tree_nodes, write_tree_preset
+
+__all__ = [
+ "load_catalog_records",
+ "load_manifest",
+ "load_tree_preset",
+ "normalize_item_paths",
+ "parse_simple_nodes_yaml",
+ "sort_tree_nodes",
+ "write_manifest",
+ "write_tree_preset",
+]
diff --git a/jiuwenswarm/symphony/indexing/io/catalog.py b/jiuwenswarm/symphony/indexing/io/catalog.py
new file mode 100644
index 0000000000..8cb4aa95fe
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/io/catalog.py
@@ -0,0 +1,35 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import List
+
+from indexing.catalog.records import CatalogRecord
+
+
+def load_catalog_records(path: Path) -> List[CatalogRecord]:
+ if not path.exists():
+ return []
+ records: List[CatalogRecord] = []
+ for line in path.read_text(encoding="utf-8").splitlines():
+ if not line.strip():
+ continue
+ payload = json.loads(line)
+ worker_id = str(payload.get("worker_id") or payload.get("skill_id") or "")
+ records.append(
+ CatalogRecord(
+ worker_id=worker_id,
+ cid=str(payload.get("cid") or ""),
+ name=str(payload.get("name") or ""),
+ description=str(payload.get("description") or ""),
+ skill_path=str(payload.get("skill_path") or ""),
+ branch_path=tuple(str(item) for item in payload.get("branch_path") or ()),
+ category=str(payload.get("category") or ""),
+ retrieval_text=str(payload.get("retrieval_text") or ""),
+ metadata=dict(payload.get("metadata") or {}),
+ )
+ )
+ return records
+
+
+__all__ = ["load_catalog_records"]
diff --git a/jiuwenswarm/symphony/indexing/io/config_loader.py b/jiuwenswarm/symphony/indexing/io/config_loader.py
new file mode 100644
index 0000000000..5224284547
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/io/config_loader.py
@@ -0,0 +1,33 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import yaml
+
+from shared.storage import is_s3_uri, read_s3_text
+
+
+def read_config_text(source: str | Path, *, description: str = "config") -> str:
+ raw_source = str(source or "").strip()
+ if not raw_source:
+ raise ValueError(f"{description} path is empty")
+ if is_s3_uri(raw_source):
+ return read_s3_text(raw_source)
+ path = Path(raw_source).expanduser().resolve()
+ if not path.exists():
+ raise FileNotFoundError(f"{description} file not found: {path}")
+ return path.read_text(encoding="utf-8")
+
+
+def parse_json_or_yaml(text: str, *, source: str) -> object:
+ 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 config file: {source}") from exc
+
+
+__all__ = ["parse_json_or_yaml", "read_config_text"]
diff --git a/jiuwenswarm/symphony/indexing/io/items_jsonl.py b/jiuwenswarm/symphony/indexing/io/items_jsonl.py
new file mode 100644
index 0000000000..b5466a7e0e
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/io/items_jsonl.py
@@ -0,0 +1,123 @@
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from urllib.parse import urlparse
+from urllib.request import urlopen
+
+from shared.storage import is_s3_uri, read_s3_text
+
+LOGGER = logging.getLogger("index_builder")
+
+
+def is_http_uri(value: str | Path) -> bool:
+ parsed = urlparse(str(value).strip())
+ scheme = str(parsed.scheme or "").strip().lower()
+ return scheme in {"http", "https"}
+
+
+def is_passthrough_item_uri(value: str | Path) -> bool:
+ raw = str(value or "").strip()
+ lowered = raw.lower()
+ return is_s3_uri(raw) or is_http_uri(raw) or lowered.startswith("jsonl://")
+
+
+def _read_http_text(uri: str, *, encoding: str = "utf-8") -> str:
+ with urlopen(uri, timeout=60) as response: # nosec B310
+ payload = response.read()
+ return payload.decode(encoding)
+
+
+def download_http_object_to_path(uri: str, destination_path: str | Path) -> Path:
+ path = Path(destination_path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with urlopen(uri, timeout=60) as response: # nosec B310
+ path.write_bytes(response.read())
+ return path
+
+
+def load_items_jsonl_text(*, item_jsonl_path: str | None = None) -> str:
+ raw_path = str(item_jsonl_path or "").strip()
+ if not raw_path:
+ return ""
+ if is_s3_uri(raw_path):
+ return read_s3_text(raw_path)
+ if is_http_uri(raw_path):
+ return _read_http_text(raw_path)
+ local_path = Path(raw_path).expanduser().resolve()
+ if not local_path.exists():
+ raise FileNotFoundError(f"JSONL path not found: {local_path}")
+ return local_path.read_text(encoding="utf-8")
+
+
+def parse_jsonl_scanned_items(jsonl_content: str) -> tuple[dict[str, dict], list[str]]:
+ scanned: dict[str, dict] = {}
+ ordered_paths: list[str] = []
+ seen_paths: set[str] = set()
+ decoder = json.JSONDecoder()
+ text = str(jsonl_content or "").lstrip("\ufeff")
+ index = 0
+ item_no = 0
+ text_len = len(text)
+
+ while index < text_len:
+ # Accept whitespace or comma as separators between adjacent JSON objects.
+ while index < text_len and (text[index].isspace() or text[index] == ","):
+ index += 1
+ if index >= text_len:
+ break
+ start_index = index
+ try:
+ payload, next_index = decoder.raw_decode(text, index)
+ except Exception as exc:
+ LOGGER.warning("skip invalid json item at char %s: %s", start_index, exc)
+ next_brace = text.find("{", start_index + 1)
+ if next_brace == -1:
+ break
+ index = next_brace
+ continue
+ item_no += 1
+ index = next_index
+ try:
+ if not isinstance(payload, dict):
+ raise ValueError(f"Invalid JSON item #{item_no}: expected object")
+ content_extend = payload.get("contentExtendParam")
+ if not isinstance(content_extend, dict):
+ raise ValueError(f"Invalid JSON item #{item_no}: missing object field 'contentExtendParam'")
+
+ skill_id = str(content_extend.get("skillId") or "").strip()
+ if not skill_id:
+ raise ValueError(f"Invalid JSON item #{item_no}: missing required field contentExtendParam.skillId")
+ if skill_id in scanned:
+ continue
+
+ skill_name = str(content_extend.get("skillName") or "").strip() or skill_id
+ skill_desc = str(content_extend.get("skillDesc") or "").strip()
+ source_path = f"jsonl://skill/{skill_id}"
+ description = skill_desc or skill_name
+
+ normalized_star = content_extend.get("stars", 0)
+ try:
+ stars = int(normalized_star or 0)
+ except Exception:
+ stars = 0
+
+ scanned[skill_id] = {
+ "id": skill_id,
+ "name": skill_name,
+ "description": description,
+ "skill_path": source_path,
+ "path": source_path,
+ "github_url": str(content_extend.get("githubUrl") or content_extend.get("github_url") or ""),
+ "stars": stars,
+ "is_official": bool(content_extend.get("isOfficial", content_extend.get("is_official", False))),
+ "author": str(content_extend.get("author") or ""),
+ "content_extend_param": dict(content_extend),
+ }
+ if source_path not in seen_paths:
+ seen_paths.add(source_path)
+ ordered_paths.append(source_path)
+ except Exception as exc:
+ LOGGER.warning("skip invalid json item #%s: %s", item_no, exc)
+ return scanned, ordered_paths
diff --git a/jiuwenswarm/symphony/indexing/io/manifest.py b/jiuwenswarm/symphony/indexing/io/manifest.py
new file mode 100644
index 0000000000..e22f4db4aa
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/io/manifest.py
@@ -0,0 +1,44 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Dict, Sequence
+
+from indexing.catalog.records import CatalogRecord
+from indexing.io.items_jsonl import is_passthrough_item_uri
+
+
+def write_manifest(
+ output_dir: Path,
+ item_paths: Sequence[str | Path],
+ records: Sequence[CatalogRecord],
+ *,
+ mode: str,
+ item_type: str | None = None,
+) -> None:
+ manifest = {
+ "mode": mode,
+ "count": len(records),
+ "item_paths": [_serialize_item_path(path) for path in item_paths],
+ "worker_ids": [record.worker_id for record in records],
+ }
+ if item_type:
+ manifest["item_type"] = str(item_type)
+ (output_dir / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
+
+
+def load_manifest(index_dir: Path) -> Dict[str, object]:
+ manifest_path = index_dir / "manifest.json"
+ if not manifest_path.exists():
+ return {}
+ return json.loads(manifest_path.read_text(encoding="utf-8"))
+
+
+def _serialize_item_path(path: str | Path) -> str:
+ raw = str(path).strip()
+ if is_passthrough_item_uri(raw):
+ return raw
+ return str(Path(raw).expanduser().resolve())
+
+
+__all__ = ["load_manifest", "write_manifest"]
diff --git a/jiuwenswarm/symphony/indexing/io/tree.py b/jiuwenswarm/symphony/indexing/io/tree.py
new file mode 100644
index 0000000000..73201d6391
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/io/tree.py
@@ -0,0 +1,123 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Dict, Iterable, List, Sequence
+
+from indexing.io.items_jsonl import is_passthrough_item_uri
+
+
+def write_tree_preset(payload: Dict[str, object], path: Path) -> None:
+ nodes = sort_tree_nodes(payload.get("nodes") or [])
+ lines = ["nodes:"]
+ for node in nodes:
+ if not isinstance(node, dict):
+ continue
+ lines.append(f" - cid: {json.dumps(str(node.get('cid', '')), ensure_ascii=False)}")
+ lines.append(f" type: {json.dumps(str(node.get('type', '')), ensure_ascii=False)}")
+ description = str(node.get("description", ""))
+ if description:
+ lines.append(f" description: {json.dumps(description, ensure_ascii=False)}")
+ select_when = str(node.get("select_when", ""))
+ if select_when:
+ lines.append(f" select_when: {json.dumps(select_when, ensure_ascii=False)}")
+ dont_select_when = str(node.get("dont_select_when", ""))
+ if dont_select_when:
+ lines.append(f" dont_select_when: {json.dumps(dont_select_when, ensure_ascii=False)}")
+ source_description = str(node.get("source_description", ""))
+ if source_description:
+ lines.append(f" source_description: {json.dumps(source_description, ensure_ascii=False)}")
+ worker_id = str(node.get("worker_id", "")).strip()
+ if worker_id:
+ lines.append(f" worker_id: {json.dumps(worker_id, ensure_ascii=False)}")
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
+def sort_tree_nodes(nodes: Sequence[Dict[str, object]]) -> List[Dict[str, object]]:
+ return sorted(
+ [dict(node) for node in nodes if isinstance(node, dict)],
+ key=lambda node: (
+ len(str(node.get("cid") or "").split(".")),
+ str(node.get("cid") or ""),
+ ),
+ )
+
+
+def normalize_item_paths(item_paths: Iterable[str | Path]) -> List[str]:
+ normalized: List[str] = []
+ seen: set[str] = set()
+ for item in item_paths:
+ raw = str(item).strip()
+ if not raw:
+ continue
+ if is_passthrough_item_uri(raw):
+ key = raw
+ else:
+ key = str(Path(raw).expanduser().resolve())
+ if key in seen:
+ continue
+ seen.add(key)
+ normalized.append(key)
+ return normalized
+
+
+def load_tree_preset(path: Path) -> Dict[str, object]:
+ try:
+ import yaml
+ except Exception:
+ yaml = None
+ text = path.read_text(encoding="utf-8")
+ if yaml is not None:
+ payload = yaml.safe_load(text) or {}
+ if isinstance(payload, dict):
+ payload["nodes"] = sort_tree_nodes(payload.get("nodes") or [])
+ return payload
+ return parse_simple_nodes_yaml(text)
+
+
+def parse_simple_nodes_yaml(text: str) -> Dict[str, object]:
+ nodes: List[Dict[str, object]] = []
+ current: Dict[str, object] | None = None
+ for raw_line in text.splitlines():
+ line = raw_line.rstrip()
+ if line.strip() == "nodes:":
+ continue
+ if line.startswith(" - "):
+ if current:
+ nodes.append(current)
+ current = {}
+ line = line[4:]
+ elif current is None:
+ continue
+ else:
+ line = line.strip()
+ if ":" not in line:
+ continue
+ key, value = line.split(":", 1)
+ raw_value = value.strip()
+ if not raw_value:
+ parsed_value = ""
+ elif (
+ raw_value[:1] in {'"', "[", "{", "-"}
+ or raw_value in {"true", "false", "null"}
+ or raw_value.replace(".", "", 1).isdigit()
+ ):
+ try:
+ parsed_value = json.loads(raw_value)
+ except Exception:
+ parsed_value = raw_value.strip('"')
+ else:
+ parsed_value = raw_value
+ current[str(key).strip()] = parsed_value
+ if current:
+ nodes.append(current)
+ return {"nodes": sort_tree_nodes(nodes)}
+
+
+__all__ = [
+ "load_tree_preset",
+ "normalize_item_paths",
+ "parse_simple_nodes_yaml",
+ "sort_tree_nodes",
+ "write_tree_preset",
+]
diff --git a/jiuwenswarm/symphony/indexing/models.py b/jiuwenswarm/symphony/indexing/models.py
new file mode 100644
index 0000000000..219fbe7d88
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/models.py
@@ -0,0 +1,9 @@
+from __future__ import annotations
+
+from indexing.catalog.records import CatalogRecord
+
+
+INDEX_MANIFEST_FILENAME = "manifest.json"
+TREE_INDEX_FILENAME = "tree_index.yaml"
+TREE_HTML_FILENAME = "tree_index.html"
+CATALOG_FILENAME = "catalog.jsonl"
diff --git a/jiuwenswarm/symphony/indexing/scanners/__init__.py b/jiuwenswarm/symphony/indexing/scanners/__init__.py
new file mode 100644
index 0000000000..dbf6e4b8b1
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/scanners/__init__.py
@@ -0,0 +1,41 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from .base import BaseScanner, ScannedItem
+from .skill import SkillScanner
+
+
+ScannerType = type[BaseScanner]
+
+
+def normalize_item_type(item_type: str | None) -> str:
+ normalized = str(item_type or "skill").strip().lower()
+ if normalized != "skill":
+ raise ValueError("item_type must be: skill")
+ return normalized
+
+
+def get_scanner_class(item_type: str | None) -> ScannerType:
+ normalize_item_type(item_type)
+ return SkillScanner
+
+
+def create_scanner(
+ item_type: str | None,
+ items_dir: Path | str,
+ *,
+ display_items_dir: Path | str | None = None,
+) -> BaseScanner:
+ scanner_cls = get_scanner_class(item_type)
+ return scanner_cls(items_dir, display_items_dir=display_items_dir)
+
+
+__all__ = [
+ "BaseScanner",
+ "ScannedItem",
+ "SkillScanner",
+ "create_scanner",
+ "get_scanner_class",
+ "normalize_item_type",
+]
diff --git a/jiuwenswarm/symphony/indexing/scanners/base.py b/jiuwenswarm/symphony/indexing/scanners/base.py
new file mode 100644
index 0000000000..1c76d1b1e9
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/scanners/base.py
@@ -0,0 +1,104 @@
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from pathlib import Path
+
+from shared.rich_compat import BarColumn, Console, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
+
+
+console = Console()
+
+
+@dataclass
+class ScannedItem:
+ """Normalized scanned item used by tree/catalog builders."""
+
+ id: str
+ name: str
+ description: str
+ item_path: str
+ content: str = ""
+ github_url: str = ""
+ stars: int = 0
+ is_official: bool = False
+ author: str = ""
+
+ def to_dict(self) -> dict[str, object]:
+ return {
+ "id": self.id,
+ "name": self.name,
+ "description": self.description,
+ "skill_path": self.item_path,
+ "path": self.item_path,
+ "content": self.content,
+ "github_url": self.github_url,
+ "stars": self.stars,
+ "is_official": self.is_official,
+ "author": self.author,
+ }
+
+
+class BaseScanner(ABC):
+ """Common scanner contract for item-type-specific scanners."""
+
+ item_type = "item"
+
+ def __init__(self, items_dir: Path | str, *, display_items_dir: Path | str | None = None) -> None:
+ self.items_dir = Path(items_dir)
+ self.display_items_dir = Path(display_items_dir) if display_items_dir is not None else self.items_dir
+
+ def scan(self, show_progress: bool = True) -> list[ScannedItem]:
+ items: list[ScannedItem] = []
+ if not self.items_dir.exists():
+ console.print(f"[red]{self.item_type.title()}s directory not found: {self.items_dir}[/red]")
+ return items
+
+ subdirs = [path for path in sorted(self.items_dir.iterdir()) if path.is_dir() and not path.name.startswith(".")]
+ if show_progress:
+ items = self._scan_with_progress(subdirs)
+ else:
+ items = self._scan_simple(subdirs)
+ items.sort(key=lambda item: item.name.lower())
+ if show_progress:
+ console.print(f"[green]Found {len(items)} {self.item_type}s in {self.display_items_dir}[/green]")
+ return items
+
+ def to_dict_list(self, items: list[ScannedItem] | None = None) -> list[dict[str, object]]:
+ resolved_items = items if items is not None else self.scan()
+ return [item.to_dict() for item in resolved_items]
+
+ def _scan_with_progress(self, subdirs: list[Path]) -> list[ScannedItem]:
+ items: list[ScannedItem] = []
+ with Progress(
+ SpinnerColumn(),
+ TextColumn(f"[bold blue]Scanning {self.item_type} files..."),
+ BarColumn(bar_width=40),
+ TaskProgressColumn(),
+ TextColumn("({task.completed}/{task.total})"),
+ console=console,
+ ) as progress:
+ task = progress.add_task("Scanning", total=len(subdirs))
+ for item_dir in subdirs:
+ item = self.scan_item_dir(item_dir)
+ if item is not None:
+ items.append(item)
+ progress.update(task, advance=1)
+ return items
+
+ def _scan_simple(self, subdirs: list[Path]) -> list[ScannedItem]:
+ items: list[ScannedItem] = []
+ for item_dir in subdirs:
+ item = self.scan_item_dir(item_dir)
+ if item is not None:
+ items.append(item)
+ return items
+
+ @classmethod
+ @abstractmethod
+ def detect_item_root(cls, path: Path) -> Path | None:
+ """Return the canonical item root when this scanner recognizes the path."""
+
+ @abstractmethod
+ def scan_item_dir(self, item_dir: Path) -> ScannedItem | None:
+ """Scan a single item directory into a normalized record."""
diff --git a/jiuwenswarm/symphony/indexing/scanners/common.py b/jiuwenswarm/symphony/indexing/scanners/common.py
new file mode 100644
index 0000000000..a25b74f1a3
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/scanners/common.py
@@ -0,0 +1,106 @@
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import Any
+
+
+def parse_frontmatter(content: str) -> tuple[dict[str, Any], str]:
+ if not content.startswith("---"):
+ return {}, content
+
+ end_match = re.search(r"\n---\s*\n", content[3:])
+ if not end_match:
+ return {}, content
+
+ frontmatter_str = content[3: end_match.start() + 3]
+ body = content[end_match.end() + 3:]
+ parsed = _safe_load_frontmatter(frontmatter_str.strip())
+ return parsed, body
+
+
+def clean_first_paragraph(body: str, *, limit: int = 500) -> str:
+ text = str(body or "").strip()
+ if not text:
+ return ""
+ first_para = text.split("\n\n")[0]
+ first_para = re.sub(r"^#+\s*", "", first_para)
+ first_para = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", first_para)
+ return first_para[:limit].strip()
+
+
+def read_text_if_exists(path: Path) -> str:
+ if not path.exists() or not path.is_file():
+ return ""
+ return path.read_text(encoding="utf-8")
+
+
+def _safe_load_frontmatter(text: str) -> dict[str, Any]:
+ try:
+ import yaml
+ except ModuleNotFoundError:
+ return _parse_simple_frontmatter(text)
+
+ try:
+ payload = yaml.safe_load(text) or {}
+ except Exception:
+ return _parse_simple_frontmatter(text)
+ if not isinstance(payload, dict):
+ return _parse_simple_frontmatter(text)
+ return payload
+
+
+def _parse_simple_frontmatter(text: str) -> dict[str, Any]:
+ payload: dict[str, Any] = {}
+ lines = text.splitlines()
+ index = 0
+ last_key: str | None = None
+
+ while index < len(lines):
+ raw_line = lines[index]
+ stripped = raw_line.strip()
+ if not stripped or stripped.startswith("#"):
+ index += 1
+ continue
+ if raw_line.startswith((" ", "\t")):
+ index += 1
+ continue
+ if ":" not in raw_line:
+ if last_key is not None and isinstance(payload.get(last_key), str):
+ payload[last_key] = f"{payload[last_key]}\n{stripped}".strip()
+ index += 1
+ continue
+
+ key, value = raw_line.split(":", 1)
+ clean_key = key.strip()
+ clean_value = value.strip()
+
+ if clean_value in {"|", "|-", "|+", ">", ">-", ">+"}:
+ block_lines: list[str] = []
+ index += 1
+ while index < len(lines):
+ block_line = lines[index]
+ if not block_line.strip():
+ block_lines.append("")
+ index += 1
+ continue
+ if not block_line.startswith((" ", "\t")):
+ break
+ block_lines.append(block_line.lstrip(" \t"))
+ index += 1
+ payload[clean_key] = "\n".join(block_lines).strip()
+ last_key = clean_key
+ continue
+
+ payload[clean_key] = _parse_simple_scalar(clean_value)
+ last_key = clean_key
+ index += 1
+
+ return payload
+
+
+def _parse_simple_scalar(value: str) -> str:
+ text = str(value or "").strip()
+ if len(text) >= 2 and text[0] == text[-1] and text[0] in {'"', "'"}:
+ return text[1:-1]
+ return text
diff --git a/jiuwenswarm/symphony/indexing/scanners/skill.py b/jiuwenswarm/symphony/indexing/scanners/skill.py
new file mode 100644
index 0000000000..039bffbdc2
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/scanners/skill.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from .base import BaseScanner, ScannedItem, console
+from .common import clean_first_paragraph, parse_frontmatter
+
+
+class SkillScanner(BaseScanner):
+ item_type = "skill"
+
+ def __init__(self, items_dir: Path | str, *, display_items_dir: Path | str | None = None) -> None:
+ super().__init__(items_dir, display_items_dir=display_items_dir)
+ self._metadata: dict[str, dict[str, object]] = {}
+ self._load_metadata()
+
+ def _load_metadata(self) -> None:
+ metadata_path = self.items_dir / "skills.json"
+ if not metadata_path.exists():
+ return
+ try:
+ payload = json.loads(metadata_path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ console.print(f"[yellow]Warning: Failed to load skills.json: {exc}[/yellow]")
+ return
+ for item in payload.get("skills", []):
+ item_id = str(item.get("id") or "").strip()
+ if not item_id:
+ continue
+ self._metadata[item_id] = {
+ "github_url": item.get("github_url", ""),
+ "stars": item.get("stars", 0),
+ "is_official": item.get("is_official", False),
+ "author": item.get("author", ""),
+ }
+
+ @classmethod
+ def detect_item_root(cls, path: Path) -> Path | None:
+ for filename in ("SKILL.md", "skill.md", "Skill.md"):
+ candidate = path / filename
+ if candidate.exists():
+ return path
+ return None
+
+ def scan_item_dir(self, item_dir: Path) -> ScannedItem | None:
+ item_root = self.detect_item_root(item_dir)
+ if item_root is None:
+ return None
+
+ skill_file = next(
+ (item_root / name for name in ("SKILL.md", "skill.md", "Skill.md") if (item_root / name).exists()), None
+ )
+ if skill_file is None:
+ return None
+ try:
+ content = skill_file.read_text(encoding="utf-8")
+ except Exception as exc:
+ console.print(f"[yellow]Failed to read {skill_file}: {exc}[/yellow]")
+ return None
+
+ frontmatter, body = parse_frontmatter(content)
+ item_id = item_root.name
+ meta = self._metadata.get(item_id, {})
+ name = str(frontmatter.get("name") or item_root.name).strip() or item_root.name
+ description = str(frontmatter.get("description") or "").strip()
+ if not description:
+ description = clean_first_paragraph(body)
+
+ return ScannedItem(
+ id=item_id,
+ name=name,
+ description=description,
+ item_path=str(skill_file.resolve()),
+ content=body.strip(),
+ github_url=str(meta.get("github_url") or ""),
+ stars=int(meta.get("stars") or 0),
+ is_official=bool(meta.get("is_official")),
+ author=str(meta.get("author") or ""),
+ )
diff --git a/jiuwenswarm/symphony/indexing/tree/__init__.py b/jiuwenswarm/symphony/indexing/tree/__init__.py
new file mode 100644
index 0000000000..356eb2f6fb
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/__init__.py
@@ -0,0 +1,37 @@
+from __future__ import annotations
+
+__all__ = [
+ "DynamicTreeConfig",
+ "Skill",
+ "SkillStatus",
+ "TreeBuildConfig",
+ "TreeBuilder",
+ "TreeManagerConfig",
+ "TreeNode",
+ "build_tree",
+]
+
+
+def __getattr__(name: str):
+ if name in {"DynamicTreeConfig", "Skill", "SkillStatus", "TreeNode", "TreeBuildConfig", "TreeManagerConfig"}:
+ from .schema import DynamicTreeConfig, Skill, SkillStatus, TreeBuildConfig, TreeManagerConfig, TreeNode
+
+ exports = {
+ "DynamicTreeConfig": DynamicTreeConfig,
+ "Skill": Skill,
+ "SkillStatus": SkillStatus,
+ "TreeBuildConfig": TreeBuildConfig,
+ "TreeManagerConfig": TreeManagerConfig,
+ "TreeNode": TreeNode,
+ }
+ value = exports.get(name)
+ if value is not None:
+ return value
+ if name in {"TreeBuilder", "build_tree"}:
+ from .builder import TreeBuilder, build_tree
+
+ exports = {"TreeBuilder": TreeBuilder, "build_tree": build_tree}
+ value = exports.get(name)
+ if value is not None:
+ return value
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/jiuwenswarm/symphony/indexing/tree/builder.py b/jiuwenswarm/symphony/indexing/tree/builder.py
new file mode 100644
index 0000000000..6f58324e9f
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/builder.py
@@ -0,0 +1,1159 @@
+from __future__ import annotations
+
+from collections import deque
+from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED, as_completed
+from dataclasses import dataclass
+from pathlib import Path
+import re
+import threading
+from time import perf_counter
+from typing import Optional
+
+try:
+ from openai import APIConnectionError, APIError, APITimeoutError, AuthenticationError, OpenAI
+except ModuleNotFoundError:
+ APIConnectionError = APIError = APITimeoutError = AuthenticationError = None
+ OpenAI = None
+
+from shared.rich_compat import BarColumn, Console, Panel, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
+
+from indexing.scanners import create_scanner
+
+from .schema import (
+ DEFAULT_TREE_OUTPUT_PATH,
+ DynamicTreeConfig,
+ SKILL_DESCRIPTION_MAX_LENGTH,
+ Skill,
+ TreeManagerConfig,
+ TreeNode,
+)
+from .expansion import TreeExpansionEngine as ExternalTreeExpansionEngine
+from .grouping import TreeGroupingEngine
+from .llm_runtime import TreeLLMRuntime as ExternalTreeLLMRuntime
+from .prompts import (
+ GROUP_MERGE_PROMPT,
+ GROUP_DISCOVERY_PROMPT,
+ SKILL_ASSIGNMENT_PROMPT,
+ EQUIVALENCE_GROUPING_PROMPT,
+ SKILL_PROFILE_PROMPT,
+)
+from .preset_writer import TreePresetWriter as ExternalTreePresetWriter
+from .repair import TreeRepairEngine as ExternalTreeRepairEngine
+from .types import ChildGroup as ExternalChildGroup, QueuedNode as ExternalQueuedNode
+
+console = Console()
+
+
+_QueuedNode = ExternalQueuedNode
+_ChildGroup = ExternalChildGroup
+_TreeLLMRuntime = ExternalTreeLLMRuntime
+_TreePresetWriter = ExternalTreePresetWriter
+_TreeExpansionEngine = ExternalTreeExpansionEngine
+_TreeRepairEngine = ExternalTreeRepairEngine
+
+
+@dataclass(frozen=True)
+class BuildTreeOptions:
+ skills_dir: Path | str | None = None
+ output_path: Path | str | None = None
+ config: DynamicTreeConfig | None = None
+ manager_config: TreeManagerConfig | None = None
+ client: OpenAI | None = None
+ model: str | None = None
+ api_key: str | None = None
+ base_url: str | None = None
+ llm_seed: int | None = None
+ max_workers: int | None = None
+ verbose: bool = False
+ show_tree: bool = True
+ generate_html: bool = True
+ display_skills_dir: Path | str | None = None
+ item_type: str = "skill"
+ skill_entries: list[dict] | None = None
+
+
+_BUILD_TREE_POSITIONAL_FIELDS = (
+ "skills_dir",
+ "output_path",
+ "config",
+ "manager_config",
+ "client",
+ "model",
+ "api_key",
+ "base_url",
+ "llm_seed",
+ "max_workers",
+ "verbose",
+ "show_tree",
+ "generate_html",
+ "display_skills_dir",
+ "item_type",
+ "skill_entries",
+)
+
+
+class TreeBuilder:
+ """
+ Unified tree builder with auto-selection and node splitting.
+
+ Features:
+ - Auto-selects build method based on skill count
+ - Splits oversized nodes (> max_skills_per_node)
+ - Simple tree visualization
+ """
+
+ # Token budget constants for auto batch size calculation
+ PROMPT_OVERHEAD_TOKENS = 3000 # prompt template + instructions
+ OUTPUT_RESERVE_TOKENS = 4000 # JSON response reserve
+ AVG_TOKENS_PER_SKILL = 75 # average tokens per skill entry
+ DEFAULT_CONTEXT_WINDOW = 128000 # fallback context window size
+ DEFAULT_MAX_OUTPUT_TOKENS = 32768 # fallback max output tokens
+
+ def __init__(
+ self,
+ skills_dir: Path | str | None = None,
+ output_path: Path | str | None = None,
+ config: Optional[DynamicTreeConfig] = None,
+ manager_config: TreeManagerConfig | None = None,
+ client: OpenAI | None = None,
+ model: Optional[str] = None,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ llm_seed: int | None = None,
+ max_workers: Optional[int] = None,
+ display_skills_dir: Path | str | None = None,
+ item_type: str = "skill",
+ skill_entries: list[dict] | None = None,
+ ):
+ mcfg = manager_config or TreeManagerConfig()
+ build_cfg = mcfg.build
+ if skills_dir is None:
+ raise ValueError("TreeBuilder requires a non-empty skills_dir")
+ self.scanner = create_scanner(item_type, skills_dir, display_items_dir=display_skills_dir)
+ self._skill_entries_override = (
+ [dict(item) for item in (skill_entries or [])] if skill_entries is not None else None
+ )
+ default_tree_path = DEFAULT_TREE_OUTPUT_PATH
+ self.output_path = Path(output_path) if output_path else default_tree_path
+ self.config = config or DynamicTreeConfig(
+ branching_factor=mcfg.branching_factor,
+ max_depth=mcfg.max_depth,
+ root_categories=mcfg.root_categories,
+ )
+ self.model = str(model or "").strip()
+ self.api_key = str(api_key or "").strip()
+ self.base_url = str(base_url or "").strip()
+ self._manager_config = mcfg
+ self._llm_seed = llm_seed
+ if not self.model:
+ raise ValueError("TreeBuilder requires a non-empty llm model")
+ if client is None and not self.api_key:
+ raise ValueError("TreeBuilder requires a non-empty llm api key")
+ self._client = (
+ client
+ if client is not None
+ else (OpenAI(api_key=self.api_key, base_url=self.base_url) if OpenAI is not None else None)
+ )
+ self.max_workers = max_workers or build_cfg.max_workers
+ self._postprocess_enabled = bool(build_cfg.postprocess_enabled)
+ self._postprocess_max_passes = max(0, int(build_cfg.postprocess_max_passes))
+ self._postprocess_min_skills = max(2, int(build_cfg.postprocess_min_skills))
+ self._equiv_grouping_enabled = bool(build_cfg.equiv_grouping_enabled)
+ self._discovery_seed = build_cfg.discovery_seed
+
+ self._llm_calls = 0
+ self._retry_calls = 0
+ self._cache_hits = 0
+ self._cache_misses = 0
+ self._cache_unknown = 0
+ self._prompt_fingerprints: set[str] = set()
+ self._leaf_skills = 0 # Skills that have reached leaf nodes
+ self._counter_lock = threading.Lock() # Protects _llm_calls, _leaf_skills, _consecutive_failures
+ self._progress = None # Rich progress bar
+ self._progress_task = None
+ self._batch_size_cache = None
+ self._max_output_tokens_cache = None
+ self._thread_local = threading.local() # Per-thread truncation flag
+ self._executor = None # Shared executor, set in _build_tree
+ self._llm_semaphore = threading.Semaphore(self.max_workers) # Limit concurrent LLM calls
+ self._consecutive_failures = 0
+ self.max_consecutive_failures = 5
+ self._llm_runtime = ExternalTreeLLMRuntime(self)
+ self._preset_writer = ExternalTreePresetWriter(self)
+ self._expansion_engine = ExternalTreeExpansionEngine(self)
+ self._repair_engine = ExternalTreeRepairEngine(self)
+ self._grouping_engine = TreeGroupingEngine(self)
+
+ def _auto_batch_size(self) -> int:
+ """Calculate batch size from model context window."""
+ return self._llm_runtime.auto_batch_size()
+
+ def _get_max_output_tokens(self) -> int:
+ """Get max output tokens for the model, with caching."""
+ return self._llm_runtime.get_max_output_tokens()
+
+ def _merged_extra_body(self) -> dict:
+ return self._llm_runtime.merged_extra_body()
+
+ def _model_limits(self) -> tuple[int, int]:
+ """Resolve model limits."""
+ return self._llm_runtime.model_limits()
+
+ def build(
+ self,
+ verbose: bool = False,
+ show_tree: bool = True,
+ generate_html: bool = True,
+ ) -> dict:
+ console.print(Panel.fit("[bold cyan]Building Capability Tree[/bold cyan]", border_style="cyan"))
+ step1_start = perf_counter()
+ skill_entries = self._load_skill_entries()
+ console.print(f"[dim]Step 1 elapsed: {(perf_counter() - step1_start) * 1000.0:.2f} ms[/dim]")
+ if not skill_entries:
+ console.print("[red]No skills found.[/red]")
+ return {}
+
+ step1b_start = perf_counter()
+ skill_entries = self._enrich_skill_profiles(skill_entries, verbose=verbose)
+ console.print(f"[dim]Step 1b elapsed: {(perf_counter() - step1b_start) * 1000.0:.2f} ms[/dim]")
+ step2_start = perf_counter()
+ tree_root = self._build_tree(skill_entries, verbose)
+ console.print(f"[dim]Step 2 elapsed: {(perf_counter() - step2_start) * 1000.0:.2f} ms[/dim]")
+ step3_start = perf_counter()
+ tree_dict = self._tree_to_dict(tree_root)
+ preset_dict = self._emit_tree_artifacts(
+ tree_dict,
+ show_tree=show_tree,
+ generate_html=generate_html,
+ )
+ console.print(f"[dim]Step 3 elapsed: {(perf_counter() - step3_start) * 1000.0:.2f} ms[/dim]")
+ self._print_cache_stats()
+ self._print_build_summary()
+ return preset_dict
+
+ def _load_skill_entries(self) -> list[dict]:
+ console.print("\n[bold]Step 1: Scanning skills...[/bold]")
+ if self._skill_entries_override is not None:
+ skill_entries = [dict(item) for item in self._skill_entries_override]
+ else:
+ skill_entries = self.scanner.to_dict_list()
+ if skill_entries:
+ console.print(f"[green]Found {len(skill_entries)} skills[/green]")
+ return skill_entries
+
+ def _enrich_skill_profiles(self, skill_entries: list[dict], *, verbose: bool = False) -> list[dict]:
+ if not self._skill_profiles_enabled:
+ return list(skill_entries)
+
+ console.print("\n[bold]Step 1b: Normalizing skill routing profiles...[/bold]")
+ enriched: list[dict] = []
+ ordered = self._sorted_skills(skill_entries)
+ for batch in self._skill_profile_batches(ordered):
+ profiles = self._generate_skill_profiles(batch, verbose=verbose)
+ for skill in batch:
+ enriched.append(self._apply_skill_profile(skill, profiles.get(str(skill.get("id") or "").strip())))
+ if self._deterministic_prompts:
+ return sorted(enriched, key=lambda item: (str(item.get("id", "")), str(item.get("name", ""))))
+ return enriched
+
+ def _skill_profile_batches(self, skills: list[dict]) -> list[list[dict]]:
+ batch_size = min(self._skill_profile_batch_size, max(1, self._auto_batch_size()))
+ return [skills[index:index + batch_size] for index in range(0, len(skills), batch_size)]
+
+ def _generate_skill_profiles(self, skills: list[dict], *, verbose: bool = False) -> dict[str, dict[str, str]]:
+ if not skills:
+ return {}
+ prompt = SKILL_PROFILE_PROMPT.format(
+ skills_list=self._format_skill_profile_inputs(skills),
+ description_limit=self._skill_profile_description_limit,
+ rule_limit=self._skill_profile_rule_limit,
+ )
+ result = self._call_llm_json(prompt)
+ raw_profiles = result.get("profiles", {}) if isinstance(result, dict) else {}
+ if not isinstance(raw_profiles, dict):
+ if verbose:
+ console.print("[yellow] Skill profile generation returned no profile mapping[/yellow]")
+ return {}
+
+ valid_ids = {str(skill.get("id") or "").strip() for skill in skills}
+ profiles: dict[str, dict[str, str]] = {}
+ for skill_id, payload in raw_profiles.items():
+ normalized_id = str(skill_id or "").strip()
+ if normalized_id not in valid_ids or not isinstance(payload, dict):
+ continue
+ profiles[normalized_id] = {
+ "description": self._compact_profile_field(
+ payload.get("description"), limit=self._skill_profile_description_limit
+ ),
+ "select_when": self._compact_profile_field(
+ payload.get("select_when"), limit=self._skill_profile_rule_limit
+ ),
+ "dont_select_when": self._compact_profile_field(
+ payload.get("dont_select_when"), limit=self._skill_profile_rule_limit
+ ),
+ }
+ return profiles
+
+ def _format_skill_profile_inputs(self, skills: list[dict]) -> str:
+ rows: list[str] = []
+ for skill in self._sorted_skills(skills):
+ skill_id = str(skill.get("id") or "").strip()
+ name = str(skill.get("name") or skill_id).strip() or skill_id
+ description = self._compact_profile_field(skill.get("description"), limit=600)
+ content = self._compact_profile_field(skill.get("content"), limit=900)
+ rows.append(f"- id: {skill_id}")
+ rows.append(f" name: {name}")
+ if description:
+ rows.append(f" source_description: {description}")
+ if content:
+ rows.append(f" source_content: {content}")
+ return "\n".join(rows)
+
+ def _apply_skill_profile(self, skill: dict, profile: dict[str, str] | None) -> dict:
+ source_description = str(skill.get("source_description") or skill.get("description") or "").strip()
+ if not profile:
+ return self._with_fallback_skill_profile(skill)
+
+ description = self._compact_profile_field(
+ profile.get("description"), limit=self._skill_profile_description_limit
+ )
+ if not description:
+ return self._with_fallback_skill_profile(skill)
+
+ select_when = self._compact_profile_field(profile.get("select_when"), limit=self._skill_profile_rule_limit)
+ dont_select_when = self._compact_profile_field(
+ profile.get("dont_select_when"), limit=self._skill_profile_rule_limit
+ )
+ if not self._skill_profile_select_rules_enabled:
+ select_when = ""
+ dont_select_when = ""
+
+ updated = dict(skill)
+ updated["source_description"] = source_description
+ updated["routing_description"] = description
+ updated["select_when"] = select_when
+ updated["dont_select_when"] = dont_select_when
+ updated["description"] = self._compose_skill_routing_description(
+ description=description,
+ select_when=select_when,
+ dont_select_when=dont_select_when,
+ )
+ return updated
+
+ def _with_fallback_skill_profile(self, skill: dict) -> dict:
+ source_description = str(skill.get("source_description") or skill.get("description") or "").strip()
+ name = str(skill.get("name") or skill.get("id") or "").strip()
+ fallback = self._compact_profile_field(source_description or name, limit=self._skill_profile_description_limit)
+ updated = dict(skill)
+ updated["source_description"] = source_description
+ updated["routing_description"] = fallback
+ updated.setdefault("select_when", "")
+ updated.setdefault("dont_select_when", "")
+ updated["description"] = self._compose_skill_routing_description(
+ description=fallback,
+ select_when=str(updated.get("select_when") or ""),
+ dont_select_when=str(updated.get("dont_select_when") or ""),
+ )
+ return updated
+
+ def _compose_skill_routing_description(
+ self, *, description: str, select_when: str = "", dont_select_when: str = ""
+ ) -> str:
+ parts = [self._compact_profile_field(description, limit=self._skill_profile_description_limit)]
+ if self._skill_profile_select_rules_enabled and select_when:
+ parts.append(
+ f"Select when: {self._compact_profile_field(select_when, limit=self._skill_profile_rule_limit)}"
+ )
+ if self._skill_profile_select_rules_enabled and dont_select_when:
+ rule_text = self._compact_profile_field(dont_select_when, limit=self._skill_profile_rule_limit)
+ parts.append(f"Don't select when: {rule_text}")
+ return "\n".join(part for part in parts if part).strip()
+
+ @staticmethod
+ def _compact_profile_field(value: object, *, limit: int) -> str:
+ text = " ".join(str(value or "").split())
+ if len(text) <= limit:
+ return text
+ return text[:max(0, limit - 3)].rstrip() + "..."
+
+ def _emit_tree_artifacts(self, tree_dict: dict, *, show_tree: bool, generate_html: bool) -> dict:
+ console.print("\n[bold]Step 3: Writing to file...[/bold]")
+ preset_dict = self._tree_to_orchestrator_preset(tree_dict)
+ self._write_yaml(preset_dict)
+ if generate_html:
+ from .visualizer import generate_html as gen_html
+
+ html_path = self.output_path.with_suffix(".html")
+ gen_html(tree_dict, html_path)
+ console.print(f"[green]Generated HTML: {html_path}[/green]")
+ if show_tree:
+ console.print("\n[bold]Tree Structure:[/bold]")
+ self._print_tree(tree_dict)
+ return preset_dict
+
+ def _print_build_summary(self) -> None:
+ summary_lines = [f"[bold green]Done![/bold green] ({self._llm_calls} LLM calls)"]
+ if self._cache_observability:
+ summary_lines.extend(
+ [
+ f"Cache hits/misses/unknown: {self._cache_hits}/{self._cache_misses}/{self._cache_unknown}",
+ f"Unique prompt fingerprints: {len(self._prompt_fingerprints)}",
+ ]
+ )
+ summary_lines.append(f"Output: {self.output_path}")
+ console.print(Panel.fit("\n".join(summary_lines), border_style="green"))
+
+ def _build_tree(self, skills: list[dict], verbose: bool = False) -> TreeNode:
+ console.print("\n[bold]Step 2: Building tree structure...[/bold]")
+ root = TreeNode(id="root", name="Root", description="Skill capability tree root")
+ self._leaf_skills = 0
+ pending_nodes: deque[ExternalQueuedNode] = deque([ExternalQueuedNode(root, skills, 0, None)])
+ active_jobs: dict = {}
+
+ with self._tree_progress(total=len(skills)) as progress:
+ self._progress = progress
+ with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
+ self._executor = executor
+ while pending_nodes or active_jobs:
+ self._submit_pending_nodes(pending_nodes, active_jobs, executor, verbose=verbose)
+ self._refresh_pending_metric(active_jobs)
+ if not active_jobs:
+ continue
+ self._harvest_finished_nodes(active_jobs, pending_nodes)
+
+ self._progress = None
+ self._executor = None
+
+ self._repair_tree(root, source_skills=skills, verbose=verbose)
+ return root
+
+ def _tree_progress(self, *, total: int) -> Progress:
+ status_text = (
+ "("
+ "{task.fields[leaf]}/{task.fields[total_count]} skills done, "
+ "{task.fields[llm]} LLM, "
+ "{task.fields[pending]} pending)"
+ )
+ progress = Progress(
+ SpinnerColumn(),
+ TextColumn("[progress.description]{task.description}"),
+ BarColumn(),
+ TaskProgressColumn(),
+ TextColumn(status_text),
+ console=console,
+ transient=False,
+ )
+ self._progress_task = progress.add_task(
+ "Building capability tree",
+ total=total,
+ pending=0,
+ leaf=0,
+ llm=0,
+ total_count=total,
+ )
+ return progress
+
+ def _submit_pending_nodes(
+ self,
+ pending_nodes: deque[ExternalQueuedNode],
+ active_jobs: dict,
+ executor: ThreadPoolExecutor,
+ *,
+ verbose: bool,
+ ) -> None:
+ while pending_nodes:
+ job = pending_nodes.popleft()
+ future = executor.submit(
+ self._process_node,
+ node=job.node,
+ skills=job.skills,
+ depth=job.depth,
+ parent_context=job.parent_context,
+ verbose=verbose,
+ )
+ active_jobs[future] = job
+
+ def _refresh_pending_metric(self, active_jobs: dict) -> None:
+ if self._progress is None or self._progress_task is None:
+ return
+ self._progress.update(self._progress_task, pending=len(active_jobs))
+
+ def _harvest_finished_nodes(
+ self,
+ active_jobs: dict,
+ pending_nodes: deque[ExternalQueuedNode],
+ ) -> None:
+ done, _ = wait(tuple(active_jobs.keys()), return_when=FIRST_COMPLETED)
+ finished = sorted(done, key=lambda future: active_jobs[future].node.id)
+ for future in finished:
+ job = active_jobs.pop(future)
+ try:
+ child_groups = future.result()
+ except Exception as exc:
+ console.print(f"[red]Error processing {job.node.id}: {exc}[/red]")
+ else:
+ for child_group in child_groups:
+ pending_nodes.append(self._queue_child_node(child_group, depth=job.depth + 1))
+
+ def _repair_tree(self, root: TreeNode, *, source_skills: list[dict], verbose: bool) -> None:
+ self._audit_tree(root, source_skills)
+ if self._postprocess_enabled and self._postprocess_max_passes > 0:
+ self._postprocess_tree(root, verbose)
+ if self._equiv_grouping_enabled:
+ self._normalize_to_equivalence_groups(root, verbose)
+ self._audit_tree(root, source_skills)
+
+ @staticmethod
+ def _collect_leaf_skills(node: TreeNode) -> set:
+ seen_ids: set[str] = set()
+ frontier = [node]
+ while frontier:
+ current = frontier.pop()
+ if current.children:
+ frontier.extend(current.children)
+ continue
+ for skill in current.skills:
+ seen_ids.add(skill.id)
+ return seen_ids
+
+ def _audit_tree(self, root: TreeNode, input_skills: list[dict]) -> None:
+ expected_ids = {str(skill.get("id", "")).strip() for skill in input_skills}
+ discovered_ids = self._collect_leaf_skills(root)
+ missing_ids = sorted(skill_id for skill_id in expected_ids if skill_id and skill_id not in discovered_ids)
+ if not missing_ids:
+ return
+
+ missing_lookup = {str(skill.get("id", "")).strip(): skill for skill in input_skills}
+ recovered_payloads = [missing_lookup[skill_id] for skill_id in missing_ids if skill_id in missing_lookup]
+ console.print(
+ Panel(
+ "\n".join(
+ [
+ "[bold red]Recovered "
+ f"{len(recovered_payloads)} missing skills after tree construction.[/bold red]",
+ "They have been attached under a fallback branch to preserve index completeness.",
+ ]
+ ),
+ title="[bold red]Tree Audit Recovery[/bold red]",
+ border_style="red",
+ )
+ )
+
+ fallback_branch = TreeNode(
+ id="uncategorized",
+ name="Uncategorized",
+ description="Skills recovered by integrity audit after tree construction.",
+ depth=1,
+ parent_id=root.id,
+ )
+ self._assign_skills_to_leaf(fallback_branch, recovered_payloads)
+ root.children.append(fallback_branch)
+
+ @staticmethod
+ def _queue_child_node(child_group: _ChildGroup, *, depth: int) -> _QueuedNode:
+ """Convert a processed child subtree into a queued work item."""
+ return _QueuedNode(
+ node=child_group.node,
+ skills=child_group.skills,
+ depth=depth,
+ parent_context={
+ "name": child_group.node.name,
+ "description": child_group.node.description,
+ },
+ )
+
+ def _process_node(
+ self,
+ node: TreeNode,
+ skills: list[dict],
+ depth: int,
+ parent_context: Optional[dict],
+ verbose: bool = False,
+ ) -> list[_ChildGroup]:
+ expansion_engine = getattr(self, "_expansion_engine", None) or _TreeExpansionEngine(self)
+ return expansion_engine.process_node(
+ node=node,
+ skills=skills,
+ depth=depth,
+ parent_context=parent_context,
+ verbose=verbose,
+ )
+
+ # =========================================================================
+ # Two-phase classification: discover groups -> flat assignment
+ # =========================================================================
+
+ def _assign_skills_to_leaf(self, node: TreeNode, skills: list[dict]) -> None:
+ """Assign skill dicts to a leaf node as Skill objects. Updates progress counter."""
+ for skill_data in skills:
+ node.skills.append(self._skill_from_data(skill_data, path=node.id))
+ # Update leaf skills count (thread-safe)
+ with self._counter_lock:
+ self._leaf_skills += len(skills)
+ if self._progress and self._progress_task is not None:
+ self._progress.update(self._progress_task, leaf=self._leaf_skills, completed=self._leaf_skills)
+
+ @staticmethod
+ def _skill_from_data(skill_data: dict, *, path: str) -> Skill:
+ """Materialize a Skill object from a skill dict."""
+ return Skill(
+ id=skill_data["id"],
+ name=skill_data.get("name", skill_data["id"]),
+ description=skill_data.get("description", ""),
+ path=path,
+ skill_path=skill_data.get("skill_path", ""),
+ content=skill_data.get("content", ""),
+ select_when=skill_data.get("select_when", ""),
+ dont_select_when=skill_data.get("dont_select_when", ""),
+ source_description=skill_data.get("source_description", ""),
+ github_url=skill_data.get("github_url", ""),
+ stars=skill_data.get("stars", 0),
+ is_official=skill_data.get("is_official", False),
+ author=skill_data.get("author", ""),
+ )
+
+ @staticmethod
+ def _skill_to_data(skill: Skill) -> dict:
+ """Convert a Skill object back into a mutable skill dict."""
+ return skill.to_dict(include_content=True)
+
+ def _root_group_definitions(self) -> dict[str, dict[str, str]]:
+ expansion_engine = getattr(self, "_expansion_engine", None) or _TreeExpansionEngine(self)
+ return expansion_engine.root_group_definitions()
+
+ def _create_child_node(
+ self,
+ *,
+ parent: TreeNode,
+ group_id: str,
+ group_data: dict,
+ depth: int,
+ ) -> TreeNode:
+ expansion_engine = getattr(self, "_expansion_engine", None) or _TreeExpansionEngine(self)
+ return expansion_engine.create_child_node(parent=parent, group_id=group_id, group_data=group_data, depth=depth)
+
+ def _build_children_from_groups(
+ self,
+ node: TreeNode,
+ skills: list[dict],
+ groups: dict,
+ depth: int,
+ verbose: bool = False,
+ ) -> list[_ChildGroup]:
+ expansion_engine = getattr(self, "_expansion_engine", None) or _TreeExpansionEngine(self)
+ return expansion_engine.build_children_from_groups(node, skills, groups, depth, verbose)
+
+ def _reassign_skills_to_children(
+ self,
+ unassigned_skills: list[dict],
+ children_to_process: list[_ChildGroup],
+ ) -> tuple[int, list[dict]]:
+ expansion_engine = getattr(self, "_expansion_engine", None) or _TreeExpansionEngine(self)
+ return expansion_engine.reassign_skills_to_children(unassigned_skills, children_to_process)
+
+ def _assign_unassigned_skills(
+ self,
+ *,
+ node: TreeNode,
+ all_skills: list[dict],
+ remaining_skill_map: dict[str, dict],
+ children_to_process: list[_ChildGroup],
+ verbose: bool = False,
+ ) -> None:
+ expansion_engine = getattr(self, "_expansion_engine", None) or _TreeExpansionEngine(self)
+ expansion_engine.assign_unassigned_skills(
+ node=node,
+ all_skills=all_skills,
+ remaining_skill_map=remaining_skill_map,
+ children_to_process=children_to_process,
+ verbose=verbose,
+ )
+
+ def _rewrite_node_label_after_singleton(
+ self,
+ node: TreeNode,
+ children_to_process: list[_ChildGroup],
+ verbose: bool = False,
+ ) -> None:
+ expansion_engine = getattr(self, "_expansion_engine", None) or _TreeExpansionEngine(self)
+ expansion_engine.rewrite_node_label_after_singleton(node, children_to_process, verbose)
+
+ def _postprocess_tree(self, root: TreeNode, verbose: bool = False) -> None:
+ repair_engine = getattr(self, "_repair_engine", None) or _TreeRepairEngine(self)
+ repair_engine.postprocess_tree(root, verbose)
+
+ def _postprocess_node(self, node: TreeNode, verbose: bool = False) -> int:
+ repair_engine = getattr(self, "_repair_engine", None) or _TreeRepairEngine(self)
+ return repair_engine.postprocess_node(node, verbose)
+
+ def _rebalance_child_assignments(self, node: TreeNode, verbose: bool = False) -> int:
+ repair_engine = getattr(self, "_repair_engine", None) or _TreeRepairEngine(self)
+ return repair_engine.rebalance_child_assignments(node, verbose)
+
+ def _collect_subtree_skill_locations(self, node: TreeNode) -> list[tuple[TreeNode, dict]]:
+ repair_engine = getattr(self, "_repair_engine", None) or _TreeRepairEngine(self)
+ return repair_engine.collect_subtree_skill_locations(node)
+
+ def _collect_subtree_skill_dicts(self, node: TreeNode) -> list[dict]:
+ repair_engine = getattr(self, "_repair_engine", None) or _TreeRepairEngine(self)
+ return repair_engine.collect_subtree_skill_dicts(node)
+
+ def _existing_child_groups(self, children: list[TreeNode]) -> list[_ChildGroup]:
+ expansion_engine = getattr(self, "_expansion_engine", None) or _TreeExpansionEngine(self)
+ return expansion_engine.existing_child_groups(children)
+
+ def _choose_child_for_skill(self, skill_data: dict, children: list[TreeNode]) -> TreeNode:
+ """Choose the best direct child for a skill, falling back to the largest subtree."""
+ child_by_id = {child.id: child for child in children}
+ groups = {
+ child.id: {
+ "name": child.name,
+ "description": child.description,
+ "select_when": child.select_when,
+ "dont_select_when": child.dont_select_when,
+ }
+ for child in children
+ }
+ assignment = self._classify_skills_single(
+ [skill_data],
+ groups,
+ verbose=False,
+ is_retry=True,
+ )
+ child_id = assignment.get(str(skill_data.get("id", "")).strip())
+ if child_id in child_by_id:
+ return child_by_id[child_id]
+ return max(children, key=lambda child: child.count_all_skills())
+
+ def _insert_skill_into_subtree(self, node: TreeNode, skill_data: dict) -> None:
+ """Insert a skill into the best-fitting location inside an existing subtree."""
+ skill_id = str(skill_data.get("id", "")).strip()
+ if not skill_id:
+ return
+
+ if node.is_leaf or not node.children:
+ if any(skill.id == skill_id for skill in node.skills):
+ return
+ node.skills.append(self._skill_from_data(skill_data, path=node.id))
+ return
+
+ target_child = self._choose_child_for_skill(skill_data, node.children)
+ self._insert_skill_into_subtree(target_child, skill_data)
+
+ def _prune_empty_children(self, node: TreeNode) -> int:
+ """Remove empty child subtrees after skill moves."""
+ removed = 0
+ kept_children: list[TreeNode] = []
+ for child in node.children:
+ removed += self._prune_empty_children(child)
+ if child.children:
+ if child.count_all_skills() <= 0:
+ removed += 1
+ continue
+ elif not child.skills:
+ removed += 1
+ continue
+ kept_children.append(child)
+ node.children = kept_children
+ return removed
+
+ def _normalize_to_equivalence_groups(self, root: TreeNode, verbose: bool = False) -> None:
+ repair_engine = getattr(self, "_repair_engine", None) or _TreeRepairEngine(self)
+ repair_engine.normalize_to_equivalence_groups(root, verbose)
+
+ @staticmethod
+ def _is_second_leaf_node(node: TreeNode) -> bool:
+ """Second-leaf node: has children and all children are leaf nodes."""
+ return _TreeRepairEngine.is_second_leaf_node(node)
+
+ def _split_second_leaf_node_into_equiv_groups(
+ self,
+ parent_node: TreeNode,
+ second_leaf_node: TreeNode,
+ verbose: bool = False,
+ ) -> list[TreeNode]:
+ repair_engine = getattr(self, "_repair_engine", None) or _TreeRepairEngine(self)
+ return repair_engine.split_second_leaf_node_into_equiv_groups(parent_node, second_leaf_node, verbose)
+
+ def _discover_equivalence_groups(
+ self,
+ second_leaf_node: TreeNode,
+ leaf_children: list[TreeNode],
+ verbose: bool = False,
+ ) -> dict:
+ """Ask LLM to partition second-leaf children into equivalence groups."""
+ leaf_lines = []
+ for leaf in leaf_children:
+ sample_skill_ids = ", ".join(skill.id for skill in leaf.skills[:5]) or "(none)"
+ leaf_lines.append(
+ f"- id: {leaf.id}\n"
+ f" name: {leaf.name}\n"
+ f" description: {leaf.description or '(no description)'}\n"
+ f" select_when: {leaf.select_when or ''}\n"
+ f" dont_select_when: {leaf.dont_select_when or ''}\n"
+ f" sample_skill_ids: {sample_skill_ids}"
+ )
+
+ prompt = EQUIVALENCE_GROUPING_PROMPT.format(
+ parent_id=second_leaf_node.id,
+ parent_name=second_leaf_node.name,
+ parent_description=second_leaf_node.description or "(no description)",
+ leaf_nodes="\n".join(leaf_lines),
+ )
+ result = self._call_llm_json(prompt)
+ groups = result.get("groups", {})
+ if not isinstance(groups, dict):
+ if verbose:
+ console.print(f"[yellow] Equivalence grouping failed for '{second_leaf_node.id}'[/yellow]")
+ return {}
+ return groups
+
+ def _normalize_equivalence_groups(self, leaf_children: list[TreeNode], groups: dict) -> list[dict]:
+ """
+ Normalize and repair LLM equivalence groups.
+
+ Guarantees:
+ - Every original leaf appears in exactly one output group
+ - Unknown leaf IDs are ignored
+ - Empty groups are removed
+ """
+ leaf_map = {leaf.id: leaf for leaf in leaf_children}
+ assigned: set[str] = set()
+ normalized: list[dict] = []
+
+ for group_id, group_data in self._iter_group_items(groups):
+ if not isinstance(group_data, dict):
+ continue
+ raw_leaf_ids = group_data.get("leaf_ids", [])
+ if not isinstance(raw_leaf_ids, list):
+ raw_leaf_ids = []
+ leaf_nodes = []
+ for leaf_id in raw_leaf_ids:
+ lid = str(leaf_id).strip()
+ if not lid or lid in assigned:
+ continue
+ leaf = leaf_map.get(lid)
+ if leaf is None:
+ continue
+ assigned.add(lid)
+ leaf_nodes.append(leaf)
+ if not leaf_nodes:
+ continue
+ normalized.append(
+ {
+ "id": self._build_equivalence_group_id(
+ group_id=str(group_id).strip(),
+ group_name=str(group_data.get("name") or "").strip(),
+ fallback="equiv-group",
+ ),
+ "name": str(group_data.get("name") or group_id),
+ "description": str(group_data.get("description") or ""),
+ "select_when": str(group_data.get("select_when") or ""),
+ "dont_select_when": str(group_data.get("dont_select_when") or ""),
+ "leaf_nodes": leaf_nodes,
+ }
+ )
+
+ # Recovery: assign missing leaves conservatively.
+ missing = [leaf for leaf in leaf_children if leaf.id not in assigned]
+ for leaf in missing:
+ normalized.append(
+ {
+ "id": f"equiv-{self._slug_term(leaf.id, fallback='leaf')}",
+ "name": leaf.name or leaf.id,
+ "description": leaf.description or "Equivalent capability group.",
+ "select_when": leaf.select_when,
+ "dont_select_when": leaf.dont_select_when,
+ "leaf_nodes": [leaf],
+ }
+ )
+
+ # Keep deterministic order.
+ for item in normalized:
+ item["leaf_nodes"] = sorted(item["leaf_nodes"], key=lambda leaf: leaf.id)
+ normalized.sort(key=lambda item: str(item.get("id", "")))
+ return normalized
+
+ def _build_equivalence_group_id(self, *, group_id: str, group_name: str, fallback: str) -> str:
+ """
+ Build a stable, readable node id for equivalence groups.
+
+ LLMs often emit placeholder ids like G1/G2. We prefer semantic ids derived
+ from the group name and only fall back to the raw id when it is informative.
+ """
+ raw_name = str(group_name or "").strip()
+ raw_id = str(group_id or "").strip()
+ generic_id = bool(re.fullmatch(r"g\d+(?:-\d+)?", raw_id.lower()))
+
+ if raw_name:
+ return self._slug_term(raw_name, fallback=fallback)
+ if raw_id and not generic_id:
+ return self._slug_term(raw_id, fallback=fallback)
+ return self._slug_term(fallback, fallback="equiv-group")
+
+ def _sorted_skills(self, skills: list[dict]) -> list[dict]:
+ return self._grouping_engine.sorted_skills(skills)
+
+ def _iter_group_items(self, groups: dict):
+ return self._grouping_engine.iter_group_items(groups)
+
+ def _normalize_prompt_for_fingerprint(self, prompt: str) -> str:
+ """Normalize prompt text to keep fingerprint stable across runs."""
+ return self._llm_runtime.normalize_prompt_for_fingerprint(prompt)
+
+ def _prompt_fingerprint(self, prompt: str) -> str:
+ """Compute deterministic prompt fingerprint."""
+ return self._llm_runtime.prompt_fingerprint(prompt)
+
+ def _sampling_seed(self, parent_context: Optional[dict], skills_count: int) -> int:
+ return self._grouping_engine.sampling_seed(parent_context, skills_count)
+
+ def _extract_cache_hit(self, response) -> Optional[bool]:
+ """Best-effort extraction of cache hit status from response metadata."""
+ return self._llm_runtime.extract_cache_hit(response)
+
+ def _extract_cache_hit_from_mapping(self, mapping: dict) -> Optional[bool]:
+ """Parse cache hit from a mapping (recursively over nested dicts)."""
+ return self._llm_runtime.extract_cache_hit_from_mapping(mapping)
+
+ def _record_cache_observation(self, cache_hit: Optional[bool]) -> None:
+ """Aggregate cache hit/miss counters."""
+ self._llm_runtime.record_cache_observation(cache_hit)
+
+ def _print_cache_stats(self) -> None:
+ """Print cache observability metrics for intuitive build feedback."""
+ self._llm_runtime.print_cache_stats()
+
+ def _build_groups_from_assignments(self, groups: dict, assignments: dict) -> dict:
+ return self._grouping_engine.build_groups_from_assignments(groups, assignments)
+
+ def _classify_skills(self, skills: list[dict], groups: dict, verbose: bool = False) -> dict:
+ return self._grouping_engine.classify_skills(skills, groups, verbose=verbose)
+
+ def _classify_skills_single(
+ self,
+ skills: list[dict],
+ groups: dict,
+ verbose: bool = False,
+ is_retry: bool = False,
+ ) -> dict:
+ return self._grouping_engine.classify_skills_single(
+ skills,
+ groups,
+ verbose=verbose,
+ is_retry=is_retry,
+ )
+
+ def _batched_classify_skills(
+ self,
+ skills: list[dict],
+ groups: dict,
+ batch_size: int,
+ verbose: bool = False,
+ ) -> dict:
+ return self._grouping_engine.batched_classify_skills(
+ skills,
+ groups,
+ batch_size=batch_size,
+ verbose=verbose,
+ )
+
+ def _validate_and_recover(
+ self,
+ skills: list[dict],
+ groups: dict,
+ assignments: dict,
+ verbose: bool = False,
+ ) -> dict:
+ return self._grouping_engine.validate_and_recover(
+ skills,
+ groups,
+ assignments,
+ verbose=verbose,
+ )
+
+ def _discover_groups(
+ self,
+ skills: list[dict],
+ parent_context: Optional[dict],
+ verbose: bool = False,
+ ) -> dict:
+ return self._grouping_engine.discover_groups(skills, parent_context, verbose=verbose)
+
+ def _merge_group_definitions(self, all_group_defs: list[dict], verbose: bool = False) -> dict:
+ return self._grouping_engine.merge_group_definitions(all_group_defs, verbose=verbose)
+
+ def _split_skills(
+ self,
+ skills: list[dict],
+ parent_context: Optional[dict],
+ verbose: bool = False,
+ ) -> dict:
+ return self._grouping_engine.split_skills(skills, parent_context, verbose=verbose)
+
+ def _split_skills_single(
+ self,
+ skills: list[dict],
+ parent_context: Optional[dict],
+ verbose: bool = False,
+ ) -> dict:
+ return self._grouping_engine.split_skills_single(skills, parent_context, verbose=verbose)
+
+ def _batched_split_skills(
+ self,
+ skills: list[dict],
+ parent_context: Optional[dict],
+ batch_size: int,
+ verbose: bool = False,
+ ) -> dict:
+ return self._grouping_engine.batched_split_skills(
+ skills,
+ parent_context,
+ batch_size=batch_size,
+ verbose=verbose,
+ )
+
+ def _call_llm(self, prompt: str, is_retry: bool = False, retry_left: int | None = None) -> str:
+ """Call LLM and return response."""
+ return self._llm_runtime.call_llm(prompt, is_retry=is_retry, retry_left=retry_left)
+
+ def _call_llm_json(self, prompt: str, max_retries: int = 3, is_retry: bool = False) -> dict:
+ """Call LLM expecting a JSON dict response, with retry on format errors."""
+ return self._llm_runtime.call_llm_json(prompt, max_retries=max_retries, is_retry=is_retry)
+
+ def _format_skills_list(self, skills: list[dict]) -> str:
+ return self._grouping_engine.format_skills_list(skills)
+
+ def _tree_to_dict(self, tree: TreeNode) -> dict:
+ writer = getattr(self, "_preset_writer", None)
+ if writer is None:
+ writer = _TreePresetWriter(self)
+ converted = writer.tree_to_dict(tree)
+ return dict(converted)
+
+ def _tree_to_orchestrator_preset(self, tree_dict: dict) -> dict:
+ return self._preset_writer.tree_to_orchestrator_preset(tree_dict)
+
+ def _flatten_capability_tree(self, tree: dict) -> list[dict]:
+ return self._preset_writer.flatten_capability_tree(tree)
+
+ def _rename_leaf_nodes(self, nodes: list[dict]) -> list[dict]:
+ return self._preset_writer.rename_leaf_nodes(nodes)
+
+ def _compact_leaf_cid_seed(self, *, worker_id: str, display_name: str, old_term: str) -> str:
+ preset_writer = getattr(self, "_preset_writer", None)
+ if preset_writer is None:
+ preset_writer = _TreePresetWriter(self)
+ return preset_writer.compact_leaf_cid_seed(
+ worker_id=worker_id,
+ display_name=display_name,
+ old_term=old_term,
+ )
+
+ def _cid_term(self, value: str, fallback: str = "Node") -> str:
+ preset_writer = getattr(self, "_preset_writer", None)
+ if preset_writer is None:
+ preset_writer = _TreePresetWriter(self)
+ return preset_writer.cid_term(value, fallback=fallback)
+
+ @staticmethod
+ def _build_routing_policy(nodes: list[dict]) -> str:
+ root_entries = sorted(
+ [item for item in nodes if "." not in str(item.get("cid", ""))], key=lambda item: str(item.get("cid", ""))
+ )
+ lines = [
+ "Route by descending the node tree one level at a time.",
+ "Treat a user request as potentially multi-step unless the latest observation already fully "
+ "satisfies every explicit requirement.",
+ "Prefer leaves whose descriptions best match the next unmet sub-problem in the user request.",
+ "After a worker returns, check whether unmet requirements still remain; if they do, continue "
+ "routing instead of finishing early.",
+ "Do not jump to User.Final after a single worker call when the user asked for multiple actions, "
+ "dependencies, or deliverables.",
+ "Use worker observations as intermediate state: one skill may gather facts or create prerequisites "
+ "for a later skill.",
+ "When multiple branches overlap, use the child descriptions as the local decision surface.",
+ "Choose User.Final only when the latest observation set is sufficient to answer the whole user "
+ "request, not just one subtask.",
+ ]
+ for item in root_entries:
+ lines.append(f"If the request matches '{item['cid']}', continue under that branch.")
+ return "\n".join(f"- {line}" for line in lines)
+
+ def _build_tree_sketch(self, nodes: list[dict]) -> str:
+ return self._preset_writer.build_tree_sketch(nodes)
+
+ def _slug_term(self, value: str, fallback: str = "node") -> str:
+ preset_writer = getattr(self, "_preset_writer", None)
+ if preset_writer is None:
+ preset_writer = _TreePresetWriter(self)
+ return preset_writer.slug_term(value, fallback=fallback)
+
+ @staticmethod
+ def _join_cid(parent: str, child: str) -> str:
+ return _TreePresetWriter.join_cid(parent, child)
+
+ @staticmethod
+ def _parent_cid(cid: str) -> str:
+ return _TreePresetWriter.parent_cid(cid)
+
+ def _unique_child_cid(self, parent_cid: str, segment: str, used: set[str]) -> str:
+ return self._preset_writer.unique_child_cid(parent_cid, segment, used)
+
+ def _extract_keywords(self, *values: str, limit: int = 8) -> list[str]:
+ return self._preset_writer.extract_keywords(*values, limit=limit)
+
+ def _node_to_dict(self, node: TreeNode) -> dict:
+ writer = getattr(self, "_preset_writer", None)
+ if writer is None:
+ writer = _TreePresetWriter(self)
+ payload = writer.node_to_dict(node)
+ return payload.copy()
+
+ def _print_tree(self, tree_dict: dict) -> None:
+ """Print tree structure using rich (supports arbitrary depth)."""
+ self._preset_writer.print_tree(tree_dict)
+
+ def _add_node_to_rich_tree(self, parent_branch, node_dict: dict) -> None:
+ """Recursively add nodes to rich tree."""
+ self._preset_writer.add_node_to_rich_tree(parent_branch, node_dict)
+
+ def _count_skills_in_dict(self, node_dict: dict) -> int:
+ """Recursively count skills in a node dict."""
+ return self._preset_writer.count_skills_in_dict(node_dict)
+
+
+# Convenience function
+def build_tree(*args, options: BuildTreeOptions | None = None, **kwargs) -> dict:
+ """Build capability tree."""
+ if options is not None and (args or kwargs):
+ raise TypeError("build_tree accepts either options or direct arguments, not both")
+ if options is None:
+ if len(args) > len(_BUILD_TREE_POSITIONAL_FIELDS):
+ raise TypeError(f"build_tree expected at most {len(_BUILD_TREE_POSITIONAL_FIELDS)} positional arguments")
+ for field_name, value in zip(_BUILD_TREE_POSITIONAL_FIELDS, args):
+ if field_name in kwargs:
+ raise TypeError(f"build_tree got multiple values for argument '{field_name}'")
+ kwargs[field_name] = value
+ options = BuildTreeOptions(**kwargs)
+
+ builder = TreeBuilder(
+ options.skills_dir,
+ options.output_path,
+ config=options.config,
+ manager_config=options.manager_config,
+ client=options.client,
+ model=options.model,
+ api_key=options.api_key,
+ base_url=options.base_url,
+ llm_seed=options.llm_seed,
+ max_workers=options.max_workers,
+ display_skills_dir=options.display_skills_dir,
+ item_type=options.item_type,
+ skill_entries=options.skill_entries,
+ )
+ return builder.build(
+ verbose=options.verbose,
+ show_tree=options.show_tree,
+ generate_html=options.generate_html,
+ )
diff --git a/jiuwenswarm/symphony/indexing/tree/expansion.py b/jiuwenswarm/symphony/indexing/tree/expansion.py
new file mode 100644
index 0000000000..33f96b91bc
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/expansion.py
@@ -0,0 +1,341 @@
+from __future__ import annotations
+
+from typing import Optional, TYPE_CHECKING
+
+from shared.rich_compat import Console, Panel
+
+from .prompts import NODE_LABEL_REWRITE_PROMPT
+from .schema import FIXED_ROOT_CATEGORIES, TreeNode
+from .types import ChildGroup
+
+if TYPE_CHECKING:
+ from .builder import TreeBuilder
+
+
+console = Console()
+
+
+def _builder_attr(builder: "TreeBuilder", name: str):
+ return getattr(builder, name)
+
+
+def _builder_call(builder: "TreeBuilder", name: str, *args, **kwargs):
+ return getattr(builder, name)(*args, **kwargs)
+
+
+class TreeExpansionEngine:
+ """Owns node splitting, child creation, and unassigned-skill recovery."""
+
+ def __init__(self, builder: "TreeBuilder") -> None:
+ self._builder = builder
+
+ def process_node(
+ self,
+ *,
+ node: TreeNode,
+ skills: list[dict],
+ depth: int,
+ parent_context: Optional[dict],
+ verbose: bool = False,
+ ) -> list[ChildGroup]:
+ builder = self._builder
+ self._update_progress(node_id=node.id, skill_count=len(skills), depth=depth)
+
+ configured_groups = self._configured_groups_for_node(node=node)
+ if not configured_groups and self._should_force_leaf(depth=depth, skill_count=len(skills)):
+ self._emit_leaf(node, skills, verbose=verbose)
+ return []
+
+ if configured_groups:
+ grouped = self._classify_configured_groups(
+ skills,
+ configured_groups,
+ node_name=node.name,
+ verbose=verbose,
+ )
+ else:
+ grouped = _builder_call(builder, "_split_skills", skills, parent_context, verbose)
+
+ if not grouped:
+ self._emit_grouping_failure(node, skill_count=len(skills), depth_reached=depth >= builder.config.max_depth)
+ self._emit_leaf(node, skills, verbose=verbose)
+ return []
+ return self.build_children_from_groups(node, skills, grouped, depth, verbose)
+
+ def _update_progress(self, *, node_id: str, skill_count: int, depth: int) -> None:
+ builder = self._builder
+ progress = _builder_attr(builder, "_progress")
+ progress_task = _builder_attr(builder, "_progress_task")
+ if progress and progress_task is not None:
+ progress.update(
+ progress_task,
+ description=f"Layer {depth}: {node_id} ({skill_count} skills)",
+ )
+
+ def _should_force_leaf(self, *, depth: int, skill_count: int) -> bool:
+ builder = self._builder
+ return skill_count <= builder.config.max_skills_per_node or depth >= builder.config.max_depth
+
+ def _emit_leaf(self, node: TreeNode, skills: list[dict], *, verbose: bool) -> None:
+ _builder_call(self._builder, "_assign_skills_to_leaf", node, skills)
+ if verbose:
+ console.print(f"[dim] Finalized leaf '{node.id}' with {len(skills)} skills[/dim]")
+
+ def _classify_root(self, skills: list[dict], *, verbose: bool) -> dict:
+ return self._classify_configured_groups(
+ skills,
+ self.root_group_definitions(),
+ node_name="Root",
+ verbose=verbose,
+ )
+
+ def _classify_configured_groups(
+ self,
+ skills: list[dict],
+ groups: dict,
+ *,
+ node_name: str,
+ verbose: bool,
+ ) -> dict:
+ builder = self._builder
+ if verbose:
+ console.print(f"[cyan]Routing {len(skills)} skills into configured categories for {node_name}[/cyan]")
+ initial = _builder_call(builder, "_classify_skills", skills, groups, verbose)
+ repaired = _builder_call(builder, "_validate_and_recover", skills, groups, initial, verbose)
+ return _builder_call(builder, "_build_groups_from_assignments", groups, repaired)
+
+ def _configured_groups_for_node(self, *, node: TreeNode) -> dict | None:
+ if node.id == "root":
+ return self.root_group_definitions()
+ configured_children = getattr(node, "_configured_children", None)
+ return configured_children if isinstance(configured_children, dict) and configured_children else None
+
+ @staticmethod
+ def _emit_grouping_failure(node: TreeNode, *, skill_count: int, depth_reached: bool) -> None:
+ if depth_reached:
+ title = "[bold red]Max Depth Reached[/bold red]"
+ body = (
+ f"[bold red]Reached max depth at '{node.id}' with {skill_count} skills still attached.[/bold red]\n"
+ "The subtree will stay collapsed into one leaf."
+ )
+ else:
+ title = "[bold red]Grouping Failed[/bold red]"
+ body = (
+ f"[bold red]Could not derive stable child groups for '{node.id}' ({skill_count} skills).[/bold red]\n"
+ "The subtree will stay collapsed into one fallback leaf."
+ )
+ console.print(Panel(body, title=title, border_style="red"))
+
+ def root_group_definitions(self) -> dict[str, dict]:
+ categories = self._builder.config.root_categories or FIXED_ROOT_CATEGORIES
+ root_groups: dict[str, dict] = {}
+ for category_id, payload in categories.items():
+ root_groups[category_id] = {
+ "name": payload.get("name", category_id),
+ "description": payload.get("description", ""),
+ "select_when": payload.get("select_when", ""),
+ "dont_select_when": payload.get("dont_select_when", ""),
+ }
+ children = payload.get("children")
+ if children:
+ root_groups[category_id]["children"] = children
+ return root_groups
+
+ @staticmethod
+ def create_child_node(*, parent: TreeNode, group_id: str, group_data: dict, depth: int) -> TreeNode:
+ child_node = TreeNode(
+ id=group_id,
+ name=group_data.get("name", group_id),
+ description=group_data.get("description", ""),
+ select_when=group_data.get("select_when", ""),
+ dont_select_when=group_data.get("dont_select_when", ""),
+ depth=depth,
+ parent_id=parent.id,
+ )
+ parent.children.append(child_node)
+ return child_node
+
+ def build_children_from_groups(
+ self,
+ node: TreeNode,
+ skills: list[dict],
+ groups: dict,
+ depth: int,
+ verbose: bool = False,
+ ) -> list[ChildGroup]:
+ builder = self._builder
+ skill_map = {s["id"]: s for s in skills}
+ children_to_process: list[ChildGroup] = []
+
+ for group_id, group_data in groups.items():
+ child_skill_ids = group_data.get("skill_ids", [])
+ child_skills = [skill_map[sid] for sid in child_skill_ids if sid in skill_map]
+ if not child_skills:
+ continue
+
+ child_node = self.create_child_node(
+ parent=node,
+ group_id=group_id,
+ group_data=group_data,
+ depth=depth + 1,
+ )
+ configured_children = group_data.get("children")
+ if configured_children:
+ setattr(child_node, "_configured_children", configured_children)
+ for sid in child_skill_ids:
+ skill_map.pop(sid, None)
+ children_to_process.append(
+ ChildGroup(
+ node=child_node,
+ skills=child_skills,
+ configured_children=configured_children,
+ )
+ )
+
+ if skill_map:
+ if children_to_process:
+ self.assign_unassigned_skills(
+ node=node,
+ all_skills=skills,
+ remaining_skill_map=skill_map,
+ children_to_process=children_to_process,
+ verbose=verbose,
+ )
+ else:
+ _builder_call(builder, "_assign_skills_to_leaf", node, skills)
+ return []
+
+ return children_to_process
+
+ def reassign_skills_to_children(
+ self,
+ unassigned_skills: list[dict],
+ children_to_process: list[ChildGroup],
+ ) -> tuple[int, list[dict]]:
+ builder = self._builder
+ if not unassigned_skills or not children_to_process:
+ return 0, unassigned_skills
+
+ groups = {
+ child_group.node.id: {
+ "name": child_group.node.name,
+ "description": child_group.node.description,
+ "select_when": child_group.node.select_when,
+ "dont_select_when": child_group.node.dont_select_when,
+ }
+ for child_group in children_to_process
+ }
+ assignments = _builder_call(
+ builder,
+ "_classify_skills_single",
+ _builder_call(builder, "_sorted_skills", unassigned_skills),
+ groups,
+ verbose=False,
+ is_retry=True,
+ )
+ if not assignments:
+ return 0, unassigned_skills
+
+ child_idx = {child_group.node.id: idx for idx, child_group in enumerate(children_to_process)}
+ reassigned_count = 0
+ remaining_unassigned = []
+ for skill in unassigned_skills:
+ group_id = assignments.get(skill["id"])
+ idx = child_idx.get(group_id)
+ if idx is None:
+ remaining_unassigned.append(skill)
+ continue
+ children_to_process[idx].skills.append(skill)
+ reassigned_count += 1
+ return reassigned_count, remaining_unassigned
+
+ def assign_unassigned_skills(
+ self,
+ *,
+ node: TreeNode,
+ all_skills: list[dict],
+ remaining_skill_map: dict[str, dict],
+ children_to_process: list[ChildGroup],
+ verbose: bool = False,
+ ) -> None:
+ unassigned = list(remaining_skill_map.values())
+ reassigned_count, unassigned = self.reassign_skills_to_children(unassigned, children_to_process)
+ if unassigned:
+ largest_idx = max(range(len(children_to_process)), key=lambda i: len(children_to_process[i].skills))
+ largest_child = children_to_process[largest_idx]
+ unassigned_ratio = len(unassigned) / len(all_skills) if all_skills else 0
+ if unassigned_ratio > 0.1:
+ console.print(
+ Panel(
+ f"[bold red]{len(unassigned)}/{len(all_skills)} skills ({unassigned_ratio:.0%}) unassigned "
+ f"at node '{node.id}'[/bold red]\n"
+ f"Dumping into '{largest_child.node.id}'.",
+ title="[bold red]High Unassigned Skill Count[/bold red]",
+ border_style="red",
+ )
+ )
+ elif verbose:
+ console.print(f"[yellow] {len(unassigned)} unassigned skills -> {largest_child.node.id}[/yellow]")
+ largest_child.skills.extend(unassigned)
+ elif verbose and reassigned_count > 0:
+ console.print(f"[dim] Reassigned {reassigned_count} skipped skills under '{node.id}'[/dim]")
+
+ def rewrite_node_label_after_singleton(
+ self,
+ node: TreeNode,
+ children_to_process: list[ChildGroup],
+ verbose: bool = False,
+ ) -> None:
+ builder = self._builder
+ if not children_to_process:
+ return
+ ranked_children = sorted(children_to_process, key=lambda item: (-len(item.skills), item.node.id))
+ summary_lines = [self._child_summary_line(child_group) for child_group in ranked_children]
+
+ prompt = NODE_LABEL_REWRITE_PROMPT.format(
+ node_id=node.id,
+ node_name=node.name,
+ node_description=node.description or "(no description)",
+ children_summary="\n".join(summary_lines),
+ )
+ result = _builder_call(builder, "_call_llm_json", prompt)
+ new_name = str(result.get("name", "")).strip()
+ new_description = str(result.get("description", "")).strip()
+ new_select_when = str(result.get("select_when", "")).strip()
+ new_dont_select_when = str(result.get("dont_select_when", "")).strip()
+ if not new_name or not new_description:
+ if verbose:
+ console.print(f"[yellow] Failed to rewrite label for '{node.id}', keeping original[/yellow]")
+ return
+ node.name = new_name
+ node.description = new_description
+ node.select_when = new_select_when
+ node.dont_select_when = new_dont_select_when
+ if verbose:
+ console.print(f"[dim] Rewrote node label for '{node.id}' after singleton reassignment[/dim]")
+
+ @staticmethod
+ def _child_summary_line(child_group: ChildGroup) -> str:
+ child = child_group.node
+ sample_ids = ", ".join(skill["id"] for skill in child_group.skills[:5]) or "(none)"
+ description = child.description or "(no description)"
+ select_when = child.select_when or ""
+ dont_select_when = child.dont_select_when or ""
+ rules = []
+ if select_when:
+ rules.append(f"select_when: {select_when}")
+ if dont_select_when:
+ rules.append(f"dont_select_when: {dont_select_when}")
+ return (
+ f"- {child.id} ({len(child_group.skills)} skills)\n"
+ f" label: {child.name}\n"
+ f" summary: {description}\n" + (f" {'; '.join(rules)}\n" if rules else "") + f" sample_ids: {sample_ids}"
+ )
+
+ def existing_child_groups(self, children: list[TreeNode]) -> list[ChildGroup]:
+ builder = self._builder
+ return [
+ ChildGroup(node=child, skills=_builder_call(builder, "_collect_subtree_skill_dicts", child))
+ for child in children
+ if child.count_all_skills() > 0
+ ]
diff --git a/jiuwenswarm/symphony/indexing/tree/grouping.py b/jiuwenswarm/symphony/indexing/tree/grouping.py
new file mode 100644
index 0000000000..ce340cce0f
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/grouping.py
@@ -0,0 +1,400 @@
+from __future__ import annotations
+
+import hashlib
+import random
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from typing import Optional, TYPE_CHECKING
+
+from shared.rich_compat import Console, Panel
+
+from .prompts import GROUP_DISCOVERY_PROMPT, GROUP_MERGE_PROMPT, SKILL_ASSIGNMENT_PROMPT
+from .schema import SKILL_DESCRIPTION_MAX_LENGTH
+
+if TYPE_CHECKING:
+ from .builder import TreeBuilder
+
+
+console = Console()
+
+
+def _builder_attr(builder: "TreeBuilder", name: str):
+ return getattr(builder, name)
+
+
+def _builder_call(builder: "TreeBuilder", name: str, *args, **kwargs):
+ return getattr(builder, name)(*args, **kwargs)
+
+
+class TreeGroupingEngine:
+ """Owns discovery, assignment, recovery, and batching for tree grouping."""
+
+ def __init__(self, builder: "TreeBuilder") -> None:
+ self._builder = builder
+
+ @staticmethod
+ def sorted_skills(skills: list[dict]) -> list[dict]:
+ return sorted(skills, key=lambda item: (str(item.get("id", "")), str(item.get("name", ""))))
+
+ @staticmethod
+ def iter_group_items(groups: dict):
+ ordered_ids = sorted(str(group_id) for group_id in groups.keys())
+ return ((group_id, groups[group_id]) for group_id in ordered_ids)
+
+ def sampling_seed(self, parent_context: Optional[dict], skills_count: int) -> int:
+ builder = self._builder
+ parent = parent_context or {}
+ payload = "|".join(
+ [
+ str(_builder_attr(builder, "_discovery_seed")),
+ str(parent.get("name", "")),
+ str(parent.get("description", "")),
+ str(skills_count),
+ ]
+ )
+ return int(hashlib.sha256(payload.encode("utf-8")).hexdigest()[:8], 16)
+
+ def format_skills_list(self, skills: list[dict]) -> str:
+ rows: list[str] = []
+ for entry in self.sorted_skills(skills):
+ skill_id = str(entry.get("id", "")).strip()
+ skill_name = str(entry.get("name", skill_id)).strip() or skill_id
+ raw_description = str(entry.get("description", "") or "")
+ description = raw_description[:SKILL_DESCRIPTION_MAX_LENGTH]
+ if len(raw_description) > SKILL_DESCRIPTION_MAX_LENGTH:
+ description = description.rstrip() + "..."
+ rows.append(f"- {skill_id}: {skill_name}")
+ if description:
+ rows.append(f" {description}")
+ return "\n".join(rows)
+
+ def build_groups_from_assignments(self, groups: dict, assignments: dict) -> dict:
+ grouped_skill_ids: dict[str, list[str]] = {}
+ for skill_id, group_id in assignments.items():
+ grouped_skill_ids.setdefault(group_id, []).append(skill_id)
+
+ result: dict[str, dict] = {}
+ for group_id, payload in self.iter_group_items(groups):
+ skill_ids = grouped_skill_ids.get(group_id, [])
+ skill_ids = sorted(skill_ids)
+ if not skill_ids:
+ continue
+ result[group_id] = {
+ "name": payload.get("name", group_id),
+ "description": payload.get("description", ""),
+ "select_when": payload.get("select_when", ""),
+ "dont_select_when": payload.get("dont_select_when", ""),
+ "skill_ids": skill_ids,
+ }
+ children = payload.get("children")
+ if children:
+ result[group_id]["children"] = children
+ return result
+
+ def classify_skills(self, skills: list[dict], groups: dict, verbose: bool = False) -> dict:
+ ordered = self.sorted_skills(skills)
+ manager_config = _builder_attr(self._builder, "_manager_config")
+ cfg_cap = int(getattr(manager_config.build, "classify_batch_cap", 20) or 20)
+ batch_size = min(_builder_call(self._builder, "_auto_batch_size"), max(1, cfg_cap))
+ if len(ordered) <= batch_size:
+ return self.classify_skills_single(ordered, groups, verbose=verbose)
+ return self.batched_classify_skills(ordered, groups, batch_size=batch_size, verbose=verbose)
+
+ def classify_skills_single(
+ self,
+ skills: list[dict],
+ groups: dict,
+ verbose: bool = False,
+ is_retry: bool = False,
+ ) -> dict:
+ del verbose
+ group_lines = []
+ for group_id, payload in self.iter_group_items(groups):
+ group_lines.append(f"- {group_id}: {payload.get('name', group_id)}")
+ description = str(payload.get("description", "") or "").strip()
+ select_when = str(payload.get("select_when", "") or "").strip()
+ dont_select_when = str(payload.get("dont_select_when", "") or "").strip()
+ if description:
+ group_lines.append(f" Description: {description}")
+ if select_when:
+ group_lines.append(f" Select when: {select_when}")
+ if dont_select_when:
+ group_lines.append(f" Don't select when: {dont_select_when}")
+ prompt = SKILL_ASSIGNMENT_PROMPT.format(
+ groups_list="\n".join(group_lines),
+ skills_list=self.format_skills_list(skills),
+ )
+ response = _builder_call(self._builder, "_call_llm_json", prompt, is_retry=is_retry)
+ raw_assignments = response.get("assignments", {}) if isinstance(response, dict) else {}
+ valid_groups = {str(group_id) for group_id in groups.keys()}
+ valid_skill_ids = {str(item.get("id", "")).strip() for item in skills}
+
+ cleaned: dict[str, str] = {}
+ for skill_id, group_id in raw_assignments.items():
+ skill_key = str(skill_id).strip()
+ group_key = self._normalize_group_id(group_id, valid_groups)
+ if skill_key in valid_skill_ids and group_key in valid_groups:
+ cleaned[skill_key] = group_key
+ return cleaned
+
+ def batched_classify_skills(
+ self,
+ skills: list[dict],
+ groups: dict,
+ *,
+ batch_size: int,
+ verbose: bool = False,
+ ) -> dict:
+ del verbose
+ partitions = self._partition_skills(skills, batch_size)
+ assignments: dict[str, str] = {}
+ max_workers = self._nested_pool_size(len(partitions))
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ jobs = self._submit_assignment_jobs(executor, partitions, groups)
+ for future in as_completed(jobs):
+ try:
+ assignments.update(future.result())
+ except Exception as exc:
+ console.print(f"[red]Classification batch failed: {exc}[/red]")
+ return assignments
+
+ @staticmethod
+ def _partition_skills(skills: list[dict], batch_size: int) -> list[list[dict]]:
+ windows: list[list[dict]] = []
+ cursor = 0
+ while cursor < len(skills):
+ windows.append(skills[cursor:cursor + batch_size])
+ cursor += batch_size
+ return windows
+
+ def _submit_assignment_jobs(self, executor, partitions: list[list[dict]], groups: dict):
+ futures = []
+ for batch in partitions:
+ futures.append(executor.submit(self.classify_skills_single, batch, groups))
+ return futures
+
+ def validate_and_recover(
+ self,
+ skills: list[dict],
+ groups: dict,
+ assignments: dict,
+ verbose: bool = False,
+ ) -> dict:
+ del verbose
+ expected = {str(item.get("id", "")).strip() for item in skills}
+ assigned = set(assignments.keys())
+ missing = expected - assigned
+ if not missing:
+ return assignments
+
+ if not assignments:
+ console.print(
+ Panel(
+ f"[bold red]Classification produced no usable assignments for {len(skills)} skills.[/bold red]",
+ title="[bold red]Classification Failed[/bold red]",
+ border_style="red",
+ )
+ )
+ return assignments
+
+ if len(missing) <= max(1, len(skills) // 2):
+ retry_inputs = [item for item in self.sorted_skills(skills) if str(item.get("id", "")).strip() in missing]
+ if retry_inputs:
+ retry_result = self.classify_skills_single(retry_inputs, groups, is_retry=True)
+ assignments = {**assignments, **retry_result}
+ missing = expected - set(assignments.keys())
+
+ if not missing:
+ return assignments
+
+ fallback_group_id = self._largest_group_id(groups, assignments)
+ for skill_id in sorted(missing):
+ assignments[skill_id] = fallback_group_id
+
+ if missing:
+ console.print(
+ Panel(
+ f"[bold red]{len(missing)}/{len(skills)} skills were placed into fallback group "
+ f"'{fallback_group_id}'.[/bold red]",
+ title="[bold red]Classification Recovery[/bold red]",
+ border_style="red",
+ )
+ )
+ return assignments
+
+ 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 {}
+ normalized: dict[str, dict[str, str]] = {}
+ for group_id, payload in self.iter_group_items(groups):
+ normalized[str(group_id)] = {
+ "name": payload.get("name", group_id),
+ "description": payload.get("description", ""),
+ "select_when": payload.get("select_when", ""),
+ "dont_select_when": payload.get("dont_select_when", ""),
+ }
+ return normalized
+
+ 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)
+ 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):
+ merged[str(group_id)] = {
+ "name": payload.get("name", group_id),
+ "description": payload.get("description", ""),
+ "select_when": payload.get("select_when", ""),
+ "dont_select_when": payload.get("dont_select_when", ""),
+ }
+ return merged
+
+ def split_skills(self, skills: list[dict], parent_context: Optional[dict], verbose: bool = False) -> dict:
+ batch_size = _builder_call(self._builder, "_auto_batch_size")
+ if len(skills) <= batch_size:
+ return self.split_skills_single(skills, parent_context, verbose=verbose)
+ return self.batched_split_skills(skills, parent_context, batch_size=batch_size, verbose=verbose)
+
+ def split_skills_single(self, skills: list[dict], parent_context: Optional[dict], verbose: bool = False) -> dict:
+ groups = self.discover_groups(skills, parent_context, verbose=verbose)
+ if not groups:
+ return {}
+ assignments = self.classify_skills(skills, groups, verbose=verbose)
+ assignments = self.validate_and_recover(skills, groups, assignments, verbose=verbose)
+ return self.build_groups_from_assignments(groups, assignments)
+
+ def batched_split_skills(
+ self,
+ skills: list[dict],
+ parent_context: Optional[dict],
+ *,
+ batch_size: int,
+ verbose: bool = False,
+ ) -> dict:
+ if verbose:
+ console.print(f"[cyan] Sampling {len(skills)} skills for grouped discovery[/cyan]")
+
+ discovery_groups = self._discover_from_samples(skills, parent_context, batch_size=batch_size, verbose=verbose)
+ if not discovery_groups:
+ return {}
+ assignments = self.classify_skills(skills, discovery_groups, verbose=verbose)
+ assignments = self.validate_and_recover(skills, discovery_groups, assignments, verbose=verbose)
+ return self.build_groups_from_assignments(discovery_groups, assignments)
+
+ def _discover_from_samples(
+ self,
+ skills: list[dict],
+ parent_context: Optional[dict],
+ *,
+ batch_size: int,
+ verbose: bool,
+ ) -> dict:
+ sampled_batches = self._sample_batches(skills, parent_context, batch_size)
+ discovered: list[dict] = []
+
+ if len(sampled_batches) == 1:
+ return self.discover_groups(sampled_batches[0], parent_context, verbose=verbose)
+
+ max_workers = self._nested_pool_size(len(sampled_batches))
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ future_map = {
+ executor.submit(self.discover_groups, batch, parent_context, verbose): index
+ for index, batch in enumerate(sampled_batches)
+ }
+ collected: list[tuple[int, dict]] = []
+ for future in as_completed(future_map):
+ try:
+ payload = future.result()
+ except Exception as exc:
+ console.print(f"[red]Discovery batch failed: {exc}[/red]")
+ else:
+ if payload:
+ collected.append((future_map[future], payload))
+ collected.sort(key=lambda item: item[0])
+ discovered = [payload for _, payload in collected]
+
+ if not discovered:
+ return {}
+ if len(discovered) == 1:
+ return discovered[0]
+ return self.merge_group_definitions(discovered, verbose=verbose)
+
+ def _sample_batches(self, skills: list[dict], parent_context: Optional[dict], batch_size: int) -> list[list[dict]]:
+ ordered = self.sorted_skills(skills)
+ if len(ordered) <= batch_size:
+ return [ordered]
+
+ shuffled = list(ordered)
+ rng = random.Random(self.sampling_seed(parent_context, len(skills)))
+ rng.shuffle(shuffled)
+
+ batches = [shuffled[index:index + batch_size] for index in range(0, len(shuffled), batch_size)]
+ return batches[:min(5, len(batches))]
+
+ def _nested_pool_size(self, total_jobs: int) -> int:
+ builder_workers = int(getattr(self._builder, "max_workers", 1) or 1)
+ return max(1, min(int(total_jobs), max(2, builder_workers)))
+
+ @staticmethod
+ def _normalize_group_id(group_id: object, valid_groups: set[str]) -> str:
+ candidate = str(group_id).strip()
+ normalized = candidate.lower().replace("_", "-")
+ return normalized if normalized in valid_groups else candidate
+
+ @staticmethod
+ def _largest_group_id(groups: dict, assignments: dict) -> str:
+ counts: dict[str, int] = {str(group_id): 0 for group_id in groups.keys()}
+ for group_id in assignments.values():
+ counts[str(group_id)] = counts.get(str(group_id), 0) + 1
+ return max(counts.items(), key=lambda item: (item[1], item[0]))[0]
+
+ @staticmethod
+ def _render_context(parent_context: Optional[dict]) -> str:
+ if not parent_context:
+ return "## Scope\nCreate the best top-level capability buckets for this skill set."
+ parent_name = str(parent_context.get("name", "")).strip()
+ parent_description = str(parent_context.get("description", "")).strip()
+ return (
+ "## Scope\n"
+ f'These groups sit under "{parent_name}".\n'
+ f"Parent description: {parent_description}\n"
+ "Keep the children mutually distinct and locally coherent."
+ )
+
+ def _render_group_definition_samples(self, all_group_defs: list[dict]) -> str:
+ sections: list[str] = []
+ for index, group_defs in enumerate(all_group_defs, start=1):
+ lines = [f"### Discovery Pass {index}"]
+ for group_id, payload in self.iter_group_items(group_defs):
+ lines.append(f"- {group_id}: {payload.get('name', group_id)}")
+ description = str(payload.get("description", "")).strip()
+ if description:
+ lines.append(f" Description: {description}")
+ select_when = str(payload.get("select_when", "")).strip()
+ if select_when:
+ lines.append(f" Select when: {select_when}")
+ dont_select_when = str(payload.get("dont_select_when", "")).strip()
+ if dont_select_when:
+ lines.append(f" Don't select when: {dont_select_when}")
+ sections.append("\n".join(lines))
+ return "\n\n".join(sections)
diff --git a/jiuwenswarm/symphony/indexing/tree/llm_runtime.py b/jiuwenswarm/symphony/indexing/tree/llm_runtime.py
new file mode 100644
index 0000000000..805b2879d3
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/llm_runtime.py
@@ -0,0 +1,292 @@
+from __future__ import annotations
+
+import hashlib
+from contextlib import suppress
+from typing import Optional, TYPE_CHECKING
+
+from shared.rich_compat import Console, Panel
+
+from .schema import parse_json_from_response
+
+try:
+ from openai import APIConnectionError, APIError, APITimeoutError, AuthenticationError
+except ModuleNotFoundError:
+ APIConnectionError = APIError = APITimeoutError = AuthenticationError = None
+
+if TYPE_CHECKING:
+ from .builder import TreeBuilder
+
+
+console = Console()
+
+
+def _builder_attr(builder: "TreeBuilder", name: str, default=None):
+ return getattr(builder, name, default)
+
+
+def _set_builder_attr(builder: "TreeBuilder", name: str, value) -> None:
+ setattr(builder, name, value)
+
+
+class TreeLLMRuntime:
+ """Owns model limits, retries, cache observability, and JSON parsing retries."""
+
+ def __init__(self, builder: "TreeBuilder") -> None:
+ self._builder = builder
+
+ def auto_batch_size(self) -> int:
+ builder = self._builder
+ batch_size_cache = _builder_attr(builder, "_batch_size_cache")
+ if batch_size_cache is not None:
+ return batch_size_cache
+ ctx_window, _ = self.model_limits()
+ available = ctx_window - builder.PROMPT_OVERHEAD_TOKENS - builder.OUTPUT_RESERVE_TOKENS
+ batch_size = available // builder.AVG_TOKENS_PER_SKILL
+ batch_size_cache = max(50, min(batch_size, 1000))
+ _set_builder_attr(builder, "_batch_size_cache", batch_size_cache)
+ return batch_size_cache
+
+ def get_max_output_tokens(self) -> int:
+ builder = self._builder
+ max_output_tokens_cache = _builder_attr(builder, "_max_output_tokens_cache")
+ if max_output_tokens_cache is not None:
+ return max_output_tokens_cache
+ _, max_out = self.model_limits()
+ max_output_tokens_cache = min(int(max_out), 4096)
+ _set_builder_attr(builder, "_max_output_tokens_cache", max_output_tokens_cache)
+ return max_output_tokens_cache
+
+ def merged_extra_body(self) -> dict:
+ merged = {
+ "thinking": {"type": "disabled"},
+ "chat_template_kwargs": {"enable_thinking": False},
+ "temperature": 0.0,
+ "top_p": 1.0,
+ }
+ llm_seed = _builder_attr(self._builder, "_llm_seed")
+ if llm_seed is not None:
+ with suppress(Exception):
+ merged["seed"] = int(llm_seed)
+ return merged
+
+ def model_limits(self) -> tuple[int, int]:
+ builder = self._builder
+ model_name = (builder.model or "").lower()
+ extended_context_markers = ("gpt-4.1", "gpt-4o", "claude", "doubao")
+ if any(marker in model_name for marker in extended_context_markers):
+ return 128000, 32768
+ if "gpt-5" in model_name:
+ return 200000, 65536
+ return builder.DEFAULT_CONTEXT_WINDOW, builder.DEFAULT_MAX_OUTPUT_TOKENS
+
+ @staticmethod
+ def normalize_prompt_for_fingerprint(prompt: str) -> str:
+ normalized_lines = []
+ for line in prompt.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+ normalized_lines.append(line.rstrip())
+ return "\n".join(normalized_lines).strip()
+
+ def prompt_fingerprint(self, prompt: str) -> str:
+ builder = self._builder
+ pieces = ["v1", builder.model or "", self.normalize_prompt_for_fingerprint(prompt)]
+ digest_input = "\n".join(str(piece) for piece in pieces)
+ return hashlib.sha256(digest_input.encode("utf-8")).hexdigest()[:16]
+
+ def extract_cache_hit(self, response) -> Optional[bool]:
+ for mapping in self._response_metadata_candidates(response):
+ parsed = self.extract_cache_hit_from_mapping(mapping)
+ if parsed is not None:
+ return parsed
+ return None
+
+ def extract_cache_hit_from_mapping(self, mapping: dict) -> Optional[bool]:
+ aliases = {"cache_hit", "cachehit", "is_cached", "cached", "x-litellm-cache-hit", "litellm_cache_hit"}
+ pending = [mapping]
+ while pending:
+ candidate = pending.pop(0)
+ if not isinstance(candidate, dict):
+ continue
+ for raw_key, raw_value in candidate.items():
+ key = str(raw_key).strip().lower()
+ if key in aliases:
+ coerced = self._coerce_cache_flag(raw_value)
+ if coerced is not None:
+ return coerced
+ if isinstance(raw_value, dict):
+ pending.append(raw_value)
+ return None
+
+ @staticmethod
+ def _response_metadata_candidates(response) -> list[dict]:
+ candidates: list[dict] = []
+ for attr_name in ("_hidden_params", "_response_headers"):
+ value = getattr(response, attr_name, None)
+ if isinstance(value, dict):
+ candidates.append(value)
+ model_dump = getattr(response, "model_dump", None)
+ if callable(model_dump):
+ try:
+ dumped = model_dump()
+ except Exception:
+ dumped = None
+ if isinstance(dumped, dict):
+ candidates.append(dumped)
+ return candidates
+
+ @staticmethod
+ def _coerce_cache_flag(value) -> Optional[bool]:
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, (int, float)):
+ return bool(value)
+ if isinstance(value, str):
+ normalized = value.strip().lower()
+ if normalized in {"1", "true", "hit", "yes"}:
+ return True
+ if normalized in {"0", "false", "miss", "no"}:
+ return False
+ return None
+
+ def record_cache_observation(self, cache_hit: Optional[bool]) -> None:
+ builder = self._builder
+ bucket_name = "unknown"
+ if cache_hit is True:
+ bucket_name = "hits"
+ elif cache_hit is False:
+ bucket_name = "misses"
+ attr_name = f"_cache_{bucket_name}"
+ setattr(builder, attr_name, getattr(builder, attr_name) + 1)
+
+ def print_cache_stats(self) -> None:
+ builder = self._builder
+ cache_hits = int(_builder_attr(builder, "_cache_hits", 0) or 0)
+ cache_misses = int(_builder_attr(builder, "_cache_misses", 0) or 0)
+ cache_unknown = int(_builder_attr(builder, "_cache_unknown", 0) or 0)
+ llm_calls = int(_builder_attr(builder, "_llm_calls", 0) or 0)
+ retry_calls = int(_builder_attr(builder, "_retry_calls", 0) or 0)
+ prompt_fingerprints = _builder_attr(builder, "_prompt_fingerprints", set()) or set()
+ known_total = cache_hits + cache_misses
+ observed_hit_rate = (cache_hits / known_total * 100.0) if known_total else 0.0
+ lower_bound_hit_rate = (cache_hits / llm_calls * 100.0) if llm_calls else 0.0
+ metrics = {
+ "LLM calls": llm_calls,
+ "Retry calls": retry_calls,
+ "Cache hits/misses/unknown": f"{cache_hits}/{cache_misses}/{cache_unknown}",
+ "Observed hit rate (known only)": f"{observed_hit_rate:.1f}%",
+ "Estimated hit rate lower bound": f"{lower_bound_hit_rate:.1f}%",
+ "Unique prompt fingerprints": len(prompt_fingerprints),
+ }
+ lines = [f"{label}: {value}" for label, value in metrics.items()]
+ console.print(Panel("\n".join(lines), title="[bold cyan]Cache Stats[/bold cyan]", border_style="cyan"))
+
+ def call_llm(self, prompt: str, is_retry: bool = False, retry_left: int | None = None) -> str:
+ builder = self._builder
+ client = _builder_attr(builder, "_client")
+ if client is None:
+ raise RuntimeError("openai is required to build the tree. Please install the openai package first.")
+ mcfg = _builder_attr(builder, "_manager_config")
+ if retry_left is None:
+ retry_left = int(mcfg.build.num_retries)
+ max_tokens = self.get_max_output_tokens()
+ prompt_fingerprint = self.prompt_fingerprint(prompt)
+ counter_lock = _builder_attr(builder, "_counter_lock")
+ with counter_lock:
+ llm_calls = int(_builder_attr(builder, "_llm_calls", 0) or 0) + 1
+ _set_builder_attr(builder, "_llm_calls", llm_calls)
+ if is_retry:
+ retry_calls = int(_builder_attr(builder, "_retry_calls", 0) or 0) + 1
+ _set_builder_attr(builder, "_retry_calls", retry_calls)
+ _builder_attr(builder, "_prompt_fingerprints").add(prompt_fingerprint)
+ progress = _builder_attr(builder, "_progress")
+ progress_task = _builder_attr(builder, "_progress_task")
+ if progress and progress_task is not None:
+ progress.update(progress_task, llm=llm_calls)
+ try:
+ with _builder_attr(builder, "_llm_semaphore"):
+ response = client.chat.completions.create(
+ model=builder.model,
+ messages=[{"role": "user", "content": prompt}],
+ max_tokens=max_tokens,
+ timeout=mcfg.build.timeout,
+ extra_body=self.merged_extra_body(),
+ )
+ finish_reason = response.choices[0].finish_reason
+ thread_local = _builder_attr(builder, "_thread_local")
+ if finish_reason == "length":
+ thread_local.truncated = True
+ console.print(
+ Panel(
+ "[bold red]OUTPUT TRUNCATED![/bold red]\n"
+ f"The LLM response was cut off at {max_tokens} tokens (finish_reason='length').\n"
+ "This will cause incomplete JSON parsing and skill loss.\n"
+ "Consider reducing batch size or increasing max_tokens.",
+ title="[bold red]Truncation Warning[/bold red]",
+ border_style="red",
+ )
+ )
+ else:
+ thread_local.truncated = False
+ with counter_lock:
+ _set_builder_attr(builder, "_consecutive_failures", 0)
+ self.record_cache_observation(None)
+ return response.choices[0].message.content or "{}"
+ except Exception as e:
+ if AuthenticationError is not None and isinstance(e, AuthenticationError):
+ console.print("[red]Authentication failed - check API key[/red]")
+ raise
+ err_text = str(e).lower()
+ is_context_exceeded = any(
+ marker in err_text for marker in ("context length", "maximum context", "too many tokens", "max context")
+ )
+ if is_context_exceeded:
+ console.print(f"[red]Context window exceeded: {e}[/red]")
+ batch_size_cache = _builder_attr(builder, "_batch_size_cache")
+ if batch_size_cache and batch_size_cache > 50:
+ batch_size_cache = max(50, batch_size_cache // 2)
+ _set_builder_attr(builder, "_batch_size_cache", batch_size_cache)
+ console.print(f"[yellow]Reduced batch size to {batch_size_cache}[/yellow]")
+ with counter_lock:
+ consecutive_failures = int(_builder_attr(builder, "_consecutive_failures", 0) or 0) + 1
+ _set_builder_attr(builder, "_consecutive_failures", consecutive_failures)
+ if consecutive_failures >= builder.max_consecutive_failures:
+ raise RuntimeError(f"Circuit breaker: {consecutive_failures} consecutive LLM failures") from e
+ return "{}"
+ is_transient = (
+ (APITimeoutError is not None and isinstance(e, APITimeoutError))
+ or (APIConnectionError is not None and isinstance(e, APIConnectionError))
+ or (APIError is not None and isinstance(e, APIError))
+ or "timed out" in err_text
+ or "timeout" in err_text
+ )
+ if is_transient and retry_left > 0:
+ return self.call_llm(prompt, is_retry=True, retry_left=retry_left - 1)
+ console.print(f"[red]LLM call failed: {e}[/red]")
+ with counter_lock:
+ consecutive_failures = int(_builder_attr(builder, "_consecutive_failures", 0) or 0) + 1
+ _set_builder_attr(builder, "_consecutive_failures", consecutive_failures)
+ if consecutive_failures >= builder.max_consecutive_failures:
+ raise RuntimeError(f"Circuit breaker: {consecutive_failures} consecutive LLM failures") from e
+ return "{}"
+
+ def call_llm_json(self, prompt: str, max_retries: int = 3, is_retry: bool = False) -> dict:
+ builder = self._builder
+ attempts_remaining = max_retries
+ attempt_index = 0
+ thread_local = _builder_attr(builder, "_thread_local")
+ while attempts_remaining > 0:
+ thread_local.truncated = False
+ response = self.call_llm(prompt, is_retry=is_retry or attempt_index > 0)
+ parsed = parse_json_from_response(response, default={})
+ if isinstance(parsed, dict):
+ return parsed
+ if getattr(thread_local, "truncated", False):
+ console.print("[yellow]Skipping retry because the model output was truncated[/yellow]")
+ return {}
+ console.print(
+ f"[yellow]Expected a JSON object but received {type(parsed).__name__} "
+ f"(attempt {attempt_index + 1}/{max_retries})[/yellow]"
+ )
+ attempt_index += 1
+ attempts_remaining -= 1
+ console.print("[red]All retries exhausted, returning empty dict[/red]")
+ return {}
diff --git a/jiuwenswarm/symphony/indexing/tree/preset_writer.py b/jiuwenswarm/symphony/indexing/tree/preset_writer.py
new file mode 100644
index 0000000000..68c1a8c271
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/preset_writer.py
@@ -0,0 +1,471 @@
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+try:
+ import yaml
+except ModuleNotFoundError:
+ yaml = None
+
+from shared.rich_compat import Console, RichTree
+
+from .schema import TreeNode
+
+if TYPE_CHECKING:
+ from .builder import TreeBuilder
+
+
+console = Console()
+GENERIC_TERMS = {
+ "a",
+ "an",
+ "and",
+ "are",
+ "as",
+ "at",
+ "be",
+ "by",
+ "for",
+ "from",
+ "how",
+ "if",
+ "in",
+ "into",
+ "is",
+ "it",
+ "of",
+ "on",
+ "or",
+ "that",
+ "the",
+ "this",
+ "to",
+ "tool",
+ "tools",
+ "use",
+ "used",
+ "using",
+ "when",
+ "with",
+}
+
+
+class TreePresetWriter:
+ """Owns recursive tree serialization, preset flattening, and YAML output."""
+
+ def __init__(self, builder: "TreeBuilder") -> None:
+ self._builder = builder
+
+ def tree_to_dict(self, tree: TreeNode) -> dict:
+ return self.node_to_dict(tree)
+
+ def tree_to_orchestrator_preset(self, tree_dict: dict) -> dict:
+ nodes = self.flatten_capability_tree(tree_dict)
+ nodes = self.rename_leaf_nodes(nodes)
+ return {
+ "tree_sketch": self.build_tree_sketch(nodes),
+ "nodes": nodes,
+ }
+
+ def flatten_capability_tree(self, tree: dict) -> list[dict]:
+ nodes: list[dict] = []
+ used_cids: set[str] = set()
+
+ def walk_category(node: dict, parent_cid: str, top_category_id: str) -> None:
+ branch_id = str(node.get("id") or node.get("name") or "category")
+ branch_name = str(node.get("name") or branch_id)
+ branch_description = str(node.get("description") or branch_name)
+ branch_select_when = str(node.get("select_when") or "").strip()
+ branch_dont_select_when = str(node.get("dont_select_when") or "").strip()
+ branch_cid = self.unique_child_cid(parent_cid, self.cid_term(branch_id, fallback="Category"), used_cids)
+
+ nodes.append(
+ {
+ "cid": branch_cid,
+ "type": "branch",
+ "description": branch_description,
+ "select_when": branch_select_when,
+ "dont_select_when": branch_dont_select_when,
+ "keywords": self.extract_keywords(
+ branch_id, branch_name, branch_description, branch_select_when, branch_dont_select_when
+ ),
+ "examples": [],
+ "category": top_category_id,
+ "source_type": "capability_group",
+ }
+ )
+
+ for child in list(node.get("children", []) or []):
+ if isinstance(child, dict):
+ walk_category(child, branch_cid, top_category_id)
+
+ for skill in list(node.get("skills", []) or []):
+ if not isinstance(skill, dict):
+ continue
+ skill_id = str(skill.get("id") or skill.get("name") or "skill").strip()
+ skill_name = str(skill.get("name") or skill_id).strip()
+ skill_description = str(skill.get("description") or skill_name).strip()
+ leaf_cid = self.unique_child_cid(
+ branch_cid,
+ self.cid_term(skill_id or skill_name, fallback="Skill"),
+ used_cids,
+ )
+ nodes.append(
+ {
+ "cid": leaf_cid,
+ "type": "leaf",
+ "worker_id": skill_id,
+ "description": skill_description,
+ "select_when": str(skill.get("select_when") or "").strip(),
+ "dont_select_when": str(skill.get("dont_select_when") or "").strip(),
+ "source_description": str(skill.get("source_description") or "").strip(),
+ "keywords": self.extract_keywords(skill_id, skill_name, skill_description),
+ "examples": [],
+ }
+ )
+
+ root_children = tree.get("children", []) if str(tree.get("id", "")).strip().lower() == "root" else [tree]
+ root_children = sorted(
+ [item for item in root_children if isinstance(item, dict)],
+ key=lambda item: str(item.get("id") or item.get("name") or ""),
+ )
+ for root_child in root_children:
+ top_category_id = self.slug_term(
+ str(root_child.get("id") or root_child.get("name") or "category"),
+ fallback="category",
+ )
+ walk_category(root_child, "", top_category_id)
+ return nodes
+
+ def rename_leaf_nodes(self, nodes: list[dict]) -> list[dict]:
+ if not nodes:
+ return nodes
+ branch_cids = {
+ str(item.get("cid", "")).strip()
+ for item in nodes
+ if str(item.get("type", "")).strip() == "branch" and str(item.get("cid", "")).strip()
+ }
+ used: set[str] = set(branch_cids)
+ leaf_items = [
+ item for item in nodes if str(item.get("type", "")).strip() == "leaf" and str(item.get("cid", "")).strip()
+ ]
+ leaf_items.sort(key=lambda item: str(item.get("cid", "")))
+
+ renamed: dict[str, str] = {}
+ for item in leaf_items:
+ old_cid = str(item.get("cid", "")).strip()
+ parent_cid = self.parent_cid(old_cid)
+ old_term = old_cid.rsplit(".", 1)[-1] if old_cid else "Skill"
+ preferred_cid_seed = self.compact_leaf_cid_seed(
+ worker_id=str(item.get("worker_id") or "").strip(),
+ display_name=str(item.get("name") or "").strip(),
+ old_term=old_term,
+ )
+ segment = self.cid_term(preferred_cid_seed, fallback="Skill")
+ new_cid = self.unique_child_cid(parent_cid, segment, used)
+ renamed[old_cid] = new_cid
+
+ updated: list[dict] = []
+ for item in nodes:
+ copied = dict(item)
+ cid = str(copied.get("cid", "")).strip()
+ if cid in renamed:
+ copied["cid"] = renamed[cid]
+ updated.append(copied)
+ return updated
+
+ @staticmethod
+ def compact_leaf_cid_seed(*, worker_id: str, display_name: str, old_term: str) -> str:
+ name_tokens = [t for t in re.split(r"[^A-Za-z0-9]+", display_name or "") if t]
+ if len(name_tokens) >= 2:
+ return " ".join(name_tokens)
+
+ raw = worker_id or old_term or "Skill"
+ tokens = [t for t in re.split(r"[^A-Za-z0-9]+", raw) if t]
+ if not tokens:
+ return "Skill"
+
+ noise_prefix = {
+ "claude",
+ "code",
+ "template",
+ "templates",
+ "skill",
+ "skills",
+ "plugin",
+ "plugins",
+ "repo",
+ "github",
+ "starter",
+ "boilerplate",
+ "awesome",
+ "example",
+ "examples",
+ }
+ noise_anywhere = {
+ "template",
+ "templates",
+ "skill",
+ "skills",
+ "plugin",
+ "plugins",
+ "boilerplate",
+ }
+
+ compact = list(tokens)
+ while len(compact) > 2:
+ head = compact[0].lower()
+ has_digit = any(ch.isdigit() for ch in head)
+ if head in noise_prefix or has_digit:
+ compact.pop(0)
+ continue
+ break
+
+ filtered: list[str] = []
+ for token in compact:
+ if len(filtered) >= 2 and token.lower() in noise_anywhere:
+ continue
+ filtered.append(token)
+ if len(filtered) >= 2:
+ compact = filtered
+
+ if len(compact) > 4:
+ compact = compact[-4:]
+
+ return " ".join(compact or tokens)
+
+ @staticmethod
+ def cid_term(value: str, fallback: str = "Node") -> str:
+ raw = str(value or "")
+ parts = [part for part in re.split(r"[^A-Za-z0-9]+", raw) if part]
+ if not parts:
+ parts = [fallback]
+ token = "".join(part[:1].upper() + part[1:] for part in parts)
+ if not token:
+ token = fallback
+ if not token[0].isalpha():
+ token = "N" + token
+ return token
+
+ def build_tree_sketch(self, nodes: list[dict]) -> str:
+ if not nodes:
+ return ""
+
+ by_cid = {str(item.get("cid", "")): item for item in nodes if item.get("cid")}
+ children_by_parent: dict[str, list[dict]] = {}
+ for node in nodes:
+ cid = str(node.get("cid", "")).strip()
+ if not cid:
+ continue
+ children_by_parent.setdefault(self.parent_cid(cid), []).append(node)
+
+ leaf_count_cache: dict[str, int] = {}
+
+ def descendant_leaf_count(cid: str) -> int:
+ cached = leaf_count_cache.get(cid)
+ if cached is not None:
+ return cached
+ node = by_cid.get(cid, {})
+ if str(node.get("type", "")) != "branch":
+ leaf_count_cache[cid] = 1
+ return 1
+ total = 0
+ for child in children_by_parent.get(cid, []):
+ child_cid = str(child.get("cid", ""))
+ if child_cid:
+ total += descendant_leaf_count(child_cid)
+ leaf_count_cache[cid] = total
+ return total
+
+ def branch_children(cid: str) -> list[dict]:
+ return sorted(
+ [item for item in children_by_parent.get(cid, []) if str(item.get("type", "")) == "branch"],
+ key=lambda item: str(item.get("cid", "")),
+ )
+
+ def leaf_children(cid: str) -> list[dict]:
+ return sorted(
+ [item for item in children_by_parent.get(cid, []) if str(item.get("type", "")) != "branch"],
+ key=lambda item: str(item.get("cid", "")),
+ )
+
+ lines: list[str] = [
+ "Global Tree Sketch",
+ "- Use this sketch only for global orientation across the whole tree.",
+ "- When selecting a concrete node path, prefer the current local state over globally similar nodes.",
+ ]
+
+ def render_branch(cid: str, indent: int) -> None:
+ node = by_cid.get(cid)
+ if not node:
+ return
+ prefix = " " * indent
+ description = self.routing_text_for_node(node) or "No summary"
+ child_branches = branch_children(cid)
+ child_leaves = leaf_children(cid)
+ details = [description, f"descendant_leaves={descendant_leaf_count(cid)}"]
+ if child_branches:
+ details.append(
+ "child_branches="
+ + ", ".join(
+ str(item.get("cid", "")).split(".")[-1] for item in child_branches[:5] if item.get("cid")
+ )
+ )
+ if child_leaves:
+ details.append(
+ "representative_leaves="
+ + ", ".join(str(item.get("cid", "")).split(".")[-1] for item in child_leaves[:3] if item.get("cid"))
+ )
+ lines.append(f"{prefix}- {cid}: " + " | ".join(details))
+ for child in child_branches:
+ render_branch(str(child.get("cid", "")), indent + 1)
+
+ root_branches = sorted(
+ [item for item in children_by_parent.get("", []) if str(item.get("type", "")) == "branch"],
+ key=lambda item: str(item.get("cid", "")),
+ )
+ for branch in root_branches:
+ render_branch(str(branch.get("cid", "")), 0)
+ return "\n".join(lines).strip()
+
+ @staticmethod
+ def slug_term(value: str, fallback: str = "node") -> str:
+ cleaned = re.sub(r"[^A-Za-z0-9_-]+", "-", str(value or ""))
+ cleaned = cleaned.replace("_", "-").lower()
+ cleaned = re.sub(r"-{2,}", "-", cleaned).strip("-")
+ if not cleaned:
+ cleaned = fallback
+ if not cleaned[0].isalpha():
+ cleaned = f"n-{cleaned}"
+ return cleaned
+
+ @staticmethod
+ def join_cid(parent: str, child: str) -> str:
+ return f"{parent}.{child}" if parent else child
+
+ @staticmethod
+ def parent_cid(cid: str) -> str:
+ if "." not in cid:
+ return ""
+ return cid.rsplit(".", 1)[0]
+
+ def unique_child_cid(self, parent_cid: str, segment: str, used: set[str]) -> str:
+ base = self.join_cid(parent_cid, segment)
+ candidate = base
+ suffix = 2
+ while candidate in used:
+ candidate = f"{base}-{suffix}"
+ suffix += 1
+ used.add(candidate)
+ return candidate
+
+ @staticmethod
+ def extract_keywords(*values: str, limit: int = 8) -> list[str]:
+ seen: set[str] = set()
+ result: list[str] = []
+ for value in values:
+ for token in re.findall(r"[A-Za-z0-9]+", str(value or "").lower()):
+ if len(token) < 3 or token in GENERIC_TERMS:
+ continue
+ if token in seen:
+ continue
+ seen.add(token)
+ result.append(token)
+ if len(result) >= limit:
+ return result
+ return result
+
+ def node_to_dict(self, node: TreeNode) -> dict:
+ payload = {"id": node.id, "name": node.name, "description": node.description}
+ if node.select_when:
+ payload["select_when"] = node.select_when
+ if node.dont_select_when:
+ payload["dont_select_when"] = node.dont_select_when
+ child_nodes = list(node.children)
+ if child_nodes:
+ payload["children"] = []
+ for child in child_nodes:
+ payload["children"].append(self.node_to_dict(child))
+ skill_items = list(node.skills)
+ if skill_items:
+ payload["skills"] = [skill.to_dict() for skill in skill_items]
+ return payload
+
+ @staticmethod
+ def routing_text_for_node(node: dict) -> str:
+ description = str(node.get("description") or "").strip()
+ select_when = str(node.get("select_when") or "").strip()
+ dont_select_when = str(node.get("dont_select_when") or "").strip()
+ parts = [description] if description else []
+ if select_when:
+ parts.append(f"Select when: {select_when}")
+ if dont_select_when:
+ parts.append(f"Don't select when: {dont_select_when}")
+ return "\n".join(parts).strip()
+
+ def write_yaml(self, tree_dict: dict) -> None:
+ output_path = self._builder.output_path
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ if yaml is not None:
+ with open(output_path, "w", encoding="utf-8") as f:
+ yaml.dump(
+ tree_dict,
+ f,
+ allow_unicode=True,
+ default_flow_style=False,
+ sort_keys=False,
+ width=120,
+ )
+ return
+ try:
+ from ruamel.yaml import YAML
+ except ModuleNotFoundError as exc:
+ raise RuntimeError("A YAML writer is required. Install PyYAML (`yaml`) or `ruamel.yaml`.") from exc
+ yml = YAML()
+ yml.default_flow_style = False
+ yml.allow_unicode = True
+ with open(output_path, "w", encoding="utf-8") as f:
+ yml.dump(tree_dict, f)
+
+ def print_tree(self, tree_dict: dict) -> None:
+ total_skills = self.count_skills_in_dict(tree_dict)
+ root_label = tree_dict.get("name", "Skill Tree")
+ rich_tree = RichTree(f"[bold]{root_label}[/bold] ({total_skills} skills)")
+ self._populate_rich_branch(rich_tree, list(tree_dict.get("children", [])))
+ console.print(rich_tree)
+
+ def add_node_to_rich_tree(self, parent_branch, node_dict: dict) -> None:
+ descendants = self.count_skills_in_dict(node_dict)
+ branch = parent_branch.add(self._branch_label(node_dict, descendants))
+ self._populate_rich_branch(branch, list(node_dict.get("children", [])))
+ self._render_skill_preview(branch, list(node_dict.get("skills", [])))
+
+ def _populate_rich_branch(self, branch, child_nodes: list[dict]) -> None:
+ for child in child_nodes:
+ self.add_node_to_rich_tree(branch, child)
+
+ @staticmethod
+ def _branch_label(node_dict: dict, skill_count: int) -> str:
+ node_id = node_dict.get("id", "unknown")
+ tone = "yellow" if node_dict.get("children") else "green"
+ return f"[{tone}]{node_id}[/{tone}] ({skill_count} skills)"
+
+ @staticmethod
+ def _render_skill_preview(branch, skills: list[dict]) -> None:
+ preview = skills[:3]
+ for skill in preview:
+ branch.add(f"[blue]{skill['id']}[/blue]")
+ extra = len(skills) - len(preview)
+ if extra > 0:
+ branch.add(f"[dim]... +{extra} more[/dim]")
+
+ @staticmethod
+ def count_skills_in_dict(node_dict: dict) -> int:
+ total = 0
+ stack = [node_dict]
+ while stack:
+ current = stack.pop()
+ total += len(current.get("skills", []))
+ stack.extend(list(current.get("children", [])))
+ return total
diff --git a/jiuwenswarm/symphony/indexing/tree/presets.py b/jiuwenswarm/symphony/indexing/tree/presets.py
new file mode 100644
index 0000000000..a862820795
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/presets.py
@@ -0,0 +1,315 @@
+from __future__ import annotations
+
+SKILLSMP_ROOT_CATEGORIES: list[dict[str, object]] = [
+ {
+ "id": "tools",
+ "name": "工具",
+ "description": "开发工具和实用程序,包括调试、生产力、系统管理、自动化、IDE、CLI、域名与 DNS。",
+ "children": [
+ {"id": "debugging", "name": "调试工具", "description": "Debugging tools and troubleshooting skills."},
+ {"id": "productivity-tools", "name": "生产力工具", "description": "Productivity and integration tools."},
+ {
+ "id": "system-admin",
+ "name": "系统管理",
+ "description": "System administration and operations utilities.",
+ },
+ {"id": "automation-tools", "name": "自动化工具", "description": "Automation tools and workflow helpers."},
+ {"id": "ide-plugins", "name": "IDE 插件", "description": "IDE plugins and editor integrations."},
+ {"id": "cli-tools", "name": "命令行工具", "description": "Command-line tools and terminal workflows."},
+ {
+ "id": "domain-utilities",
+ "name": "域名与 DNS 工具",
+ "description": "Domain, DNS, and network utility skills.",
+ },
+ ],
+ },
+ {
+ "id": "business",
+ "name": "商业",
+ "description": "商业场景技能,包括销售营销、项目管理、金融投资、法律地产、健康健身、支付、电商和商业应用。",
+ "children": [
+ {
+ "id": "sales-marketing",
+ "name": "销售与营销",
+ "description": "Sales, marketing, growth, SEO, and customer acquisition.",
+ },
+ {
+ "id": "project-management",
+ "name": "项目管理",
+ "description": "Project planning, tracking, coordination, and delivery.",
+ },
+ {
+ "id": "finance-investment",
+ "name": "金融与投资",
+ "description": "Finance, investment, accounting, and market analysis.",
+ },
+ {
+ "id": "real-estate-legal",
+ "name": "房地产与法律",
+ "description": "Real estate and legal workflow skills.",
+ },
+ {
+ "id": "health-fitness",
+ "name": "健康健身",
+ "description": "Health, fitness, and wellness business workflows.",
+ },
+ {"id": "payment", "name": "支付", "description": "Payment, billing, and checkout workflows."},
+ {"id": "ecommerce", "name": "电子商务", "description": "E-commerce operations and storefront workflows."},
+ {"id": "business-apps", "name": "商业应用", "description": "Business applications and office workflows."},
+ ],
+ },
+ {
+ "id": "development",
+ "name": "开发",
+ "description": "软件开发技能,包括架构、前端、后端、CMS、游戏、脚本、移动端、全栈、包发布和框架内核。",
+ "children": [
+ {
+ "id": "architecture-patterns",
+ "name": "架构模式",
+ "description": "Software architecture, patterns, and design decisions.",
+ },
+ {
+ "id": "frontend",
+ "name": "前端开发",
+ "description": "Frontend development, UI engineering, and web clients.",
+ },
+ {
+ "id": "backend",
+ "name": "后端开发",
+ "description": "Backend services, APIs, and server-side development.",
+ },
+ {"id": "cms-platforms", "name": "CMS 与平台开发", "description": "CMS and platform development skills."},
+ {"id": "gaming", "name": "游戏开发", "description": "Game development and interactive experiences."},
+ {"id": "scripting", "name": "脚本编程", "description": "Scripting, automation code, and small utilities."},
+ {"id": "mobile", "name": "移动开发", "description": "Mobile app development and device clients."},
+ {"id": "full-stack", "name": "全栈开发", "description": "Full-stack product and application development."},
+ {
+ "id": "package-distribution",
+ "name": "包管理与发布",
+ "description": "Package management, distribution, and publishing.",
+ },
+ {
+ "id": "framework-internals",
+ "name": "框架内核开发",
+ "description": "Framework internals and low-level platform work.",
+ },
+ {
+ "id": "ecommerce-development",
+ "name": "电商开发",
+ "description": "E-commerce development and commerce integrations.",
+ },
+ ],
+ },
+ {
+ "id": "data-ai",
+ "name": "数据与AI",
+ "description": "数据和 AI 技能,包括 LLM/AI、机器学习、数据工程、数据分析。",
+ "children": [
+ {
+ "id": "llm-ai",
+ "name": "LLM 与 AI",
+ "description": "Large language models, AI agents, prompting, and model workflows.",
+ },
+ {
+ "id": "machine-learning",
+ "name": "机器学习",
+ "description": "Machine learning modeling, training, and evaluation.",
+ },
+ {
+ "id": "data-engineering",
+ "name": "数据工程",
+ "description": "Data pipelines, ETL, and data infrastructure.",
+ },
+ {
+ "id": "data-analysis",
+ "name": "数据分析",
+ "description": "Data analysis, BI, reporting, and visualization.",
+ },
+ ],
+ },
+ {
+ "id": "testing-security",
+ "name": "测试与安全",
+ "description": "测试、安全和代码质量技能。",
+ "children": [
+ {
+ "id": "code-quality",
+ "name": "代码质量",
+ "description": "Code quality, linting, refactoring, and maintainability.",
+ },
+ {"id": "testing", "name": "测试", "description": "Testing, QA, test automation, and validation."},
+ {
+ "id": "security",
+ "name": "安全",
+ "description": "Security analysis, hardening, auditing, and vulnerability workflows.",
+ },
+ ],
+ },
+ {
+ "id": "devops",
+ "name": "DevOps",
+ "description": "DevOps 技能,包括 Git 工作流、CI/CD、云平台、容器和监控。",
+ "children": [
+ {
+ "id": "git-workflows",
+ "name": "Git 工作流",
+ "description": "Git, version control, branching, and collaboration workflows.",
+ },
+ {
+ "id": "cicd",
+ "name": "CI/CD",
+ "description": "Continuous integration, deployment, and release automation.",
+ },
+ {"id": "cloud", "name": "云平台", "description": "Cloud platform operations and infrastructure."},
+ {"id": "containers", "name": "容器", "description": "Containers, Docker, Kubernetes, and orchestration."},
+ {"id": "monitoring", "name": "监控", "description": "Monitoring, observability, logging, and alerts."},
+ ],
+ },
+ {
+ "id": "documentation",
+ "name": "文档",
+ "description": "文档技能,包括知识库、技术文档和教育材料。",
+ "children": [
+ {
+ "id": "knowledge-base",
+ "name": "知识库",
+ "description": "Knowledge base creation, maintenance, and retrieval.",
+ },
+ {
+ "id": "technical-docs",
+ "name": "技术文档",
+ "description": "Technical documentation, API docs, and developer guides.",
+ },
+ {"id": "education", "name": "教育", "description": "Education, tutorials, courses, and learning content."},
+ ],
+ },
+ {
+ "id": "content-media",
+ "name": "内容与媒体",
+ "description": "内容和媒体技能,包括文档处理、内容创作、设计、媒体处理。",
+ "children": [
+ {
+ "id": "documents",
+ "name": "文档处理",
+ "description": "Document processing, conversion, extraction, and editing.",
+ },
+ {
+ "id": "content-creation",
+ "name": "内容创作",
+ "description": "Content creation, writing, publishing, and creative workflows.",
+ },
+ {"id": "design", "name": "设计", "description": "Design, visual assets, UX, and creative production."},
+ {"id": "media", "name": "媒体处理", "description": "Image, audio, video, and media processing."},
+ ],
+ },
+ {
+ "id": "research",
+ "name": "研究",
+ "description": "研究技能,包括学术研究、生物信息、计算化学、实验室工具、科学计算和天文物理。",
+ "children": [
+ {
+ "id": "academic",
+ "name": "学术研究",
+ "description": "Academic research, papers, citations, and literature review.",
+ },
+ {
+ "id": "bioinformatics",
+ "name": "生物信息学",
+ "description": "Bioinformatics, genomics, and computational biology.",
+ },
+ {
+ "id": "computational-chemistry",
+ "name": "计算化学",
+ "description": "Computational chemistry and molecular workflows.",
+ },
+ {
+ "id": "lab-tools",
+ "name": "实验室工具",
+ "description": "Laboratory tools, protocols, and research operations.",
+ },
+ {
+ "id": "scientific-computing",
+ "name": "科学计算",
+ "description": "Scientific computing, simulations, and numerical analysis.",
+ },
+ {
+ "id": "astronomy-physics",
+ "name": "天文物理",
+ "description": "Astronomy, physics, and space-science workflows.",
+ },
+ ],
+ },
+ {
+ "id": "lifestyle",
+ "name": "生活方式",
+ "description": "生活方式技能,包括健康养生、文学写作、哲学伦理、占卜玄学、艺术手工、烹饪艺术。",
+ "children": [
+ {
+ "id": "wellness-health",
+ "name": "健康养生",
+ "description": "Wellness, health, habits, and personal care.",
+ },
+ {
+ "id": "literature-writing",
+ "name": "文学与写作",
+ "description": "Literature, writing, journaling, and creative text.",
+ },
+ {
+ "id": "philosophy-ethics",
+ "name": "哲学与伦理",
+ "description": "Philosophy, ethics, reasoning, and reflection.",
+ },
+ {
+ "id": "divination-mysticism",
+ "name": "占卜与玄学",
+ "description": "Divination, mysticism, and esoteric workflows.",
+ },
+ {"id": "arts-crafts", "name": "艺术与手工", "description": "Arts, crafts, and hands-on creative projects."},
+ {
+ "id": "culinary-arts",
+ "name": "烹饪艺术",
+ "description": "Cooking, recipes, food, and culinary workflows.",
+ },
+ ],
+ },
+ {
+ "id": "databases",
+ "name": "数据库",
+ "description": "数据库技能,包括 SQL 数据库、数据库工具和 NoSQL 数据库。",
+ "children": [
+ {
+ "id": "sql-databases",
+ "name": "SQL 数据库",
+ "description": "SQL databases, schema, queries, and relational data.",
+ },
+ {
+ "id": "database-tools",
+ "name": "数据库工具",
+ "description": "Database tools, administration, migration, and maintenance.",
+ },
+ {
+ "id": "nosql-databases",
+ "name": "NoSQL 数据库",
+ "description": "NoSQL databases, document stores, key-value, and graph data.",
+ },
+ ],
+ },
+ {
+ "id": "blockchain",
+ "name": "区块链",
+ "description": "区块链技能,包括 Web3 工具、智能合约和 DeFi。",
+ "children": [
+ {
+ "id": "web3-tools",
+ "name": "Web3 工具",
+ "description": "Web3 tools, wallets, chains, and dApp workflows.",
+ },
+ {
+ "id": "smart-contracts",
+ "name": "智能合约",
+ "description": "Smart contract development, auditing, and deployment.",
+ },
+ {"id": "defi", "name": "DeFi", "description": "DeFi protocols, trading, liquidity, and on-chain finance."},
+ ],
+ },
+]
diff --git a/jiuwenswarm/symphony/indexing/tree/prompts.py b/jiuwenswarm/symphony/indexing/tree/prompts.py
new file mode 100644
index 0000000000..5ee08f113d
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/prompts.py
@@ -0,0 +1,157 @@
+"""Minimal prompt bank for Demo's tree indexer."""
+
+GROUP_DISCOVERY_PROMPT = """Capability tree planning pass.
+
+Scope note:
+{context_section}
+
+Candidate skills:
+{skills_list}
+
+Return {min_groups}-{max_groups} proposed groups only. Do not place skills into groups yet.
+
+Design guidance:
+- optimize for retrieval usefulness rather than implementation taxonomy
+- 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
+- description should be a short positive definition
+- select_when should state when to route here
+- dont_select_when should state the most important boundary
+
+Respond as JSON:
+{{
+ "groups": {{
+ "group-id": {{
+ "name": "Short readable label",
+ "description": "Short positive definition of what belongs here.",
+ "select_when": "Route here when ...",
+ "dont_select_when": "Do not route here when ..."
+ }}
+ }}
+}}
+"""
+
+SKILL_ASSIGNMENT_PROMPT = """Routing pass for an existing tree layer.
+
+Available groups:
+{groups_list}
+
+Skills awaiting placement:
+{skills_list}
+
+Rules:
+- every skill must appear once
+- only use one of the listed group ids
+- choose the best primary fit for retrieval
+- if a skill spans multiple groups, prefer the broadest correct home
+
+Respond as JSON:
+{{
+ "assignments": {{
+ "skill-id-1": "group-id",
+ "skill-id-2": "group-id"
+ }}
+}}
+"""
+
+SKILL_PROFILE_PROMPT = """Skill routing profile normalization pass.
+
+Create compact routing profiles for these skills. Use the source description and content to infer capability,
+but do not copy long text.
+
+Skills:
+{skills_list}
+
+Rules:
+- description: one sentence, <= {description_limit} characters, describing what the skill does
+- select_when: optional, <= {rule_limit} characters, describing requests where this skill is the right choice
+- dont_select_when: optional, <= {rule_limit} characters, describing requests where a nearby skill would be better
+- keep wording concrete and retrieval-friendly
+- every skill id must appear once
+
+Respond as JSON:
+{{
+ "profiles": {{
+ "skill-id": {{
+ "description": "One-sentence capability summary.",
+ "select_when": "Use for ...",
+ "dont_select_when": "Avoid for ..."
+ }}
+ }}
+}}
+"""
+
+NODE_LABEL_REWRITE_PROMPT = """A tree node needs a cleaner label after regrouping.
+
+Current node:
+- id: {node_id}
+- name: {node_name}
+- description: {node_description}
+
+Current children summary:
+{children_summary}
+
+Return a replacement routing profile that better summarizes the children now under this node.
+Avoid mentioning repair passes or internal mechanics.
+
+Respond as JSON:
+{{
+ "name": "Updated label",
+ "description": "Updated short positive definition",
+ "select_when": "Route here when ...",
+ "dont_select_when": "Do not route here when ..."
+}}
+"""
+
+GROUP_MERGE_PROMPT = """Canonicalization pass across several discovery runs.
+
+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.
+
+Respond as JSON:
+{{
+ "canonical_groups": {{
+ "canonical-id": {{
+ "name": "Canonical label",
+ "description": "Short positive definition of what belongs here.",
+ "select_when": "Route here when ...",
+ "dont_select_when": "Do not route here when ..."
+ }}
+ }},
+ "mapping": {{
+ "source-group-id": "canonical-id"
+ }}
+}}
+"""
+
+EQUIVALENCE_GROUPING_PROMPT = """Equivalence regrouping pass for sibling leaves.
+
+Parent:
+- id: {parent_id}
+- name: {parent_name}
+- description: {parent_description}
+
+Leaves:
+{leaf_nodes}
+
+Group leaf ids that are near substitutes during retrieval.
+Partition all provided leaves into equivalence groups.
+
+Respond as JSON:
+{{
+ "groups": {{
+ "group-id": {{
+ "name": "Equivalence label",
+ "description": "What these leaves have in common for routing.",
+ "select_when": "Route here when ...",
+ "dont_select_when": "Do not route here when ...",
+ "leaf_ids": ["leaf-a", "leaf-b"]
+ }}
+ }}
+}}
+"""
diff --git a/jiuwenswarm/symphony/indexing/tree/repair.py b/jiuwenswarm/symphony/indexing/tree/repair.py
new file mode 100644
index 0000000000..afb7525373
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/repair.py
@@ -0,0 +1,241 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from shared.rich_compat import Console, Panel
+
+from .schema import TreeNode
+
+if TYPE_CHECKING:
+ from .builder import TreeBuilder
+
+
+console = Console()
+
+
+def _builder_attr(builder: "TreeBuilder", name: str):
+ return getattr(builder, name)
+
+
+def _builder_call(builder: "TreeBuilder", name: str, *args, **kwargs):
+ return getattr(builder, name)(*args, **kwargs)
+
+
+class TreeRepairEngine:
+ """Owns post-build repair passes and equivalence regrouping."""
+
+ def __init__(self, builder: "TreeBuilder") -> None:
+ self._builder = builder
+
+ def postprocess_tree(self, root: TreeNode, verbose: bool = False) -> None:
+ total_reassignments = 0
+ max_passes = int(_builder_attr(self._builder, "_postprocess_max_passes"))
+ for repair_pass in range(1, max_passes + 1):
+ moved = self.postprocess_node(root, verbose=verbose)
+ total_reassignments += moved
+ if verbose:
+ console.print(f"[dim] Post-process pass {repair_pass}: reassigned {moved} skills[/dim]")
+ if moved <= 0:
+ break
+ if total_reassignments > 0:
+ console.print(
+ Panel(
+ "[bold green]Post-process repaired "
+ f"{total_reassignments} misplaced skill assignments.[/bold green]",
+ title="[bold green]Tree Repair[/bold green]",
+ border_style="green",
+ )
+ )
+
+ def postprocess_node(self, node: TreeNode, verbose: bool = False) -> int:
+ if node.is_leaf:
+ return 0
+ moved = 0
+ for child in list(node.children):
+ moved += self.postprocess_node(child, verbose=verbose)
+ moved += self.rebalance_child_assignments(node, verbose=verbose)
+ return moved
+
+ def rebalance_child_assignments(self, node: TreeNode, verbose: bool = False) -> int:
+ builder = self._builder
+ if len(node.children) < 2:
+ return 0
+ groups = {
+ child.id: {
+ "name": child.name,
+ "description": child.description,
+ "select_when": child.select_when,
+ "dont_select_when": child.dont_select_when,
+ }
+ for child in node.children
+ }
+ if len(groups) < 2:
+ return 0
+
+ skill_entries: list[dict] = []
+ skill_data_by_id: dict[str, dict] = {}
+ source_leaf_by_skill_id: dict[str, TreeNode] = {}
+ source_child_by_skill_id: dict[str, str] = {}
+
+ for child in node.children:
+ for leaf_node, skill_data in self.collect_subtree_skill_locations(child):
+ skill_id = str(skill_data.get("id", "")).strip()
+ if not skill_id:
+ continue
+ skill_entries.append(skill_data)
+ skill_data_by_id[skill_id] = skill_data
+ source_leaf_by_skill_id[skill_id] = leaf_node
+ source_child_by_skill_id[skill_id] = child.id
+
+ if len(skill_entries) < int(_builder_attr(builder, "_postprocess_min_skills")):
+ return 0
+
+ assignments = _builder_call(builder, "_classify_skills", skill_entries, groups, verbose=False)
+ assignments = _builder_call(
+ builder,
+ "_validate_and_recover",
+ skill_entries,
+ groups,
+ assignments,
+ verbose=False,
+ )
+
+ child_by_id = {child.id: child for child in node.children}
+ moves: list[tuple[str, str]] = []
+ for skill_id, current_child_id in source_child_by_skill_id.items():
+ target_child_id = assignments.get(skill_id)
+ if not target_child_id or target_child_id == current_child_id or target_child_id not in child_by_id:
+ continue
+ moves.append((skill_id, target_child_id))
+
+ if not moves:
+ return 0
+
+ for skill_id, target_child_id in moves:
+ source_leaf = source_leaf_by_skill_id.get(skill_id)
+ skill_data = skill_data_by_id.get(skill_id)
+ target_child = child_by_id.get(target_child_id)
+ if source_leaf is None or skill_data is None or target_child is None:
+ continue
+ source_leaf.skills = [skill for skill in source_leaf.skills if skill.id != skill_id]
+ _builder_call(builder, "_insert_skill_into_subtree", target_child, skill_data)
+
+ removed_empty = _builder_call(builder, "_prune_empty_children", node)
+ if removed_empty:
+ _builder_call(builder, "_prune_empty_children", node)
+ if len(node.children) >= 2:
+ _builder_call(
+ builder,
+ "_rewrite_node_label_after_singleton",
+ node,
+ _builder_call(builder, "_existing_child_groups", node.children),
+ verbose=verbose,
+ )
+
+ total_moved = len(moves)
+ if verbose and total_moved > 0:
+ console.print(
+ f"[dim] Post-process repaired '{node.id}': moved={len(moves)}, " f"removed_empty={removed_empty}[/dim]"
+ )
+ return total_moved
+
+ def collect_subtree_skill_locations(self, node: TreeNode) -> list[tuple[TreeNode, dict]]:
+ if node.is_leaf:
+ return [(node, _builder_call(self._builder, "_skill_to_data", skill)) for skill in node.skills]
+ results: list[tuple[TreeNode, dict]] = []
+ for child in node.children:
+ results.extend(self.collect_subtree_skill_locations(child))
+ return results
+
+ def collect_subtree_skill_dicts(self, node: TreeNode) -> list[dict]:
+ return [skill_data for _, skill_data in self.collect_subtree_skill_locations(node)]
+
+ def normalize_to_equivalence_groups(self, root: TreeNode, verbose: bool = False) -> None:
+ if root.is_leaf:
+ return
+ updated_children: list[TreeNode] = []
+ split_count = 0
+ for child in list(root.children):
+ self.normalize_to_equivalence_groups(child, verbose=verbose)
+ if root.id != "root" and self.is_second_leaf_node(child):
+ replacement_nodes = self.split_second_leaf_node_into_equiv_groups(root, child, verbose=verbose)
+ updated_children.extend(replacement_nodes)
+ if len(replacement_nodes) > 1 or replacement_nodes[0].id != child.id:
+ split_count += 1
+ else:
+ updated_children.append(child)
+ root.children = updated_children
+ if verbose and split_count > 0:
+ console.print(
+ f"[dim] Equivalence regrouping updated {split_count} second-leaf nodes under '{root.id}'[/dim]"
+ )
+
+ @staticmethod
+ def is_second_leaf_node(node: TreeNode) -> bool:
+ if not node.children:
+ return False
+ return all(child.is_leaf for child in node.children)
+
+ def split_second_leaf_node_into_equiv_groups(
+ self,
+ parent_node: TreeNode,
+ second_leaf_node: TreeNode,
+ verbose: bool = False,
+ ) -> list[TreeNode]:
+ builder = self._builder
+ leaf_children = list(second_leaf_node.children)
+ if len(leaf_children) <= 1:
+ return [second_leaf_node]
+ groups = _builder_call(
+ builder,
+ "_discover_equivalence_groups",
+ second_leaf_node,
+ leaf_children,
+ verbose=verbose,
+ )
+ if not groups:
+ return [second_leaf_node]
+ normalized_groups = _builder_call(builder, "_normalize_equivalence_groups", leaf_children, groups)
+ if len(normalized_groups) <= 1:
+ only_group = normalized_groups[0]
+ second_leaf_node.name = only_group.get("name", second_leaf_node.name)
+ second_leaf_node.description = only_group.get("description", second_leaf_node.description)
+ second_leaf_node.select_when = only_group.get("select_when", second_leaf_node.select_when)
+ second_leaf_node.dont_select_when = only_group.get("dont_select_when", second_leaf_node.dont_select_when)
+ return [second_leaf_node]
+
+ used_ids = {child.id for child in parent_node.children}
+ replacement_nodes: list[TreeNode] = []
+ for idx, group in enumerate(normalized_groups, start=1):
+ base_id = _builder_call(
+ builder,
+ "_build_equivalence_group_id",
+ group_id=str(group.get("id") or "").strip(),
+ group_name=str(group.get("name") or "").strip(),
+ fallback=f"{second_leaf_node.id}-equiv-{idx}",
+ )
+ group_id = base_id
+ suffix = 2
+ while group_id in used_ids:
+ group_id = f"{base_id}-{suffix}"
+ suffix += 1
+ used_ids.add(group_id)
+ new_node = TreeNode(
+ id=group_id,
+ name=str(group.get("name") or group_id),
+ description=str(group.get("description") or second_leaf_node.description),
+ select_when=str(group.get("select_when") or ""),
+ dont_select_when=str(group.get("dont_select_when") or ""),
+ depth=second_leaf_node.depth,
+ parent_id=second_leaf_node.parent_id,
+ )
+ for leaf in group.get("leaf_nodes", []):
+ leaf.parent_id = new_node.id
+ leaf.depth = new_node.depth + 1
+ new_node.children.append(leaf)
+ replacement_nodes.append(new_node)
+ if verbose:
+ console.print(
+ f"[dim] Split '{second_leaf_node.id}' into {len(replacement_nodes)} equivalence groups[/dim]"
+ )
+ return replacement_nodes
diff --git a/jiuwenswarm/symphony/indexing/tree/root_categories.py b/jiuwenswarm/symphony/indexing/tree/root_categories.py
new file mode 100644
index 0000000000..fd6963b141
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/root_categories.py
@@ -0,0 +1,45 @@
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Sequence
+
+from indexing.io.config_loader import parse_json_or_yaml, read_config_text
+
+RootCategory = str | dict[str, object]
+RootCategoryInput = Sequence[RootCategory] | str | Path | None
+
+
+def resolve_tree_root_categories(value: RootCategoryInput) -> list[RootCategory] | None:
+ if value in (None, [], ()):
+ return None
+ if isinstance(value, (str, Path)):
+ return load_tree_root_categories(value)
+ return list(value)
+
+
+def load_tree_root_categories(source: str | Path) -> list[RootCategory]:
+ raw_source = str(source or "").strip()
+ if not raw_source:
+ raise ValueError("tree_root_categories file path is empty")
+ payload = parse_json_or_yaml(
+ read_config_text(raw_source, description="tree_root_categories"),
+ source=raw_source,
+ )
+ return list(_extract_categories(payload, source=raw_source))
+
+
+def _extract_categories(payload: object, *, source: str) -> list[RootCategory]:
+ 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 root category object")
+
+
+__all__ = ["RootCategory", "RootCategoryInput", "load_tree_root_categories", "resolve_tree_root_categories"]
diff --git a/jiuwenswarm/symphony/indexing/tree/schema.py b/jiuwenswarm/symphony/indexing/tree/schema.py
new file mode 100644
index 0000000000..b0a00a161c
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/schema.py
@@ -0,0 +1,854 @@
+"""Core schema and config objects for Demo's capability-tree indexing flow."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from dataclasses import dataclass, field
+from enum import Enum
+from pathlib import Path
+from typing import Optional, Union
+
+
+class SkillStatus(str, Enum):
+ ACTIVE = "active"
+ DORMANT = "dormant"
+ PINNED = "pinned"
+
+ @classmethod
+ def default(cls) -> "SkillStatus":
+ return cls.ACTIVE
+
+
+SKILL_DESCRIPTION_MAX_LENGTH = 150
+
+PROJECT_ROOT = Path(__file__).resolve().parents[2]
+SKILLS_DIR = PROJECT_ROOT / "data" / "skills"
+DEFAULT_TREE_OUTPUT_PATH = PROJECT_ROOT / "data" / "capability_trees" / "tree.yaml"
+
+BRANCHING_FACTOR = 8
+MAX_DEPTH = 6
+
+TREE_BUILD_MAX_WORKERS = 1
+TREE_BUILD_NUM_RETRIES = 2
+TREE_BUILD_TIMEOUT = 180.0
+TREE_BUILD_POSTPROCESS_ENABLED = True
+TREE_BUILD_POSTPROCESS_MAX_PASSES = 1
+TREE_BUILD_POSTPROCESS_MIN_SKILLS = 6
+TREE_BUILD_EQUIV_GROUPING_ENABLED = True
+
+MAX_SKILLS_PER_NODE_MULTIPLIER = 1.5
+EXPAND_THRESHOLD_MULTIPLIER = 0.7
+EARLY_STOP_MULTIPLIER = 1.7
+LAZY_SPLIT_MULTIPLIER = 1.3
+CLASSIFICATION_BATCH_MULTIPLIER = 6
+STRUCTURE_SAMPLE_MULTIPLIER = 12
+FALLBACK_CATEGORY_ID_HASH_LENGTH = 12
+
+FIXED_ROOT_CATEGORIES = {
+ "office-docs": {
+ "name": "办公文档",
+ "description": "办公文件的生成、编辑、转换、提取、排版和结构化处理。",
+ "select_when": "用户要处理 Word、PDF、PPT、Excel、Markdown、邮件、会议纪要或办公流程产物。",
+ "dont_select_when": "用户只是写普通文章/营销文案、管理个人知识库/笔记/任务、联网查资料、开发网页、生成图片视频或查询金融行情。",
+ "children": {
+ "documents": {
+ "name": "文档处理",
+ "description": "Word、PDF、TXT、Markdown、格式转换、OCR 后文档整理、文档提取和文档清洗。",
+ "select_when": "请求涉及具体文件的 Word、PDF、TXT、Markdown、格式转换、文档抽取、阅读、合并、拆分或排版。",
+ "dont_select_when": "请求主要是个人知识库、笔记、备忘、收藏、知识图谱、表格计算、PPT 生成、写原创文章或联网搜索。",
+ },
+ "spreadsheets": {
+ "name": "表格数据",
+ "description": "Excel、XLSX、CSV、数据分析、图表、公式、透视表和表格生成。",
+ "select_when": "请求涉及表格、数据清洗、统计分析、图表、公式、仪表盘、预算或 Excel 输出。",
+ "dont_select_when": "请求只是写报告正文、做 PPT、查网页资料或开发数据库。",
+ },
+ "slides": {
+ "name": "PPT演示",
+ "description": "PPT、幻灯片、演示文稿、学术海报、演讲材料和课件生成美化。",
+ "select_when": "用户明确要 PPT、slides、演示文稿、路演材料、答辩材料、课程幻灯片或学术海报。",
+ "dont_select_when": "用户只是写文章、生成图片、处理 PDF 或开发网页。",
+ },
+ "mail-meeting": {
+ "name": "邮件会议",
+ "description": "邮件收发、会议管理、会议纪要、日程协同和办公自动化流程。",
+ "select_when": "请求涉及真实邮件收发、会议工具、会议纪要、日程协同、办公事务流转或办公自动化。",
+ "dont_select_when": "请求只是管理待办/项目/主动跟进/智能体任务、创建 skill、处理单个文档或网页搜索。",
+ },
+ },
+ },
+ "writing-content": {
+ "name": "写作内容",
+ "description": "文章、故事、新闻、营销文案、内容策划、文本润色和写作风格处理。",
+ "select_when": "用户要写、改写、润色、策划或生成面向读者的文字内容,而不是操作具体办公文件。",
+ "dont_select_when": "用户明确要输出 Word/PDF/PPT/Excel 文件、生成图片视频、联网调研、管理知识库或构建智能体/skill。",
+ "children": {
+ "general-writing": {
+ "name": "通用写作",
+ "description": "文章、博客、新闻稿、报告正文、长文、口播稿和普通内容撰写。",
+ "select_when": "请求写文章、写新闻、写报告正文、写视频脚本、整理成可读内容或生成长篇文字。",
+ "dont_select_when": "请求重点是营销转化、文学故事、AI 痕迹消除、知识库管理、智能体人格/skill 构建或输出办公文件。",
+ },
+ "marketing-copy": {
+ "name": "营销文案",
+ "description": "产品文案、广告文案、落地页 copy、增长创意、CTA、社媒传播和品牌表达。",
+ "select_when": "请求涉及营销、增长、转化、产品介绍、广告、品牌、官网文案或社交媒体传播。",
+ "dont_select_when": "请求只是文学创作、新闻写作、普通润色或产品 PRD。",
+ },
+ "story-creative": {
+ "name": "故事创作",
+ "description": "儿童故事、寓言、小说、脑洞、人物故事、绘本故事和文学风格创作。",
+ "select_when": "请求创作故事、小说、儿童读物、儿童书、寓言、脑洞设定、人物叙事或指定文学风格文本。",
+ "dont_select_when": "请求是视觉绘本图片生成、视频制作、营销文案或新闻稿。",
+ },
+ "text-polish": {
+ "name": "文本润色",
+ "description": "文本润色、改写、降 AI 味、风格迭代、语气调整和中英文表达优化。",
+ "select_when": "请求润色、改写、去 AI 痕迹、人类化、调整语气、优化表达或学习用户写作风格。",
+ "dont_select_when": "请求是从零写 PRD、生成 PPT、处理 PDF 或进行事实调研。",
+ },
+ },
+ },
+ "search-research": {
+ "name": "搜索研究",
+ "description": "网页搜索、内容抓取、新闻、论文、深度调研和知识库检索。",
+ "select_when": "用户要查找已有信息、联网搜索、读取网页、研究主题、检索论文、查询新闻或使用知识库/笔记/记忆。",
+ "dont_select_when": "用户已经给定资料且只要求生成具体文件、图片、视频、表格或创作文案。",
+ "children": {
+ "web-search": {
+ "name": "网页搜索",
+ "description": "联网搜索、网页读取、浏览器访问、多平台内容访问、网页抓取和网页转 Markdown。",
+ "select_when": "请求查网页、找资料、查产品参数、读取链接、访问平台内容或需要浏览器/爬取能力。",
+ "dont_select_when": "请求是深度报告、论文阅读、个人知识库或本地文档处理。",
+ },
+ "deep-research": {
+ "name": "深度调研",
+ "description": "多源调研、竞品分析、行业研究、技术研究、综合报告和洞察分析。",
+ "select_when": "用户要系统调研、深度分析、竞品/行业/技术研究、多源验证或带引用报告。",
+ "dont_select_when": "用户只要简单搜索结果、新闻列表、论文检索、课程/课堂/研学方案或纯文字创作。",
+ },
+ "news-papers": {
+ "name": "新闻论文",
+ "description": "新闻热点、新闻抽取、科技日报、arXiv、论文搜索、论文阅读和学术速递。",
+ "select_when": "请求涉及新闻、热点、公众号/新闻提取、论文检索、论文阅读、学术论文或每日资讯。",
+ "dont_select_when": "请求是通用网页搜索、深度行业报告、办公文件生成或文学写作。",
+ },
+ "knowledge-notes": {
+ "name": "知识笔记",
+ "description": "个人知识库、笔记、收藏、记忆、备忘录、IMA、second brain、ontology 和结构化知识管理。",
+ "select_when": "用户要记录、保存、检索个人笔记/收藏/知识库/记忆/备忘录,或管理结构化知识关系。",
+ "dont_select_when": "用户要搜索公开互联网、处理本地文件、生成 Word/PDF 或操作手机文件。",
+ },
+ },
+ },
+ "media-creative": {
+ "name": "图片音视频",
+ "description": "图片理解、图像生成、视觉设计、视频动画、语音音乐、漫画和绘本视觉产物。",
+ "select_when": "用户输入或输出涉及图片、截图、照片、OCR、音频、语音、音乐、视频、动画、漫画或视觉设计。",
+ "dont_select_when": "用户主要是在写文本、做办公文件、网页开发、旅行查询或金融分析。",
+ "children": {
+ "image-understand": {
+ "name": "图片理解",
+ "description": "图片识别、OCR、图片翻译、图库搜索、图片内容理解和已有图片素材查找。",
+ "select_when": "用户提供或引用图片、截图、手写、图中文字/表格,或要查找已有图片素材。",
+ "dont_select_when": "用户要生成、绘制、编辑、美化或设计一张新图片。",
+ },
+ "image-design": {
+ "name": "图片设计",
+ "description": "图像生成、海报、Logo、表情包、视觉设计、流程图、漫画绘本插图和设计提示词。",
+ "select_when": "用户要画图、生成图片、设计海报/Logo/视觉素材、制作表情包/漫画/绘本插图或图像编辑。",
+ "dont_select_when": "用户只是识别、翻译、OCR、搜索已有图片或写纯文本故事。",
+ },
+ "video-animation": {
+ "name": "视频动画",
+ "description": "视频生成、动画、Remotion、短片、Vlog、科普视频、电影场景和短剧制作。",
+ "select_when": "请求生成、剪辑、策划或制作视频、动画、短剧、Vlog、科普片或电影场景。",
+ "dont_select_when": "请求只是写短视频脚本、生成静态图片、转写音频或做 PPT。",
+ },
+ "audio-music": {
+ "name": "语音音乐",
+ "description": "语音转写、文字转语音、声音合成、配音、播客和音乐生成。",
+ "select_when": "请求涉及语音转文字、配音、TTS、声音克隆、播客、有声书或音乐创作。",
+ "dont_select_when": "请求是视频画面生成、文本润色、会议管理本身或普通写作。",
+ },
+ },
+ },
+ "life-services": {
+ "name": "生活服务",
+ "description": "出行旅行、地图天气、健康教育、本地优惠、餐饮和日常生活服务。",
+ "select_when": "用户请求与真实生活行动、位置、旅行、天气、健康、学习、优惠券、餐饮或本地服务有关。",
+ "dont_select_when": "请求主要是内容创作、办公文件、网页开发、系统配置或金融投资。",
+ "children": {
+ "travel": {
+ "name": "出行旅行",
+ "description": "机票、火车票、酒店、景点、旅游规划、航空信息和旅行产品查询预订。",
+ "select_when": "请求订票、查航班/火车/酒店、规划旅行、查景点、做旅游攻略或查询旅行产品。",
+ "dont_select_when": "请求只是市内路线、附近地点、天气、打车或优惠券。",
+ },
+ "maps-weather": {
+ "name": "地图天气",
+ "description": "定位、地图、路线、打车、周边搜索、天气、交通出行和本地 POI。",
+ "select_when": "请求当前位置、怎么走、打车、路线规划、附近地点、天气或通勤出发时间。",
+ "dont_select_when": "请求是跨城旅行订票、酒店预订、金融行情或办公地图可视化开发。",
+ },
+ "health-edu": {
+ "name": "健康教育",
+ "description": "运动健康、饮食营养、健身、禁食、K12、公考、数学、课程和研学教育。",
+ "select_when": "请求涉及健康数据、心率血压、饮食、健身、学习辅导、考试备考、课堂生成、课程设计或研学方案。",
+ "dont_select_when": "请求是儿童故事/儿童书创作、旅行路线、天气查询、金融市场分析或普通内容写作。",
+ },
+ "local-deals": {
+ "name": "本地优惠",
+ "description": "美团优惠、餐饮团购、麦当劳、电影、本地生活、食谱和购物清单。",
+ "select_when": "请求找餐厅、领券、外卖/团购优惠、麦当劳、电影信息、菜谱或本地消费。",
+ "dont_select_when": "请求只是路线导航、旅行订票、健康营养分析或金融优惠。",
+ },
+ },
+ },
+ "product-dev": {
+ "name": "开发产品",
+ "description": "网页应用、产品需求、UX/UI、部署数据库、代码测试和工程质量。",
+ "select_when": "用户要设计产品、写 PRD、做网页/应用、部署网站、接数据库、优化前端或测试代码。",
+ "dont_select_when": "用户只是写营销文案、生成办公文件、做图片视频、查询资料或配置智能体。",
+ "children": {
+ "web-apps": {
+ "name": "网页应用",
+ "description": "HTML、前端、React、Web 应用、交互网页、地图 JSAPI 和网页端功能开发。",
+ "select_when": "请求开发网站、网页应用、HTML 页面、前端交互、React/Next 优化或 Web 地图可视化。",
+ "dont_select_when": "请求只是网页搜索、生成海报、写 PRD 或部署已有应用。",
+ },
+ "product-ux": {
+ "name": "产品UX",
+ "description": "PRD、产品规划、用户研究、A/B 实验、UX 设计、方案评审和需求梳理。",
+ "select_when": "请求产品需求文档、用户故事、产品策略、实验设计、用户研究、UX 方案或产品评审。",
+ "dont_select_when": "请求直接写代码、部署应用、写普通文章或营销文案。",
+ },
+ "deploy-data": {
+ "name": "部署数据",
+ "description": "网站部署、云数据库、云端后端、上线发布和应用数据存储。",
+ "select_when": "请求部署网站、发布应用、接入云数据库、云端存储或让网页支持共享数据。",
+ "dont_select_when": "请求只是做静态网页设计、前端代码优化、产品规划或本地文件上传。",
+ },
+ "code-test": {
+ "name": "代码测试",
+ "description": "代码审查、Web 自动化测试、测试用例、技能测试和工程质量验证。",
+ "select_when": "请求 review 代码、测试网页、生成测试用例、验证功能、审计工程质量或测试 skill。",
+ "dont_select_when": "请求是产品需求、网页视觉设计、部署上线或普通安全合规检查。",
+ },
+ },
+ },
+ "finance-business": {
+ "name": "金融商业",
+ "description": "股票行情、投资分析、金融新闻、量化交易、模拟交易和企业信息查询。",
+ "select_when": "用户询问股票、基金、指数、黄金、行情、投资、金融新闻、企业工商或商业数据。",
+ "dont_select_when": "用户只是做普通市场调研、表格分析、营销文案或产品竞品分析。",
+ "children": {
+ "market-data": {
+ "name": "行情数据",
+ "description": "股票、基金、指数、贵金属、宏观和金融实时/历史行情查询。",
+ "select_when": "请求查价格、走势、K线、涨跌幅、资金流、宏观数据或金融基础数据。",
+ "dont_select_when": "请求是投资建议、情绪分析、企业工商资料或模拟下单。",
+ },
+ "investment": {
+ "name": "投资分析",
+ "description": "金融新闻、情绪分析、预测、信号追踪、选股、研报和投资研判。",
+ "select_when": "请求分析走势、拐点、投资价值、市场事件影响、选股、研报或金融情绪。",
+ "dont_select_when": "请求只是实时行情数字、企业工商资料、普通新闻搜索或模拟交易。",
+ },
+ "business-data": {
+ "name": "企业查询",
+ "description": "企查查、企业工商、商业主体、公司风险、知识产权和企业经营信息查询。",
+ "select_when": "请求查询公司、企业工商、风险、知识产权、经营信息或商业主体资料。",
+ "dont_select_when": "请求是股票交易数据、投资预测、行业深度研究或营销文案。",
+ },
+ "trading-sim": {
+ "name": "模拟交易",
+ "description": "模拟炒股、投资练习、虚拟持仓、交易组合管理和交易训练。",
+ "select_when": "用户明确要模拟交易、虚拟持仓、买卖练习、组合管理或炒股大师模拟。",
+ "dont_select_when": "用户要真实行情、投资分析、金融新闻或企业信息查询。",
+ },
+ },
+ },
+ "system-tools": {
+ "name": "系统工具",
+ "description": "手机设备、文件云盘、智能体/技能管理、任务自动化、安全合规和连接配置。",
+ "select_when": "用户请求操作设备系统、管理文件云盘、配置渠道、创建技能/智能体、切换人格、管理任务或做安全校验。",
+ "dont_select_when": "用户主要要完成一个具体业务任务,如写文档、查资料、做图、出行或金融分析。",
+ "children": {
+ "device-home": {
+ "name": "设备家庭",
+ "description": "手机 APP 操控、联系人、电话、短信、闹钟、日历、收藏、图库和智能家居设备。",
+ "select_when": "请求操作手机应用、系统功能、联系人短信电话、闹钟日历、收藏图库或智能家居。",
+ "dont_select_when": "请求是云盘文件、办公文档、网页搜索或旅行地图查询。",
+ },
+ "files-cloud": {
+ "name": "文件云盘",
+ "description": "本地文件、云空间、百度网盘、文件上传、下载、分享和文件资源管理。",
+ "select_when": "请求找文件、上传下载、云盘管理、网盘分享、本地文件资源读取或获取文件链接。",
+ "dont_select_when": "请求是解析文件内容、生成 Word/PDF/PPT、图片理解或搜索网页。",
+ },
+ "agents-tasks": {
+ "name": "智能体任务",
+ "description": "技能创建安装查找、智能体构建、人设人格、SOUL、主动任务、待办项目、计划管理和自我进化。",
+ "select_when": "请求创建/安装/查找 skill,构建 agent,切换 persona,管理待办/项目/目标,或让智能体主动执行/跟进。",
+ "dont_select_when": "请求只是调用已有业务 skill 完成普通任务,或写 PRD/产品方案。",
+ },
+ "safety-channels": {
+ "name": "安全连接",
+ "description": "安全合规、隐私保护、执行校验、渠道机器人和消息平台连接配置。",
+ "select_when": "请求安全扫描、合规检测、密钥保护、命令验证,或配置飞书/微信/QQ/企微/微博等通道。",
+ "dont_select_when": "请求是普通邮件短信发送、办公文件处理、业务查询或手机联系人操作。",
+ },
+ },
+ },
+}
+
+
+def _slug_term(value: str, fallback: str = "category") -> str:
+ source = str(value or "")
+ normalized = re.sub(r"[^0-9A-Za-z_-]+", "-", source).replace("_", "-").lower()
+ normalized = re.sub(r"-{2,}", "-", normalized).strip("-") or fallback
+ if normalized == fallback and source.strip():
+ # Non-ASCII names may not produce a readable slug; append a stable short hash.
+ digest = hashlib.sha256(source.encode("utf-8")).hexdigest()[:FALLBACK_CATEGORY_ID_HASH_LENGTH]
+ normalized = f"{fallback}-{digest}"
+ return normalized if normalized[0].isalpha() else f"n-{normalized}"
+
+
+def normalize_root_categories(raw_categories) -> Optional[dict]:
+ if raw_categories in (None, [], ()):
+ return None
+ if not isinstance(raw_categories, list):
+ raise ValueError("TREE_BUILDER_ROOT_CATEGORIES must be a list.")
+
+ def normalize_entries(entries: list, *, label_path: str) -> dict:
+ items: list[tuple[str, dict]] = []
+ for entry in entries:
+ if isinstance(entry, str):
+ label = entry.strip()
+ if not label:
+ continue
+ category_id = _slug_term(label)
+ payload: dict[str, object] = {
+ "name": label,
+ "description": f"Skills related to {label.lower()}.",
+ }
+ elif isinstance(entry, dict):
+ label = str(entry.get("name") or entry.get("id") or "").strip()
+ if not label:
+ raise ValueError(f"Each {label_path} item must include 'name' or 'id'.")
+ category_id = _slug_term(str(entry.get("id") or label))
+ payload = {
+ "name": label,
+ "description": str(entry.get("description") or f"Skills related to {label.lower()}.").strip(),
+ }
+ select_when = str(entry.get("select_when") or "").strip()
+ dont_select_when = str(entry.get("dont_select_when") or "").strip()
+ if select_when:
+ payload["select_when"] = select_when
+ if dont_select_when:
+ payload["dont_select_when"] = dont_select_when
+ raw_children = entry.get("children")
+ if raw_children in (None, [], ()):
+ raw_children = None
+ if raw_children is not None:
+ if isinstance(raw_children, dict):
+ child_entries = [
+ {"id": child_id, **dict(child_payload)}
+ for child_id, child_payload in raw_children.items()
+ if isinstance(child_payload, dict)
+ ]
+ if len(child_entries) != len(raw_children):
+ raise ValueError(f"{label_path} item '{category_id}' children dict values must be objects.")
+ elif isinstance(raw_children, list):
+ child_entries = raw_children
+ else:
+ raise ValueError(f"{label_path} item '{category_id}' children must be a list or dict.")
+ children = normalize_entries(child_entries, label_path=f"{label_path}.{category_id}.children")
+ if children:
+ payload["children"] = children
+ else:
+ raise ValueError(f"{label_path} items must be strings or dicts.")
+ items.append((category_id, payload))
+
+ normalized: dict[str, dict] = {}
+ for category_id, payload in items:
+ if category_id in normalized:
+ raise ValueError(f"Duplicate {label_path} id: {category_id}")
+ normalized[category_id] = payload
+ return normalized
+
+ normalized = normalize_entries(raw_categories, label_path="TREE_BUILDER_ROOT_CATEGORIES")
+ return normalized or None
+
+
+@dataclass(frozen=True)
+class TreeBuildConfig:
+ max_workers: int = TREE_BUILD_MAX_WORKERS
+ num_retries: int = TREE_BUILD_NUM_RETRIES
+ timeout: float = TREE_BUILD_TIMEOUT
+ postprocess_enabled: bool = TREE_BUILD_POSTPROCESS_ENABLED
+ postprocess_max_passes: int = TREE_BUILD_POSTPROCESS_MAX_PASSES
+ postprocess_min_skills: int = TREE_BUILD_POSTPROCESS_MIN_SKILLS
+ equiv_grouping_enabled: bool = TREE_BUILD_EQUIV_GROUPING_ENABLED
+ discovery_seed: int = 42
+ classify_batch_cap: int = 20
+
+
+@dataclass(frozen=True)
+class TreeManagerConfig:
+ branching_factor: int = BRANCHING_FACTOR
+ max_depth: int = MAX_DEPTH
+ root_categories: Optional[dict] = None
+ build: TreeBuildConfig = field(default_factory=TreeBuildConfig)
+
+
+@dataclass
+class DynamicTreeConfig:
+ branching_factor: int = BRANCHING_FACTOR
+ max_depth: int = MAX_DEPTH
+ root_categories: Optional[dict] = None
+ rebalance_interval: int = 50
+
+ def _scaled(self, multiplier: float, seed: Optional[int] = None) -> int:
+ anchor = self.branching_factor if seed is None else seed
+ return int(anchor * multiplier)
+
+ def _derived_value(self, key: str) -> int:
+ if key == "max_skills_per_node":
+ return self._scaled(MAX_SKILLS_PER_NODE_MULTIPLIER)
+ if key == "expand_threshold":
+ return self._scaled(EXPAND_THRESHOLD_MULTIPLIER)
+ if key == "early_stop_skill_count":
+ return self._scaled(EARLY_STOP_MULTIPLIER)
+ if key == "lazy_split_threshold":
+ return self._scaled(LAZY_SPLIT_MULTIPLIER, self.max_skills_per_node)
+ if key == "classification_batch_size":
+ return self._scaled(CLASSIFICATION_BATCH_MULTIPLIER)
+ if key == "structure_sample_size":
+ return self._scaled(STRUCTURE_SAMPLE_MULTIPLIER)
+ raise KeyError(key)
+
+ @property
+ def max_skills_per_node(self) -> int:
+ return self._derived_value("max_skills_per_node")
+
+ @property
+ def expand_threshold(self) -> int:
+ return self._derived_value("expand_threshold")
+
+ @property
+ def early_stop_skill_count(self) -> int:
+ return self._derived_value("early_stop_skill_count")
+
+ @property
+ def lazy_split_threshold(self) -> int:
+ return self._derived_value("lazy_split_threshold")
+
+ @property
+ def classification_batch_size(self) -> int:
+ return self._derived_value("classification_batch_size")
+
+ @property
+ def structure_sample_size(self) -> int:
+ return self._derived_value("structure_sample_size")
+
+
+class Skill:
+ def __init__(
+ self,
+ *,
+ item_id: str = "",
+ name: str,
+ description: str = "",
+ path: str = "",
+ skill_path: str = "",
+ content: str = "",
+ selection_reason: str = "",
+ select_when: str = "",
+ dont_select_when: str = "",
+ source_description: str = "",
+ github_url: str = "",
+ stars: int = 0,
+ is_official: bool = False,
+ author: str = "",
+ status: SkillStatus = SkillStatus.ACTIVE,
+ installs_count: int = 0,
+ pinned_at: Optional[str] = None,
+ last_used: Optional[str] = None,
+ **extra: object,
+ ) -> None:
+ legacy_id = str(extra.pop("id", "") or "").strip()
+ if extra:
+ unknown = ", ".join(sorted(str(key) for key in extra))
+ raise TypeError(f"Unexpected Skill arguments: {unknown}")
+ self.id = item_id or legacy_id
+ self.name = name
+ self.description = description
+ self.path = path
+ self.skill_path = skill_path
+ self.content = content
+ self.selection_reason = selection_reason
+ self.select_when = select_when
+ self.dont_select_when = dont_select_when
+ self.source_description = source_description
+ self.github_url = github_url
+ self.stars = stars
+ self.is_official = is_official
+ self.author = author
+ self.status = status
+ self.installs_count = installs_count
+ self.pinned_at = pinned_at
+ self.last_used = last_used
+
+ def to_dict(self, include_content: bool = True) -> dict:
+ keys = (
+ "id",
+ "name",
+ "description",
+ "skill_path",
+ "select_when",
+ "dont_select_when",
+ "source_description",
+ "github_url",
+ "stars",
+ "is_official",
+ "author",
+ )
+ values = (
+ self.id,
+ self.name,
+ self.description,
+ self.skill_path,
+ self.select_when,
+ self.dont_select_when,
+ self.source_description,
+ self.github_url,
+ self.stars,
+ self.is_official,
+ self.author,
+ )
+ payload = dict(zip(keys, values))
+ if include_content:
+ payload["content"] = self.content
+ return payload
+
+
+class TreeNode:
+ def __init__(
+ self,
+ *,
+ node_id: str = "",
+ name: str,
+ description: str = "",
+ select_when: str = "",
+ dont_select_when: str = "",
+ children: Optional[list["TreeNode"]] = None,
+ skills: Optional[list[Skill]] = None,
+ depth: int = 0,
+ parent_id: Optional[str] = None,
+ pending_split: bool = False,
+ **extra: object,
+ ) -> None:
+ legacy_id = str(extra.pop("id", "") or "").strip()
+ if extra:
+ unknown = ", ".join(sorted(str(key) for key in extra))
+ raise TypeError(f"Unexpected TreeNode arguments: {unknown}")
+ self.id = node_id or legacy_id
+ self.name = name
+ self.description = description
+ self.select_when = select_when
+ self.dont_select_when = dont_select_when
+ self.children = list(children or [])
+ self.skills = list(skills or [])
+ self.depth = depth
+ self.parent_id = parent_id
+ self.pending_split = pending_split
+
+ @property
+ def is_leaf(self) -> bool:
+ return len(self.children) == 0
+
+ @property
+ def is_intermediate(self) -> bool:
+ return not self.is_leaf
+
+ def count_all_skills(self) -> int:
+ total = 0
+ stack = [self]
+ while stack:
+ current = stack.pop()
+ if current.children:
+ stack.extend(current.children)
+ else:
+ total += len(current.skills)
+ return total
+
+ def collect_all_skills(self) -> list[Skill]:
+ gathered: list[Skill] = []
+ agenda = [self]
+ while agenda:
+ current = agenda.pop()
+ if current.children:
+ agenda.extend(current.children)
+ continue
+ if current.skills:
+ gathered.extend(current.skills)
+ return gathered
+
+ def get_leaf_nodes(self) -> list["TreeNode"]:
+ result: list[TreeNode] = []
+ frontier = [self]
+ while frontier:
+ current = frontier.pop()
+ if current.children:
+ frontier.extend(current.children)
+ else:
+ result.append(current)
+ return result
+
+ def get_pending_split_nodes(self) -> list["TreeNode"]:
+ flagged: list[TreeNode] = []
+ queue = [self]
+ while queue:
+ current = queue.pop()
+ if current.pending_split:
+ flagged.append(current)
+ queue.extend(current.children)
+ return flagged
+
+ def clear_pending_splits(self) -> None:
+ for current in [self, *self._walk_descendants()]:
+ current.pending_split = False
+
+ def get_path(self) -> str:
+ return self.id
+
+ def to_dict(self) -> dict:
+ payload: dict = {}
+ payload.update(id=self.id, name=self.name, description=self.description)
+ if self.select_when:
+ payload["select_when"] = self.select_when
+ if self.dont_select_when:
+ payload["dont_select_when"] = self.dont_select_when
+ child_items = list(self.children)
+ skill_items = list(self.skills)
+ if child_items:
+ serialized_children: list[dict] = []
+ for child in child_items:
+ serialized_children.append(child.to_dict())
+ payload["children"] = serialized_children
+ if skill_items:
+ payload["skills"] = [item.to_dict() for item in skill_items]
+ return payload
+
+ def _walk_descendants(self):
+ stack = list(self.children)
+ while stack:
+ current = stack.pop()
+ yield current
+ stack.extend(current.children)
+
+ @classmethod
+ def from_recursive_tree(
+ cls,
+ tree_dict: dict,
+ depth: int = 0,
+ parent_id: Optional[str] = None,
+ ) -> "TreeNode":
+ node = cls(
+ id=tree_dict.get("id", "unknown"),
+ name=tree_dict.get("name", ""),
+ description=tree_dict.get("description", ""),
+ select_when=tree_dict.get("select_when", ""),
+ dont_select_when=tree_dict.get("dont_select_when", ""),
+ depth=depth,
+ parent_id=parent_id,
+ )
+ for child_payload in list(tree_dict.get("children", []) or []):
+ node.children.append(cls.from_recursive_tree(child_payload, depth + 1, node.id))
+ for skill_payload in list(tree_dict.get("skills", []) or []):
+ node.skills.append(
+ Skill(
+ id=skill_payload.get("id", ""),
+ name=skill_payload.get("name", ""),
+ description=skill_payload.get("description", ""),
+ path=node.id,
+ skill_path=skill_payload.get("skill_path", ""),
+ content=skill_payload.get("content", ""),
+ select_when=skill_payload.get("select_when", ""),
+ dont_select_when=skill_payload.get("dont_select_when", ""),
+ source_description=skill_payload.get("source_description", ""),
+ github_url=skill_payload.get("github_url", ""),
+ stars=skill_payload.get("stars", 0),
+ is_official=skill_payload.get("is_official", False),
+ author=skill_payload.get("author", ""),
+ )
+ )
+ return node
+
+ @classmethod
+ def from_capability_tree(cls, tree_dict: dict) -> "TreeNode":
+ root = cls(id="root", name="Root", description="Skill Tree Root")
+ domains = tree_dict.get("domains", {}) or {}
+ for domain_id, domain_payload in domains.items():
+ domain_node = cls(
+ id=domain_id,
+ name=domain_payload.get("name", domain_id),
+ description=domain_payload.get("description", ""),
+ select_when=domain_payload.get("select_when", ""),
+ dont_select_when=domain_payload.get("dont_select_when", ""),
+ depth=1,
+ parent_id=root.id,
+ )
+ for type_id, type_payload in (domain_payload.get("types", {}) or {}).items():
+ type_node = cls(
+ id=type_id,
+ name=type_payload.get("name", type_id),
+ description=type_payload.get("description", ""),
+ select_when=type_payload.get("select_when", ""),
+ dont_select_when=type_payload.get("dont_select_when", ""),
+ depth=2,
+ parent_id=domain_id,
+ )
+ for skill_payload in list(type_payload.get("skills", []) or []):
+ type_node.skills.append(
+ Skill(
+ id=skill_payload.get("id", ""),
+ name=skill_payload.get("name", ""),
+ description=skill_payload.get("description", ""),
+ path="/".join([domain_id, type_id]),
+ select_when=skill_payload.get("select_when", ""),
+ dont_select_when=skill_payload.get("dont_select_when", ""),
+ source_description=skill_payload.get("source_description", ""),
+ github_url=skill_payload.get("github_url", ""),
+ stars=skill_payload.get("stars", 0),
+ is_official=skill_payload.get("is_official", False),
+ author=skill_payload.get("author", ""),
+ )
+ )
+ domain_node.children.append(type_node)
+ root.children.append(domain_node)
+ return root
+
+
+class SearchStep:
+ def __init__(
+ self,
+ *,
+ level: int,
+ node_id: str,
+ options: list[str],
+ selected: list[str],
+ is_parallel: bool = False,
+ ) -> None:
+ self.level = level
+ self.node_id = node_id
+ self.options = list(options)
+ self.selected = list(selected)
+ self.is_parallel = is_parallel
+
+
+class MultiLevelSearchResult:
+ def __init__(
+ self,
+ *,
+ query: str,
+ selected_skills: list[dict],
+ steps: Optional[list[SearchStep]] = None,
+ llm_calls: int = 0,
+ parallel_rounds: int = 0,
+ early_stops: int = 0,
+ ) -> None:
+ self.query = query
+ self.selected_skills = list(selected_skills)
+ self.steps = list(steps or [])
+ self.llm_calls = llm_calls
+ self.parallel_rounds = parallel_rounds
+ self.early_stops = early_stops
+
+
+def parse_json_from_response(response: str, default: Union[dict, list, None] = None) -> Union[dict, list]:
+ fallback = {} if default is None else default
+ if not isinstance(response, str):
+ return fallback
+
+ for candidate in _json_candidates(response):
+ try:
+ decoded = json.loads(candidate)
+ except json.JSONDecodeError:
+ decoded = None
+ if isinstance(decoded, (dict, list)):
+ return decoded
+ return fallback
+
+
+def _json_candidates(response: str) -> list[str]:
+ raw = response.strip()
+ candidates: list[str] = []
+ if raw:
+ candidates.append(raw)
+ fenced = _strip_wrapping_fence(raw)
+ if fenced and fenced != raw:
+ candidates.insert(0, fenced)
+ candidates.extend(_extract_balanced_fragments(response))
+ seen: set[str] = set()
+ unique: list[str] = []
+ for item in candidates:
+ cleaned = item.strip()
+ if not cleaned or cleaned in seen:
+ continue
+ seen.add(cleaned)
+ unique.append(cleaned)
+ return unique
+
+
+def _strip_wrapping_fence(text: str) -> str:
+ if not text.startswith("```"):
+ return text
+ body = text.splitlines()
+ if body and body[0].startswith("```"):
+ body = body[1:]
+ if body and body[-1].strip() == "```":
+ body = body[:-1]
+ return "\n".join(body).strip()
+
+
+def _extract_balanced_fragments(text: str) -> list[str]:
+ fragments: list[str] = []
+ for opening, closing in (("{", "}"), ("[", "]")):
+ index = text.find(opening)
+ while index >= 0:
+ fragment = _slice_balanced(text, index, opening, closing)
+ if fragment:
+ fragments.append(fragment)
+ break
+ index = text.find(opening, index + 1)
+ return fragments
+
+
+def _slice_balanced(text: str, start: int, opening: str, closing: str) -> Optional[str]:
+ level = 0
+ inside_string = False
+ escaped = False
+ for cursor, char in enumerate(text[start:], start=start):
+ if escaped:
+ escaped = False
+ continue
+ if char == "\\" and inside_string:
+ escaped = True
+ continue
+ if char == '"':
+ inside_string = not inside_string
+ continue
+ if inside_string:
+ continue
+ if char == opening:
+ level += 1
+ elif char == closing:
+ level -= 1
+ if level == 0:
+ return text[start:cursor + 1]
+ return None
diff --git a/jiuwenswarm/symphony/indexing/tree/types.py b/jiuwenswarm/symphony/indexing/tree/types.py
new file mode 100644
index 0000000000..a9c0003252
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/types.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Optional
+
+from .schema import TreeNode
+
+
+@dataclass(frozen=True)
+class QueuedNode:
+ """Pending subtree build work item."""
+
+ node: TreeNode
+ skills: list[dict]
+ depth: int
+ parent_context: Optional[dict]
+
+
+@dataclass
+class ChildGroup:
+ """Mutable wrapper for a child node and the skill dicts assigned under it."""
+
+ node: TreeNode
+ skills: list[dict]
+ configured_children: dict | None = None
diff --git a/jiuwenswarm/symphony/indexing/tree/visualizer.py b/jiuwenswarm/symphony/indexing/tree/visualizer.py
new file mode 100644
index 0000000000..993348b93f
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/tree/visualizer.py
@@ -0,0 +1,336 @@
+from __future__ import annotations
+
+import html
+import json
+from pathlib import Path
+
+
+def generate_html(tree_dict: dict, output_path: Path) -> None:
+ payload = _normalize_tree(tree_dict)
+ stats = _tree_stats(payload)
+ html_text = _render_document(payload, stats)
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ output_path.write_text(html_text, encoding="utf-8")
+
+
+def _normalize_tree(tree_dict: dict) -> dict:
+ if "children" in tree_dict or "skills" in tree_dict:
+ return _normalize_recursive_node(tree_dict, depth=0)
+ return _normalize_legacy_tree(tree_dict)
+
+
+def _normalize_recursive_node(node_dict: dict, *, depth: int) -> dict:
+ # Compatibility: workflow tree payloads may encode leaf skills as
+ # children nodes (type=leaf) rather than under a "skills" list.
+ if _is_leaf_skill_node(node_dict):
+ return _skill_leaf_from_node(node_dict)
+
+ children = [_normalize_recursive_node(child, depth=depth + 1) for child in node_dict.get("children", [])]
+ skill_children = [_skill_leaf(skill) for skill in node_dict.get("skills", [])]
+ node_type = "root" if depth == 0 else "category"
+ return {
+ "name": node_dict.get("name", node_dict.get("id", "category")),
+ "id": node_dict.get("id", ""),
+ "description": node_dict.get("description", ""),
+ "type": node_type,
+ "children": children + skill_children,
+ }
+
+
+def _is_leaf_skill_node(node_dict: dict) -> bool:
+ node_type = str(node_dict.get("type", "") or "").strip().lower()
+ if node_type in {"leaf", "skill"}:
+ return True
+ has_children = bool(list(node_dict.get("children", []) or []))
+ has_worker_id = bool(str(node_dict.get("worker_id", "") or "").strip())
+ return (not has_children) and has_worker_id
+
+
+def _skill_leaf_from_node(node_dict: dict) -> dict:
+ worker_id = str(node_dict.get("worker_id", "") or "").strip()
+ node_id = str(node_dict.get("id", "") or node_dict.get("cid", "") or "").strip()
+ return {
+ "name": node_dict.get("name", worker_id or node_id or "skill"),
+ "id": worker_id or node_id,
+ "description": node_dict.get("description", ""),
+ "type": "skill",
+ "meta": {
+ "github_url": node_dict.get("github_url", ""),
+ "stars": node_dict.get("stars", 0),
+ "author": node_dict.get("author", ""),
+ },
+ "children": [],
+ }
+
+
+def _normalize_legacy_tree(tree_dict: dict) -> dict:
+ root = {"name": "Skills", "id": "root", "description": "", "type": "root", "children": []}
+ for domain_id, domain_data in tree_dict.get("domains", {}).items():
+ domain_node = {
+ "name": domain_data.get("name", domain_id),
+ "id": domain_id,
+ "description": domain_data.get("description", ""),
+ "type": "domain",
+ "children": [],
+ }
+ for type_id, type_data in domain_data.get("types", {}).items():
+ type_node = {
+ "name": type_data.get("name", type_id),
+ "id": type_id,
+ "description": type_data.get("description", ""),
+ "type": "category",
+ "children": [_skill_leaf(skill) for skill in type_data.get("skills", [])],
+ }
+ domain_node["children"].append(type_node)
+ root["children"].append(domain_node)
+ return root
+
+
+def _skill_leaf(skill: dict) -> dict:
+ return {
+ "name": skill.get("name", skill.get("id", "skill")),
+ "id": skill.get("id", ""),
+ "description": skill.get("description", ""),
+ "type": "skill",
+ "meta": {
+ "github_url": skill.get("github_url", ""),
+ "stars": skill.get("stars", 0),
+ "author": skill.get("author", ""),
+ },
+ "children": [],
+ }
+
+
+def _tree_stats(root: dict) -> dict:
+ category_count = 0
+ skill_count = 0
+ max_depth = 1
+
+ def walk(node: dict, depth: int) -> None:
+ nonlocal category_count, skill_count, max_depth
+ max_depth = max(max_depth, depth)
+ if node.get("type") == "skill":
+ skill_count += 1
+ return
+ if depth > 1:
+ category_count += 1
+ for child in node.get("children", []):
+ walk(child, depth + 1)
+
+ walk(root, 1)
+ return {"categories": category_count, "skills": skill_count, "depth": max_depth}
+
+
+def _render_document(root: dict, stats: dict) -> str:
+ tree_json = json.dumps(root, ensure_ascii=False)
+ head = _html_head()
+ hero = _hero_markup(root, stats)
+ tree_section = f'<section class="tree">{_render_node_children(root.get("children", []))}</section>'
+ raw_section = f'<pre class="raw">{html.escape(json.dumps(root, ensure_ascii=False, indent=2))}</pre>'
+ return f"""<!DOCTYPE html>
+<html lang="en">
+{head}
+<body>
+ <main>
+ {hero}
+ {tree_section}
+ {raw_section}
+ </main>
+</body>
+</html>"""
+
+
+def _html_head() -> str:
+ return """<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Capability Tree</title>
+ <style>
+ :root {
+ --bg: #f5efe4;
+ --ink: #1b2a2f;
+ --panel: rgba(255,255,255,0.86);
+ --line: rgba(27,42,47,0.12);
+ --accent: #0f766e;
+ --accent-2: #9a3412;
+ --skill: #164e63;
+ }
+ * { box-sizing: border-box; }
+ body {
+ margin: 0;
+ font-family: Georgia, "Times New Roman", serif;
+ color: var(--ink);
+ background:
+ radial-gradient(circle at top left, rgba(15,118,110,0.12), transparent 30%),
+ radial-gradient(circle at top right, rgba(154,52,18,0.10), transparent 28%),
+ linear-gradient(180deg, #fbf7ef, var(--bg));
+ min-height: 100vh;
+ }
+ main {
+ max-width: 1100px;
+ margin: 0 auto;
+ padding: 40px 20px 72px;
+ }
+ .hero {
+ background: var(--panel);
+ border: 1px solid var(--line);
+ border-radius: 24px;
+ padding: 28px 28px 24px;
+ box-shadow: 0 22px 60px rgba(27,42,47,0.08);
+ backdrop-filter: blur(8px);
+ }
+ h1 {
+ margin: 0 0 10px;
+ font-size: clamp(2rem, 4vw, 3.3rem);
+ line-height: 1.05;
+ }
+ .lede {
+ margin: 0;
+ max-width: 720px;
+ font-size: 1.05rem;
+ line-height: 1.6;
+ color: rgba(27,42,47,0.82);
+ }
+ .stats {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
+ gap: 12px;
+ margin-top: 22px;
+ }
+ .stat {
+ border: 1px solid var(--line);
+ border-radius: 18px;
+ padding: 14px 16px;
+ background: rgba(255,255,255,0.72);
+ }
+ .stat strong {
+ display: block;
+ font-size: 1.5rem;
+ color: var(--accent);
+ }
+ .tree {
+ margin-top: 26px;
+ display: grid;
+ gap: 10px;
+ }
+ details {
+ background: rgba(255,255,255,0.78);
+ border: 1px solid var(--line);
+ border-radius: 18px;
+ padding: 0 14px 10px;
+ }
+ summary {
+ list-style: none;
+ cursor: pointer;
+ padding: 14px 0;
+ font-weight: 700;
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ }
+ summary::-webkit-details-marker { display: none; }
+ .node-meta {
+ font-size: 0.83rem;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: rgba(27,42,47,0.55);
+ }
+ .node-desc {
+ margin: 0 0 8px;
+ color: rgba(27,42,47,0.84);
+ line-height: 1.55;
+ }
+ .children {
+ margin-left: 14px;
+ padding-left: 14px;
+ border-left: 2px solid var(--line);
+ display: grid;
+ gap: 10px;
+ }
+ .skill {
+ border: 1px solid rgba(22,78,99,0.16);
+ background: rgba(240,249,255,0.7);
+ border-radius: 16px;
+ padding: 12px 14px;
+ }
+ .skill h4 {
+ margin: 0 0 6px;
+ color: var(--skill);
+ font-size: 1rem;
+ }
+ .skill p {
+ margin: 0;
+ line-height: 1.5;
+ color: rgba(27,42,47,0.82);
+ }
+ .meta-row {
+ margin-top: 8px;
+ font-size: 0.88rem;
+ color: rgba(27,42,47,0.66);
+ }
+ .raw {
+ margin-top: 28px;
+ background: rgba(16,24,40,0.92);
+ color: #dce7ea;
+ border-radius: 22px;
+ padding: 18px;
+ overflow: auto;
+ font: 13px/1.5 Consolas, monospace;
+ }
+ </style>
+</head>"""
+
+
+def _hero_markup(root: dict, stats: dict) -> str:
+ title = html.escape(root.get("name", "Capability Tree"))
+ stat_cards = "".join(
+ [
+ f'<div class="stat"><strong>{stats["categories"]}</strong><span>Categories</span></div>',
+ f'<div class="stat"><strong>{stats["skills"]}</strong><span>Skills</span></div>',
+ f'<div class="stat"><strong>{stats["depth"]}</strong><span>Tree Depth</span></div>',
+ ]
+ )
+ return (
+ '<section class="hero">'
+ f"<h1>{title}</h1>"
+ '<p class="lede">Interactive browse view for the generated capability tree. '
+ "Expand categories to inspect subtrees and leaf skills.</p>"
+ f'<div class="stats">{stat_cards}</div>'
+ "</section>"
+ )
+
+
+def _render_node_children(nodes: list[dict]) -> str:
+ return "".join(_render_node(node) for node in nodes)
+
+
+def _render_node(node: dict) -> str:
+ node_type = html.escape(str(node.get("type", "category")))
+ name = html.escape(str(node.get("name", "Unknown")))
+ node_id = html.escape(str(node.get("id", "")))
+ description = html.escape(str(node.get("description", "") or ""))
+ children = node.get("children", [])
+
+ if node.get("type") == "skill":
+ meta = node.get("meta", {})
+ meta_bits = []
+ if meta.get("author"):
+ meta_bits.append(f"author: {html.escape(str(meta['author']))}")
+ if meta.get("stars"):
+ meta_bits.append(f"stars: {html.escape(str(meta['stars']))}")
+ if meta.get("github_url"):
+ url = html.escape(str(meta["github_url"]))
+ meta_bits.append(f'<a href="{url}" target="_blank" rel="noreferrer">source</a>')
+ meta_row = f'<div class="meta-row">{" | ".join(meta_bits)}</div>' if meta_bits else ""
+ return f'<article class="skill"><h4>{name}</h4><p>{description}</p>{meta_row}</article>'
+
+ open_attr = " open" if node.get("type") in {"root", "domain"} else ""
+ description_html = f'<p class="node-desc">{description}</p>' if description else ""
+ children_html = f'<div class="children">{_render_node_children(children)}</div>' if children else ""
+ return (
+ f"<details{open_attr}>"
+ f'<summary><span>{name}</span><span class="node-meta">{node_type} {node_id}</span></summary>'
+ f"{description_html}"
+ f"{children_html}"
+ f"</details>"
+ )
diff --git a/jiuwenswarm/symphony/indexing/workflows/__init__.py b/jiuwenswarm/symphony/indexing/workflows/__init__.py
new file mode 100644
index 0000000000..111cfefe66
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/workflows/__init__.py
@@ -0,0 +1,33 @@
+from .artifacts import (
+ BuildConfig,
+ BuildExecutionConfig,
+ BuildLLMConfig,
+ BuildOutputConfig,
+ ResolvedBuildConfig,
+ ResolvedTaxonomyBuildConfig,
+ TaxonomyBuildConfig,
+ build_catalog_records_from_nodes,
+ build_retrieval_text,
+ can_build_tree_with_llm,
+ compact_text,
+ resolve_build_config,
+ write_catalog,
+)
+from .index_builder import IndexBuilder
+
+__all__ = [
+ "BuildConfig",
+ "BuildExecutionConfig",
+ "BuildLLMConfig",
+ "BuildOutputConfig",
+ "IndexBuilder",
+ "ResolvedBuildConfig",
+ "ResolvedTaxonomyBuildConfig",
+ "TaxonomyBuildConfig",
+ "build_catalog_records_from_nodes",
+ "build_retrieval_text",
+ "can_build_tree_with_llm",
+ "compact_text",
+ "resolve_build_config",
+ "write_catalog",
+]
diff --git a/jiuwenswarm/symphony/indexing/workflows/artifacts.py b/jiuwenswarm/symphony/indexing/workflows/artifacts.py
new file mode 100644
index 0000000000..4e2a886be9
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/workflows/artifacts.py
@@ -0,0 +1,384 @@
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from enum import IntFlag
+from pathlib import Path
+from typing import Any, Dict, List, Sequence
+
+try:
+ from openai import OpenAI
+except Exception:
+ OpenAI = Any
+
+from indexing.catalog.records import CatalogRecord
+from indexing.tree.root_categories import RootCategoryInput, resolve_tree_root_categories
+
+
+class BuildMethod(IntFlag):
+ """Compatibility enum for callers that still import build methods."""
+
+ TREE = 4
+
+
+@dataclass(frozen=True)
+class BuildLLMConfig:
+ """LLM settings for offline tree construction.
+
+ Attributes:
+ model: Model name sent to the chat-completions compatible client.
+ client: Optional prebuilt OpenAI-compatible client. When omitted,
+ `api_key` and `base_url` are used by the tree builder.
+ api_key: API key used when `client` is not supplied.
+ base_url: Optional OpenAI-compatible base URL.
+ seed: Optional deterministic seed forwarded through `extra_body`.
+ """
+
+ # Model identity is required for real tree construction. An empty value is
+ # allowed at config construction time so default construction stays cheap;
+ # the build workflow fails before running without a usable LLM config.
+ model: str = ""
+ client: OpenAI | None = None
+ api_key: str = ""
+ base_url: str = ""
+
+ # Seed controls deterministic sampling for providers that support it.
+ seed: int | None = None
+
+
+@dataclass(frozen=True)
+class TaxonomyBuildConfig:
+ """Tree shape and taxonomy refinement settings.
+
+ Attributes:
+ branching_factor: Target maximum branching factor for discovered groups.
+ 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.
+ postprocess_enabled: Whether to run tree repair after construction.
+ postprocess_max_passes: Maximum repair pass count.
+ postprocess_min_skills: Minimum skill count for repair candidates.
+ equivalence_enabled: Whether to add one equivalence-group layer under
+ sibling leaf sets after normal tree construction.
+ """
+
+ branching_factor: int = 128
+ max_depth: int = 6
+ root_categories: RootCategoryInput = None
+
+ postprocess_enabled: bool = True
+ postprocess_max_passes: int = 1
+ postprocess_min_skills: int = 6
+
+ equivalence_enabled: bool = True
+
+
+@dataclass(frozen=True)
+class BuildExecutionConfig:
+ """Execution controls for the offline build.
+
+ Attributes:
+ max_workers: Maximum concurrent LLM calls.
+ max_retries: Retry count for transient LLM failures.
+ request_timeout_seconds: Per-request timeout for LLM calls.
+ classification_batch_limit: Upper bound for one classification prompt.
+ discovery_seed: Seed used for deterministic discovery sampling.
+ """
+
+ max_workers: int = 2
+ max_retries: int = 2
+ request_timeout_seconds: float = 420.0
+
+ classification_batch_limit: int = 32
+
+ discovery_seed: int = 42
+
+
+@dataclass(frozen=True)
+class BuildOutputConfig:
+ """Output artifact settings.
+
+ Attributes:
+ generate_html: Whether to emit the optional HTML tree visualization.
+ """
+
+ generate_html: bool = False
+
+
+@dataclass(frozen=True)
+class BuildConfig:
+ """Public offline build configuration.
+
+ The build path is intentionally fixed to LLM-driven TREE construction. This
+ config only exposes settings that still affect that path.
+
+ Attributes:
+ llm_config: OpenAI-compatible LLM client configuration.
+ taxonomy_config: Tree shape, postprocess, and equivalence settings.
+ execution_config: Concurrency, retry, timeout, and deterministic seed.
+ output_config: Optional output artifact controls.
+ """
+
+ llm_config: BuildLLMConfig = field(default_factory=BuildLLMConfig)
+ taxonomy_config: TaxonomyBuildConfig = field(default_factory=TaxonomyBuildConfig)
+ execution_config: BuildExecutionConfig = field(default_factory=BuildExecutionConfig)
+ output_config: BuildOutputConfig = field(default_factory=BuildOutputConfig)
+
+
+@dataclass(frozen=True)
+class ResolvedTaxonomyBuildConfig:
+ """Normalized taxonomy build settings used inside workflows.
+
+ Attributes:
+ branching_factor: Normalized tree branching factor.
+ max_depth: Normalized maximum tree depth.
+ root_categories: Root categories after applying schema defaults.
+ postprocess_enabled: Whether repair passes run.
+ postprocess_max_passes: Normalized repair pass limit.
+ postprocess_min_skills: Normalized repair minimum size.
+ equivalence_enabled: Whether equivalence-group refinement runs.
+ """
+
+ branching_factor: int
+ max_depth: int
+ root_categories: list[str | dict[str, object]] | None
+
+ postprocess_enabled: bool
+ postprocess_max_passes: int
+ postprocess_min_skills: int
+
+ equivalence_enabled: bool
+
+
+@dataclass(frozen=True)
+class ResolvedBuildConfig:
+ """Normalized build configuration used by workflow internals.
+
+ Attributes:
+ llm_config: Normalized LLM config.
+ taxonomy_config: Normalized taxonomy config.
+ execution_config: Normalized execution config.
+ output_config: Normalized output config.
+ """
+
+ llm_config: BuildLLMConfig
+ taxonomy_config: ResolvedTaxonomyBuildConfig
+ execution_config: BuildExecutionConfig
+ output_config: BuildOutputConfig
+
+
+def resolve_build_config(*, config: BuildConfig | None = None) -> ResolvedBuildConfig:
+ """Normalize public build config for workflow execution.
+
+ Args:
+ config: Optional public build configuration.
+
+ Returns:
+ A resolved config with stripped strings and bounded numeric values.
+ """
+
+ cfg = config or BuildConfig()
+ llm_cfg = cfg.llm_config
+ taxonomy_cfg = cfg.taxonomy_config
+ execution_cfg = cfg.execution_config
+ output_cfg = cfg.output_config
+ return ResolvedBuildConfig(
+ llm_config=BuildLLMConfig(
+ model=str(llm_cfg.model or "").strip(),
+ client=llm_cfg.client,
+ api_key=str(llm_cfg.api_key or "").strip(),
+ base_url=str(llm_cfg.base_url or "").strip(),
+ seed=llm_cfg.seed,
+ ),
+ taxonomy_config=ResolvedTaxonomyBuildConfig(
+ branching_factor=max(1, int(taxonomy_cfg.branching_factor or 8)),
+ max_depth=max(1, int(taxonomy_cfg.max_depth or 6)),
+ root_categories=resolve_tree_root_categories(taxonomy_cfg.root_categories),
+ postprocess_enabled=bool(taxonomy_cfg.postprocess_enabled),
+ postprocess_max_passes=max(0, int(taxonomy_cfg.postprocess_max_passes or 0)),
+ postprocess_min_skills=max(2, int(taxonomy_cfg.postprocess_min_skills or 2)),
+ equivalence_enabled=bool(taxonomy_cfg.equivalence_enabled),
+ ),
+ execution_config=BuildExecutionConfig(
+ max_workers=max(1, int(execution_cfg.max_workers or 1)),
+ max_retries=max(0, int(execution_cfg.max_retries or 0)),
+ request_timeout_seconds=float(execution_cfg.request_timeout_seconds),
+ classification_batch_limit=max(1, int(execution_cfg.classification_batch_limit or 1)),
+ discovery_seed=int(execution_cfg.discovery_seed),
+ ),
+ output_config=BuildOutputConfig(generate_html=bool(output_cfg.generate_html)),
+ )
+
+
+def build_catalog_records_from_nodes(
+ *,
+ nodes: Sequence[object],
+ scanned_skills: Dict[str, dict],
+ restrict_worker_ids: set[str] | None = None,
+) -> List[CatalogRecord]:
+ """Build catalog records from tree leaf nodes.
+
+ Args:
+ nodes: Raw tree preset nodes.
+ scanned_skills: Scanned item metadata keyed by worker id.
+ restrict_worker_ids: Optional worker-id allowlist for incremental builds.
+
+ Returns:
+ Catalog records sorted by CID.
+ """
+
+ records: List[CatalogRecord] = []
+ for raw_node in nodes:
+ if not isinstance(raw_node, dict):
+ continue
+ worker_id = str(raw_node.get("worker_id") or "").strip()
+ if not worker_id:
+ continue
+ if restrict_worker_ids is not None and worker_id not in restrict_worker_ids:
+ continue
+ scanned = scanned_skills.get(worker_id) or {}
+ cid = str(raw_node.get("cid") or "")
+ name = str(scanned.get("name") or worker_id)
+ has_tree_profile = any(
+ str(raw_node.get(key) or "").strip() for key in ("source_description", "select_when", "dont_select_when")
+ )
+ description = (
+ str(raw_node.get("description") or scanned.get("description") or "").strip()
+ if has_tree_profile
+ else str(scanned.get("description") or raw_node.get("description") or "").strip()
+ )
+ content = str(scanned.get("content") or "").strip()
+ source_description = str(raw_node.get("source_description") or scanned.get("description") or "").strip()
+ select_when = str(raw_node.get("select_when") or "").strip()
+ dont_select_when = str(raw_node.get("dont_select_when") or "").strip()
+ skill_path = str(scanned.get("path") or "")
+ records.append(
+ CatalogRecord(
+ worker_id=worker_id,
+ cid=cid,
+ name=name,
+ description=description,
+ skill_path=skill_path,
+ branch_path=tuple(cid.split(".")[:-1]),
+ category=".".join(cid.split(".")[:-1]),
+ retrieval_text=build_retrieval_text(
+ skill_id=worker_id,
+ name=name,
+ description=description,
+ content=content,
+ cid=cid,
+ ),
+ metadata={
+ "content": content,
+ "source_description": source_description,
+ "select_when": select_when,
+ "dont_select_when": dont_select_when,
+ },
+ )
+ )
+ return sorted(records, key=lambda item: item.cid)
+
+
+def write_catalog(records: Sequence[CatalogRecord], path: Path) -> None:
+ """Write catalog records as JSONL.
+
+ Args:
+ records: Catalog records to serialize.
+ path: Destination JSONL path.
+ """
+
+ lines = [
+ json.dumps(
+ {
+ "worker_id": record.worker_id,
+ "cid": record.cid,
+ "name": record.name,
+ "description": record.description,
+ "skill_path": record.skill_path,
+ "branch_path": list(record.branch_path),
+ "category": record.category,
+ "retrieval_text": record.retrieval_text,
+ "metadata": record.metadata,
+ },
+ ensure_ascii=False,
+ )
+ for record in records
+ ]
+ path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
+
+
+def build_retrieval_text(*, skill_id: str, name: str, description: str, content: str, cid: str) -> str:
+ """Build text used by non-tree retrieval artifacts.
+
+ Args:
+ skill_id: Skill id.
+ name: Skill display name.
+ description: Skill description.
+ content: Source skill content.
+ cid: Tree CID assigned to the skill.
+
+ Returns:
+ A compact newline-joined retrieval text string.
+ """
+
+ parts = [
+ compact_text(name, limit=200),
+ compact_text(description, limit=400),
+ compact_text(content, limit=1200),
+ compact_text(skill_id, limit=120),
+ compact_text(cid, limit=200),
+ ]
+ return "\n".join(part for part in parts if part)
+
+
+def compact_text(text: str, *, limit: int) -> str:
+ """Compact text to a single line with a fixed character limit.
+
+ Args:
+ text: Input text.
+ limit: Maximum number of characters.
+
+ Returns:
+ Normalized text, truncated with an ellipsis when necessary.
+ """
+
+ normalized = " ".join(str(text or "").split())
+ if len(normalized) <= limit:
+ return normalized
+ return normalized[:max(0, limit - 1)].rstrip() + "..."
+
+
+def can_build_tree_with_llm(config: BuildConfig | ResolvedBuildConfig | None = None) -> bool:
+ """Check whether the LLM tree build path can run.
+
+ Args:
+ config: Public or resolved build config.
+
+ Returns:
+ True when both a model and either a client or API key are configured.
+ """
+
+ llm_config = (
+ config.llm_config if isinstance(config, ResolvedBuildConfig) else resolve_build_config(config=config).llm_config
+ )
+ return bool(str(llm_config.model or "").strip()) and (
+ llm_config.client is not None or bool(str(llm_config.api_key or "").strip())
+ )
+
+
+__all__ = [
+ "BuildConfig",
+ "BuildExecutionConfig",
+ "BuildLLMConfig",
+ "BuildMethod",
+ "BuildOutputConfig",
+ "ResolvedBuildConfig",
+ "ResolvedTaxonomyBuildConfig",
+ "TaxonomyBuildConfig",
+ "build_catalog_records_from_nodes",
+ "build_retrieval_text",
+ "can_build_tree_with_llm",
+ "compact_text",
+ "resolve_build_config",
+ "write_catalog",
+]
diff --git a/jiuwenswarm/symphony/indexing/workflows/index_builder.py b/jiuwenswarm/symphony/indexing/workflows/index_builder.py
new file mode 100644
index 0000000000..f14a287687
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/workflows/index_builder.py
@@ -0,0 +1,770 @@
+from __future__ import annotations
+
+import logging
+import shutil
+import tempfile
+import zipfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Dict, Sequence
+
+from indexing.models import (
+ CATALOG_FILENAME,
+ TREE_HTML_FILENAME,
+ TREE_INDEX_FILENAME,
+)
+from indexing.io.items_jsonl import (
+ download_http_object_to_path,
+ is_http_uri,
+ is_passthrough_item_uri,
+ load_items_jsonl_text,
+ parse_jsonl_scanned_items,
+)
+from indexing.workflows.tree_ops import (
+ align_leaf_nodes_with_catalog,
+ build_catalog_records_from_existing,
+ enrich_branch_descriptions,
+ merge_added_skills_into_tree,
+ prune_deleted_skills_from_tree,
+ tree_nodes_to_tree_dict,
+)
+from indexing.tree.visualizer import generate_html as generate_tree_html
+
+from indexing.io import (
+ load_catalog_records,
+ load_manifest,
+ load_tree_preset,
+ normalize_item_paths,
+ write_manifest,
+ write_tree_preset,
+)
+from indexing.scanners import create_scanner, get_scanner_class, normalize_item_type
+from indexing.tree import DynamicTreeConfig, TreeBuildConfig, TreeManagerConfig
+from indexing.tree.builder import build_tree
+from indexing.tree.schema import normalize_root_categories
+from shared.profiling import StageTimer
+from shared.storage import download_s3_object_to_path, is_s3_uri, materialize_s3_dir, upload_local_dir_to_s3
+
+from .artifacts import (
+ BuildConfig,
+ ResolvedBuildConfig,
+ build_catalog_records_from_nodes,
+ can_build_tree_with_llm,
+ resolve_build_config,
+ write_catalog,
+)
+
+LOGGER = logging.getLogger("index_builder")
+
+
+@dataclass(frozen=True)
+class ResolvedItemPath:
+ source_path: str
+ source_type: str
+ materialized_dir: Path
+
+
+class IndexBuilder:
+ @staticmethod
+ def build(
+ item_paths: list[str] | None = None,
+ output_dir: str | Path | None = None,
+ *,
+ item_type: str = "skill",
+ config: BuildConfig | None = None,
+ item_jsonl_path: str | None = None,
+ ) -> str | Path:
+ timer = StageTimer("IndexBuilder.build", logger=LOGGER)
+ try:
+ with timer.phase("resolve_inputs"):
+ if output_dir is None:
+ raise ValueError("IndexBuilder.build: output_dir is required")
+ normalized_item_paths = _resolve_item_paths_or_error(
+ item_paths=item_paths,
+ item_jsonl_path=item_jsonl_path,
+ operation="build",
+ )
+ resolved_config = resolve_build_config(config=config)
+ normalized_item_type = normalize_item_type(item_type)
+ pre_scanned_skills, manifest_item_paths = _load_pre_scanned_items(
+ item_jsonl_path=item_jsonl_path,
+ default_paths=normalized_item_paths,
+ )
+ output_value = str(output_dir).strip()
+ if is_s3_uri(output_value):
+ with tempfile.TemporaryDirectory(prefix="retriever-index-s3-output-") as tmpdir:
+ local_output_dir = Path(tmpdir) / "index"
+ _IndexBuildWorkflow(
+ item_paths=manifest_item_paths,
+ output_dir=local_output_dir,
+ resolved_config=resolved_config,
+ item_type=normalized_item_type,
+ pre_scanned_skills=pre_scanned_skills,
+ manifest_item_paths=manifest_item_paths,
+ ).build()
+ with timer.phase("upload_s3_output"):
+ upload_local_dir_to_s3(local_output_dir, output_value)
+ return output_value.rstrip("/")
+ return _IndexBuildWorkflow(
+ item_paths=manifest_item_paths,
+ output_dir=Path(output_dir),
+ resolved_config=resolved_config,
+ item_type=normalized_item_type,
+ pre_scanned_skills=pre_scanned_skills,
+ manifest_item_paths=manifest_item_paths,
+ ).build()
+ finally:
+ timer.finish()
+
+ @staticmethod
+ def add(
+ item_paths: list[str] | None = None,
+ base_index_dir: str | Path | None = None,
+ output_dir: str | Path | None = None,
+ *,
+ item_type: str = "skill",
+ config: BuildConfig | None = None,
+ item_jsonl_path: str | None = None,
+ ) -> str | Path:
+ timer = StageTimer("IndexBuilder.add", logger=LOGGER)
+ try:
+ with timer.phase("resolve_inputs"):
+ if base_index_dir is None:
+ raise ValueError("IndexBuilder.add: base_index_dir is required")
+ if output_dir is None:
+ raise ValueError("IndexBuilder.add: output_dir is required")
+ base_dir = _materialize_existing_index_dir(base_index_dir, cache_namespace="retriever-index-add-cache")
+ manifest = load_manifest(base_dir)
+ existing = normalize_item_paths(manifest.get("item_paths") or ())
+ normalized_item_paths = _resolve_item_paths_or_error(
+ item_paths=item_paths,
+ item_jsonl_path=item_jsonl_path,
+ operation="add",
+ )
+ added_scanned_skills, added_paths = _load_pre_scanned_items(
+ item_jsonl_path=item_jsonl_path,
+ default_paths=normalized_item_paths,
+ )
+ combined = normalize_item_paths([*existing, *added_paths])
+ resolved_config = resolve_build_config(config=config)
+ normalized_item_type = normalize_item_type(item_type)
+ output_value = str(output_dir).strip()
+ if is_s3_uri(output_value):
+ with tempfile.TemporaryDirectory(prefix="retriever-index-add-s3-output-") as tmpdir:
+ local_output_dir = Path(tmpdir) / "index"
+ _IncrementalIndexBuildWorkflow(
+ item_paths=combined,
+ output_dir=local_output_dir,
+ resolved_config=resolved_config,
+ base_index_dir=base_dir,
+ added_paths=added_paths,
+ removed_paths=[],
+ item_type=normalized_item_type,
+ added_scanned_skills=added_scanned_skills,
+ manifest_item_paths=combined,
+ ).build()
+ with timer.phase("upload_s3_output"):
+ upload_local_dir_to_s3(local_output_dir, output_value)
+ return output_value.rstrip("/")
+ return _IncrementalIndexBuildWorkflow(
+ item_paths=combined,
+ output_dir=Path(output_dir),
+ resolved_config=resolved_config,
+ base_index_dir=base_dir,
+ added_paths=added_paths,
+ removed_paths=[],
+ item_type=normalized_item_type,
+ added_scanned_skills=added_scanned_skills,
+ manifest_item_paths=combined,
+ ).build()
+ finally:
+ timer.finish()
+
+ @staticmethod
+ def delete(
+ item_paths: list[str] | None = None,
+ base_index_dir: str | Path | None = None,
+ output_dir: str | Path | None = None,
+ *,
+ item_type: str = "skill",
+ config: BuildConfig | None = None,
+ item_jsonl_path: str | None = None,
+ ) -> str | Path:
+ timer = StageTimer("IndexBuilder.delete", logger=LOGGER)
+ try:
+ with timer.phase("resolve_inputs"):
+ if base_index_dir is None:
+ raise ValueError("IndexBuilder.delete: base_index_dir is required")
+ if output_dir is None:
+ raise ValueError("IndexBuilder.delete: output_dir is required")
+ base_dir = _materialize_existing_index_dir(
+ base_index_dir, cache_namespace="retriever-index-delete-cache"
+ )
+ manifest = load_manifest(base_dir)
+ existing = normalize_item_paths(manifest.get("item_paths") or ())
+ normalized_item_paths = _resolve_item_paths_or_error(
+ item_paths=item_paths,
+ item_jsonl_path=item_jsonl_path,
+ operation="delete",
+ )
+ _, removed_paths = _load_pre_scanned_items(
+ item_jsonl_path=item_jsonl_path,
+ default_paths=normalized_item_paths,
+ )
+ removed = set(removed_paths)
+ remaining = [path for path in existing if path not in removed]
+ normalized_remaining = normalize_item_paths(remaining)
+ resolved_config = resolve_build_config(config=config)
+ normalized_item_type = normalize_item_type(item_type)
+ output_value = str(output_dir).strip()
+ if is_s3_uri(output_value):
+ with tempfile.TemporaryDirectory(prefix="retriever-index-delete-s3-output-") as tmpdir:
+ local_output_dir = Path(tmpdir) / "index"
+ _IncrementalIndexBuildWorkflow(
+ item_paths=normalized_remaining,
+ output_dir=local_output_dir,
+ resolved_config=resolved_config,
+ base_index_dir=base_dir,
+ added_paths=[],
+ removed_paths=sorted(removed),
+ item_type=normalized_item_type,
+ manifest_item_paths=normalized_remaining,
+ ).build()
+ with timer.phase("upload_s3_output"):
+ upload_local_dir_to_s3(local_output_dir, output_value)
+ return output_value.rstrip("/")
+ return _IncrementalIndexBuildWorkflow(
+ item_paths=normalized_remaining,
+ output_dir=Path(output_dir),
+ resolved_config=resolved_config,
+ base_index_dir=base_dir,
+ added_paths=[],
+ removed_paths=sorted(removed),
+ item_type=normalized_item_type,
+ manifest_item_paths=normalized_remaining,
+ ).build()
+ finally:
+ timer.finish()
+
+
+def _load_pre_scanned_items(
+ *,
+ item_jsonl_path: str | None,
+ default_paths: Sequence[str],
+) -> tuple[Dict[str, dict] | None, list[str]]:
+ jsonl_text = load_items_jsonl_text(item_jsonl_path=item_jsonl_path)
+ if not str(jsonl_text or "").strip():
+ return None, list(default_paths)
+ scanned_items, manifest_paths = parse_jsonl_scanned_items(jsonl_text)
+ return scanned_items, normalize_item_paths(manifest_paths)
+
+
+def _resolve_item_paths_or_error(
+ *,
+ item_paths: Sequence[str] | None,
+ item_jsonl_path: str | None,
+ operation: str,
+) -> list[str]:
+ normalized_item_paths = normalize_item_paths(item_paths or ())
+ if normalized_item_paths:
+ return normalized_item_paths
+ if str(item_jsonl_path or "").strip():
+ return []
+ raise ValueError(f"IndexBuilder.{operation}: item_paths is empty and item_jsonl_path is not provided")
+
+
+def _materialize_existing_index_dir(base_index_dir: str | Path, *, cache_namespace: str) -> Path:
+ raw = str(base_index_dir).strip()
+ if is_s3_uri(raw):
+ return materialize_s3_dir(raw, cache_namespace=cache_namespace)
+ return Path(base_index_dir).resolve()
+
+
+def _resolve_materialized_item_paths(
+ item_paths: Sequence[str], *, work_dir: Path, item_type: str
+) -> list[ResolvedItemPath]:
+ resolved: list[ResolvedItemPath] = []
+ extracted_root = work_dir / "materialized"
+ extracted_root.mkdir(parents=True, exist_ok=True)
+ scanner_cls = get_scanner_class(item_type)
+
+ for index, raw_path in enumerate(item_paths):
+ raw_text = str(raw_path).strip()
+ if not raw_text:
+ continue
+ if is_s3_uri(raw_text) or is_http_uri(raw_text):
+ archive_path = _download_remote_zip(raw_text, extracted_root / f"item-{index}.zip")
+ item_dir = _extract_item_zip(archive_path, extracted_root / f"item-{index}", scanner_cls=scanner_cls)
+ source_type = "s3_zip" if is_s3_uri(raw_text) else "http_zip"
+ resolved.append(ResolvedItemPath(source_path=raw_text, source_type=source_type, materialized_dir=item_dir))
+ continue
+
+ local_path = Path(raw_text).expanduser().resolve()
+ if not local_path.exists():
+ raise FileNotFoundError(f"Item path not found: {local_path}")
+ if local_path.is_dir():
+ candidate = scanner_cls.detect_item_root(local_path)
+ if candidate is None:
+ LOGGER.warning(
+ f"Skipping invalid {scanner_cls.item_type} directory "
+ f"(no {scanner_cls.item_type} root found): {local_path}"
+ )
+ continue
+ resolved.append(
+ ResolvedItemPath(
+ source_path=str(local_path),
+ source_type="local_dir",
+ materialized_dir=candidate,
+ )
+ )
+ continue
+ if local_path.is_file() and local_path.suffix.lower() == ".zip":
+ item_dir = _extract_item_zip(local_path, extracted_root / f"item-{index}", scanner_cls=scanner_cls)
+ resolved.append(
+ ResolvedItemPath(
+ source_path=str(local_path),
+ source_type="local_zip",
+ materialized_dir=item_dir,
+ )
+ )
+ continue
+ raise ValueError(
+ f"Unsupported item path: {raw_text}. Only local dir/zip, s3://...zip, and http(s)://...zip are supported"
+ )
+
+ names: set[str] = set()
+ for item in resolved:
+ if item.materialized_dir.name in names:
+ raise ValueError(f"Duplicate skill directory name detected: {item.materialized_dir.name}")
+ names.add(item.materialized_dir.name)
+ return resolved
+
+
+def _download_remote_zip(uri: str, destination_path: Path) -> Path:
+ if not str(uri).lower().endswith(".zip"):
+ raise ValueError(f"Remote item path must point to a zip file: {uri}")
+ if is_http_uri(uri):
+ return download_http_object_to_path(str(uri), destination_path)
+ return download_s3_object_to_path(str(uri), destination_path)
+
+
+def _extract_item_zip(zip_path: Path, target_dir: Path, *, scanner_cls) -> Path:
+ if zip_path.suffix.lower() != ".zip":
+ raise ValueError(f"Zip path expected, got: {zip_path}")
+ if target_dir.exists():
+ shutil.rmtree(target_dir)
+ target_dir.mkdir(parents=True, exist_ok=True)
+ with zipfile.ZipFile(zip_path) as archive:
+ _safe_extract_zip(archive, target_dir)
+
+ direct_candidate = scanner_cls.detect_item_root(target_dir)
+ if direct_candidate is not None:
+ return direct_candidate
+
+ child_dirs = [path for path in sorted(target_dir.iterdir()) if path.is_dir() and not path.name.startswith(".")]
+ if len(child_dirs) == 1:
+ nested_candidate = scanner_cls.detect_item_root(child_dirs[0])
+ if nested_candidate is not None:
+ return nested_candidate
+
+ unique_parents = sorted(
+ {
+ path.resolve()
+ for path in target_dir.rglob("*")
+ if path.is_dir() and "__MACOSX" not in path.parts and scanner_cls.detect_item_root(path) is not None
+ }
+ )
+ if len(unique_parents) == 1:
+ return unique_parents[0]
+ if len(unique_parents) > 1:
+ pretty = ", ".join(str(path.relative_to(target_dir)) for path in unique_parents[:5])
+ raise ValueError("Zip archive contains multiple item roots; unable to choose one: " f"{pretty}")
+ raise ValueError(f"Zip archive does not contain a valid {scanner_cls.item_type} root: {zip_path}")
+
+
+def _safe_extract_zip(archive: zipfile.ZipFile, target_dir: Path) -> None:
+ target_root = target_dir.resolve()
+ for member in archive.infolist():
+ member_name = str(member.filename or "").replace("\\", "/")
+ try:
+ (target_root / member_name).resolve().relative_to(target_root)
+ except ValueError as exc:
+ raise ValueError(f"Unsafe zip member path: {member.filename}") from exc
+ archive.extractall(target_root)
+
+
+def _validate_item_dir(path: Path, *, scanner_cls) -> Path:
+ candidate = scanner_cls.detect_item_root(path)
+ if candidate is None:
+ raise ValueError(f"Item directory does not contain a valid {scanner_cls.item_type} root: {path}")
+ return candidate
+
+
+def _normalize_manifest_item_path(value: str | Path) -> str:
+ raw = str(value).strip()
+ if is_passthrough_item_uri(raw):
+ return raw
+ return str(Path(raw).expanduser().resolve())
+
+
+class _IndexBuildWorkflow:
+ def __init__(
+ self,
+ *,
+ item_paths: Sequence[str],
+ output_dir: Path,
+ resolved_config: ResolvedBuildConfig,
+ item_type: str,
+ pre_scanned_skills: Dict[str, dict] | None = None,
+ manifest_item_paths: Sequence[str] | None = None,
+ ) -> None:
+ self._item_paths = [str(path).strip() for path in item_paths if str(path).strip()]
+ self._output_dir = output_dir.resolve()
+ self._config = resolved_config
+ self._item_type = normalize_item_type(item_type)
+ self._pre_scanned_skills = (
+ {str(key): dict(value) for key, value in (pre_scanned_skills or {}).items()}
+ if pre_scanned_skills is not None
+ else None
+ )
+ self._manifest_item_paths = [
+ str(path).strip() for path in (manifest_item_paths or self._item_paths) if str(path).strip()
+ ]
+
+ def build(self) -> Path:
+ timer = StageTimer("_IndexBuildWorkflow.build", logger=LOGGER)
+ try:
+ with timer.phase("prepare_workspace"):
+ self._output_dir.mkdir(parents=True, exist_ok=True)
+ if self._pre_scanned_skills is not None:
+ return self._build_from_pre_scanned(timer=timer)
+ with tempfile.TemporaryDirectory(prefix="retriever-index-build-") as tmpdir:
+ aggregate_dir = Path(tmpdir) / "skills"
+ aggregate_dir.mkdir(parents=True, exist_ok=True)
+ pre_scanned_skills = self._pre_scanned_skills
+ if pre_scanned_skills is None:
+ with timer.phase("materialize_items"):
+ resolved_item_paths = _resolve_materialized_item_paths(
+ self._item_paths, work_dir=Path(tmpdir), item_type=self._item_type
+ )
+ self._materialize_skill_dirs(aggregate_dir, resolved_item_paths)
+ tree_skill_entries = None
+ else:
+ resolved_item_paths = []
+ tree_skill_entries = list(pre_scanned_skills.values())
+
+ tree_output_path = self._output_dir / TREE_INDEX_FILENAME
+ self._require_llm_tree_build()
+ with timer.phase("build_tree_llm"):
+ self._build_llm_tree(
+ skills_dir=aggregate_dir,
+ tree_output_path=tree_output_path,
+ display_skills_dir=(
+ self._infer_display_skills_dir(resolved_item_paths) if pre_scanned_skills is None else None
+ ),
+ skill_entries=tree_skill_entries,
+ )
+
+ with timer.phase("build_catalog_and_tree_outputs"):
+ catalog_records = self._build_catalog_records(
+ aggregate_dir,
+ tree_output_path,
+ resolved_item_paths=resolved_item_paths,
+ pre_scanned_skills=pre_scanned_skills,
+ )
+ nodes = enrich_branch_descriptions(
+ load_tree_preset(tree_output_path).get("nodes") or [], catalog_records=catalog_records
+ )
+ write_tree_preset({"nodes": nodes}, tree_output_path)
+ if self._config.output_config.generate_html:
+ generate_tree_html(
+ tree_nodes_to_tree_dict(nodes, catalog_records), self._output_dir / TREE_HTML_FILENAME
+ )
+ else:
+ self._unlink_if_exists(self._output_dir / TREE_HTML_FILENAME)
+ write_catalog(catalog_records, self._output_dir / CATALOG_FILENAME)
+ with timer.phase("write_manifest"):
+ write_manifest(
+ self._output_dir,
+ self._manifest_item_paths,
+ catalog_records,
+ mode="full",
+ item_type=self._item_type,
+ )
+ return self._output_dir
+ finally:
+ timer.finish()
+
+ def _require_llm_tree_build(self) -> None:
+ """Validate that the fixed LLM tree build path can run.
+
+ Raises:
+ ValueError: If model and client credentials are not configured.
+ """
+
+ if can_build_tree_with_llm(self._config):
+ return
+ raise ValueError(
+ "Offline tree build requires llm_config.model and either llm_config.client or llm_config.api_key"
+ )
+
+ def _build_llm_tree(
+ self,
+ *,
+ skills_dir: Path,
+ tree_output_path: Path,
+ display_skills_dir: Path | None = None,
+ skill_entries: Sequence[dict] | None = None,
+ ) -> None:
+ """Run the canonical LLM tree build.
+
+ Args:
+ skills_dir: Materialized item directory used by the scanner.
+ tree_output_path: Destination tree preset path.
+ display_skills_dir: Optional original directory shown in scanned paths.
+ skill_entries: Optional pre-scanned entries, bypassing directory scan.
+ """
+
+ llm_config = self._config.llm_config
+ taxonomy_config = self._config.taxonomy_config
+ execution_config = self._config.execution_config
+ output_config = self._config.output_config
+ root_categories = normalize_root_categories(taxonomy_config.root_categories)
+ LOGGER.info(
+ "tree llm runtime | workers=%s | timeout_seconds=%s | classify_batch_cap=%s",
+ execution_config.max_workers,
+ execution_config.request_timeout_seconds,
+ execution_config.classification_batch_limit,
+ )
+ build_tree(
+ skills_dir=skills_dir,
+ output_path=tree_output_path,
+ config=DynamicTreeConfig(
+ branching_factor=taxonomy_config.branching_factor,
+ max_depth=taxonomy_config.max_depth,
+ root_categories=root_categories,
+ ),
+ manager_config=TreeManagerConfig(
+ branching_factor=taxonomy_config.branching_factor,
+ max_depth=taxonomy_config.max_depth,
+ root_categories=root_categories,
+ build=TreeBuildConfig(
+ max_workers=execution_config.max_workers,
+ num_retries=execution_config.max_retries,
+ timeout=execution_config.request_timeout_seconds,
+ classify_batch_cap=execution_config.classification_batch_limit,
+ postprocess_enabled=taxonomy_config.postprocess_enabled,
+ postprocess_max_passes=taxonomy_config.postprocess_max_passes,
+ postprocess_min_skills=taxonomy_config.postprocess_min_skills,
+ equiv_grouping_enabled=taxonomy_config.equivalence_enabled,
+ discovery_seed=execution_config.discovery_seed,
+ ),
+ ),
+ client=llm_config.client,
+ model=llm_config.model,
+ api_key=llm_config.api_key,
+ base_url=llm_config.base_url,
+ llm_seed=llm_config.seed,
+ max_workers=execution_config.max_workers,
+ verbose=False,
+ show_tree=False,
+ generate_html=output_config.generate_html,
+ display_skills_dir=display_skills_dir,
+ item_type=self._item_type,
+ skill_entries=list(skill_entries) if skill_entries is not None else None,
+ )
+
+ def _build_from_pre_scanned(self, *, timer: StageTimer) -> Path:
+ pre_scanned_skills = self._pre_scanned_skills or {}
+ tree_output_path = self._output_dir / TREE_INDEX_FILENAME
+ self._require_llm_tree_build()
+ with timer.phase("build_tree_llm"):
+ self._build_llm_tree(
+ skills_dir=self._output_dir,
+ tree_output_path=tree_output_path,
+ skill_entries=list(pre_scanned_skills.values()),
+ )
+
+ with timer.phase("build_catalog_and_tree_outputs"):
+ catalog_records = self._build_catalog_records(
+ self._output_dir,
+ tree_output_path,
+ resolved_item_paths=[],
+ pre_scanned_skills=pre_scanned_skills,
+ )
+ nodes = enrich_branch_descriptions(
+ load_tree_preset(tree_output_path).get("nodes") or [], catalog_records=catalog_records
+ )
+ write_tree_preset({"nodes": nodes}, tree_output_path)
+ if self._config.output_config.generate_html:
+ generate_tree_html(
+ tree_nodes_to_tree_dict(nodes, catalog_records), self._output_dir / TREE_HTML_FILENAME
+ )
+ else:
+ self._unlink_if_exists(self._output_dir / TREE_HTML_FILENAME)
+ write_catalog(catalog_records, self._output_dir / CATALOG_FILENAME)
+ with timer.phase("write_manifest"):
+ write_manifest(
+ self._output_dir, self._manifest_item_paths, catalog_records, mode="full", item_type=self._item_type
+ )
+ return self._output_dir
+
+ @staticmethod
+ def _unlink_if_exists(path: Path) -> None:
+ if path.exists():
+ path.unlink()
+
+ @staticmethod
+ def _materialize_skill_dirs(aggregate_dir: Path, item_paths: Sequence[ResolvedItemPath]) -> None:
+ for item in item_paths:
+ skill_dir = item.materialized_dir
+ destination = aggregate_dir / skill_dir.name
+ if destination.exists():
+ raise ValueError(f"Duplicate skill directory name detected: {skill_dir.name}")
+ try:
+ destination.symlink_to(skill_dir, target_is_directory=True)
+ except Exception:
+ shutil.copytree(skill_dir, destination)
+
+ @staticmethod
+ def _infer_display_skills_dir(item_paths: Sequence[ResolvedItemPath]) -> Path | None:
+ local_dirs = [item.materialized_dir.parent.resolve() for item in item_paths if item.source_type == "local_dir"]
+ if not local_dirs:
+ return None
+ parents = set(local_dirs)
+ return next(iter(parents)) if len(parents) == 1 else None
+
+ def _build_catalog_records(
+ self,
+ aggregate_dir: Path,
+ tree_output_path: Path,
+ *,
+ resolved_item_paths: Sequence[ResolvedItemPath],
+ pre_scanned_skills: Dict[str, dict] | None = None,
+ ):
+ if pre_scanned_skills is not None:
+ scanned = {str(key): dict(value) for key, value in pre_scanned_skills.items()}
+ return build_catalog_records_from_nodes(
+ nodes=load_tree_preset(tree_output_path).get("nodes") or [], scanned_skills=scanned
+ )
+ source_by_skill = {item.materialized_dir.name: item.source_path for item in resolved_item_paths}
+ scanned: Dict[str, dict] = {}
+ scanner = create_scanner(self._item_type, aggregate_dir, display_items_dir=aggregate_dir)
+ for item in scanner.to_dict_list():
+ scanned[str(item["id"])] = item
+ for worker_id, item in scanned.items():
+ source_path = source_by_skill.get(worker_id)
+ if source_path:
+ item["path"] = source_path
+ return build_catalog_records_from_nodes(
+ nodes=load_tree_preset(tree_output_path).get("nodes") or [], scanned_skills=scanned
+ )
+
+
+class _IncrementalIndexBuildWorkflow(_IndexBuildWorkflow):
+ def __init__(
+ self,
+ *,
+ item_paths: Sequence[str],
+ output_dir: Path,
+ resolved_config: ResolvedBuildConfig,
+ base_index_dir: Path,
+ added_paths: Sequence[str],
+ removed_paths: Sequence[str],
+ item_type: str,
+ added_scanned_skills: Dict[str, dict] | None = None,
+ manifest_item_paths: Sequence[str] | None = None,
+ ) -> None:
+ super().__init__(
+ item_paths=item_paths,
+ output_dir=output_dir,
+ resolved_config=resolved_config,
+ item_type=item_type,
+ manifest_item_paths=manifest_item_paths,
+ )
+ self._base_index_dir = base_index_dir.resolve()
+ self._added_paths = [str(path).strip() for path in added_paths if str(path).strip()]
+ self._removed_paths = [str(path).strip() for path in removed_paths if str(path).strip()]
+ self._added_scanned_skills = (
+ {str(key): dict(value) for key, value in (added_scanned_skills or {}).items()}
+ if added_scanned_skills is not None
+ else None
+ )
+
+ def build(self) -> Path:
+ self._output_dir.mkdir(parents=True, exist_ok=True)
+ if not (self._base_index_dir / TREE_INDEX_FILENAME).exists():
+ return super().build()
+
+ existing_catalog = load_catalog_records(self._base_index_dir / CATALOG_FILENAME)
+ existing_nodes = list(load_tree_preset(self._base_index_dir / TREE_INDEX_FILENAME).get("nodes") or [])
+
+ remaining_paths = set(self._item_paths)
+ removed_path_set = set(self._removed_paths)
+ kept_catalog = []
+ for record in existing_catalog:
+ normalized_path = _normalize_manifest_item_path(record.skill_path)
+ if normalized_path in remaining_paths and normalized_path not in removed_path_set:
+ kept_catalog.append(record)
+
+ if self._added_paths:
+ scanned_added = (
+ self._added_scanned_skills if self._added_scanned_skills is not None else self._scan_added_skills()
+ )
+ existing_nodes = merge_added_skills_into_tree(nodes=existing_nodes, added_skills=scanned_added)
+ added_catalog = build_catalog_records_from_nodes(
+ nodes=existing_nodes,
+ scanned_skills=scanned_added,
+ restrict_worker_ids=set(scanned_added),
+ )
+ merged = {record.worker_id: record for record in kept_catalog}
+ for record in added_catalog:
+ merged[record.worker_id] = record
+ catalog_records = sorted(merged.values(), key=lambda item: item.cid)
+ else:
+ removed_worker_ids = {
+ record.worker_id
+ for record in existing_catalog
+ if _normalize_manifest_item_path(record.skill_path) in removed_path_set
+ }
+ existing_nodes = prune_deleted_skills_from_tree(existing_nodes, removed_worker_ids=removed_worker_ids)
+ catalog_records = sorted(kept_catalog, key=lambda item: item.cid)
+
+ worker_to_record = {record.worker_id: record for record in catalog_records}
+ nodes = align_leaf_nodes_with_catalog(existing_nodes, worker_to_record)
+ catalog_records = build_catalog_records_from_existing(nodes=nodes, records_by_worker=worker_to_record)
+ nodes = enrich_branch_descriptions(nodes, catalog_records=catalog_records)
+
+ write_tree_preset({"nodes": nodes}, self._output_dir / TREE_INDEX_FILENAME)
+ if self._config.output_config.generate_html:
+ generate_tree_html(tree_nodes_to_tree_dict(nodes, catalog_records), self._output_dir / TREE_HTML_FILENAME)
+ else:
+ self._unlink_if_exists(self._output_dir / TREE_HTML_FILENAME)
+ write_catalog(catalog_records, self._output_dir / CATALOG_FILENAME)
+ write_manifest(
+ self._output_dir, self._manifest_item_paths, catalog_records, mode="incremental", item_type=self._item_type
+ )
+ return self._output_dir
+
+ def _scan_added_skills(self) -> dict[str, dict]:
+ scanned: dict[str, dict] = {}
+ with tempfile.TemporaryDirectory(prefix="retriever-index-added-items-") as tmpdir:
+ resolved_item_paths = _resolve_materialized_item_paths(
+ self._added_paths, work_dir=Path(tmpdir), item_type=self._item_type
+ )
+ for item in resolved_item_paths:
+ skill_dir = item.materialized_dir
+ scan_root = skill_dir.parent
+ scanner = create_scanner(self._item_type, scan_root, display_items_dir=scan_root)
+ for scanned_item in scanner.to_dict_list():
+ if str(scanned_item.get("id") or "") == skill_dir.name:
+ scanned[skill_dir.name] = scanned_item
+ if not is_s3_uri(item.source_path):
+ scanned[skill_dir.name]["path"] = _normalize_manifest_item_path(item.source_path)
+ else:
+ scanned[skill_dir.name]["path"] = item.source_path
+ break
+ return scanned
+
+
+__all__ = ["IndexBuilder", "_IndexBuildWorkflow", "_IncrementalIndexBuildWorkflow"]
diff --git a/jiuwenswarm/symphony/indexing/workflows/tree_ops.py b/jiuwenswarm/symphony/indexing/workflows/tree_ops.py
new file mode 100644
index 0000000000..11e4bd9229
--- /dev/null
+++ b/jiuwenswarm/symphony/indexing/workflows/tree_ops.py
@@ -0,0 +1,310 @@
+from __future__ import annotations
+
+from collections import Counter
+from pathlib import Path
+from typing import Dict, List, Sequence
+
+from indexing.models import CatalogRecord
+
+
+def scan_skill_paths(item_paths: Sequence[Path]) -> Dict[str, dict]:
+ from indexing.scanners import SkillScanner
+
+ skill_map: Dict[str, dict] = {}
+ for path in item_paths:
+ scanner = SkillScanner(path.parent if path.name == "skills" else path.parent)
+ for item in scanner.to_dict_list():
+ if str(item.get("id") or "") == path.name:
+ skill_map[path.name] = item
+ return skill_map
+
+
+def merge_added_skills_into_tree(*, nodes: Sequence[object], added_skills: Dict[str, dict]) -> List[Dict[str, object]]:
+ normalized = [dict(node) for node in nodes if isinstance(node, dict)]
+ used_cids = {str(node.get("cid") or "") for node in normalized}
+ branch_nodes = [node for node in normalized if str(node.get("type") or "") == "branch"]
+ branch_token_cache = {
+ str(node.get("cid") or ""): text_tokens(str(node.get("cid") or ""), str(node.get("description") or ""))
+ for node in branch_nodes
+ }
+ for worker_id, skill in sorted(added_skills.items()):
+ selected_parent_cid = choose_parent_branch_for_skill(
+ skill=skill, branch_nodes=branch_nodes, branch_token_cache=branch_token_cache
+ )
+ cid = unique_child_cid(
+ parent=selected_parent_cid,
+ segment=slug_term(worker_id, fallback="skill"),
+ used=used_cids,
+ )
+ node = {
+ "cid": cid,
+ "type": "leaf",
+ "description": str(skill.get("description") or "").strip(),
+ "worker_id": worker_id,
+ }
+ normalized.append(node)
+ used_cids.add(cid)
+ return normalized
+
+
+def choose_parent_branch_for_skill(
+ *, skill: dict, branch_nodes: Sequence[Dict[str, object]], branch_token_cache: Dict[str, set[str]]
+) -> str:
+ if not branch_nodes:
+ return ""
+ skill_tokens = text_tokens(
+ str(skill.get("name") or ""),
+ str(skill.get("description") or ""),
+ str(skill.get("content") or ""),
+ )
+ best_cid = ""
+ best_score = -1
+ for node in branch_nodes:
+ cid = str(node.get("cid") or "")
+ overlap = len(skill_tokens & branch_token_cache.get(cid, set()))
+ depth_bonus = len(cid.split(".")) if cid else 0
+ score = overlap * 100 + depth_bonus
+ if score > best_score:
+ best_score = score
+ best_cid = cid
+ return best_cid
+
+
+def prune_deleted_skills_from_tree(nodes: Sequence[object], *, removed_worker_ids: set[str]) -> List[Dict[str, object]]:
+ normalized = [dict(node) for node in nodes if isinstance(node, dict)]
+ normalized = [node for node in normalized if str(node.get("worker_id") or "") not in removed_worker_ids]
+ while True:
+ child_counts: Dict[str, int] = {}
+ for node in normalized:
+ cid = str(node.get("cid") or "")
+ if not cid:
+ continue
+ parent = parent_cid(cid)
+ if parent:
+ child_counts[parent] = child_counts.get(parent, 0) + 1
+ pruned = [
+ node
+ for node in normalized
+ if str(node.get("type") or "") != "branch" or child_counts.get(str(node.get("cid") or ""), 0) > 0
+ ]
+ if len(pruned) == len(normalized):
+ return pruned
+ normalized = pruned
+
+
+def align_leaf_nodes_with_catalog(
+ nodes: Sequence[object], records_by_worker: Dict[str, CatalogRecord]
+) -> List[Dict[str, object]]:
+ aligned: List[Dict[str, object]] = []
+ for raw_node in nodes:
+ if not isinstance(raw_node, dict):
+ continue
+ node = dict(raw_node)
+ worker_id = str(node.get("worker_id") or "").strip()
+ if worker_id and worker_id in records_by_worker:
+ record = records_by_worker[worker_id]
+ node["cid"] = record.cid
+ node["description"] = record.description
+ aligned.append(node)
+ return aligned
+
+
+def build_catalog_records_from_existing(
+ *, nodes: Sequence[object], records_by_worker: Dict[str, CatalogRecord]
+) -> List[CatalogRecord]:
+ records: List[CatalogRecord] = []
+ for raw_node in nodes:
+ if not isinstance(raw_node, dict):
+ continue
+ worker_id = str(raw_node.get("worker_id") or "").strip()
+ if not worker_id:
+ continue
+ record = records_by_worker.get(worker_id)
+ if record is None:
+ continue
+ records.append(
+ CatalogRecord(
+ worker_id=record.worker_id,
+ cid=str(raw_node.get("cid") or record.cid),
+ name=record.name,
+ description=str(raw_node.get("description") or record.description),
+ skill_path=record.skill_path,
+ branch_path=tuple(str(raw_node.get("cid") or record.cid).split(".")[:-1]),
+ category=record.category,
+ retrieval_text=record.retrieval_text,
+ metadata=dict(record.metadata),
+ )
+ )
+ return sorted(records, key=lambda item: item.cid)
+
+
+def tree_nodes_to_tree_dict(nodes: Sequence[object], records: Sequence[CatalogRecord]) -> dict:
+ nodes_by_cid = {str(node.get("cid") or ""): dict(node) for node in nodes if isinstance(node, dict)}
+ children: Dict[str, list[str]] = {}
+ for cid in nodes_by_cid:
+ parent = parent_cid(cid)
+ children.setdefault(parent, []).append(cid)
+ records_by_cid = {record.cid: record for record in records}
+
+ def build(cid: str) -> dict:
+ node = nodes_by_cid.get(cid, {})
+ label = cid.split(".")[-1] if cid else "ROOT"
+ payload = {
+ "name": str(node.get("worker_id") or label),
+ "cid": cid,
+ "type": str(node.get("type") or "branch"),
+ "description": str(node.get("description") or ""),
+ "children": [build(child) for child in sorted(children.get(cid, []))],
+ }
+ record = records_by_cid.get(cid)
+ if record is not None:
+ payload["skill_path"] = record.skill_path
+ payload["worker_id"] = record.worker_id
+ return payload
+
+ root_children = [build(cid) for cid in sorted(children.get("", []))]
+ return {"name": "ROOT", "cid": "ROOT", "type": "root", "children": root_children}
+
+
+def enrich_branch_descriptions(
+ nodes: Sequence[object], *, catalog_records: Sequence[CatalogRecord]
+) -> List[Dict[str, object]]:
+ catalog_by_branch: Dict[str, list[CatalogRecord]] = {}
+ for record in catalog_records:
+ parts = record.cid.split(".")
+ for depth in range(1, len(parts)):
+ branch_cid = ".".join(parts[:depth])
+ catalog_by_branch.setdefault(branch_cid, []).append(record)
+
+ enriched: List[Dict[str, object]] = []
+ for raw_node in nodes:
+ if not isinstance(raw_node, dict):
+ continue
+ node = dict(raw_node)
+ if str(node.get("type") or "") == "branch":
+ cid = str(node.get("cid") or "")
+ node["description"] = build_branch_description(
+ cid=cid,
+ existing_description=str(node.get("description") or ""),
+ descendants=catalog_by_branch.get(cid, ()),
+ )
+ enriched.append(node)
+ return enriched
+
+
+def build_branch_description(*, cid: str, existing_description: str, descendants: Sequence[CatalogRecord]) -> str:
+ base = strip_branch_exposure(existing_description)
+ if not descendants:
+ return base
+ samples = sample_catalog_records(descendants, limit=3)
+ parts: List[str] = []
+ if base:
+ parts.append(base)
+ parts.append(f"Covers {len(descendants)} descendant skill{'s' if len(descendants) != 1 else ''}.")
+ keywords = collect_branch_keywords(descendants, limit=8)
+ if keywords:
+ parts.append("Representative keywords: " + ", ".join(keywords))
+ parts.append(
+ "Representative descendants: " + "; ".join(format_catalog_record_snippet(record) for record in samples)
+ )
+ return "\n\n".join(part for part in parts if part).strip()
+
+
+def strip_branch_exposure(description: str) -> str:
+ marker = "Representative descendants:"
+ head, _sep, _tail = str(description or "").partition(marker)
+ return head.strip()
+
+
+def sample_catalog_records(records: Sequence[CatalogRecord], *, limit: int) -> List[CatalogRecord]:
+ target = max(0, limit)
+ if target <= 0:
+ return []
+ ordered = sorted(records, key=lambda item: (item.name.lower(), item.worker_id.lower(), item.cid))
+ selected: List[CatalogRecord] = []
+ seen_worker_ids: set[str] = set()
+ seen_tokens: set[str] = set()
+ while len(selected) < min(target, len(ordered)):
+ best_record: CatalogRecord | None = None
+ best_score = -1
+ for record in ordered:
+ if record.worker_id in seen_worker_ids:
+ continue
+ tokens = _record_text_tokens(record)
+ novelty = len(tokens - seen_tokens)
+ coverage = len(tokens)
+ score = novelty * 10 + coverage
+ if best_record is None or score > best_score:
+ best_record = record
+ best_score = score
+ if best_record is None:
+ break
+ selected.append(best_record)
+ seen_worker_ids.add(best_record.worker_id)
+ seen_tokens.update(_record_text_tokens(best_record))
+ return selected
+
+
+def format_catalog_record_snippet(record: CatalogRecord) -> str:
+ name = str(record.name or record.worker_id).strip() or record.worker_id
+ summary = _compact_summary(record.description, limit=96)
+ if summary:
+ return f"{name}: {summary}"
+ return name
+
+
+def collect_branch_keywords(records: Sequence[CatalogRecord], *, limit: int) -> List[str]:
+ counter: Counter[str] = Counter()
+ for record in records:
+ counter.update(_record_text_tokens(record))
+ if not counter:
+ return []
+ ranked = sorted(counter.items(), key=lambda item: (-item[1], item[0]))
+ return [token for token, _count in ranked[:max(0, limit)]]
+
+
+def _record_text_tokens(record: CatalogRecord) -> set[str]:
+ return text_tokens(record.name, record.description, record.worker_id, record.cid)
+
+
+def _compact_summary(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 text_tokens(*values: str) -> set[str]:
+ tokens: set[str] = set()
+ for value in values:
+ for token in str(value or "").replace("-", " ").replace("_", " ").replace(".", " ").split():
+ cleaned = token.strip().lower()
+ if cleaned:
+ tokens.add(cleaned)
+ return tokens
+
+
+def slug_term(value: str, fallback: str = "node") -> str:
+ raw = "".join(ch.lower() if ch.isalnum() else "-" for ch in str(value or ""))
+ compact = "-".join(part for part in raw.split("-") if part)
+ return compact or fallback
+
+
+def join_cid(parent: str, child: str) -> str:
+ return f"{parent}.{child}" if parent else child
+
+
+def parent_cid(cid: str) -> str:
+ return cid.rsplit(".", 1)[0] if "." in cid else ""
+
+
+def unique_child_cid(*, parent: str, segment: str, used: set[str]) -> str:
+ candidate = join_cid(parent, segment)
+ if candidate not in used:
+ return candidate
+ index = 2
+ while True:
+ candidate = join_cid(parent, f"{segment}-{index}")
+ if candidate not in used:
+ return candidate
+ index += 1
diff --git a/jiuwenswarm/symphony/models/__init__.py b/jiuwenswarm/symphony/models/__init__.py
new file mode 100644
index 0000000000..9b5058337c
--- /dev/null
+++ b/jiuwenswarm/symphony/models/__init__.py
@@ -0,0 +1,21 @@
+from .cid import CID, NodeSpec, NodeType
+from .retrieval import (
+ RetrieverCandidate,
+ RetrieverChoice,
+ RetrieverItem,
+ RetrieverNode,
+ RetrieverTrace,
+ RetrieverTraceEvent,
+)
+
+__all__ = [
+ "CID",
+ "NodeSpec",
+ "NodeType",
+ "RetrieverCandidate",
+ "RetrieverChoice",
+ "RetrieverItem",
+ "RetrieverNode",
+ "RetrieverTrace",
+ "RetrieverTraceEvent",
+]
diff --git a/jiuwenswarm/symphony/models/cid/__init__.py b/jiuwenswarm/symphony/models/cid/__init__.py
new file mode 100644
index 0000000000..33d6517e82
--- /dev/null
+++ b/jiuwenswarm/symphony/models/cid/__init__.py
@@ -0,0 +1,28 @@
+from .converters import (
+ WorkerCIDConverters,
+ build_worker_cid_converters,
+ build_worker_cid_converters_from_yaml_file,
+ build_worker_cid_converters_from_yaml_text,
+ load_worker_cid_converter_functions_from_yaml_file,
+)
+from .node_spec import CID, NodeSpec, NodeType
+from .tid import TIDBuildConfig, TIDBuildDecision, TIDBuildResult, WorkerProfile
+from .tree import CIDTree, InvalidPathError, ParseError
+
+__all__ = [
+ "CID",
+ "CIDTree",
+ "InvalidPathError",
+ "NodeSpec",
+ "NodeType",
+ "ParseError",
+ "TIDBuildConfig",
+ "TIDBuildDecision",
+ "TIDBuildResult",
+ "WorkerCIDConverters",
+ "WorkerProfile",
+ "build_worker_cid_converters",
+ "build_worker_cid_converters_from_yaml_file",
+ "build_worker_cid_converters_from_yaml_text",
+ "load_worker_cid_converter_functions_from_yaml_file",
+]
diff --git a/jiuwenswarm/symphony/models/cid/converters.py b/jiuwenswarm/symphony/models/cid/converters.py
new file mode 100644
index 0000000000..411540dd72
--- /dev/null
+++ b/jiuwenswarm/symphony/models/cid/converters.py
@@ -0,0 +1,70 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, Dict, Tuple
+
+from .node_spec import CID
+from .tree import CIDTree
+
+
+@dataclass(frozen=True)
+class WorkerCIDConverters:
+ worker_id_to_cid_map: Dict[str, str]
+ cid_to_worker_id_map: Dict[str, str]
+
+ def worker_id_to_cid(self, worker_id: str) -> str | None:
+ key = str(worker_id or "").strip()
+ if not key:
+ return None
+ return self.worker_id_to_cid_map.get(key)
+
+ def cid_to_worker_id(self, cid: str | CID) -> str | None:
+ if isinstance(cid, CID):
+ key = cid.to_str()
+ else:
+ key = str(cid or "").strip()
+ if not key:
+ return None
+ return self.cid_to_worker_id_map.get(key)
+
+ def as_functions(self) -> Tuple[Callable[[str], str | None], Callable[[str | CID], str | None]]:
+ return self.worker_id_to_cid, self.cid_to_worker_id
+
+
+def build_worker_cid_converters(cid_tree: CIDTree) -> WorkerCIDConverters:
+ worker_id_to_cid: Dict[str, str] = {}
+ cid_to_worker_id: Dict[str, str] = {}
+
+ for spec in cid_tree.all():
+ worker_id = str(spec.worker_id or "").strip()
+ if not worker_id:
+ continue
+ cid = spec.cid.to_str()
+ if not cid:
+ continue
+ existing_cid = worker_id_to_cid.get(worker_id)
+ if existing_cid is not None and existing_cid != cid:
+ raise ValueError(f"Duplicate worker_id '{worker_id}' for CIDs '{existing_cid}' and '{cid}'")
+ worker_id_to_cid[worker_id] = cid
+ cid_to_worker_id[cid] = worker_id
+
+ return WorkerCIDConverters(
+ worker_id_to_cid_map=worker_id_to_cid,
+ cid_to_worker_id_map=cid_to_worker_id,
+ )
+
+
+def build_worker_cid_converters_from_yaml_text(preset_yaml: str) -> WorkerCIDConverters:
+ return build_worker_cid_converters(CIDTree.from_yaml(str(preset_yaml or "")))
+
+
+def build_worker_cid_converters_from_yaml_file(path: str | Path) -> WorkerCIDConverters:
+ preset_path = Path(path)
+ return build_worker_cid_converters_from_yaml_text(preset_path.read_text(encoding="utf-8"))
+
+
+def load_worker_cid_converter_functions_from_yaml_file(
+ path: str | Path,
+) -> Tuple[Callable[[str], str | None], Callable[[str | CID], str | None]]:
+ return build_worker_cid_converters_from_yaml_file(path).as_functions()
diff --git a/jiuwenswarm/symphony/models/cid/node_spec.py b/jiuwenswarm/symphony/models/cid/node_spec.py
new file mode 100644
index 0000000000..3505fd7564
--- /dev/null
+++ b/jiuwenswarm/symphony/models/cid/node_spec.py
@@ -0,0 +1,75 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+from typing import Tuple, Optional
+import re
+
+
+_TERM_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_-]*$")
+
+
+def _validate_term(term: str) -> None:
+ if not _TERM_RE.match(term):
+ raise ValueError(
+ "Invalid term: %s. Terms must start with a letter and contain only letters, numbers, '_' or '-'."
+ % term
+ )
+
+
+@dataclass(frozen=True)
+class CID:
+ terms: Tuple[str, ...] = ()
+
+ @staticmethod
+ def from_str(value: str) -> "CID":
+ value = (value or "").strip()
+ if value == "":
+ return CID(())
+ parts = tuple(part.strip() for part in value.split("."))
+ for term in parts:
+ _validate_term(term)
+ return CID(parts)
+
+ def to_str(self) -> str:
+ return ".".join(self.terms)
+
+ def is_root(self) -> bool:
+ return len(self.terms) == 0
+
+ def parent(self) -> Optional["CID"]:
+ if self.is_root():
+ return None
+ return CID(self.terms[:-1])
+
+ def child(self, term: str) -> "CID":
+ _validate_term(term)
+ return CID(self.terms + (term,))
+
+ def startswith(self, other: "CID") -> bool:
+ if len(other.terms) > len(self.terms):
+ return False
+ return self.terms[:len(other.terms)] == other.terms
+
+ def replace_prefix(self, old_prefix: "CID", new_prefix: "CID") -> "CID":
+ if not self.startswith(old_prefix):
+ raise ValueError(f"{self.to_str()} does not start with prefix {old_prefix.to_str()}")
+ suffix = self.terms[len(old_prefix.terms):]
+ return CID(new_prefix.terms + suffix)
+
+
+class NodeType(str, Enum):
+ BRANCH = "branch"
+ LEAF = "leaf"
+ SYSTEM = "system"
+
+
+@dataclass(frozen=True)
+class NodeSpec:
+ cid: CID
+ name: str
+ description: str
+ node_type: NodeType
+ worker_id: Optional[str]
+ keywords: Tuple[str, ...] = ()
+ examples: Tuple[str, ...] = ()
diff --git a/jiuwenswarm/symphony/models/cid/tid.py b/jiuwenswarm/symphony/models/cid/tid.py
new file mode 100644
index 0000000000..bf0b8fa0fe
--- /dev/null
+++ b/jiuwenswarm/symphony/models/cid/tid.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Tuple
+
+
+@dataclass(frozen=True)
+class WorkerProfile:
+ worker_id: str
+ name: str
+ description: str
+ keywords: Tuple[str, ...] = ()
+ examples: Tuple[str, ...] = ()
+
+
+@dataclass(frozen=True)
+class TIDBuildDecision:
+ action: str
+ cid: str
+ reason: str
+
+
+@dataclass(frozen=True)
+class TIDBuildResult:
+ worker_id: str
+ tid: str
+ created_nodes: Tuple[str, ...] = ()
+ moved_nodes: Tuple[str, ...] = ()
+ decisions: Tuple[TIDBuildDecision, ...] = ()
+ rebalanced_branches: Tuple[str, ...] = ()
+
+
+@dataclass(frozen=True)
+class TIDBuildConfig:
+ max_children_per_branch: int = 10
+ max_new_branch_depth: int = 2
+ descend_threshold: float = 1.0
+ sibling_margin: float = 0.25
+ min_group_size_for_rebalance: int = 2
+ protected_branch_terms: Tuple[str, ...] = field(default_factory=lambda: ("User", "Guard", "TaskAssistant"))
diff --git a/jiuwenswarm/symphony/models/cid/tree.py b/jiuwenswarm/symphony/models/cid/tree.py
new file mode 100644
index 0000000000..c087fe4506
--- /dev/null
+++ b/jiuwenswarm/symphony/models/cid/tree.py
@@ -0,0 +1,668 @@
+from __future__ import annotations
+
+import logging
+import re
+from dataclasses import replace
+from importlib import import_module
+from typing import Any, Iterable, List, Tuple
+
+from orchestration.utils.naming import fuzzy_name_distance, normalize_name_key, to_pascal_case
+from .node_spec import CID, NodeSpec, NodeType
+
+
+class NodeError(Exception):
+ pass
+
+
+class ParseError(NodeError):
+ pass
+
+
+class InvalidPathError(NodeError):
+ pass
+
+
+class CIDTree:
+ _CID_PATTERN = re.compile(r"([A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)*)")
+ _PLACEHOLDER_TOKENS = {"CID", "MESSAGE", "PATH", "NODE"}
+
+ def __init__(
+ self,
+ *,
+ nodes: dict[str, NodeSpec] | None = None,
+ routing_policy: str = "",
+ tree_sketch: str = "",
+ ) -> None:
+ self._nodes: dict[str, NodeSpec] = dict(nodes or {})
+ self._children: dict[str, list[str]] = {}
+ self._routing_policy = routing_policy
+ self._tree_sketch = tree_sketch
+ self._leaf_count_cache: dict[str, int] = {}
+ self._subtree_cache: dict[tuple[str, int], str] = {}
+ self.rebuild()
+
+ @classmethod
+ def from_yaml(cls, preset: str, logger: logging.Logger | None = None) -> "CIDTree":
+ yaml = cls._require_yaml_module()
+ data = yaml.safe_load(preset) or {}
+ if not isinstance(data, dict):
+ raise ValueError(
+ "Preset content must deserialize to a mapping\
+ with optional 'routing_policy', 'tree_sketch', and 'nodes' fields"
+ )
+
+ nodes = data.get("nodes", [])
+ if not isinstance(nodes, list):
+ raise ValueError("Preset 'nodes' must be a list")
+
+ cid_tree = cls(
+ routing_policy=cls._render_routing_policy(data.get("routing_policy")),
+ tree_sketch=cls._render_tree_sketch(data.get("tree_sketch")),
+ )
+ for item in nodes:
+ if not isinstance(item, dict):
+ raise ValueError("Each node entry must be a mapping")
+ spec = cid_tree._spec_from_definition(item)
+ cid_tree.register(spec)
+
+ for spec in list(cid_tree.all()):
+ cid_tree._ensure_ancestors(spec.cid)
+
+ cid_tree.rebuild()
+ cid_tree._refresh_branch_descriptions()
+ cid_tree.rebuild()
+
+ if logger is not None:
+ logger.info("Loaded %d nodes", len(list(cid_tree.all())))
+ return cid_tree
+
+ @property
+ def routing_policy(self) -> str:
+ return self._routing_policy
+
+ @property
+ def tree_sketch(self) -> str:
+ return self._tree_sketch
+
+ @staticmethod
+ def _require_yaml_module():
+ try:
+ return import_module("yaml")
+ except ModuleNotFoundError as exc:
+ raise ModuleNotFoundError(
+ "PyYAML is required to load orchestrator presets. Install the `yaml` package dependency first."
+ ) from exc
+
+ @classmethod
+ def normalize_cid_str(cls, value: str) -> str:
+ value = (value or "").strip()
+ if value.startswith("<") and value.endswith(">") and len(value) > 2:
+ value = value[1:-1].strip()
+ return value
+
+ @classmethod
+ def parse_cid_message(cls, text: str) -> Tuple[str, str]:
+ if not text or not text.strip():
+ raise ParseError("Empty response")
+ lines = text.strip().splitlines()
+ for idx, line in enumerate(lines):
+ if ":" not in line:
+ continue
+ left, right = line.split(":", 1)
+ left = left.strip()
+ if left.lower().startswith("to "):
+ left = left[3:].strip()
+ left = cls.normalize_cid_str(left)
+ right = right.rstrip()
+ if not left:
+ continue
+ if left.upper() in cls._PLACEHOLDER_TOKENS:
+ continue
+ if not cls._CID_PATTERN.fullmatch(left):
+ continue
+ rest = lines[idx + 1:] if idx + 1 < len(lines) else []
+ message = right.strip()
+ if rest:
+ message = (message + "\n" + "\n".join(rest)).strip()
+ return left, message
+ raise ParseError("No 'To <CID>: <Instruction>' pattern found")
+
+ @classmethod
+ def extract_cid_from_text(cls, text: str) -> str | None:
+ if not text:
+ return None
+ prefixed = re.search(r"\bTo\s+([A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)*)", text)
+ if prefixed:
+ candidate = cls.normalize_cid_str(prefixed.group(1))
+ if candidate.upper() not in cls._PLACEHOLDER_TOKENS:
+ return candidate
+ match = cls._CID_PATTERN.search(text)
+ if not match:
+ return None
+ candidate = cls.normalize_cid_str(match.group(1))
+ if candidate.upper() in cls._PLACEHOLDER_TOKENS or candidate.lower() == "to":
+ return None
+ return candidate
+
+ @staticmethod
+ def parse_cid(value: str) -> CID:
+ return CID.from_str(value)
+
+ @staticmethod
+ def _normalize_name_token(value: str) -> str:
+ return normalize_name_key(value)
+
+ @staticmethod
+ def _display_name(spec: NodeSpec) -> str:
+ fallback = spec.cid.terms[-1] if spec.cid.terms else "ROOT"
+ name = str(spec.name or "").strip()
+ return name if name else fallback
+
+ def _spec_lookup_keys(self, spec: NodeSpec) -> set[str]:
+ keys: set[str] = set()
+ display_name = self._display_name(spec)
+ if display_name:
+ keys.add(self._normalize_name_token(display_name))
+ cid_str = spec.cid.to_str()
+ if cid_str:
+ keys.add(self._normalize_name_token(cid_str))
+ term = spec.cid.terms[-1] if spec.cid.terms else ""
+ if term:
+ keys.add(self._normalize_name_token(term))
+ worker_id = str(spec.worker_id or "").strip()
+ if worker_id:
+ keys.add(self._normalize_name_token(worker_id))
+ return {key for key in keys if key}
+
+ def _match_specs_by_name(self, specs: Iterable[NodeSpec], raw_name: str) -> list[NodeSpec]:
+ query_key = self._normalize_name_token(raw_name)
+ if not query_key:
+ return []
+
+ exact_matches: list[NodeSpec] = []
+ fuzzy_matches: list[tuple[int, NodeSpec]] = []
+ for spec in specs:
+ keys = self._spec_lookup_keys(spec)
+ if not keys:
+ continue
+ if query_key in keys:
+ exact_matches.append(spec)
+ continue
+ best_distance: int | None = None
+ for key in keys:
+ distance = fuzzy_name_distance(query_key, key)
+ if distance is None:
+ continue
+ if best_distance is None or distance < best_distance:
+ best_distance = distance
+ if best_distance is not None:
+ fuzzy_matches.append((best_distance, spec))
+
+ if exact_matches:
+ return self._dedupe_specs(exact_matches)
+ if not fuzzy_matches:
+ return []
+ best_distance = min(distance for distance, _spec in fuzzy_matches)
+ return self._dedupe_specs([spec for distance, spec in fuzzy_matches if distance == best_distance])
+
+ @staticmethod
+ def _dedupe_specs(specs: Iterable[NodeSpec]) -> list[NodeSpec]:
+ ordered: list[NodeSpec] = []
+ seen: set[str] = set()
+ for spec in specs:
+ cid = spec.cid.to_str()
+ if cid in seen:
+ continue
+ seen.add(cid)
+ ordered.append(spec)
+ return ordered
+
+ def resolve_cid_from_name_path(self, raw_path: str) -> str | None:
+ text = str(raw_path or "").strip().strip("`").strip("<>").strip()
+ if not text:
+ return None
+ if text.upper().startswith("ROOT."):
+ text = text[5:].strip()
+ if text.upper() == "ROOT":
+ return ""
+
+ # Direct CID fast-path.
+ try:
+ cid = CID.from_str(text)
+ if self.exists(cid):
+ return cid.to_str()
+ except ValueError as e:
+ if logger is not None:
+ logger.debug("Direct CID parsing failed for '%s': %s", text, str(e))
+
+ segments = [segment.strip() for segment in text.split(".") if segment.strip()]
+ if not segments:
+ return None
+ if self._normalize_name_token(segments[0]) == "root":
+ segments = segments[1:]
+ if not segments:
+ return ""
+
+ current = CID(())
+ for segment in segments:
+ matches = self._match_specs_by_name(self.get_children(current), segment)
+ if len(matches) != 1:
+ return None
+ current = matches[0].cid
+ return current.to_str()
+
+ def resolve_leaf_cids_from_name(self, raw_name: str) -> list[str]:
+ leaf_specs = [spec for spec in self.all() if spec.node_type in (NodeType.LEAF, NodeType.SYSTEM)]
+ return sorted(spec.cid.to_str() for spec in self._match_specs_by_name(leaf_specs, raw_name))
+
+ def register(self, spec: NodeSpec) -> None:
+ self._nodes[spec.cid.to_str()] = spec
+ self._add_node(spec)
+
+ def update(self, spec: NodeSpec) -> None:
+ self._nodes[spec.cid.to_str()] = spec
+ self.rebuild()
+
+ def rebuild(self) -> None:
+ self._children = {}
+ for spec in self._nodes.values():
+ self._add_node(spec)
+ self._leaf_count_cache = {}
+ self._subtree_cache = {}
+
+ def get(self, cid: str | CID) -> NodeSpec | None:
+ return self._nodes.get(self._coerce_cid(cid).to_str())
+
+ def exists(self, cid: str | CID) -> bool:
+ return self._coerce_cid(cid).to_str() in self._nodes
+
+ def all(self) -> Iterable[NodeSpec]:
+ return self._nodes.values()
+
+ def get_children(self, cid: str | CID) -> List[NodeSpec]:
+ parent = self._coerce_cid(cid)
+ terms = self._children.get(parent.to_str(), [])
+ children: List[NodeSpec] = []
+ for term in terms:
+ spec = self.get(parent.child(term))
+ if spec is not None:
+ children.append(spec)
+ return children
+
+ def validate_child(self, parent_cid: str | CID, term: str) -> bool:
+ return term in self._children.get(self._coerce_cid(parent_cid).to_str(), [])
+
+ def is_leaf(self, cid: str | CID) -> bool:
+ spec = self.get(cid)
+ if spec is None:
+ return False
+ return spec.node_type in (NodeType.LEAF, NodeType.SYSTEM)
+
+ def is_second_leaf(self, cid: str | CID) -> bool:
+ """
+ Second-leaf node: a branch whose direct children are all leaf/system nodes.
+ """
+ node_cid = self._coerce_cid(cid)
+ spec = self.get(node_cid)
+ if spec is None or self.is_leaf(node_cid):
+ return False
+ children = self.get_children(node_cid)
+ if not children:
+ return False
+ return all(self.is_leaf(child.cid) for child in children)
+
+ def leaf_count(self, cid: str | CID) -> int:
+ node_cid = self._coerce_cid(cid)
+ key = node_cid.to_str()
+ cached = self._leaf_count_cache.get(key)
+ if cached is not None:
+ return cached
+ if self.is_leaf(node_cid):
+ self._leaf_count_cache[key] = 1
+ return 1
+ count = sum(self.leaf_count(child.cid) for child in self.get_children(node_cid))
+ self._leaf_count_cache[key] = count
+ return count
+
+ def get_descendant_leaves(self, cid: str | CID) -> List[NodeSpec]:
+ node_cid = self._coerce_cid(cid)
+ if self.is_leaf(node_cid):
+ spec = self.get(node_cid)
+ return [spec] if spec is not None else []
+ leaves: List[NodeSpec] = []
+ for child in self.get_children(node_cid):
+ leaves.extend(self.get_descendant_leaves(child.cid))
+ return leaves
+
+ def child_terms(self, cid: str | CID) -> List[str]:
+ return [spec.cid.terms[-1] for spec in self.get_children(cid)]
+
+ def serialize_subtree(self, cid: str | CID, max_depth: int = 1) -> str:
+ parent_cid = self._coerce_cid(cid)
+ if max_depth <= 0:
+ max_depth = 1
+ cache_key = (parent_cid.to_str(), int(max_depth))
+ cached = self._subtree_cache.get(cache_key)
+ if cached is not None:
+ return cached
+ children = self.get_children(parent_cid)
+ if not children:
+ self._subtree_cache[cache_key] = "(no children)"
+ return "(no children)"
+ lines: List[str] = []
+ for child in children:
+ self._append_subtree_prompt_lines(lines, child, remaining_depth=max_depth, indent="")
+ rendered = "\n".join(lines)
+ self._subtree_cache[cache_key] = rendered
+ return rendered
+
+ def serialize_root_subtree(self, max_depth: int = 1) -> str:
+ return self.serialize_subtree(CID(()), max_depth)
+
+ def serialize_name_tree(self, cid: str | CID = CID(())) -> str:
+ parent_cid = self._coerce_cid(cid)
+ children = self.get_children(parent_cid)
+ if not children:
+ return "(no children)"
+ lines: List[str] = []
+ for child in children:
+ self._append_name_tree_lines(lines, child, indent="")
+ return "\n".join(lines)
+
+ def serialize_cid_tree(
+ self,
+ cid: str | CID = CID(()),
+ *,
+ include_user_nodes: bool = True,
+ include_system_nodes: bool = True,
+ draft_selection_level: str = "leaf",
+ ) -> str:
+ selection_level = str(draft_selection_level or "leaf").strip().lower()
+ if selection_level not in {"leaf", "second_leaf"}:
+ selection_level = "leaf"
+ parent_cid = self._coerce_cid(cid)
+ children = []
+
+ for child in self.get_children(parent_cid):
+ if self._include_in_llm_tree(
+ child,
+ include_user_nodes=include_user_nodes,
+ include_system_nodes=include_system_nodes,
+ draft_selection_level=selection_level,
+ ):
+ children.append(child)
+
+ if not children:
+ return "(no children)"
+ lines: List[str] = []
+ for child in children:
+ self._append_cid_tree_lines(
+ lines,
+ child,
+ indent="",
+ include_user_nodes=include_user_nodes,
+ include_system_nodes=include_system_nodes,
+ draft_selection_level=selection_level,
+ )
+ return "\n".join(lines)
+
+ def clip_to_valid_prefix_with_flag(self, cid: str | CID) -> tuple[CID | None, bool]:
+ current = CID(())
+ clipped = False
+ target = self._coerce_cid(cid)
+ for term in target.terms:
+ if self.validate_child(current, term):
+ current = current.child(term)
+ continue
+ clipped = True
+ break
+ if current.is_root() and target.terms:
+ return None, True
+ return current, clipped
+
+ def analyze_invalid_path(self, cid: str | CID) -> tuple[str, str]:
+ target = self._coerce_cid(cid)
+ current = CID(())
+ for term in target.terms:
+ if self.validate_child(current, term):
+ current = current.child(term)
+ continue
+ parent = current.to_str() or "ROOT"
+ children = self.child_terms(current)
+ detail = f"CID '{target.to_str()}' is invalid because '{term}' is not a child of '{parent}'."
+ if children:
+ hint = f"Choose an existing child under '{parent}': {', '.join(children)}."
+ else:
+ hint = f"Go back to '{parent}' or choose User.Chat if no worker in this branch fits."
+ return detail, hint
+ return "The selected CID does not exist in the current tree.", "Choose an existing node from the current tree."
+
+ def collapse_unique_chain(self, cid: str | CID) -> CID:
+ current = self._coerce_cid(cid)
+ visited: set[str] = set()
+ while not self.is_leaf(current):
+ key = current.to_str()
+ if key in visited:
+ break
+ visited.add(key)
+ children = self.get_children(current)
+ if len(children) != 1:
+ break
+ current = children[0].cid
+ return current
+
+ def _add_node(self, spec: NodeSpec) -> None:
+ cid_str = spec.cid.to_str()
+ parent = spec.cid.parent()
+ parent_str = parent.to_str() if parent else ""
+ self._children.setdefault(parent_str, [])
+ if not spec.cid.is_root():
+ term = spec.cid.terms[-1]
+ if term not in self._children[parent_str]:
+ self._children[parent_str].append(term)
+ self._children[parent_str].sort()
+ self._children.setdefault(cid_str, [])
+
+ def _append_subtree_prompt_lines(self, lines: List[str], spec: NodeSpec, remaining_depth: int, indent: str) -> None:
+ label = self._llm_tree_label(spec)
+ if spec.node_type == NodeType.SYSTEM:
+ kind = "system"
+ elif self.is_leaf(spec.cid):
+ kind = "leaf"
+ else:
+ kind = "branch"
+ line = f"{indent}- {label} [{kind}]"
+ details = [spec.description]
+ if spec.keywords:
+ details.append("keywords: " + ", ".join(spec.keywords[:6]))
+ if not self.is_leaf(spec.cid):
+ details.append(f"descendant_leaves={self.leaf_count(spec.cid)}")
+ line += ": " + " | ".join(detail for detail in details if detail)
+ lines.append(line)
+ if remaining_depth <= 1 or self.is_leaf(spec.cid):
+ return
+ for child in self.get_children(spec.cid):
+ self._append_subtree_prompt_lines(lines, child, remaining_depth - 1, indent + " ")
+
+ def _append_name_tree_lines(self, lines: List[str], spec: NodeSpec, indent: str) -> None:
+ label = self._display_name(spec)
+ description = " ".join(str(spec.description or "").split())
+ node_kind = "worker" if self.is_leaf(spec.cid) else "category"
+ line = f"{indent}- {label} [{node_kind}]"
+ if description and self.is_leaf(spec.cid):
+ line += f": {description}"
+ lines.append(line)
+ if self.is_leaf(spec.cid):
+ return
+ for child in self.get_children(spec.cid):
+ self._append_name_tree_lines(lines, child, indent + " ")
+
+ def _append_cid_tree_lines(
+ self,
+ lines: List[str],
+ spec: NodeSpec,
+ indent: str,
+ *,
+ include_user_nodes: bool,
+ include_system_nodes: bool,
+ draft_selection_level: str,
+ ) -> None:
+ label = self._llm_tree_label(spec)
+ description = " ".join(str(spec.description or "").split())
+ selection_level = str(draft_selection_level or "leaf").strip().lower()
+ is_terminal = self.is_second_leaf(spec.cid) if selection_level == "second_leaf" else self.is_leaf(spec.cid)
+ node_kind = "worker" if is_terminal else "category"
+ line = f"{indent}- {label} [{node_kind}]"
+ if description and is_terminal:
+ line += f": {description}"
+ lines.append(line)
+ if is_terminal:
+ return
+ for child in self.get_children(spec.cid):
+ if not self._include_in_llm_tree(
+ child,
+ include_user_nodes=include_user_nodes,
+ include_system_nodes=include_system_nodes,
+ draft_selection_level=selection_level,
+ ):
+ continue
+ self._append_cid_tree_lines(
+ lines,
+ child,
+ indent + " ",
+ include_user_nodes=include_user_nodes,
+ include_system_nodes=include_system_nodes,
+ draft_selection_level=selection_level,
+ )
+
+ @staticmethod
+ def _include_in_llm_tree(
+ spec: NodeSpec,
+ *,
+ include_user_nodes: bool,
+ include_system_nodes: bool,
+ draft_selection_level: str = "leaf",
+ ) -> bool:
+ selection_level = str(draft_selection_level or "leaf").strip().lower()
+ cid_str = spec.cid.to_str()
+ if cid_str == "Guard":
+ return False
+ if cid_str.startswith("User."):
+ return include_user_nodes
+ if selection_level == "second_leaf" and spec.node_type == NodeType.LEAF:
+ # In second-leaf drafting mode, real leaf nodes are hidden.
+ return False
+ if spec.node_type == NodeType.SYSTEM:
+ return include_system_nodes
+ return True
+
+ def _llm_tree_label(self, spec: NodeSpec) -> str:
+ if self.is_leaf(spec.cid):
+ worker_id = str(spec.worker_id or "").strip()
+ if worker_id:
+ return to_pascal_case(worker_id)
+ term = spec.cid.terms[-1] if spec.cid.terms else "ROOT"
+ return to_pascal_case(term) or term
+
+ def _ensure_ancestors(self, cid: CID) -> None:
+ for i in range(1, len(cid.terms)):
+ ancestor = CID(tuple(cid.terms[:i]))
+ if self.exists(ancestor):
+ continue
+ self.register(
+ NodeSpec(
+ cid=ancestor,
+ name=ancestor.terms[-1] if ancestor.terms else "ROOT",
+ description="",
+ node_type=NodeType.BRANCH,
+ worker_id=None,
+ )
+ )
+
+ def _refresh_branch_descriptions(self) -> None:
+ branch_specs = sorted(
+ [spec for spec in self.all() if spec.node_type == NodeType.BRANCH],
+ key=lambda item: len(item.cid.terms),
+ )
+ for spec in branch_specs:
+ if spec.description.strip():
+ continue
+ title = spec.cid.terms[-1] if spec.cid.terms else "Root"
+ description = f"Semantic branch for {title}"
+ self.update(replace(spec, description=description, keywords=spec.keywords))
+
+ @classmethod
+ def _render_routing_policy(cls, value: Any) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, str):
+ return value.strip()
+ if isinstance(value, list):
+ lines = [str(item).strip() for item in value if str(item).strip()]
+ if not lines:
+ return ""
+ return "\n".join(f"- {line}" for line in lines)
+ raise ValueError("routing_policy must be a string or a list of strings")
+
+ @classmethod
+ def _render_tree_sketch(cls, value: Any) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, str):
+ return value.strip()
+ if isinstance(value, list):
+ lines = [str(item).rstrip() for item in value if str(item).strip()]
+ return "\n".join(lines).strip()
+ raise ValueError("tree_sketch must be a string or a list of strings")
+
+ @staticmethod
+ def _sanitize_cid_value(value: str) -> str:
+ parts = [part.strip() for part in str(value or "").split(".") if part.strip()]
+ normalized: list[str] = []
+ for part in parts:
+ cleaned = re.sub(r"[^A-Za-z0-9_-]+", "", part)
+ if not cleaned:
+ cleaned = "Node"
+ if not cleaned[0].isalpha():
+ cleaned = "N" + cleaned
+ normalized.append(cleaned)
+ return ".".join(normalized)
+
+ def _spec_from_definition(self, item: dict[str, Any]) -> NodeSpec:
+ if "cid" not in item:
+ raise ValueError("Each node must define a cid")
+ if "type" not in item:
+ raise ValueError(f"Node '{item.get('cid', '<unknown>')}' must define a type")
+ raw_cid = str(item["cid"])
+ try:
+ cid = CID.from_str(raw_cid)
+ except ValueError:
+ cid = CID.from_str(self._sanitize_cid_value(raw_cid))
+ if self.exists(cid):
+ raise ValueError(f"Duplicate cid found in preset: {cid.to_str()}")
+ node_type = NodeType(str(item["type"]))
+ description = str(item.get("description", "") or "").strip()
+ name = str(item.get("name", "") or "").strip()
+ raw_worker_id = item.get("worker_id")
+ worker_id = str(raw_worker_id).strip() if raw_worker_id is not None else None
+ if node_type == NodeType.LEAF and not worker_id:
+ raise ValueError(f"Leaf node '{cid.to_str()}' must define a non-empty worker_id")
+ if node_type == NodeType.SYSTEM and not worker_id:
+ raise ValueError(f"System node '{cid.to_str()}' must define a non-empty worker_id")
+ if node_type == NodeType.BRANCH and worker_id:
+ raise ValueError(f"Branch node '{cid.to_str()}' must not define worker_id")
+ return NodeSpec(
+ cid=cid,
+ name=name or (cid.terms[-1] if cid.terms else "ROOT"),
+ description=description,
+ node_type=node_type,
+ worker_id=worker_id,
+ keywords=tuple(item.get("keywords", []) or []),
+ examples=tuple(item.get("examples", []) or []),
+ )
+
+ @staticmethod
+ def _coerce_cid(cid: str | CID) -> CID:
+ if isinstance(cid, CID):
+ return cid
+ return CID.from_str(cid)
diff --git a/jiuwenswarm/symphony/models/retrieval/__init__.py b/jiuwenswarm/symphony/models/retrieval/__init__.py
new file mode 100644
index 0000000000..c8ead8d415
--- /dev/null
+++ b/jiuwenswarm/symphony/models/retrieval/__init__.py
@@ -0,0 +1,12 @@
+from .candidate import RetrieverCandidate
+from .tree import RetrieverChoice, RetrieverItem, RetrieverNode
+from .trace import RetrieverTrace, RetrieverTraceEvent
+
+__all__ = [
+ "RetrieverCandidate",
+ "RetrieverChoice",
+ "RetrieverItem",
+ "RetrieverNode",
+ "RetrieverTrace",
+ "RetrieverTraceEvent",
+]
diff --git a/jiuwenswarm/symphony/models/retrieval/candidate.py b/jiuwenswarm/symphony/models/retrieval/candidate.py
new file mode 100644
index 0000000000..708957a20a
--- /dev/null
+++ b/jiuwenswarm/symphony/models/retrieval/candidate.py
@@ -0,0 +1,16 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class RetrieverCandidate:
+ rank: int
+ item_id: str
+ payload: str
+ branch_path: tuple[str, ...]
+ label: str = ""
+ description: str = ""
+
+
+__all__ = ["RetrieverCandidate"]
diff --git a/jiuwenswarm/symphony/models/retrieval/trace.py b/jiuwenswarm/symphony/models/retrieval/trace.py
new file mode 100644
index 0000000000..4569ea4f83
--- /dev/null
+++ b/jiuwenswarm/symphony/models/retrieval/trace.py
@@ -0,0 +1,26 @@
+from __future__ import annotations
+
+import threading
+from dataclasses import dataclass, field
+from typing import Dict, List
+
+
+@dataclass(frozen=True)
+class RetrieverTraceEvent:
+ event_type: str
+ node_id: str
+ depth: int
+ detail: Dict[str, object] = field(default_factory=dict)
+
+
+@dataclass
+class RetrieverTrace:
+ events: List[RetrieverTraceEvent] = field(default_factory=list)
+ _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
+
+ def record(self, event_type: str, *, node_id: str, depth: int, detail: Dict[str, object] | None = None) -> None:
+ payload = dict(detail or {})
+ with self._lock:
+ self.events.append(RetrieverTraceEvent(event_type=event_type, node_id=node_id, depth=depth, detail=payload))
+
+__all__ = ["RetrieverTrace", "RetrieverTraceEvent"]
diff --git a/jiuwenswarm/symphony/models/retrieval/tree.py b/jiuwenswarm/symphony/models/retrieval/tree.py
new file mode 100644
index 0000000000..c9c1e4f74c
--- /dev/null
+++ b/jiuwenswarm/symphony/models/retrieval/tree.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class RetrieverItem:
+ item_id: str
+ payload: str
+ label: str = ""
+ description: str = ""
+
+
+@dataclass(frozen=True)
+class RetrieverChoice:
+ choice_id: str
+ payload: str
+ description: str = ""
+
+
+@dataclass(frozen=True)
+class RetrieverNode:
+ node_id: str
+ label: str
+ description: str = ""
+ children: tuple["RetrieverNode", ...] = ()
+ items: tuple[RetrieverItem, ...] = ()
+
+
+__all__ = ["RetrieverChoice", "RetrieverItem", "RetrieverNode"]
diff --git a/jiuwenswarm/symphony/orchestration/utils/__init__.py b/jiuwenswarm/symphony/orchestration/utils/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/jiuwenswarm/symphony/orchestration/utils/naming.py b/jiuwenswarm/symphony/orchestration/utils/naming.py
new file mode 100644
index 0000000000..cba18bce92
--- /dev/null
+++ b/jiuwenswarm/symphony/orchestration/utils/naming.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+import re
+
+
+_CAMEL_BOUNDARY_RE = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
+_NON_ALNUM_RE = re.compile(r"[^A-Za-z0-9]+")
+
+
+def _split_name_parts(value: str) -> list[str]:
+ text = str(value or "").strip()
+ if not text:
+ return []
+ text = _CAMEL_BOUNDARY_RE.sub("-", text)
+ text = text.replace("_", "-")
+ text = _NON_ALNUM_RE.sub("-", text)
+ text = re.sub(r"-{2,}", "-", text)
+ return [part.lower() for part in text.strip("-").split("-") if part]
+
+
+def to_kebab_case(value: str) -> str:
+ return "-".join(_split_name_parts(value))
+
+
+def to_camel_case(value: str) -> str:
+ parts = _split_name_parts(value)
+ if not parts:
+ return ""
+ head, *tail = parts
+ return head + "".join(part[:1].upper() + part[1:] for part in tail)
+
+
+def to_pascal_case(value: str) -> str:
+ parts = _split_name_parts(value)
+ if not parts:
+ return ""
+ return "".join(part[:1].upper() + part[1:] for part in parts)
+
+
+def to_camel_path(value: str) -> str:
+ text = str(value or "").strip()
+ if not text:
+ return ""
+ parts = [segment.strip() for segment in text.split(".") if segment.strip()]
+ return ".".join(to_camel_case(part) for part in parts if part)
+
+
+def to_pascal_path(value: str) -> str:
+ text = str(value or "").strip()
+ if not text:
+ return ""
+ parts = [segment.strip() for segment in text.split(".") if segment.strip()]
+ return ".".join(to_pascal_case(part) for part in parts if part)
+
+
+def normalize_name_key(value: str) -> str:
+ return to_kebab_case(value).replace("-", "")
+
+
+def bounded_edit_distance(left: str, right: str, *, max_distance: int) -> int | None:
+ if max_distance < 0:
+ return None
+ if left == right:
+ return 0
+ if abs(len(left) - len(right)) > max_distance:
+ return None
+
+ previous = list(range(len(right) + 1))
+ for i, left_char in enumerate(left, start=1):
+ current = [i]
+ row_min = current[0]
+ for j, right_char in enumerate(right, start=1):
+ insertion = current[j - 1] + 1
+ deletion = previous[j] + 1
+ substitution = previous[j - 1] + (0 if left_char == right_char else 1)
+ value = min(insertion, deletion, substitution)
+ current.append(value)
+ if value < row_min:
+ row_min = value
+ if row_min > max_distance:
+ return None
+ previous = current
+
+ distance = previous[-1]
+ if distance > max_distance:
+ return None
+ return distance
+
+
+def fuzzy_name_distance(left: str, right: str) -> int | None:
+ normalized_left = normalize_name_key(left)
+ normalized_right = normalize_name_key(right)
+ if not normalized_left or not normalized_right:
+ return None
+ if normalized_left == normalized_right:
+ return 0
+ max_len = max(len(normalized_left), len(normalized_right))
+ allowed_distance = 1 if max_len >= 8 else 0
+ return bounded_edit_distance(normalized_left, normalized_right, max_distance=allowed_distance)
diff --git a/jiuwenswarm/symphony/pyproject.toml b/jiuwenswarm/symphony/pyproject.toml
new file mode 100644
index 0000000000..3dc16a2fee
--- /dev/null
+++ b/jiuwenswarm/symphony/pyproject.toml
@@ -0,0 +1,20 @@
+[build-system]
+requires = ["setuptools>=68", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "openjiuwen-skillsdispatch"
+version = "0.1.0"
+description = "openJiuwen skills dispatch SDK for skill indexing, retrieval, and orchestration"
+readme = "README.md"
+requires-python = ">=3.9"
+dependencies = [
+ "PyYAML>=6.0",
+]
+
+[tool.setuptools.packages.find]
+include = ["indexing*", "models*", "orchestration*", "retrieval*", "shared*"]
+exclude = ["tests*", "data*"]
+
+[tool.setuptools.package-data]
+"retrieval.tree.render" = ["*.yaml"]
diff --git a/jiuwenswarm/symphony/retrieval/__init__.py b/jiuwenswarm/symphony/retrieval/__init__.py
new file mode 100644
index 0000000000..4eca631d6d
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/__init__.py
@@ -0,0 +1,7 @@
+"""Canonical online retrieval package.
+
+Keep package import lightweight to avoid eager initialization of the full
+retrieval stack during compatibility imports.
+"""
+
+__all__ = ["io", "lexical", "merge", "protocols", "semantic", "service", "tree"]
diff --git a/jiuwenswarm/symphony/retrieval/algorithm.md b/jiuwenswarm/symphony/retrieval/algorithm.md
new file mode 100644
index 0000000000..970ba7de2f
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/algorithm.md
@@ -0,0 +1,51 @@
+# Retrieval Algorithm
+
+## Problem Definition
+
+Given:
+
+- a loaded offline index
+- a user query
+- a progressive tree retriever
+
+Return:
+
+- the best matching executable payloads in ranked order
+
+## Retrieval Policy
+
+The dispatch package currently loads the progressive tree artifacts produced by `indexing/`:
+
+- `tree_index.yaml`
+- `catalog.jsonl`
+- `manifest.json`
+
+Online retrieval runs progressive tree routing over those artifacts and returns the selected leaf payloads.
+
+## Progressive Tree Retrieval
+
+Input:
+
+- query
+- tree root
+- `top_k`
+
+Process:
+
+1. start from the current visible subtree
+2. if the structure is trivial, use deterministic shortcuts
+3. otherwise ask the LLM to choose among the current visible boundary nodes
+4. recurse into selected branches or terminate on selected items
+5. reduce branch results to the requested `top_k`
+
+Important rules:
+
+- every LLM routing decision sees only the current visible subtree
+- the model outputs the visible boundary node display names only
+- display names are uniquified automatically if collisions exist
+- single-candidate situations do not call the LLM
+
+## Main Implementations
+
+- `retrieval/tree/progressive.py`
+- `retrieval/service/retriever.py`
diff --git a/jiuwenswarm/symphony/retrieval/doc.md b/jiuwenswarm/symphony/retrieval/doc.md
new file mode 100644
index 0000000000..fa406e004b
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/doc.md
@@ -0,0 +1,56 @@
+# Retrieval
+
+## Purpose
+
+`retrieval/` owns online retrieval.
+
+It loads offline artifacts built by `indexing/`, runs retrieval over them, and returns ordered candidates or payloads.
+
+## Canonical Online Route
+
+The canonical route uses the progressive tree index:
+
+1. load `tree_index.yaml` and `catalog.jsonl`
+2. route the query through the progressive tree
+3. return selected leaf payloads from the catalog
+
+## Package Layout
+
+### `retrieval/io/`
+
+- loads tree and catalog artifacts
+
+### `retrieval/tree/`
+
+- progressive tree search
+- disclosure decisions
+- branch reduction
+- trace generation
+
+### `retrieval/protocols/`
+
+- prompt generation
+- display-name normalization
+- output parsing
+
+### `retrieval/service/`
+
+- high-level retriever interfaces
+
+## Main Entry Points
+
+- `retrieval/service/retriever.py`
+- `retrieval/tree/progressive.py`
+
+Typical usage:
+
+```python
+from retrieval.service.retriever import Retriever
+
+retriever = Retriever.from_index("/abs/path/to/index")
+payloads = retriever.search("find tools for browser automation", top_k=5)
+```
+
+## Dependency Boundary
+
+`retrieval/` does not import orchestration core runtime. Orchestration consumes retrieval through canonical retrieval modules and the retrieval adapter layer under `orchestration/`.
diff --git a/jiuwenswarm/symphony/retrieval/io/__init__.py b/jiuwenswarm/symphony/retrieval/io/__init__.py
new file mode 100644
index 0000000000..96c85bc228
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/io/__init__.py
@@ -0,0 +1,9 @@
+from .loading import CatalogRecord, LoadedRetrieverIndex, load_catalog_records, load_retriever_index, load_tree_root
+
+__all__ = [
+ "CatalogRecord",
+ "LoadedRetrieverIndex",
+ "load_catalog_records",
+ "load_retriever_index",
+ "load_tree_root",
+]
diff --git a/jiuwenswarm/symphony/retrieval/io/loading.py b/jiuwenswarm/symphony/retrieval/io/loading.py
new file mode 100644
index 0000000000..fb45ebbfe8
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/io/loading.py
@@ -0,0 +1,265 @@
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field, replace
+from pathlib import Path
+from typing import Dict, List, Sequence
+
+from models.retrieval import RetrieverItem, RetrieverNode, RetrieverChoice
+from shared.storage import is_s3_uri, materialize_s3_dir
+
+
+@dataclass(frozen=True)
+class CatalogRecord:
+ choice_id: str
+ payload: str
+ worker_id: str = ""
+ name: str = ""
+ description: str = ""
+ retrieval_text: str = ""
+ branch_path: tuple[str, ...] = ()
+ metadata: Dict[str, object] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class LoadedRetrieverIndex:
+ index_dir: Path
+ tree_root: RetrieverNode
+ choices: tuple[RetrieverChoice, ...]
+ catalog_records: tuple[CatalogRecord, ...]
+ manifest: Dict[str, object] = field(default_factory=dict)
+
+
+def load_retriever_index(index_dir: str | Path) -> LoadedRetrieverIndex:
+ base_dir = _materialize_index_dir(index_dir)
+ manifest = _load_manifest(base_dir)
+ catalog_path = base_dir / _artifact_path(manifest, "catalog", "catalog.jsonl")
+ tree_path = base_dir / _artifact_path(manifest, "tree_index", "tree_index.yaml")
+ catalog_records = tuple(load_catalog_records(catalog_path))
+ catalog_records = tuple(_apply_tree_worker_ids(catalog_records, worker_ids_by_cid=_load_tree_worker_ids(tree_path)))
+ tree_root = load_tree_root(tree_path, catalog_records=catalog_records)
+ choices = tuple(
+ RetrieverChoice(
+ choice_id=record.choice_id,
+ payload=record.payload,
+ description=record.description or record.retrieval_text,
+ )
+ for record in catalog_records
+ )
+ return LoadedRetrieverIndex(
+ index_dir=base_dir,
+ tree_root=tree_root,
+ choices=choices,
+ catalog_records=catalog_records,
+ manifest=manifest,
+ )
+
+
+def _materialize_index_dir(index_dir: str | Path) -> Path:
+ raw = str(index_dir).strip()
+ if is_s3_uri(raw):
+ return materialize_s3_dir(raw, cache_namespace="retriever-s3-index-cache")
+ return Path(index_dir).resolve()
+
+
+def load_catalog_records(path: str | Path) -> List[CatalogRecord]:
+ records: List[CatalogRecord] = []
+ for line in Path(path).read_text(encoding="utf-8").splitlines():
+ text = line.strip()
+ if not text:
+ continue
+ payload = json.loads(text)
+ choice_id = str(payload.get("name") or payload.get("choice_id") or "").strip()
+ candidate_payload = str(payload.get("cid") or payload.get("payload") or "").strip()
+ if not choice_id or not candidate_payload:
+ continue
+ records.append(
+ CatalogRecord(
+ choice_id=choice_id,
+ payload=candidate_payload,
+ worker_id=str(payload.get("worker_id") or "").strip(),
+ name=str(payload.get("name") or choice_id).strip() or choice_id,
+ description=str(payload.get("description") or "").strip(),
+ retrieval_text=str(payload.get("retrieval_text") or "").strip(),
+ branch_path=tuple(
+ str(item).strip() for item in (payload.get("branch_path") or []) if str(item).strip()
+ ),
+ metadata={
+ "skill_path": str(payload.get("skill_path") or "").strip(),
+ "category": str(payload.get("category") or "").strip(),
+ "worker_id": str(payload.get("worker_id") or "").strip(),
+ },
+ )
+ )
+ records.sort(key=lambda item: (item.payload, item.choice_id))
+ return records
+
+
+def load_tree_root(path: str | Path, *, catalog_records: Sequence[CatalogRecord]) -> RetrieverNode:
+ payload = _load_yaml_like(Path(path).read_text(encoding="utf-8"))
+ nodes = payload.get("nodes") or []
+ record_by_payload = {record.payload: record for record in catalog_records}
+ return _build_tree_from_nodes(nodes, record_by_payload=record_by_payload)
+
+
+def _load_tree_worker_ids(path: str | Path) -> Dict[str, str]:
+ payload = _load_yaml_like(Path(path).read_text(encoding="utf-8"))
+ worker_ids_by_cid: Dict[str, str] = {}
+ for raw_node in payload.get("nodes") or []:
+ if not isinstance(raw_node, dict):
+ continue
+ cid = str(raw_node.get("cid") or "").strip()
+ worker_id = str(raw_node.get("worker_id") or "").strip()
+ if cid and worker_id:
+ worker_ids_by_cid[cid] = worker_id
+ return worker_ids_by_cid
+
+
+def _apply_tree_worker_ids(
+ records: Sequence[CatalogRecord], *, worker_ids_by_cid: Dict[str, str]
+) -> List[CatalogRecord]:
+ if not worker_ids_by_cid:
+ return list(records)
+ updated: List[CatalogRecord] = []
+ for record in records:
+ worker_id = str(worker_ids_by_cid.get(record.payload) or record.worker_id or "").strip()
+ if not worker_id:
+ updated.append(record)
+ continue
+ metadata = dict(record.metadata or {})
+ metadata["worker_id"] = worker_id
+ updated.append(replace(record, worker_id=worker_id, metadata=metadata))
+ return updated
+
+
+def _build_tree_from_nodes(nodes: Sequence[object], *, record_by_payload: Dict[str, CatalogRecord]) -> RetrieverNode:
+ branch_specs: Dict[str, Dict[str, object]] = {}
+ children_map: Dict[str, List[str]] = {}
+ items_by_parent: Dict[str, List[RetrieverItem]] = {}
+
+ for raw_node in nodes:
+ if not isinstance(raw_node, dict):
+ continue
+ cid = str(raw_node.get("cid") or "").strip()
+ node_type = str(raw_node.get("type") or "").strip().lower()
+ if not cid:
+ continue
+ parent_cid = cid.rsplit(".", 1)[0] if "." in cid else ""
+ if node_type == "leaf":
+ record = record_by_payload.get(cid)
+ item_id = str(
+ (record.name if record else "") or (record.choice_id if record else "") or cid.rsplit(".", 1)[-1]
+ ).strip()
+ label = str((record.name if record else "") or item_id or cid.rsplit(".", 1)[-1]).strip() or item_id or cid
+ description = _compose_routing_description(
+ description=str(raw_node.get("description") or (record.description if record else "") or "").strip(),
+ select_when=str(raw_node.get("select_when") or "").strip(),
+ dont_select_when=str(raw_node.get("dont_select_when") or "").strip(),
+ )
+ items_by_parent.setdefault(parent_cid, []).append(
+ RetrieverItem(
+ item_id=item_id,
+ payload=cid,
+ label=label,
+ description=description,
+ )
+ )
+ continue
+ branch_specs[cid] = raw_node
+ children_map.setdefault(parent_cid, []).append(cid)
+
+ def build_branch(cid: str, *, root: bool = False) -> RetrieverNode | None:
+ child_branch_ids = sorted(children_map.get(cid, []))
+ children = [child for child in (build_branch(child_cid) for child_cid in child_branch_ids) if child is not None]
+ items = sorted(items_by_parent.get(cid, []), key=lambda item: (item.payload, item.item_id))
+ if not root and not children and not items:
+ return None
+ spec = branch_specs.get(cid, {})
+ label = "ROOT" if root else (cid.rsplit(".", 1)[-1] if cid else "ROOT")
+ description = (
+ _compose_routing_description(
+ description=str(spec.get("description") or "").strip(),
+ select_when=str(spec.get("select_when") or "").strip(),
+ dont_select_when=str(spec.get("dont_select_when") or "").strip(),
+ )
+ if isinstance(spec, dict)
+ else ""
+ )
+ return RetrieverNode(
+ node_id="ROOT" if root else cid,
+ label=label,
+ description=description,
+ children=tuple(children),
+ items=tuple(items),
+ )
+
+ root = build_branch("", root=True)
+ return root or RetrieverNode(node_id="ROOT", label="ROOT")
+
+
+def _compose_routing_description(*, description: str, select_when: str = "", dont_select_when: str = "") -> str:
+ parts = [str(description or "").strip()] if str(description or "").strip() else []
+ if select_when and "Select when:" not in description:
+ parts.append(f"Select when: {select_when}")
+ if dont_select_when and "Don't select when:" not in description:
+ parts.append(f"Don't select when: {dont_select_when}")
+ return "\n".join(part for part in parts if part).strip()
+
+
+def _load_manifest(index_dir: Path) -> Dict[str, object]:
+ manifest_path = index_dir / "manifest.json"
+ if not manifest_path.exists():
+ return {}
+ return json.loads(manifest_path.read_text(encoding="utf-8"))
+
+
+def _artifact_path(manifest: Dict[str, object], key: str, fallback: str) -> str:
+ artifacts = manifest.get("artifacts") or {}
+ if isinstance(artifacts, dict):
+ value = str(artifacts.get(key) or "").strip()
+ if value:
+ return value
+ return fallback
+
+
+def _load_yaml_like(text: str) -> Dict[str, object]:
+ try:
+ import yaml
+
+ payload = yaml.safe_load(text) or {}
+ if isinstance(payload, dict):
+ return payload
+ except Exception:
+ return _parse_simple_nodes_yaml(text)
+ return _parse_simple_nodes_yaml(text)
+
+
+def _parse_simple_nodes_yaml(text: str) -> Dict[str, object]:
+ nodes: List[Dict[str, str]] = []
+ current: Dict[str, str] | None = None
+ for raw_line in text.splitlines():
+ line = raw_line.rstrip()
+ stripped = line.strip()
+ if not stripped or stripped == "nodes:":
+ continue
+ if stripped.startswith("- "):
+ if current:
+ nodes.append(current)
+ current = {}
+ stripped = stripped[2:]
+ if current is None or ":" not in stripped:
+ continue
+ key, value = stripped.split(":", 1)
+ current[key.strip()] = value.strip()
+ if current:
+ nodes.append(current)
+ return {"nodes": nodes}
+
+
+__all__ = [
+ "CatalogRecord",
+ "LoadedRetrieverIndex",
+ "load_catalog_records",
+ "load_retriever_index",
+ "load_tree_root",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/__init__.py b/jiuwenswarm/symphony/retrieval/llm/__init__.py
new file mode 100644
index 0000000000..2995596d52
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/__init__.py
@@ -0,0 +1,78 @@
+from .base import (
+ CandidateEncodingError,
+ CandidateScore,
+ CandidateScoringError,
+ CandidateScoringResult,
+ GenerationConfig,
+ GenerationConstraints,
+ LLMClientCapabilities,
+ LLMClientError,
+ LLMRequestError,
+ LLMStreamChunk,
+ MaxNewTokensTooLarge,
+ Message,
+ PrefixCacheError,
+ PrefixCacheRuntimeOOM,
+ PrefixCacheUnavailable,
+ PromptCacheHint,
+ ProgressiveLLMClient,
+ QueryTooLongForPrefixCache,
+ TrieConstraint,
+ UnsupportedCapability,
+ generation_config_to_debug_dict,
+)
+from .config import (
+ LLMClientConfig,
+ OpenAIClientConfig,
+ TransformersClientConfig,
+ VLLMClientConfig,
+)
+from .factory import (
+ coerce_generation_client,
+ create_progressive_client,
+ progressive_client_cache_key,
+)
+from .openai_api import OpenAICompatibleClient
+from .transformers_prefix_cached_generation import (
+ DistributedGenerationConfig,
+ TransformersPrefixCachedGenerationClient,
+)
+from .transformers_logit_selection import TransformersLogitSelectionClient
+from .vllm import LocalVLLMClient, LocalVLLMPrefixCacheHandle
+
+__all__ = [
+ "CandidateEncodingError",
+ "CandidateScore",
+ "CandidateScoringError",
+ "CandidateScoringResult",
+ "DistributedGenerationConfig",
+ "GenerationConfig",
+ "GenerationConstraints",
+ "LLMClientCapabilities",
+ "LLMClientConfig",
+ "LLMClientError",
+ "LLMRequestError",
+ "LLMStreamChunk",
+ "LocalVLLMClient",
+ "LocalVLLMPrefixCacheHandle",
+ "MaxNewTokensTooLarge",
+ "Message",
+ "OpenAICompatibleClient",
+ "OpenAIClientConfig",
+ "PrefixCacheError",
+ "PrefixCacheRuntimeOOM",
+ "PrefixCacheUnavailable",
+ "PromptCacheHint",
+ "ProgressiveLLMClient",
+ "QueryTooLongForPrefixCache",
+ "TransformersLogitSelectionClient",
+ "TransformersClientConfig",
+ "TransformersPrefixCachedGenerationClient",
+ "TrieConstraint",
+ "UnsupportedCapability",
+ "VLLMClientConfig",
+ "coerce_generation_client",
+ "create_progressive_client",
+ "generation_config_to_debug_dict",
+ "progressive_client_cache_key",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/base/__init__.py b/jiuwenswarm/symphony/retrieval/llm/base/__init__.py
new file mode 100644
index 0000000000..20f98b5d67
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/base/__init__.py
@@ -0,0 +1,49 @@
+from .errors import (
+ CandidateEncodingError,
+ CandidateScoringError,
+ LLMClientError,
+ LLMRequestError,
+ MaxNewTokensTooLarge,
+ PrefixCacheError,
+ PrefixCacheRuntimeOOM,
+ PrefixCacheUnavailable,
+ QueryTooLongForPrefixCache,
+ UnsupportedCapability,
+)
+from .protocols import ProgressiveLLMClient
+from .types import (
+ CandidateScore,
+ CandidateScoringResult,
+ GenerationConfig,
+ GenerationConstraints,
+ LLMClientCapabilities,
+ LLMStreamChunk,
+ Message,
+ PromptCacheHint,
+ TrieConstraint,
+ generation_config_to_debug_dict,
+)
+
+__all__ = [
+ "CandidateEncodingError",
+ "CandidateScore",
+ "CandidateScoringError",
+ "CandidateScoringResult",
+ "GenerationConfig",
+ "GenerationConstraints",
+ "LLMClientCapabilities",
+ "LLMClientError",
+ "LLMRequestError",
+ "LLMStreamChunk",
+ "MaxNewTokensTooLarge",
+ "Message",
+ "PrefixCacheError",
+ "PrefixCacheRuntimeOOM",
+ "PrefixCacheUnavailable",
+ "PromptCacheHint",
+ "ProgressiveLLMClient",
+ "QueryTooLongForPrefixCache",
+ "TrieConstraint",
+ "UnsupportedCapability",
+ "generation_config_to_debug_dict",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/base/errors.py b/jiuwenswarm/symphony/retrieval/llm/base/errors.py
new file mode 100644
index 0000000000..3affe8a7f4
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/base/errors.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+
+class LLMClientError(RuntimeError):
+ """Base error for progressive LLM client failures."""
+
+
+class UnsupportedCapability(LLMClientError):
+ """Raised when a client is asked to use a capability it does not expose."""
+
+
+class LLMRequestError(LLMClientError):
+ """Raised when a backend request fails."""
+
+
+class CandidateEncodingError(LLMClientError):
+ """Raised when visible candidate codes cannot be encoded safely."""
+
+
+class CandidateScoringError(LLMClientError):
+ """Raised when candidate scoring fails."""
+
+
+class PrefixCacheError(LLMClientError):
+ """Raised when prefix-cache generation cannot use the low-latency path."""
+
+
+class PrefixCacheUnavailable(PrefixCacheError):
+ """Raised when a required prefix-cache handle or slot is unavailable."""
+
+
+class QueryTooLongForPrefixCache(PrefixCacheError):
+ """Raised when the dynamic suffix cannot fit in a preallocated cache slot."""
+
+
+class MaxNewTokensTooLarge(PrefixCacheError):
+ """Raised when requested decode length exceeds the preallocated tail budget."""
+
+
+class PrefixCacheRuntimeOOM(PrefixCacheError):
+ """Raised after an OOM while using a prefix-cache slot."""
+
+
+__all__ = [
+ "CandidateEncodingError",
+ "CandidateScoringError",
+ "LLMClientError",
+ "LLMRequestError",
+ "MaxNewTokensTooLarge",
+ "PrefixCacheError",
+ "PrefixCacheRuntimeOOM",
+ "PrefixCacheUnavailable",
+ "QueryTooLongForPrefixCache",
+ "UnsupportedCapability",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/base/protocols.py b/jiuwenswarm/symphony/retrieval/llm/base/protocols.py
new file mode 100644
index 0000000000..4c94888918
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/base/protocols.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import Iterable, Mapping, Sequence
+
+from .errors import UnsupportedCapability
+from .types import (
+ CandidateScoringResult,
+ GenerationConfig,
+ LLMClientCapabilities,
+ LLMStreamChunk,
+ Message,
+)
+
+
+class ProgressiveLLMClient(ABC):
+ name: str = "base"
+
+ @property
+ @abstractmethod
+ def capabilities(self) -> LLMClientCapabilities:
+ raise NotImplementedError
+
+ def default_generation_config(self) -> GenerationConfig:
+ return GenerationConfig()
+
+ def complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ n: int = 1,
+ request_timeout: float | None = None,
+ ) -> list[str]:
+ raise UnsupportedCapability(f"{self.name} does not support completion")
+
+ def stream_complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ request_timeout: float | None = None,
+ early_stop: object | None = None,
+ ) -> Iterable[str | LLMStreamChunk]:
+ del early_stop
+ outputs = self.complete(
+ model=model,
+ messages=messages,
+ max_tokens=max_tokens,
+ stop_sequences=stop_sequences,
+ generation_config=generation_config,
+ n=1,
+ request_timeout=request_timeout,
+ )
+ yield outputs[0] if outputs else ""
+
+ def score_candidate_codes(
+ self,
+ *,
+ model: str,
+ messages: list[Message],
+ candidate_codes: Sequence[str],
+ code_to_canonical_id: Mapping[str, str],
+ top_k: int | None = None,
+ require_single_token_codes: bool = True,
+ request_timeout: float | None = None,
+ ) -> CandidateScoringResult:
+ raise UnsupportedCapability(f"{self.name} does not support candidate scoring")
+
+ def close(self) -> None:
+ return None
+
+
+__all__ = ["ProgressiveLLMClient"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/base/scoring.py b/jiuwenswarm/symphony/retrieval/llm/base/scoring.py
new file mode 100644
index 0000000000..9a89342b00
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/base/scoring.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from time import perf_counter
+from typing import Mapping, Sequence
+
+from .errors import CandidateEncodingError, CandidateScoringError
+from .types import CandidateScore, CandidateScoringResult
+
+
+@dataclass(frozen=True)
+class CandidateTokenization:
+ candidate_codes: tuple[str, ...]
+ token_to_code: Mapping[int, str]
+ candidate_token_ids: tuple[int, ...]
+ encode_ms: float
+
+
+def prepare_candidate_token_ids(
+ *,
+ candidate_codes: Sequence[str],
+ encoded_codes: Mapping[str, int | None],
+ require_single_token_codes: bool,
+) -> CandidateTokenization:
+ started = perf_counter()
+ resolved_codes = tuple(str(code) for code in candidate_codes)
+ missing = [code for code in resolved_codes if encoded_codes.get(code) is None]
+ if require_single_token_codes and missing:
+ raise CandidateEncodingError(
+ f"visible candidate ids are not single-token under the scoring tokenizer: {missing}"
+ )
+
+ token_to_code: dict[int, str] = {}
+ token_collisions: dict[int, list[str]] = {}
+ for code in resolved_codes:
+ token_id = encoded_codes.get(code)
+ if token_id is None:
+ continue
+ resolved_token_id = int(token_id)
+ previous = token_to_code.get(resolved_token_id)
+ if previous is not None and previous != code:
+ token_collisions.setdefault(resolved_token_id, [previous]).append(code)
+ continue
+ token_to_code[resolved_token_id] = code
+ if token_collisions:
+ collision_details = ", ".join(
+ f"{token_id}: {sorted(set(codes))}" for token_id, codes in sorted(token_collisions.items())
+ )
+ raise CandidateEncodingError(f"visible candidate ids collide under the scoring tokenizer: {collision_details}")
+
+ return CandidateTokenization(
+ candidate_codes=resolved_codes,
+ token_to_code=token_to_code,
+ candidate_token_ids=tuple(sorted(token_to_code.keys())),
+ encode_ms=round((perf_counter() - started) * 1000.0, 3),
+ )
+
+
+def build_candidate_scoring_result(
+ *,
+ tokenization: CandidateTokenization,
+ scored_pairs: Sequence[tuple[int, float]],
+ code_to_canonical_id: Mapping[str, str],
+ latency_breakdown: Mapping[str, float],
+) -> CandidateScoringResult:
+ if not tokenization.token_to_code:
+ return CandidateScoringResult(
+ scores=(),
+ candidate_codes=tokenization.candidate_codes,
+ candidate_token_ids=(),
+ latency_breakdown=dict(latency_breakdown),
+ )
+ if not scored_pairs:
+ return CandidateScoringResult(
+ scores=(),
+ candidate_codes=tokenization.candidate_codes,
+ candidate_token_ids=tokenization.candidate_token_ids,
+ latency_breakdown=dict(latency_breakdown),
+ )
+
+ returned_token_ids: list[int] = []
+ seen_token_ids: set[int] = set()
+ for token_id, _logit in scored_pairs:
+ resolved_token_id = int(token_id)
+ if resolved_token_id not in tokenization.token_to_code:
+ raise CandidateScoringError(f"scoring backend returned an unknown candidate token id: {resolved_token_id}")
+ if resolved_token_id in seen_token_ids:
+ raise CandidateScoringError(f"scoring backend returned duplicate candidate token id: {resolved_token_id}")
+ seen_token_ids.add(resolved_token_id)
+ returned_token_ids.append(resolved_token_id)
+ missing_token_ids = sorted(set(tokenization.token_to_code.keys()) - set(returned_token_ids))
+ if missing_token_ids:
+ raise CandidateScoringError(
+ "scoring backend did not return scores for every visible candidate token: " f"{missing_token_ids}"
+ )
+
+ normalize_started = perf_counter()
+ logits = [float(logit) for _token_id, logit in scored_pairs]
+ max_logit = max(logits)
+ exp_values = [math.exp(logit - max_logit) for logit in logits]
+ denom = sum(exp_values) or 1.0
+ scores: list[CandidateScore] = []
+ for index, ((token_id, logit), exp_value) in enumerate(zip(scored_pairs, exp_values), start=1):
+ code = tokenization.token_to_code[int(token_id)]
+ scores.append(
+ CandidateScore(
+ code=code,
+ canonical_id=str(code_to_canonical_id.get(code) or code),
+ token_id=int(token_id),
+ logit=float(logit),
+ probability=float(exp_value / denom),
+ rank=index,
+ )
+ )
+ merged_latency = dict(latency_breakdown)
+ merged_latency["normalize_ms"] = round((perf_counter() - normalize_started) * 1000.0, 3)
+ return CandidateScoringResult(
+ scores=tuple(scores),
+ candidate_codes=tokenization.candidate_codes,
+ candidate_token_ids=tokenization.candidate_token_ids,
+ latency_breakdown=merged_latency,
+ )
+
+
+__all__ = [
+ "CandidateTokenization",
+ "build_candidate_scoring_result",
+ "prepare_candidate_token_ids",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/base/tokenization.py b/jiuwenswarm/symphony/retrieval/llm/base/tokenization.py
new file mode 100644
index 0000000000..cbe896fef7
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/base/tokenization.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Sequence
+
+from .types import Message
+
+
+def join_messages(messages: Sequence[Message]) -> str:
+ parts: list[str] = []
+ for message in messages:
+ role = str(message.get("role") or "").strip()
+ content = str(message.get("content") or "")
+ parts.append(f"{role}: {content}".strip())
+ return "\n".join(parts).strip()
+
+
+@dataclass
+class CandidateCodeTokenizer:
+ tokenizer: object
+ _cache: dict[tuple[str, str], int | None] = field(default_factory=dict)
+
+ @classmethod
+ def from_pretrained(cls, path: str) -> "CandidateCodeTokenizer":
+ try:
+ from transformers import AutoTokenizer
+ except ImportError as exc:
+ raise RuntimeError("transformers is required for candidate code tokenization") from exc
+ return cls(tokenizer=AutoTokenizer.from_pretrained(path, trust_remote_code=True))
+
+ def render_generation_prefix(self, messages: Sequence[Message]) -> str | None:
+ tokenizer = self.tokenizer
+ if not hasattr(tokenizer, "apply_chat_template"):
+ return None
+ return str(
+ tokenizer.apply_chat_template(
+ list(messages),
+ add_generation_prompt=True,
+ tokenize=False,
+ enable_thinking=False,
+ preserve_thinking=False,
+ add_vision_id=False,
+ )
+ )
+
+ def encode_text(self, text: str) -> list[int]:
+ return list(self.tokenizer.encode(text, add_special_tokens=False))
+
+ def encode_single_token(self, code: str, *, messages: Sequence[Message] | None = None) -> int | None:
+ text = str(code or "")
+ prefix = self.render_generation_prefix(messages) if messages else None
+ cache_key = (prefix or "", text)
+ if cache_key in self._cache:
+ return self._cache[cache_key]
+ token_ids = self.encode_text(text)
+ value = int(token_ids[0]) if len(token_ids) == 1 else None
+ if value is not None and prefix:
+ prefix_ids = self.encode_text(prefix)
+ output_suffixes = ("", "\n", "\nAA")
+ for suffix in output_suffixes:
+ suffix_ids = self.encode_text(suffix)
+ combined_ids = self.encode_text(prefix + text + suffix)
+ if combined_ids != prefix_ids + token_ids + suffix_ids:
+ value = None
+ break
+ self._cache[cache_key] = value
+ return value
+
+ def encode_many(self, codes: Sequence[str], *, messages: Sequence[Message] | None = None) -> dict[str, int | None]:
+ return {str(code): self.encode_single_token(str(code), messages=messages) for code in codes}
+
+
+__all__ = ["CandidateCodeTokenizer", "join_messages"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/base/types.py b/jiuwenswarm/symphony/retrieval/llm/base/types.py
new file mode 100644
index 0000000000..e4dd1322cc
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/base/types.py
@@ -0,0 +1,129 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Mapping
+
+Message = dict[str, str]
+
+
+@dataclass(frozen=True)
+class LLMClientCapabilities:
+ # Supports complete(...) one-shot generation.
+ completion: bool = True
+ # Supports stream_complete(...) streaming generation.
+ streaming: bool = False
+ # Supports score_candidate_codes(...) for logit-selection.
+ candidate_scoring: bool = False
+ # Supports structured trie constraints through GenerationConfig.
+ trie_constrained_decoding: bool = False
+ # Supports progressive retriever fixed-prefix KV cache handles.
+ progressive_prefix_kv_cache: bool = False
+ # Safe to invoke concurrently from multiple threads.
+ thread_safe: bool = True
+ # Holds local model/device/cache resources that may need lifecycle control.
+ local_resources: bool = False
+
+
+class LLMStreamChunk(str):
+ def __new__(cls, content: str, *, usage: Mapping[str, Any] | None = None):
+ obj = str.__new__(cls, content)
+ obj.usage = dict(usage or {})
+ return obj
+
+
+@dataclass(frozen=True)
+class TrieConstraint:
+ allowed_output_ids: tuple[str, ...]
+ excluded_output_ids: tuple[str, ...] = ()
+ top_k: int = 1
+ version: str | None = None
+
+
+@dataclass(frozen=True)
+class GenerationConstraints:
+ trie: TrieConstraint | None = None
+
+
+@dataclass(frozen=True)
+class PromptCacheHint:
+ handle: Any | None = None
+ suffix_text: str = ""
+ suffix_token_ids: tuple[int, ...] | None = None
+ expected_prefix_len: int | None = None
+
+
+@dataclass(frozen=True)
+class GenerationConfig:
+ disable_thinking: bool = True
+ temperature: float = 0.0
+ top_p: float = 1.0
+ seed: int | None = 1223
+ constraints: GenerationConstraints = field(default_factory=GenerationConstraints)
+ prompt_cache: PromptCacheHint | None = None
+
+
+@dataclass(frozen=True)
+class CandidateScore:
+ code: str
+ canonical_id: str
+ token_id: int | None
+ logit: float
+ probability: float
+ rank: int
+
+
+@dataclass(frozen=True)
+class CandidateScoringResult:
+ scores: tuple[CandidateScore, ...]
+ candidate_codes: tuple[str, ...]
+ candidate_token_ids: tuple[int, ...] = ()
+ latency_breakdown: Mapping[str, float] = field(default_factory=dict)
+
+
+def generation_config_to_debug_dict(config: GenerationConfig | None) -> dict[str, Any]:
+ resolved = config or GenerationConfig()
+ constraints: dict[str, Any] = {}
+ if resolved.constraints.trie is not None:
+ trie = resolved.constraints.trie
+ constraints["trie"] = {
+ "allowed_output_ids": list(trie.allowed_output_ids),
+ "excluded_output_ids": list(trie.excluded_output_ids),
+ "top_k": int(trie.top_k),
+ "version": trie.version,
+ }
+ prompt_cache: dict[str, Any] = {}
+ if resolved.prompt_cache is not None:
+ hint = resolved.prompt_cache
+ handle = hint.handle
+ prompt_cache = {
+ "enabled": handle is not None,
+ "suffix_text_len": len(str(hint.suffix_text or "")),
+ "suffix_token_count": None if hint.suffix_token_ids is None else len(tuple(hint.suffix_token_ids)),
+ "expected_prefix_len": hint.expected_prefix_len,
+ }
+ for attr in ("cache_id", "prefix_len", "dp_replica_id"):
+ value = getattr(handle, attr, None)
+ if value is not None:
+ prompt_cache[attr] = value
+ return {
+ "disable_thinking": bool(resolved.disable_thinking),
+ "temperature": float(resolved.temperature),
+ "top_p": float(resolved.top_p),
+ "seed": resolved.seed,
+ "constraints": constraints,
+ "prompt_cache": prompt_cache,
+ }
+
+
+__all__ = [
+ "CandidateScore",
+ "CandidateScoringResult",
+ "GenerationConfig",
+ "GenerationConstraints",
+ "LLMClientCapabilities",
+ "LLMStreamChunk",
+ "Message",
+ "PromptCacheHint",
+ "TrieConstraint",
+ "generation_config_to_debug_dict",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/config.py b/jiuwenswarm/symphony/retrieval/llm/config.py
new file mode 100644
index 0000000000..212295e293
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/config.py
@@ -0,0 +1,105 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Literal, TypeAlias
+
+TransformersBackend: TypeAlias = Literal[
+ "transformers",
+ "transformers_prefix_cached",
+ "transformers_prefix_cached_generation",
+]
+
+
+@dataclass(frozen=True)
+class OpenAIClientConfig:
+ """OpenAI-compatible LLM client configuration."""
+
+ # Client type discriminator used by the resolver.
+ backend: Literal["openai"] = "openai"
+
+ # OpenAI-compatible model name used for generation requests.
+ model: str = ""
+
+ # Optional externally-created OpenAI-compatible client.
+ client: Any | None = None
+
+ # API key used when creating the OpenAI-compatible client internally.
+ api_key: str = ""
+
+ # OpenAI-compatible base URL.
+ base_url: str = ""
+
+ # Optional request seed for deterministic-compatible providers.
+ seed: int | None = None
+
+ # Provider-specific request body extensions, such as disabling thinking.
+ extra_body: dict[str, object] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class VLLMClientConfig:
+ """Local custom vLLM client configuration."""
+
+ # Client type discriminator used by the resolver.
+ backend: Literal["vllm"] = "vllm"
+
+ # Local model directory loaded by custom vLLM.
+ model_path: str = ""
+
+ # Local tokenizer directory. Defaults to model_path in the runtime adapter.
+ tokenizer_path: str = ""
+
+ # Model name sent with requests and logs.
+ request_model: str = ""
+
+ # Custom vLLM startup and private adapter options.
+ vllm_kwargs: dict[str, object] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class TransformersClientConfig:
+ """Local transformers client configuration."""
+
+ # Client type discriminator used by the resolver.
+ backend: TransformersBackend = "transformers"
+
+ # Local model directory.
+ model_path: str = ""
+
+ # Local tokenizer directory. Defaults to model_path in the runtime adapter.
+ tokenizer_path: str = ""
+
+ # Device selection, such as auto, cpu, or cuda:0.
+ device: str = "auto"
+
+ # Model dtype for local inference.
+ dtype: str = "bfloat16"
+
+ # Tensor parallel size for transformers local inference.
+ tensor_parallel_size: int = 1
+
+ # Data parallel size for transformers local inference.
+ data_parallel_size: int = 1
+
+ # Explicit device ids. Empty means the client resolves devices itself.
+ device_ids: tuple[int, ...] = ()
+
+ # Optional transformers attention implementation.
+ attn_implementation: str = ""
+
+ # Whether to enable torch.compile for the local model.
+ torch_compile: bool = False
+
+ # Optional tensor parallel plan name.
+ tensor_parallel_plan: str = ""
+
+
+LLMClientConfig: TypeAlias = OpenAIClientConfig | VLLMClientConfig | TransformersClientConfig
+
+
+__all__ = [
+ "LLMClientConfig",
+ "OpenAIClientConfig",
+ "TransformersClientConfig",
+ "VLLMClientConfig",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/factory.py b/jiuwenswarm/symphony/retrieval/llm/factory.py
new file mode 100644
index 0000000000..c728e2bf31
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/factory.py
@@ -0,0 +1,282 @@
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any
+
+from .base import ProgressiveLLMClient
+from .base.errors import UnsupportedCapability
+from .config import LLMClientConfig, TransformersClientConfig, VLLMClientConfig
+from .openai_api import OpenAICompatibleClient
+from .transformers_prefix_cached_generation import TransformersPrefixCachedGenerationClient
+from .transformers_logit_selection import TransformersLogitSelectionClient
+from .vllm import LocalVLLMClient
+from ..tree.types import ProgressiveRetrieverConfig
+
+LOGGER = logging.getLogger(__name__)
+
+
+def coerce_generation_client(client: Any | None) -> ProgressiveLLMClient | None:
+ if client is None:
+ return None
+ if isinstance(client, ProgressiveLLMClient):
+ return client
+ if _is_openai_compatible_client(client):
+ return OpenAICompatibleClient(client)
+ raise TypeError(
+ "llm client must be a ProgressiveLLMClient or an OpenAI-compatible client exposing chat.completions.create"
+ )
+
+
+def create_progressive_client(
+ *,
+ generation_client: ProgressiveLLMClient | None,
+ config: ProgressiveRetrieverConfig,
+) -> ProgressiveLLMClient | None:
+ resolved_generation_client = generation_client
+ llm_client_config = config.llm_client_config
+ if (
+ _needs_local_vllm_generation_client(llm_client_config)
+ and not isinstance(resolved_generation_client, LocalVLLMClient)
+ ):
+ if not isinstance(llm_client_config, VLLMClientConfig):
+ raise TypeError("local vllm generation requires VLLMClientConfig")
+ vllm_config = llm_client_config
+ model_path = str(vllm_config.model_path or "").strip()
+ tokenizer_path = str(vllm_config.tokenizer_path or model_path).strip()
+ if not model_path or not tokenizer_path:
+ raise ValueError("local vllm generation requires model_path or tokenizer_path")
+ vllm_kwargs, device, dtype = _vllm_runtime_options(vllm_config)
+ vllm_kwargs.setdefault(
+ "tensor_parallel_size",
+ max(1, int(vllm_kwargs.get("tensor_parallel_size", 1) or 1)),
+ )
+ LOGGER.info(
+ "creating progressive generation client backend=%s model=%s tokenizer=%s dtype=%s",
+ _client_backend(vllm_config),
+ model_path,
+ tokenizer_path,
+ dtype,
+ )
+ resolved_generation_client = LocalVLLMClient.from_pretrained(
+ model_path=model_path,
+ tokenizer_path=tokenizer_path,
+ device=device,
+ dtype=dtype,
+ vllm_kwargs=vllm_kwargs,
+ max_new_tokens=_derived_cache_max_new_tokens(config),
+ )
+ elif _needs_prefix_cached_generation_client(llm_client_config):
+ if not isinstance(llm_client_config, TransformersClientConfig):
+ raise TypeError("prefix-cached generation requires TransformersClientConfig")
+ transformers_config = llm_client_config
+ model_path = str(transformers_config.model_path or "").strip()
+ tokenizer_path = str(transformers_config.tokenizer_path or model_path).strip()
+ if not model_path or not tokenizer_path:
+ raise ValueError("prefix-cached generation requires model_path or tokenizer_path")
+ LOGGER.info(
+ "creating progressive generation client backend=%s model=%s tokenizer=%s dtype=%s",
+ _client_backend(transformers_config),
+ model_path,
+ tokenizer_path,
+ str(transformers_config.dtype or "bfloat16"),
+ )
+ resolved_generation_client = TransformersPrefixCachedGenerationClient.from_pretrained(
+ model_path=model_path,
+ tokenizer_path=tokenizer_path,
+ device=str(transformers_config.device or "auto"),
+ dtype=str(transformers_config.dtype or "bfloat16"),
+ tp_size=max(1, int(transformers_config.tensor_parallel_size)),
+ dp_size=max(1, int(transformers_config.data_parallel_size)),
+ device_ids=tuple(int(item) for item in transformers_config.device_ids),
+ attn_implementation=str(transformers_config.attn_implementation or ""),
+ torch_compile=bool(transformers_config.torch_compile),
+ tp_plan=str(transformers_config.tensor_parallel_plan or ""),
+ max_new_tokens=_derived_cache_max_new_tokens(config),
+ )
+ if not _needs_logit_selection_client(config):
+ return resolved_generation_client
+ backend_name = _client_backend(llm_client_config)
+ model_path = _local_model_path(llm_client_config)
+ tokenizer_path = _local_tokenizer_path(llm_client_config)
+ LOGGER.info(
+ "progressive logit selection requested backend=%s model=%s tokenizer=%s generation_client=%s",
+ backend_name,
+ model_path,
+ tokenizer_path,
+ type(resolved_generation_client).__name__ if resolved_generation_client is not None else "None",
+ )
+ if not model_path or not tokenizer_path:
+ LOGGER.warning(
+ "progressive logit selection skipped because local model/tokenizer path is empty backend=%s",
+ backend_name,
+ )
+ return resolved_generation_client
+ if isinstance(llm_client_config, TransformersClientConfig):
+ scoring_client = TransformersLogitSelectionClient.from_pretrained(
+ model_path=model_path,
+ tokenizer_path=tokenizer_path,
+ device=str(llm_client_config.device or "auto"),
+ dtype=str(llm_client_config.dtype or "auto"),
+ generation_client=resolved_generation_client,
+ )
+ LOGGER.info(
+ "progressive logit selection client ready backend=%s client=%s",
+ backend_name,
+ type(scoring_client).__name__,
+ )
+ return scoring_client
+ if isinstance(llm_client_config, VLLMClientConfig):
+ LOGGER.warning("progressive logit selection is unsupported for local vllm backend")
+ raise UnsupportedCapability("local vllm client is generation-only and does not support logit selection")
+ LOGGER.info("progressive logit selection has no local scoring client for backend=%s", backend_name)
+ return resolved_generation_client
+
+
+def progressive_client_cache_key(config: ProgressiveRetrieverConfig) -> tuple[object, ...] | None:
+ parts: list[object] = []
+ llm_client_config = config.llm_client_config
+ if _needs_prefix_cached_generation_client(llm_client_config):
+ if not isinstance(llm_client_config, TransformersClientConfig):
+ raise TypeError("prefix-cached generation requires TransformersClientConfig")
+ transformers_config = llm_client_config
+ backend_name = _client_backend(transformers_config)
+ model_path = str(transformers_config.model_path or "").strip()
+ tokenizer_path = str(transformers_config.tokenizer_path or model_path).strip()
+ if model_path and tokenizer_path:
+ parts.extend(
+ [
+ (
+ "generation",
+ backend_name,
+ model_path,
+ tokenizer_path,
+ str(transformers_config.device or "auto"),
+ str(transformers_config.dtype or "bfloat16"),
+ max(1, int(transformers_config.tensor_parallel_size)),
+ max(1, int(transformers_config.data_parallel_size)),
+ tuple(int(item) for item in transformers_config.device_ids),
+ str(transformers_config.attn_implementation or ""),
+ bool(transformers_config.torch_compile),
+ str(transformers_config.tensor_parallel_plan or ""),
+ _derived_cache_max_new_tokens(config),
+ )
+ ]
+ )
+ elif _needs_local_vllm_generation_client(llm_client_config):
+ if not isinstance(llm_client_config, VLLMClientConfig):
+ raise TypeError("local vllm generation requires VLLMClientConfig")
+ vllm_config = llm_client_config
+ backend_name = _client_backend(vllm_config)
+ model_path = str(vllm_config.model_path or "").strip()
+ tokenizer_path = str(vllm_config.tokenizer_path or model_path).strip()
+ if model_path and tokenizer_path:
+ vllm_kwargs, device, dtype = _vllm_runtime_options(vllm_config)
+ parts.extend(
+ [
+ (
+ "generation",
+ backend_name,
+ model_path,
+ tokenizer_path,
+ device,
+ dtype,
+ max(1, int(vllm_kwargs.get("tensor_parallel_size", 1) or 1)),
+ _derived_cache_max_new_tokens(config),
+ json.dumps(vllm_kwargs, ensure_ascii=False, sort_keys=True, default=str),
+ )
+ ]
+ )
+ if not _needs_logit_selection_client(config):
+ return tuple(parts) if parts else None
+ logit_key = _logit_selection_cache_key(config)
+ if logit_key is not None:
+ parts.append(logit_key)
+ return tuple(parts) if parts else None
+
+
+def _logit_selection_cache_key(config: ProgressiveRetrieverConfig) -> tuple[object, ...] | None:
+ if not _needs_logit_selection_client(config):
+ return None
+ llm_client_config = config.llm_client_config
+ backend_name = _client_backend(llm_client_config)
+ if not isinstance(llm_client_config, (TransformersClientConfig, VLLMClientConfig)):
+ return None
+ model_path = _local_model_path(llm_client_config)
+ tokenizer_path = _local_tokenizer_path(llm_client_config)
+ if not model_path or not tokenizer_path:
+ return None
+ if isinstance(llm_client_config, VLLMClientConfig):
+ vllm_kwargs, device, dtype = _vllm_runtime_options(llm_client_config)
+ backend_options = (device, dtype, json.dumps(vllm_kwargs, ensure_ascii=False, sort_keys=True, default=str))
+ else:
+ backend_options = (str(llm_client_config.device or "auto"), str(llm_client_config.dtype or "auto"))
+ return (backend_name, model_path, tokenizer_path, backend_options)
+
+
+def _needs_prefix_cached_generation_client(config: LLMClientConfig) -> bool:
+ return isinstance(config, TransformersClientConfig) and _client_backend(config) in {
+ "transformers_prefix_cached",
+ "transformers_prefix_cached_generation",
+ }
+
+
+def _needs_local_vllm_generation_client(config: LLMClientConfig) -> bool:
+ return isinstance(config, VLLMClientConfig) and _client_backend(config) in {"vllm", "local_vllm"}
+
+
+def _client_backend(config: LLMClientConfig) -> str:
+ return str(getattr(config, "backend", "openai") or "openai").strip().lower() or "openai"
+
+
+def _needs_logit_selection_client(config: ProgressiveRetrieverConfig) -> bool:
+ return str(config.selection_mode or "").strip().lower() == "logit_selection"
+
+
+def _local_model_path(config: LLMClientConfig) -> str:
+ return str(getattr(config, "model_path", "") or "").strip()
+
+
+def _local_tokenizer_path(config: LLMClientConfig) -> str:
+ model_path = _local_model_path(config)
+ return str(getattr(config, "tokenizer_path", "") or model_path).strip()
+
+
+def _vllm_runtime_options(config: VLLMClientConfig) -> tuple[dict[str, object], str, str]:
+ vllm_kwargs = dict(config.vllm_kwargs or {})
+ dtype = str(vllm_kwargs.pop("dtype", "bfloat16") or "bfloat16")
+ device = str(vllm_kwargs.pop("device", "") or "")
+ request_model = str(config.request_model or "").strip()
+ if request_model and "request_model" not in vllm_kwargs:
+ vllm_kwargs["request_model"] = request_model
+ return vllm_kwargs, device, dtype
+
+
+def _derived_cache_max_new_tokens(config: ProgressiveRetrieverConfig) -> int:
+ return max(
+ 1,
+ int(config.max_tokens),
+ _compact_code_generation_max_tokens(
+ config.top_k,
+ generated_decimal_codes=not bool(config.compact_boundary_codebook),
+ ),
+ )
+
+
+def _compact_code_generation_max_tokens(top_k: int, *, generated_decimal_codes: bool) -> int:
+ code_token_budget = 8 if generated_decimal_codes else 1
+ return max(1, (code_token_budget + 1) * max(1, int(top_k)) - 1)
+
+
+def _is_openai_compatible_client(client: Any) -> bool:
+ chat = getattr(client, "chat", None)
+ completions = getattr(chat, "completions", None)
+ create = getattr(completions, "create", None)
+ return callable(create)
+
+
+__all__ = [
+ "coerce_generation_client",
+ "create_progressive_client",
+ "progressive_client_cache_key",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/openai_api/__init__.py b/jiuwenswarm/symphony/retrieval/llm/openai_api/__init__.py
new file mode 100644
index 0000000000..31040917c5
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/openai_api/__init__.py
@@ -0,0 +1,3 @@
+from .client import OpenAICompatibleClient
+
+__all__ = ["OpenAICompatibleClient"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/openai_api/client.py b/jiuwenswarm/symphony/retrieval/llm/openai_api/client.py
new file mode 100644
index 0000000000..3c378716dd
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/openai_api/client.py
@@ -0,0 +1,277 @@
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any, Iterable, Mapping, Sequence
+
+from ..base import (
+ GenerationConfig,
+ LLMClientCapabilities,
+ LLMRequestError,
+ LLMStreamChunk,
+ Message,
+ ProgressiveLLMClient,
+)
+
+
+class OpenAICompatibleClient(ProgressiveLLMClient):
+ DEFAULT_TEMPERATURE = 0.0
+ DEFAULT_TOP_P = 1.0
+ DEFAULT_SEED = 1223
+
+ name = "openai_api"
+
+ def __init__(
+ self,
+ client: Any,
+ *,
+ log_io: bool = False,
+ logger: logging.Logger | None = None,
+ seed: int | None = None,
+ extra_body: Mapping[str, Any] | None = None,
+ ) -> None:
+ self._client = client
+ self._log_io = bool(log_io)
+ self._logger = logger or logging.getLogger(__name__)
+ self._seed = int(self.DEFAULT_SEED if seed is None else seed)
+ self._extra_body = dict(extra_body or {})
+
+ @property
+ def capabilities(self) -> LLMClientCapabilities:
+ return LLMClientCapabilities(
+ completion=True,
+ streaming=True,
+ candidate_scoring=False,
+ trie_constrained_decoding=True,
+ thread_safe=True,
+ local_resources=False,
+ )
+
+ def default_generation_config(self) -> GenerationConfig:
+ return GenerationConfig(seed=self._seed)
+
+ def stream_complete(
+ self,
+ model: str,
+ messages: list[Message],
+ early_stop: object | None = None,
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ request_timeout: float | None = None,
+ ) -> Iterable[str | LLMStreamChunk]:
+ config = generation_config or self.default_generation_config()
+ controller = _EarlyStopController(early_stop)
+ stop = list(controller.stop_sequences() or [])
+ for item in stop_sequences or []:
+ if item and item not in stop:
+ stop.append(str(item))
+ kwargs: dict[str, Any] = {
+ "model": model,
+ "messages": messages,
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ "extra_body": self.extra_body_from_generation_config(config),
+ }
+ if config.seed is not None:
+ kwargs["seed"] = int(config.seed)
+ elif self._seed is not None:
+ kwargs["seed"] = int(self._seed)
+ if self._log_io:
+ self._emit_io("LLM REQUEST", {"model": model, "messages": messages, "stream": True, "stop": list(stop)})
+ if stop:
+ kwargs["stop"] = stop
+ if max_tokens is not None and max_tokens > 0:
+ kwargs["max_tokens"] = int(max_tokens)
+ if request_timeout is not None and float(request_timeout) > 0:
+ kwargs["timeout"] = float(request_timeout)
+ try:
+ stream = self._client.chat.completions.create(**kwargs)
+ except Exception as exc:
+ raise LLMRequestError(f"OpenAI-compatible streaming request failed: {exc}") from exc
+ chunks: list[str] = []
+ usage: dict[str, Any] | None = None
+ try:
+ for chunk in stream:
+ chunk_usage = self._usage_to_dict(getattr(chunk, "usage", None))
+ if chunk_usage:
+ usage = chunk_usage
+ delta = self._extract_delta_content(chunk)
+ if not delta:
+ if chunk_usage:
+ yield LLMStreamChunk("", usage=chunk_usage)
+ continue
+ chunks.append(delta)
+ current = "".join(chunks)
+ yield LLMStreamChunk(delta, usage=chunk_usage)
+ if controller.should_abort(current):
+ break
+ finally:
+ close = getattr(stream, "close", None)
+ if callable(close):
+ close()
+ if self._log_io:
+ self._emit_io(
+ "LLM RESPONSE", {"model": model, "content": "".join(chunks), "stream": True, "usage": usage or {}}
+ )
+
+ def complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ n: int = 1,
+ request_timeout: float | None = None,
+ ) -> list[str]:
+ config = generation_config or self.default_generation_config()
+ stop = [str(item) for item in (stop_sequences or []) if item]
+ kwargs: dict[str, Any] = {
+ "model": model,
+ "messages": messages,
+ "stream": False,
+ "extra_body": self.extra_body_from_generation_config(config),
+ }
+ if config.seed is not None:
+ kwargs["seed"] = int(config.seed)
+ elif self._seed is not None:
+ kwargs["seed"] = int(self._seed)
+ if stop:
+ kwargs["stop"] = stop
+ if max_tokens is not None and max_tokens > 0:
+ kwargs["max_tokens"] = int(max_tokens)
+ if n > 1:
+ kwargs["n"] = int(n)
+ if request_timeout is not None and float(request_timeout) > 0:
+ kwargs["timeout"] = float(request_timeout)
+ if self._log_io:
+ self._emit_io("LLM REQUEST", {"model": model, "messages": messages, "stream": False, "n": int(max(1, n))})
+ try:
+ response = self._client.chat.completions.create(**kwargs)
+ except Exception as exc:
+ raise LLMRequestError(f"OpenAI-compatible completion request failed: {exc}") from exc
+ results = self._extract_completion_contents(response)
+ if self._log_io:
+ self._emit_io("LLM RESPONSE", {"model": model, "stream": False, "choices": results})
+ return results
+
+ def extra_body_from_generation_config(self, config: GenerationConfig | None) -> dict[str, Any]:
+ resolved = config or self.default_generation_config()
+ extra_body: dict[str, Any] = {
+ "temperature": float(resolved.temperature),
+ "top_p": float(resolved.top_p),
+ }
+ if resolved.disable_thinking:
+ extra_body["thinking"] = {"type": "disabled"}
+ extra_body["chat_template_kwargs"] = {"enable_thinking": False}
+ if resolved.seed is not None:
+ extra_body["seed"] = int(resolved.seed)
+ trie = resolved.constraints.trie
+ if trie is not None:
+ version = trie.version
+ if not version:
+ version = _constraint_version(trie.allowed_output_ids)
+ extra_body["vllm_xargs"] = {
+ "constraint_type": "leaf_id_multicid_trie",
+ "constraint_version": version,
+ "top_k": max(1, int(trie.top_k)),
+ "leaf_ids_json": json.dumps(list(trie.allowed_output_ids), ensure_ascii=False),
+ "excluded_leaf_ids_json": json.dumps(list(trie.excluded_output_ids), ensure_ascii=False),
+ }
+ extra_body.update(self._extra_body)
+ return extra_body
+
+ def _emit_io(self, title: str, payload: Mapping[str, Any]) -> None:
+ text = f"\n=== {title} ===\n{dict(payload)}\n=== END {title} ===\n"
+ try:
+ self._logger.info(text)
+ except Exception as exc:
+ self._logger.debug("failed to emit OpenAI API IO log: %s", exc)
+
+ @staticmethod
+ def _extract_delta_content(chunk: Any) -> str:
+ try:
+ delta = chunk.choices[0].delta
+ except Exception:
+ return ""
+ if isinstance(delta, Mapping):
+ return str(delta.get("content") or "")
+ return str(getattr(delta, "content", "") or "")
+
+ @classmethod
+ def _extract_completion_contents(cls, response: Any) -> list[str]:
+ choices = getattr(response, "choices", None)
+ if choices is None and isinstance(response, Mapping):
+ choices = response.get("choices")
+ results: list[str] = []
+ for choice in choices or []:
+ message = getattr(choice, "message", None)
+ if message is None and isinstance(choice, Mapping):
+ message = choice.get("message")
+ content = ""
+ if isinstance(message, Mapping):
+ content = str(message.get("content") or "")
+ elif message is not None:
+ content = str(getattr(message, "content", "") or "")
+ results.append(content)
+ return results
+
+ @staticmethod
+ def _usage_to_dict(usage: Any) -> dict[str, Any]:
+ if usage is None:
+ return {}
+ if isinstance(usage, Mapping):
+ return dict(usage)
+ model_dump = getattr(usage, "model_dump", None)
+ if callable(model_dump):
+ try:
+ return dict(model_dump())
+ except Exception:
+ return {}
+ data: dict[str, Any] = {}
+ for key in ("prompt_tokens", "completion_tokens", "total_tokens"):
+ value = getattr(usage, key, None)
+ if value is not None:
+ data[key] = value
+ return data
+
+
+class _EarlyStopController:
+ def __init__(self, policy: object | None) -> None:
+ self._policy = policy
+
+ def stop_sequences(self) -> Sequence[str]:
+ policy = self._policy
+ if policy is None:
+ return ()
+ method = getattr(policy, "stop_sequences", None)
+ if callable(method):
+ try:
+ return tuple(str(item) for item in (method() or ()) if item)
+ except Exception:
+ return ()
+ return ()
+
+ def should_abort(self, text: str) -> bool:
+ policy = self._policy
+ if policy is None:
+ return False
+ method = getattr(policy, "should_abort", None)
+ if callable(method):
+ try:
+ return bool(method(text))
+ except Exception:
+ return False
+ return False
+
+
+def _constraint_version(allowed_output_ids: Sequence[str]) -> str:
+ import hashlib
+
+ return hashlib.sha256(json.dumps(list(allowed_output_ids), ensure_ascii=False).encode("utf-8")).hexdigest()
+
+
+__all__ = ["OpenAICompatibleClient"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/transformers_logit_selection/__init__.py b/jiuwenswarm/symphony/retrieval/llm/transformers_logit_selection/__init__.py
new file mode 100644
index 0000000000..a78dad91c5
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/transformers_logit_selection/__init__.py
@@ -0,0 +1,3 @@
+from .client import TransformersLogitSelectionClient
+
+__all__ = ["TransformersLogitSelectionClient"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/transformers_logit_selection/client.py b/jiuwenswarm/symphony/retrieval/llm/transformers_logit_selection/client.py
new file mode 100644
index 0000000000..5f74fb5be9
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/transformers_logit_selection/client.py
@@ -0,0 +1,238 @@
+from __future__ import annotations
+
+import logging
+import threading
+from dataclasses import dataclass
+from time import perf_counter
+from typing import Mapping, Sequence
+
+from ..base import (
+ CandidateScoringResult,
+ GenerationConfig,
+ LLMClientCapabilities,
+ LLMStreamChunk,
+ Message,
+ ProgressiveLLMClient,
+ UnsupportedCapability,
+)
+from ..base.scoring import build_candidate_scoring_result, prepare_candidate_token_ids
+from ..base.tokenization import CandidateCodeTokenizer, join_messages
+
+LOGGER = logging.getLogger("retrieval.llm.transformers_logit_selection")
+
+
+@dataclass
+class TransformersLogitSelectionClient(ProgressiveLLMClient):
+ model_obj: object
+ candidate_tokenizer: CandidateCodeTokenizer
+ device: str = "cpu"
+ generation_client: ProgressiveLLMClient | None = None
+
+ name = "transformers_logit_selection"
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ *,
+ model_path: str,
+ tokenizer_path: str | None = None,
+ device: str = "auto",
+ dtype: str = "auto",
+ generation_client: ProgressiveLLMClient | None = None,
+ ) -> "TransformersLogitSelectionClient":
+ try:
+ import torch
+ from transformers import AutoModelForCausalLM
+ except ImportError as exc:
+ raise RuntimeError(
+ "transformers and torch are required for the transformers logit-selection client"
+ ) from exc
+
+ resolved_device = (
+ "cuda" if device == "auto" and torch.cuda.is_available() else ("cpu" if device == "auto" else device)
+ )
+ torch_dtype = None
+ if dtype == "float16":
+ torch_dtype = torch.float16
+ elif dtype == "bfloat16":
+ torch_dtype = torch.bfloat16
+ elif dtype == "float32":
+ torch_dtype = torch.float32
+ resolved_tokenizer_path = tokenizer_path or model_path
+ tokenizer = CandidateCodeTokenizer.from_pretrained(resolved_tokenizer_path)
+ model_obj = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch_dtype, trust_remote_code=True)
+ model_obj.to(resolved_device)
+ model_obj.eval()
+ return cls(
+ model_obj=model_obj,
+ candidate_tokenizer=tokenizer,
+ device=resolved_device,
+ generation_client=generation_client,
+ )
+
+ def __post_init__(self) -> None:
+ self._lock = threading.Lock()
+
+ @property
+ def capabilities(self) -> LLMClientCapabilities:
+ generation_caps = self.generation_client.capabilities if self.generation_client is not None else None
+ return LLMClientCapabilities(
+ completion=bool(generation_caps.completion) if generation_caps is not None else False,
+ streaming=bool(generation_caps.streaming) if generation_caps is not None else False,
+ candidate_scoring=True,
+ trie_constrained_decoding=False,
+ thread_safe=False,
+ local_resources=True,
+ )
+
+ def complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ n: int = 1,
+ request_timeout: float | None = None,
+ ) -> list[str]:
+ if self.generation_client is None:
+ raise UnsupportedCapability("transformers logit-selection client does not provide generation")
+ return self.generation_client.complete(
+ model=model,
+ messages=messages,
+ max_tokens=max_tokens,
+ stop_sequences=stop_sequences,
+ generation_config=generation_config,
+ n=n,
+ request_timeout=request_timeout,
+ )
+
+ def stream_complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ request_timeout: float | None = None,
+ early_stop: object | None = None,
+ ):
+ if self.generation_client is None:
+ yield from super().stream_complete(
+ model=model,
+ messages=messages,
+ max_tokens=max_tokens,
+ stop_sequences=stop_sequences,
+ generation_config=generation_config,
+ request_timeout=request_timeout,
+ early_stop=early_stop,
+ )
+ return
+ yield from self.generation_client.stream_complete(
+ model=model,
+ messages=messages,
+ max_tokens=max_tokens,
+ stop_sequences=stop_sequences,
+ generation_config=generation_config,
+ request_timeout=request_timeout,
+ early_stop=early_stop,
+ )
+
+ def score_candidate_codes(
+ self,
+ *,
+ model: str,
+ messages: list[Message],
+ candidate_codes: Sequence[str],
+ code_to_canonical_id: Mapping[str, str],
+ top_k: int | None = None,
+ require_single_token_codes: bool = True,
+ request_timeout: float | None = None,
+ ) -> CandidateScoringResult:
+ del model, request_timeout
+ started = perf_counter()
+ candidate_codes_tuple = tuple(str(code) for code in candidate_codes)
+ encode_started = perf_counter()
+ encoded = self.candidate_tokenizer.encode_many(candidate_codes_tuple, messages=messages)
+ tokenization = prepare_candidate_token_ids(
+ candidate_codes=candidate_codes_tuple,
+ encoded_codes=encoded,
+ require_single_token_codes=require_single_token_codes,
+ )
+ encode_ms = (perf_counter() - encode_started) * 1000.0
+ if not tokenization.token_to_code:
+ return CandidateScoringResult(
+ scores=(),
+ candidate_codes=tokenization.candidate_codes,
+ candidate_token_ids=(),
+ latency_breakdown={
+ "encode_ms": round(encode_ms, 3),
+ "backend_ms": 0.0,
+ "normalize_ms": 0.0,
+ "total_ms": round((perf_counter() - started) * 1000.0, 3),
+ },
+ )
+ backend_started = perf_counter()
+ scored_pairs = self._score_token_ids(messages=messages, candidate_token_ids=tokenization.candidate_token_ids)
+ backend_ms = (perf_counter() - backend_started) * 1000.0
+ result = build_candidate_scoring_result(
+ tokenization=tokenization,
+ scored_pairs=scored_pairs,
+ code_to_canonical_id=code_to_canonical_id,
+ latency_breakdown={
+ "encode_ms": round(encode_ms, 3),
+ "backend_ms": round(backend_ms, 3),
+ "total_ms": round((perf_counter() - started) * 1000.0, 3),
+ },
+ )
+ LOGGER.info(
+ "transformers logit-selection complete candidates=%d returned=%d",
+ len(candidate_codes_tuple),
+ len(result.scores),
+ )
+ return result
+
+ def _score_token_ids(
+ self, *, messages: list[Message], candidate_token_ids: Sequence[int]
+ ) -> list[tuple[int, float]]:
+ try:
+ import torch
+ except ImportError as exc:
+ raise RuntimeError("torch is required for the transformers logit-selection client") from exc
+ tokenizer = self.candidate_tokenizer.tokenizer
+ with self._lock:
+ if hasattr(tokenizer, "apply_chat_template"):
+ encoded = tokenizer.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ return_tensors="pt",
+ tokenize=True,
+ enable_thinking=False,
+ preserve_thinking=False,
+ add_vision_id=False,
+ )
+ if hasattr(encoded, "to"):
+ input_ids = encoded.to(self.device)
+ else:
+ input_ids = torch.as_tensor(encoded, device=self.device)
+ attention_mask = torch.ones_like(input_ids, device=self.device)
+ model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask}
+ else:
+ prompt = join_messages(messages)
+ model_inputs = tokenizer(prompt, return_tensors="pt")
+ model_inputs = {key: value.to(self.device) for key, value in model_inputs.items()}
+ with torch.no_grad():
+ outputs = self.model_obj(**model_inputs)
+ logits = outputs.logits[(slice(None), -1, slice(None))].detach().float()[0]
+ pairs = [(int(token_id), float(logits[int(token_id)].item())) for token_id in candidate_token_ids]
+ pairs.sort(key=lambda item: item[1], reverse=True)
+ return pairs
+
+ def close(self) -> None:
+ if self.generation_client is not None:
+ self.generation_client.close()
+
+
+__all__ = ["TransformersLogitSelectionClient"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/__init__.py b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/__init__.py
new file mode 100644
index 0000000000..654e83de82
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/__init__.py
@@ -0,0 +1,29 @@
+from .cache import (
+ PrefixCacheEntry,
+ PrefixCacheHandle,
+ PrefixCacheRegistry,
+ PrefixCacheReplica,
+ PrefixStaticCachePool,
+ PrefixStaticCacheSlot,
+ RequestCacheState,
+)
+from .client import DistributedGenerationConfig, TransformersPrefixCachedGenerationClient
+from .generation import PrefixGenerationDecoder, PrefixGenerationResult, TransformersForwardDecoder
+from .warmup import PrefixCacheWarmupResult, warmup_progressive_prefix_cache
+
+__all__ = [
+ "DistributedGenerationConfig",
+ "PrefixCacheEntry",
+ "PrefixCacheHandle",
+ "PrefixCacheRegistry",
+ "PrefixCacheReplica",
+ "PrefixCacheWarmupResult",
+ "PrefixGenerationDecoder",
+ "PrefixGenerationResult",
+ "PrefixStaticCachePool",
+ "PrefixStaticCacheSlot",
+ "RequestCacheState",
+ "TransformersForwardDecoder",
+ "TransformersPrefixCachedGenerationClient",
+ "warmup_progressive_prefix_cache",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/cache.py b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/cache.py
new file mode 100644
index 0000000000..92704725f9
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/cache.py
@@ -0,0 +1,266 @@
+from __future__ import annotations
+
+import logging
+import threading
+from dataclasses import dataclass, field
+from typing import Any, Literal, Sequence
+
+from ..base import PrefixCacheUnavailable
+
+logger = logging.getLogger(__name__)
+
+SlotState = Literal["idle", "busy", "poisoned", "rebuilding", "disabled"]
+ReplicaState = Literal["healthy", "degraded", "draining", "disabled"]
+
+
+@dataclass(frozen=True)
+class PrefixCacheEntry:
+ cache_id: str
+ prefix_input_ids: Any | None
+ prefix_len: int
+ past_key_values: Any
+ attention_mask_prefix: Any | None = None
+ next_cache_position: int = 0
+ device: str = ""
+ dtype: str = ""
+ readonly: bool = True
+
+
+@dataclass
+class PrefixStaticCacheSlot:
+ slot_id: str
+ cache_id: str
+ static_cache: Any
+ replica_id: int
+ tp_rank_devices: tuple[int, ...]
+ prefix_len: int
+ max_cache_len: int
+ prefix_messages: tuple[dict[str, str], ...] = ()
+ state: SlotState = "idle"
+ active_len: int = 0
+ poison_reason: str = ""
+
+
+@dataclass
+class PrefixCacheReplica:
+ replica_id: int
+ tp_rank_devices: tuple[int, ...]
+ state: ReplicaState = "healthy"
+ degraded_reason: str = ""
+
+ def mark_degraded(self, *, reason: str) -> None:
+ if self.state == "disabled":
+ return
+ self.state = "degraded"
+ self.degraded_reason = str(reason or "").strip()
+ logger.debug(
+ "prefix cache replica degraded replica_id=%s reason=%s",
+ self.replica_id,
+ self.degraded_reason,
+ )
+
+ def mark_healthy(self) -> None:
+ if self.state != "disabled":
+ self.state = "healthy"
+ self.degraded_reason = ""
+ logger.debug("prefix cache replica healthy replica_id=%s", self.replica_id)
+
+
+class PrefixStaticCachePool:
+ def __init__(
+ self,
+ *,
+ cache_id: str,
+ replica: PrefixCacheReplica,
+ slots: Sequence[PrefixStaticCacheSlot],
+ ) -> None:
+ self.cache_id = str(cache_id)
+ self.replica = replica
+ self._slots = list(slots)
+ self._condition = threading.Condition()
+
+ @property
+ def slots(self) -> tuple[PrefixStaticCacheSlot, ...]:
+ return tuple(self._slots)
+
+ def acquire(self) -> PrefixStaticCacheSlot:
+ with self._condition:
+ logger.debug(
+ "prefix cache slot acquire start cache_id=%s replica_id=%s idle=%s",
+ self.cache_id,
+ self.replica.replica_id,
+ sum(1 for slot in self._slots if slot.state == "idle"),
+ )
+ if self.replica.state != "disabled":
+ for slot in self._slots:
+ if slot.state == "idle":
+ slot.state = "busy"
+ slot.active_len = int(slot.prefix_len)
+ logger.debug(
+ "prefix cache slot acquired cache_id=%s slot_id=%s replica_id=%s "
+ "prefix_len=%s max_cache_len=%s",
+ self.cache_id,
+ slot.slot_id,
+ self.replica.replica_id,
+ slot.prefix_len,
+ slot.max_cache_len,
+ )
+ return slot
+ logger.debug(
+ "prefix cache slot acquire rejected cache_id=%s replica_id=%s replica_state=%s",
+ self.cache_id,
+ self.replica.replica_id,
+ self.replica.state,
+ )
+ raise PrefixCacheUnavailable(f"prefix cache pool exhausted: {self.cache_id}")
+
+ def release(self, slot: PrefixStaticCacheSlot) -> None:
+ with self._condition:
+ if slot.state == "busy":
+ slot.active_len = int(slot.prefix_len)
+ slot.state = "idle"
+ logger.debug(
+ "prefix cache slot released cache_id=%s slot_id=%s active_len=%s",
+ self.cache_id,
+ slot.slot_id,
+ slot.active_len,
+ )
+ self._condition.notify()
+
+ def mark_poisoned(self, slot: PrefixStaticCacheSlot, *, reason: str) -> None:
+ with self._condition:
+ slot.state = "poisoned"
+ slot.poison_reason = str(reason or "").strip()
+ logger.debug(
+ "prefix cache slot poisoned cache_id=%s slot_id=%s reason=%s",
+ self.cache_id,
+ slot.slot_id,
+ slot.poison_reason,
+ )
+ self._condition.notify()
+
+ def disable_slot(self, slot: PrefixStaticCacheSlot, *, reason: str) -> None:
+ with self._condition:
+ slot.state = "disabled"
+ slot.poison_reason = str(reason or "").strip()
+ logger.debug(
+ "prefix cache slot disabled cache_id=%s slot_id=%s reason=%s",
+ self.cache_id,
+ slot.slot_id,
+ slot.poison_reason,
+ )
+ self._condition.notify()
+
+ def mark_rebuilt(self, slot: PrefixStaticCacheSlot) -> None:
+ with self._condition:
+ slot.poison_reason = ""
+ slot.active_len = int(slot.prefix_len)
+ slot.state = "idle"
+ logger.debug(
+ "prefix cache slot rebuilt cache_id=%s slot_id=%s prefix_len=%s max_cache_len=%s",
+ self.cache_id,
+ slot.slot_id,
+ slot.prefix_len,
+ slot.max_cache_len,
+ )
+ self._condition.notify()
+
+ def idle_count(self) -> int:
+ with self._condition:
+ return sum(1 for slot in self._slots if slot.state == "idle")
+
+
+@dataclass(frozen=True)
+class RequestCacheState:
+ handle: "PrefixCacheHandle"
+ pool: PrefixStaticCachePool
+ slot: PrefixStaticCacheSlot
+ suffix_token_ids: tuple[int, ...]
+ max_new_tokens: int
+
+
+@dataclass(frozen=True)
+class PrefixCacheHandle:
+ cache_id: str
+ pools: tuple[PrefixStaticCachePool, ...]
+ prefix_len: int
+ prefix_token_hash: str
+ model_fingerprint: str
+ tokenizer_fingerprint: str
+ chat_template_hash: str
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+ @property
+ def dp_replica_id(self) -> int | None:
+ return self.pools[0].replica.replica_id if self.pools else None
+
+ def acquire_slot(self) -> tuple[PrefixStaticCachePool, PrefixStaticCacheSlot]:
+ ordered = sorted(
+ self.pools,
+ key=lambda pool: (
+ 0 if pool.replica.state == "healthy" else 1,
+ -pool.idle_count(),
+ pool.replica.replica_id,
+ ),
+ )
+ last_error: Exception | None = None
+ for pool in ordered:
+ if pool.replica.state == "disabled":
+ logger.debug(
+ "prefix cache skipping disabled replica cache_id=%s replica_id=%s",
+ self.cache_id,
+ pool.replica.replica_id,
+ )
+ continue
+ try:
+ return pool, pool.acquire()
+ except PrefixCacheUnavailable as exc:
+ last_error = exc
+ logger.debug(
+ "prefix cache replica unavailable cache_id=%s replica_id=%s reason=%s",
+ self.cache_id,
+ pool.replica.replica_id,
+ exc,
+ )
+ continue
+ if last_error is not None:
+ raise PrefixCacheUnavailable(str(last_error)) from last_error
+ raise PrefixCacheUnavailable(f"prefix cache handle has no available pools: {self.cache_id}")
+
+
+class PrefixCacheRegistry:
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._handles: dict[str, PrefixCacheHandle] = {}
+
+ def register(self, handle: PrefixCacheHandle) -> None:
+ with self._lock:
+ self._handles[str(handle.cache_id)] = handle
+ logger.debug(
+ "prefix cache handle registered cache_id=%s prefix_len=%s pools=%s metadata=%s",
+ handle.cache_id,
+ handle.prefix_len,
+ len(handle.pools),
+ handle.metadata,
+ )
+
+ def get(self, cache_id: str) -> PrefixCacheHandle | None:
+ with self._lock:
+ handle = self._handles.get(str(cache_id))
+ logger.debug("prefix cache handle lookup cache_id=%s hit=%s", cache_id, handle is not None)
+ return handle
+
+ def __len__(self) -> int:
+ with self._lock:
+ return len(self._handles)
+
+
+__all__ = [
+ "PrefixCacheEntry",
+ "PrefixCacheHandle",
+ "PrefixCacheRegistry",
+ "PrefixCacheReplica",
+ "PrefixStaticCachePool",
+ "PrefixStaticCacheSlot",
+ "RequestCacheState",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/client.py b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/client.py
new file mode 100644
index 0000000000..cb7b4b3a1b
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/client.py
@@ -0,0 +1,675 @@
+from __future__ import annotations
+
+import hashlib
+import logging
+import threading
+import gc
+from dataclasses import dataclass
+from time import perf_counter
+from typing import Any, Sequence
+
+from ..base import (
+ GenerationConfig,
+ LLMClientCapabilities,
+ LLMStreamChunk,
+ MaxNewTokensTooLarge,
+ Message,
+ PrefixCacheRuntimeOOM,
+ PrefixCacheUnavailable,
+ ProgressiveLLMClient,
+ QueryTooLongForPrefixCache,
+ UnsupportedCapability,
+)
+
+from .cache import (
+ PrefixCacheHandle,
+ PrefixCacheRegistry,
+ PrefixCacheReplica,
+ PrefixStaticCachePool,
+ RequestCacheState,
+)
+from .generation import PrefixGenerationDecoder, TransformersForwardDecoder, log_runtime_memory_snapshot
+
+logger = logging.getLogger(__name__)
+_STATIC_CACHE_SUFFIX_CAPACITY_TOKENS = 256
+
+
+@dataclass(frozen=True)
+class DistributedGenerationConfig:
+ tp_size: int = 1
+ dp_size: int = 1
+ device_type: str = "auto"
+ device_ids: tuple[int, ...] = ()
+
+ @property
+ def world_size(self) -> int:
+ return max(1, int(self.tp_size)) * max(1, int(self.dp_size))
+
+
+class TransformersPrefixCachedGenerationClient(ProgressiveLLMClient):
+ name = "transformers_prefix_cached_generation"
+
+ def __init__(
+ self,
+ *,
+ decoders: Sequence[PrefixGenerationDecoder],
+ distributed: DistributedGenerationConfig | None = None,
+ tokenizer_fingerprint: str = "",
+ model_fingerprint: str = "",
+ chat_template_hash: str = "",
+ max_new_tokens: int = 128,
+ ) -> None:
+ if not decoders:
+ raise ValueError("at least one decoder/replica is required")
+ self._decoders = tuple(decoders)
+ self._distributed = distributed or DistributedGenerationConfig(dp_size=len(self._decoders))
+ self._registry = PrefixCacheRegistry()
+ self._replicas = tuple(
+ PrefixCacheReplica(
+ replica_id=index,
+ tp_rank_devices=self._replica_devices(index),
+ )
+ for index in range(len(self._decoders))
+ )
+ self._tokenizer_fingerprint = str(tokenizer_fingerprint or "tokenizer")
+ self._model_fingerprint = str(model_fingerprint or "model")
+ self._chat_template_hash = str(chat_template_hash or "chat_template")
+ self._max_suffix_tokens = _STATIC_CACHE_SUFFIX_CAPACITY_TOKENS
+ self._max_new_tokens = max(1, int(max_new_tokens))
+ logger.debug(
+ "transformers prefix cached client initialized replicas=%s tp_size=%s dp_size=%s world_size=%s "
+ "max_suffix_tokens=%s max_new_tokens=%s slots_per_prefix=1 model_fingerprint=%s tokenizer_fingerprint=%s",
+ len(self._decoders),
+ self._distributed.tp_size,
+ self._distributed.dp_size,
+ self._distributed.world_size,
+ self._max_suffix_tokens,
+ self._max_new_tokens,
+ self._model_fingerprint,
+ self._tokenizer_fingerprint,
+ )
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ *,
+ model_path: str,
+ tokenizer_path: str | None = None,
+ device: str = "auto",
+ dtype: str = "auto",
+ tp_size: int = 1,
+ dp_size: int = 1,
+ device_ids: Sequence[int] = (),
+ attn_implementation: str = "",
+ torch_compile: bool = False,
+ tp_plan: str = "",
+ max_new_tokens: int = 128,
+ ) -> "TransformersPrefixCachedGenerationClient":
+ try:
+ import torch
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+ except ImportError as exc:
+ raise RuntimeError("transformers and torch are required for prefix-cached generation") from exc
+
+ resolved_tokenizer_path = tokenizer_path or model_path
+ logger.debug(
+ "loading transformers prefix cached client model_path=%s tokenizer_path=%s "
+ "device=%s dtype=%s tp_size=%s dp_size=%s "
+ "device_ids=%s attn_implementation=%s torch_compile=%s tp_plan=%s",
+ model_path,
+ resolved_tokenizer_path,
+ device,
+ dtype,
+ tp_size,
+ dp_size,
+ tuple(device_ids),
+ attn_implementation,
+ torch_compile,
+ tp_plan,
+ )
+ tokenizer = AutoTokenizer.from_pretrained(resolved_tokenizer_path, trust_remote_code=True)
+ torch_dtype = None
+ if dtype == "float16":
+ torch_dtype = torch.float16
+ elif dtype == "bfloat16":
+ torch_dtype = torch.bfloat16
+ elif dtype == "float32":
+ torch_dtype = torch.float32
+ distributed = DistributedGenerationConfig(
+ tp_size=max(1, int(tp_size)),
+ dp_size=max(1, int(dp_size)),
+ device_type=str(device or "auto"),
+ device_ids=tuple(int(item) for item in device_ids),
+ )
+ decoders: list[PrefixGenerationDecoder] = []
+ normalized_tp_plan = str(tp_plan or "").strip()
+ if normalized_tp_plan and distributed.dp_size != 1:
+ raise ValueError("Transformers tp_plan generation currently requires dp_size=1")
+ for replica_id in range(distributed.dp_size):
+ device_map = (
+ None if normalized_tp_plan else _device_map_for_replica(distributed=distributed, replica_id=replica_id)
+ )
+ logger.debug(
+ "loading transformers prefix cached replica replica_id=%s device_map=%s "
+ "torch_dtype=%s attn_implementation=%s tp_plan=%s",
+ replica_id,
+ device_map,
+ torch_dtype,
+ attn_implementation,
+ normalized_tp_plan,
+ )
+ log_runtime_memory_snapshot(
+ "before_model_load",
+ devices=_replica_devices_for_logging(distributed=distributed, replica_id=replica_id),
+ context={"replica_id": replica_id, "model_path": model_path, "device_map": device_map},
+ )
+ model_kwargs: dict[str, Any] = {"trust_remote_code": True}
+ if torch_dtype is not None:
+ model_kwargs["torch_dtype"] = torch_dtype
+ if device_map is not None:
+ model_kwargs["device_map"] = device_map
+ if str(attn_implementation or "").strip():
+ model_kwargs["attn_implementation"] = str(attn_implementation).strip()
+ if normalized_tp_plan:
+ model_kwargs["tp_plan"] = normalized_tp_plan
+ model = AutoModelForCausalLM.from_pretrained(model_path, **model_kwargs)
+ model.eval()
+ if bool(torch_compile):
+ logger.debug(
+ "compiling transformers prefix cached replica forward replica_id=%s "
+ "mode=reduce-overhead fullgraph=True",
+ replica_id,
+ )
+ model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
+ log_runtime_memory_snapshot(
+ "after_model_load",
+ model=model,
+ context={
+ "replica_id": replica_id,
+ "model_path": model_path,
+ "device_map": getattr(model, "hf_device_map", None),
+ },
+ )
+ decoders.append(
+ TransformersForwardDecoder(
+ model=model,
+ tokenizer=tokenizer,
+ device=_primary_device_for_replica(distributed=distributed, replica_id=replica_id),
+ )
+ )
+ return cls(
+ decoders=decoders,
+ distributed=distributed,
+ tokenizer_fingerprint=str(resolved_tokenizer_path),
+ model_fingerprint=str(model_path),
+ chat_template_hash=_chat_template_hash(tokenizer),
+ max_new_tokens=max_new_tokens,
+ )
+
+ @property
+ def capabilities(self) -> LLMClientCapabilities:
+ return LLMClientCapabilities(
+ completion=True,
+ streaming=True,
+ candidate_scoring=False,
+ trie_constrained_decoding=False,
+ progressive_prefix_kv_cache=True,
+ thread_safe=False,
+ local_resources=True,
+ )
+
+ def get_prompt_cache_handle(self, cache_id: str) -> PrefixCacheHandle | None:
+ handle = self._registry.get(cache_id)
+ logger.debug("get prompt cache handle cache_id=%s hit=%s", cache_id, handle is not None)
+ return handle
+
+ def prepare_prefix_cache(
+ self,
+ *,
+ cache_id: str,
+ prefix_messages: Sequence[Message],
+ prefix_token_hash: str = "",
+ metadata: dict[str, Any] | None = None,
+ ) -> PrefixCacheHandle:
+ prepare_started = perf_counter()
+ logger.debug(
+ "prepare prefix cache start cache_id=%s prefix_messages=%s prefix_token_hash=%s metadata=%s",
+ cache_id,
+ len(prefix_messages),
+ prefix_token_hash,
+ metadata or {},
+ )
+ existing = self._registry.get(cache_id)
+ if existing is not None:
+ logger.debug(
+ "prepare prefix cache hit existing cache_id=%s prefix_len=%s pools=%s elapsed_ms=%.3f",
+ cache_id,
+ existing.prefix_len,
+ len(existing.pools),
+ (perf_counter() - prepare_started) * 1000.0,
+ )
+ return existing
+ pools: list[PrefixStaticCachePool] = []
+ prefix_len: int | None = None
+ max_cache_len: int | None = None
+ for replica, decoder in zip(self._replicas, self._decoders):
+ logger.debug(
+ "prepare prefix cache building slot cache_id=%s replica_id=%s",
+ cache_id,
+ replica.replica_id,
+ )
+ try:
+ slot = decoder.build_slot(
+ cache_id=cache_id,
+ slot_id=f"{cache_id}:r{replica.replica_id}:s0",
+ prefix_messages=prefix_messages,
+ prefix_len=None,
+ max_cache_len=None,
+ max_suffix_tokens=self._max_suffix_tokens,
+ max_new_tokens=self._max_new_tokens,
+ replica_id=replica.replica_id,
+ tp_rank_devices=replica.tp_rank_devices,
+ )
+ except (MemoryError, RuntimeError) as exc:
+ if not _looks_like_oom(exc):
+ raise
+ logger.debug(
+ "prepare prefix cache OOM cache_id=%s replica_id=%s error=%s",
+ cache_id,
+ replica.replica_id,
+ exc,
+ )
+ self._clear_runtime_cache_safely()
+ raise PrefixCacheRuntimeOOM(f"prefix-cache prepare OOM: {exc}") from exc
+ prefix_len = int(slot.prefix_len if prefix_len is None else prefix_len)
+ max_cache_len = int(slot.max_cache_len if max_cache_len is None else max_cache_len)
+ logger.debug(
+ "prepare prefix cache built slot cache_id=%s slot_id=%s replica_id=%s "
+ "prefix_len=%s max_cache_len=%s",
+ cache_id,
+ slot.slot_id,
+ replica.replica_id,
+ slot.prefix_len,
+ slot.max_cache_len,
+ )
+ slots = [slot]
+ pools.append(PrefixStaticCachePool(cache_id=cache_id, replica=replica, slots=slots))
+ handle = PrefixCacheHandle(
+ cache_id=cache_id,
+ pools=tuple(pools),
+ prefix_len=int(prefix_len or 0),
+ prefix_token_hash=str(prefix_token_hash or ""),
+ model_fingerprint=self._model_fingerprint,
+ tokenizer_fingerprint=self._tokenizer_fingerprint,
+ chat_template_hash=self._chat_template_hash,
+ metadata=dict(metadata or {}),
+ )
+ self._registry.register(handle)
+ logger.debug(
+ "prepare prefix cache complete cache_id=%s prefix_len=%s pools=%s slots_per_pool=%s elapsed_ms=%.3f",
+ cache_id,
+ handle.prefix_len,
+ len(handle.pools),
+ 1,
+ (perf_counter() - prepare_started) * 1000.0,
+ )
+ return handle
+
+ def complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ n: int = 1,
+ request_timeout: float | None = None,
+ ) -> list[str]:
+ del model, messages, n, request_timeout
+ logger.debug("complete using prefix cache max_tokens=%s stop_sequences=%s", max_tokens, stop_sequences)
+ result = self._generate_with_prefix_cache(
+ max_tokens=max_tokens,
+ stop_sequences=stop_sequences,
+ generation_config=generation_config,
+ )
+ return [result.text]
+
+ def stream_complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ request_timeout: float | None = None,
+ early_stop: object | None = None,
+ ):
+ del model, messages, request_timeout, early_stop
+ logger.debug("stream_complete using prefix cache max_tokens=%s stop_sequences=%s", max_tokens, stop_sequences)
+ result = self._generate_with_prefix_cache(
+ max_tokens=max_tokens,
+ stop_sequences=stop_sequences,
+ generation_config=generation_config,
+ )
+ yield LLMStreamChunk(result.text, usage={**result.usage, "latency": dict(result.latency)})
+
+ def _generate_with_prefix_cache(
+ self,
+ *,
+ max_tokens: int | None,
+ stop_sequences: Sequence[str] | None,
+ generation_config: GenerationConfig | None,
+ ):
+ config = generation_config or self.default_generation_config()
+ if config.constraints.trie is not None:
+ raise UnsupportedCapability(
+ "transformers prefix-cached generation currently does not support trie decoding"
+ )
+ started = perf_counter()
+ hint = config.prompt_cache
+ handle = getattr(hint, "handle", None)
+ if handle is None:
+ logger.debug("prefix cache generation rejected: missing handle")
+ raise PrefixCacheUnavailable("missing prefix cache handle for low-latency generation")
+ if not isinstance(handle, PrefixCacheHandle):
+ logger.debug("prefix cache generation rejected: invalid handle type=%s", type(handle).__name__)
+ raise PrefixCacheUnavailable("prompt cache handle is not a PrefixCacheHandle")
+ logger.debug(
+ "prefix cache generation start cache_id=%s expected_prefix_len=%s "
+ "max_tokens=%s has_suffix_token_ids=%s suffix_text_chars=%s",
+ handle.cache_id,
+ getattr(hint, "expected_prefix_len", None),
+ max_tokens,
+ getattr(hint, "suffix_token_ids", None) is not None,
+ len(str(getattr(hint, "suffix_text", "") or "")),
+ )
+ validate_started = perf_counter()
+ self._validate_handle(handle, expected_prefix_len=getattr(hint, "expected_prefix_len", None))
+ handler_validate_ms = (perf_counter() - validate_started) * 1000.0
+ logger.debug(
+ "prefix cache handle validated cache_id=%s prefix_len=%s validate_ms=%.3f",
+ handle.cache_id,
+ handle.prefix_len,
+ handler_validate_ms,
+ )
+ requested_max_new_tokens = max(1, int(max_tokens if max_tokens is not None else self._max_new_tokens))
+ if requested_max_new_tokens > self._max_new_tokens:
+ logger.debug(
+ "prefix cache generation rejected: max_tokens too large cache_id=%s requested=%s budget=%s",
+ handle.cache_id,
+ requested_max_new_tokens,
+ self._max_new_tokens,
+ )
+ raise MaxNewTokensTooLarge(
+ f"requested max_tokens={requested_max_new_tokens} exceeds prefix cache budget {self._max_new_tokens}"
+ )
+ tokenize_started = perf_counter()
+ if hint.suffix_token_ids is not None:
+ suffix_token_ids = tuple(int(item) for item in hint.suffix_token_ids)
+ else:
+ if not handle.pools:
+ logger.debug("prefix cache generation rejected: no pools cache_id=%s", handle.cache_id)
+ raise PrefixCacheUnavailable(f"prefix cache has no pools: {handle.cache_id}")
+ decoder = self._decoders[handle.pools[0].replica.replica_id]
+ suffix_token_ids = decoder.encode_suffix(str(hint.suffix_text or ""))
+ suffix_tokenize_ms = (perf_counter() - tokenize_started) * 1000.0
+ logger.debug(
+ "prefix cache suffix ready cache_id=%s suffix_tokens=%s tokenize_ms=%.3f source=%s",
+ handle.cache_id,
+ len(suffix_token_ids),
+ suffix_tokenize_ms,
+ "pretokenized" if hint.suffix_token_ids is not None else "text",
+ )
+ if len(suffix_token_ids) > self._max_suffix_tokens:
+ logger.debug(
+ "prefix cache generation rejected: query too long cache_id=%s suffix_tokens=%s budget=%s",
+ handle.cache_id,
+ len(suffix_token_ids),
+ self._max_suffix_tokens,
+ )
+ raise QueryTooLongForPrefixCache(
+ f"suffix_tokens={len(suffix_token_ids)} exceeds max_suffix_tokens={self._max_suffix_tokens}"
+ )
+ pool = None
+ slot = None
+ try:
+ acquire_started = perf_counter()
+ pool, slot = handle.acquire_slot()
+ request_cache_prepare_ms = (perf_counter() - acquire_started) * 1000.0
+ logger.debug(
+ "prefix cache request slot ready cache_id=%s slot_id=%s replica_id=%s acquire_ms=%.3f",
+ handle.cache_id,
+ slot.slot_id,
+ pool.replica.replica_id,
+ request_cache_prepare_ms,
+ )
+ request_state = RequestCacheState(
+ handle=handle,
+ pool=pool,
+ slot=slot,
+ suffix_token_ids=tuple(suffix_token_ids),
+ max_new_tokens=requested_max_new_tokens,
+ )
+ decoder = self._decoders[pool.replica.replica_id]
+ result = decoder.generate(
+ slot=request_state.slot,
+ suffix_token_ids=request_state.suffix_token_ids,
+ max_new_tokens=request_state.max_new_tokens,
+ generation_config=config,
+ stop_sequences=stop_sequences,
+ )
+ pool.release(slot)
+ result.usage.setdefault("cache_hit", True)
+ result.usage.setdefault("cached_prefix_tokens", int(slot.prefix_len))
+ result.usage.setdefault("suffix_tokens", len(suffix_token_ids))
+ result.usage.setdefault("cache_id", handle.cache_id)
+ result.usage.setdefault("replica_id", pool.replica.replica_id)
+ total_client_ms = (perf_counter() - started) * 1000.0
+ result.latency.setdefault("handler_validate_ms", round(handler_validate_ms, 3))
+ result.latency.setdefault("cache_handle_access_ms", 0.0)
+ result.latency.setdefault("suffix_tokenize_ms", round(suffix_tokenize_ms, 3))
+ result.latency.setdefault("request_cache_prepare_ms", round(request_cache_prepare_ms, 3))
+ result.latency.setdefault("cache_clone_ms", 0.0)
+ result.latency.setdefault("total_client_ms", round(total_client_ms, 3))
+ model_ms = float(result.latency.get("suffix_prefill_ms", 0.0) or 0.0) + float(
+ result.latency.get("decode_ms", 0.0) or 0.0
+ )
+ result.latency.setdefault(
+ "non_model_overhead_ms",
+ round(max(0.0, total_client_ms - model_ms - suffix_tokenize_ms), 3),
+ )
+ logger.debug(
+ "prefix cache generation complete cache_id=%s slot_id=%s replica_id=%s "
+ "text_chars=%s usage=%s latency=%s",
+ handle.cache_id,
+ slot.slot_id,
+ pool.replica.replica_id,
+ len(result.text),
+ result.usage,
+ result.latency,
+ )
+ return result
+ except (MemoryError, RuntimeError) as exc:
+ if not _looks_like_oom(exc):
+ if pool is not None and slot is not None:
+ pool.release(slot)
+ logger.debug("prefix cache generation runtime error cache_id=%s error=%s", handle.cache_id, exc)
+ raise
+ if pool is not None and slot is not None:
+ pool.mark_poisoned(slot, reason=str(exc))
+ pool.replica.mark_degraded(reason=str(exc))
+ logger.debug(
+ "prefix cache generation OOM marked slot poisoned cache_id=%s slot_id=%s replica_id=%s",
+ handle.cache_id,
+ slot.slot_id,
+ pool.replica.replica_id,
+ )
+ self._clear_runtime_cache_safely()
+ if pool is not None and slot is not None:
+ self._schedule_slot_refresh(pool=pool, slot=slot)
+ logger.debug("prefix cache generation OOM cache_id=%s error=%s", handle.cache_id, exc)
+ raise PrefixCacheRuntimeOOM(f"prefix-cache generation OOM: {exc}") from exc
+ except Exception as exc:
+ if pool is not None and slot is not None:
+ pool.release(slot)
+ logger.debug("prefix cache generation failed cache_id=%s error=%s", handle.cache_id, exc)
+ raise
+
+ def _validate_handle(self, handle: PrefixCacheHandle, *, expected_prefix_len: int | None) -> None:
+ logger.debug(
+ "validating prefix cache handle cache_id=%s handle_prefix_len=%s expected_prefix_len=%s",
+ handle.cache_id,
+ handle.prefix_len,
+ expected_prefix_len,
+ )
+ if handle.model_fingerprint and handle.model_fingerprint != self._model_fingerprint:
+ raise PrefixCacheUnavailable(f"prefix cache model mismatch: {handle.cache_id}")
+ if handle.tokenizer_fingerprint and handle.tokenizer_fingerprint != self._tokenizer_fingerprint:
+ raise PrefixCacheUnavailable(f"prefix cache tokenizer mismatch: {handle.cache_id}")
+ if handle.chat_template_hash and handle.chat_template_hash != self._chat_template_hash:
+ raise PrefixCacheUnavailable(f"prefix cache chat template mismatch: {handle.cache_id}")
+ if expected_prefix_len is not None and int(expected_prefix_len) != int(handle.prefix_len):
+ raise PrefixCacheUnavailable(f"prefix cache prefix_len mismatch: {handle.cache_id}")
+
+ def _schedule_slot_refresh(self, *, pool: PrefixStaticCachePool, slot) -> None:
+ def _run() -> None:
+ try:
+ logger.debug(
+ "prefix cache slot refresh start cache_id=%s slot_id=%s replica_id=%s",
+ slot.cache_id,
+ slot.slot_id,
+ pool.replica.replica_id,
+ )
+ decoder = self._decoders[pool.replica.replica_id]
+ rebuilt = decoder.build_slot(
+ cache_id=slot.cache_id,
+ slot_id=slot.slot_id,
+ prefix_messages=slot.prefix_messages,
+ prefix_len=slot.prefix_len,
+ max_cache_len=slot.max_cache_len,
+ max_suffix_tokens=self._max_suffix_tokens,
+ max_new_tokens=self._max_new_tokens,
+ replica_id=slot.replica_id,
+ tp_rank_devices=slot.tp_rank_devices,
+ )
+ slot.static_cache = rebuilt.static_cache
+ slot.prefix_len = rebuilt.prefix_len
+ slot.max_cache_len = rebuilt.max_cache_len
+ slot.prefix_messages = tuple(rebuilt.prefix_messages)
+ slot.active_len = rebuilt.prefix_len
+ pool.mark_rebuilt(slot)
+ pool.replica.mark_healthy()
+ logger.debug(
+ "prefix cache slot refresh complete cache_id=%s slot_id=%s replica_id=%s",
+ slot.cache_id,
+ slot.slot_id,
+ pool.replica.replica_id,
+ )
+ except Exception as exc:
+ pool.disable_slot(slot, reason=str(exc))
+ logger.debug(
+ "prefix cache slot refresh failed cache_id=%s slot_id=%s replica_id=%s error=%s",
+ slot.cache_id,
+ slot.slot_id,
+ pool.replica.replica_id,
+ exc,
+ )
+
+ logger.debug("prefix cache slot refresh scheduled cache_id=%s slot_id=%s", slot.cache_id, slot.slot_id)
+ threading.Thread(target=_run, name=f"prefix-cache-refresh-{slot.slot_id}", daemon=True).start()
+
+ def _replica_devices(self, replica_id: int) -> tuple[int, ...]:
+ tp_size = max(1, int(self._distributed.tp_size))
+ device_ids = tuple(int(item) for item in self._distributed.device_ids)
+ if not device_ids:
+ start = replica_id * tp_size
+ return tuple(range(start, start + tp_size))
+ start = replica_id * tp_size
+ return tuple(device_ids[start:start + tp_size])
+
+ @staticmethod
+ def _clear_runtime_cache_safely() -> None:
+ try:
+ import torch
+
+ gc.collect()
+ if hasattr(torch, "cuda") and torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ logger.debug("cleared torch cuda runtime cache")
+ except Exception:
+ logger.debug("failed to clear torch cuda runtime cache", exc_info=True)
+ try:
+ import torch_npu
+
+ npu = getattr(torch_npu, "npu", None)
+ empty_cache = getattr(npu, "empty_cache", None)
+ if callable(empty_cache):
+ empty_cache()
+ logger.debug("cleared torch npu runtime cache")
+ except Exception:
+ logger.debug("failed to clear torch npu runtime cache", exc_info=True)
+
+
+def _looks_like_oom(exc: BaseException) -> bool:
+ text = str(exc).lower()
+ return "out of memory" in text or "oom" in text or "memory allocation" in text
+
+
+def _chat_template_hash(tokenizer: Any) -> str:
+ template = getattr(tokenizer, "chat_template", "") or ""
+ return hashlib.sha256(str(template).encode("utf-8")).hexdigest()
+
+
+def _device_map_for_replica(*, distributed: DistributedGenerationConfig, replica_id: int) -> Any:
+ if distributed.device_type == "cpu":
+ return {"": "cpu"}
+ tp_size = max(1, int(distributed.tp_size))
+ device_ids = tuple(int(item) for item in distributed.device_ids)
+ if not device_ids and distributed.device_type in {"auto", "cuda", "npu"}:
+ if tp_size == 1:
+ return "auto"
+ return "auto"
+ start = replica_id * tp_size
+ selected = device_ids[start:start + tp_size]
+ if len(selected) <= 1:
+ return {"": selected[0]} if selected else "auto"
+ return "auto"
+
+
+def _primary_device_for_replica(*, distributed: DistributedGenerationConfig, replica_id: int) -> str | None:
+ if str(distributed.device_type or "").strip().lower() == "cpu":
+ return "cpu"
+ devices = tuple(int(item) for item in distributed.device_ids)
+ if devices:
+ index = replica_id * max(1, int(distributed.tp_size))
+ if index < len(devices):
+ return _format_accelerator_device(distributed.device_type, devices[index])
+ if str(distributed.device_type or "").strip().lower() in {"cuda", "npu"}:
+ return _format_accelerator_device(distributed.device_type, replica_id * max(1, int(distributed.tp_size)))
+ return None
+
+
+def _format_accelerator_device(device_type: str, device_id: int) -> str:
+ normalized = str(device_type or "cuda").strip().lower()
+ if normalized == "npu":
+ return f"npu:{int(device_id)}"
+ return f"cuda:{int(device_id)}"
+
+
+def _replica_devices_for_logging(*, distributed: DistributedGenerationConfig, replica_id: int) -> tuple[str, ...]:
+ devices = _replica_device_ids(distributed=distributed, replica_id=replica_id)
+ return tuple(_format_accelerator_device(distributed.device_type, device_id) for device_id in devices)
+
+
+def _replica_device_ids(*, distributed: DistributedGenerationConfig, replica_id: int) -> tuple[int, ...]:
+ tp_size = max(1, int(distributed.tp_size))
+ explicit = tuple(int(item) for item in distributed.device_ids)
+ start = replica_id * tp_size
+ if explicit:
+ return explicit[start:start + tp_size]
+ return tuple(range(start, start + tp_size))
+
+
+__all__ = ["DistributedGenerationConfig", "TransformersPrefixCachedGenerationClient"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/generation.py b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/generation.py
new file mode 100644
index 0000000000..e92a7052c4
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/generation.py
@@ -0,0 +1,885 @@
+from __future__ import annotations
+
+from inspect import Parameter
+from inspect import signature
+import logging
+import re
+from dataclasses import dataclass, field
+from time import perf_counter
+from typing import Any, Callable, Sequence
+
+from ..base import GenerationConfig
+
+from .cache import PrefixStaticCacheSlot
+
+logger = logging.getLogger(__name__)
+_PREFIX_PREFILL_CHUNK_TOKENS = 512
+
+
+@dataclass(frozen=True)
+class PrefixGenerationResult:
+ text: str
+ usage: dict[str, Any] = field(default_factory=dict)
+ latency: dict[str, float] = field(default_factory=dict)
+
+
+class PrefixGenerationDecoder:
+ def encode_suffix(self, suffix_text: str) -> tuple[int, ...]:
+ raise NotImplementedError
+
+ def build_slot(
+ self,
+ *,
+ cache_id: str,
+ slot_id: str,
+ prefix_messages: Sequence[dict[str, str]],
+ prefix_len: int | None,
+ max_cache_len: int | None,
+ max_suffix_tokens: int,
+ max_new_tokens: int,
+ replica_id: int,
+ tp_rank_devices: tuple[int, ...],
+ ) -> PrefixStaticCacheSlot:
+ raise NotImplementedError
+
+ def generate(
+ self,
+ *,
+ slot: PrefixStaticCacheSlot,
+ suffix_token_ids: Sequence[int],
+ max_new_tokens: int,
+ generation_config: GenerationConfig,
+ stop_sequences: Sequence[str] | None,
+ on_text: Callable[[str], None] | None = None,
+ ) -> PrefixGenerationResult:
+ raise NotImplementedError
+
+
+class TransformersForwardDecoder(PrefixGenerationDecoder):
+ def __init__(self, *, model: Any, tokenizer: Any, device: Any = None) -> None:
+ self.model = model
+ self.tokenizer = tokenizer
+ self.device = device
+
+ def encode_suffix(self, suffix_text: str) -> tuple[int, ...]:
+ encoded = self.tokenizer.encode(str(suffix_text or ""), add_special_tokens=False)
+ token_ids = tuple(int(item) for item in encoded)
+ logger.debug(
+ "prefix generation encoded suffix chars=%s tokens=%s",
+ len(str(suffix_text or "")),
+ len(token_ids),
+ )
+ return token_ids
+
+ def _encode_prefix(self, prefix_messages: Sequence[dict[str, str]]) -> Any:
+ if hasattr(self.tokenizer, "apply_chat_template"):
+ encoded = self.tokenizer.apply_chat_template(
+ list(prefix_messages),
+ add_generation_prompt=False,
+ return_tensors="pt",
+ tokenize=True,
+ )
+ else:
+ text = "\n".join(str(message.get("content") or "") for message in prefix_messages)
+ encoded = self.tokenizer(text, return_tensors="pt")["input_ids"]
+ resolved_device = self._resolve_execution_device(encoded)
+ if resolved_device is not None and hasattr(encoded, "to"):
+ encoded = encoded.to(resolved_device)
+ logger.debug(
+ "prefix generation encoded prefix messages=%s tokens=%s device=%s",
+ len(prefix_messages),
+ getattr(encoded, "shape", ("?", "?"))[-1],
+ resolved_device,
+ )
+ return encoded
+
+ def _resolve_execution_device(self, input_ids: Any | None = None) -> Any | None:
+ device = _infer_model_execution_device(self.model) or self.device
+ if device is None and input_ids is not None:
+ device = getattr(input_ids, "device", None)
+ return device
+
+ def build_slot(
+ self,
+ *,
+ cache_id: str,
+ slot_id: str,
+ prefix_messages: Sequence[dict[str, str]],
+ prefix_len: int | None,
+ max_cache_len: int | None,
+ max_suffix_tokens: int,
+ max_new_tokens: int,
+ replica_id: int,
+ tp_rank_devices: tuple[int, ...],
+ ) -> PrefixStaticCacheSlot:
+ build_started = perf_counter()
+ logger.debug(
+ "prefix cache slot build start cache_id=%s slot_id=%s replica_id=%s "
+ "tp_rank_devices=%s max_suffix_tokens=%s max_new_tokens=%s",
+ cache_id,
+ slot_id,
+ replica_id,
+ tp_rank_devices,
+ max_suffix_tokens,
+ max_new_tokens,
+ )
+ try:
+ from transformers import StaticCache
+ except ImportError as exc:
+ raise RuntimeError("transformers is required for StaticCache prefix generation") from exc
+ input_ids = self._encode_prefix(prefix_messages)
+ execution_device = self._resolve_execution_device(input_ids)
+ resolved_prefix_len = int(prefix_len if prefix_len is not None else input_ids.shape[-1])
+ resolved_max_cache_len = int(max_cache_len or 0)
+ if resolved_max_cache_len <= 0:
+ resolved_max_cache_len = resolved_prefix_len + max(0, int(max_suffix_tokens)) + max(1, int(max_new_tokens))
+ _log_memory_snapshot(
+ "before_static_cache_alloc",
+ model=self.model,
+ cache_id=cache_id,
+ slot_id=slot_id,
+ prefix_len=resolved_prefix_len,
+ max_cache_len=resolved_max_cache_len,
+ execution_device=execution_device,
+ )
+ static_cache = _build_static_cache(
+ StaticCache,
+ model=self.model,
+ input_ids=input_ids,
+ max_cache_len=resolved_max_cache_len,
+ device=execution_device,
+ )
+ logger.debug(
+ "prefix cache static cache allocated cache_id=%s slot_id=%s prefix_len=%s max_cache_len=%s device=%s",
+ cache_id,
+ slot_id,
+ resolved_prefix_len,
+ resolved_max_cache_len,
+ execution_device,
+ )
+ _log_memory_snapshot(
+ "after_static_cache_alloc",
+ model=self.model,
+ cache_id=cache_id,
+ slot_id=slot_id,
+ prefix_len=resolved_prefix_len,
+ max_cache_len=resolved_max_cache_len,
+ execution_device=execution_device,
+ )
+ prefill_started = perf_counter()
+ try:
+ import torch
+
+ with torch.inference_mode():
+ outputs = _prefill_static_cache_in_chunks(
+ model=self.model,
+ input_ids=input_ids,
+ static_cache=static_cache,
+ chunk_size=_prefix_prefill_chunk_size(),
+ )
+ except ImportError:
+ outputs = _forward_keep_last_logits(
+ self.model,
+ input_ids=input_ids,
+ past_key_values=static_cache,
+ use_cache=True,
+ )
+ static_cache = getattr(outputs, "past_key_values", static_cache)
+ _log_memory_snapshot(
+ "after_prefix_prefill",
+ model=self.model,
+ cache_id=cache_id,
+ slot_id=slot_id,
+ prefix_len=resolved_prefix_len,
+ max_cache_len=resolved_max_cache_len,
+ execution_device=execution_device,
+ )
+ logger.debug(
+ "prefix cache slot build complete cache_id=%s slot_id=%s prefix_prefill_ms=%.3f total_ms=%.3f",
+ cache_id,
+ slot_id,
+ (perf_counter() - prefill_started) * 1000.0,
+ (perf_counter() - build_started) * 1000.0,
+ )
+ return PrefixStaticCacheSlot(
+ slot_id=slot_id,
+ cache_id=cache_id,
+ static_cache=static_cache,
+ replica_id=replica_id,
+ tp_rank_devices=tp_rank_devices,
+ prefix_len=resolved_prefix_len,
+ max_cache_len=resolved_max_cache_len,
+ prefix_messages=tuple(dict(message) for message in prefix_messages),
+ active_len=resolved_prefix_len,
+ )
+
+ def generate(
+ self,
+ *,
+ slot: PrefixStaticCacheSlot,
+ suffix_token_ids: Sequence[int],
+ max_new_tokens: int,
+ generation_config: GenerationConfig,
+ stop_sequences: Sequence[str] | None,
+ on_text: Callable[[str], None] | None = None,
+ ) -> PrefixGenerationResult:
+ try:
+ import torch
+ except ImportError as exc:
+ raise RuntimeError("torch is required for transformers prefix generation") from exc
+ started = perf_counter()
+ logger.debug(
+ "prefix generation start cache_id=%s slot_id=%s replica_id=%s "
+ "suffix_tokens=%s max_new_tokens=%s prefix_len=%s",
+ slot.cache_id,
+ slot.slot_id,
+ slot.replica_id,
+ len(suffix_token_ids),
+ max_new_tokens,
+ slot.prefix_len,
+ )
+ _log_memory_snapshot(
+ "before_generation",
+ model=self.model,
+ cache_id=slot.cache_id,
+ slot_id=slot.slot_id,
+ prefix_len=slot.prefix_len,
+ max_cache_len=slot.max_cache_len,
+ execution_device=self._resolve_execution_device(),
+ )
+ device = self._resolve_execution_device()
+ input_prepare_started = perf_counter()
+ suffix_tokens = list(int(item) for item in suffix_token_ids)
+ input_ids = torch.tensor([suffix_tokens], dtype=torch.long)
+ if device is not None:
+ input_ids = input_ids.to(device)
+ cache_position = torch.arange(slot.prefix_len, slot.prefix_len + len(suffix_token_ids), device=input_ids.device)
+ attention_mask = torch.ones(
+ (1, slot.prefix_len + len(suffix_token_ids)),
+ dtype=torch.long,
+ device=input_ids.device,
+ )
+ input_prepare_ms = (perf_counter() - input_prepare_started) * 1000.0
+ logger.debug(
+ "prefix generation suffix tensors ready cache_id=%s slot_id=%s suffix_tokens=%s input_device=%s "
+ "attention_mask_shape=%s cache_position_shape=%s input_prepare_ms=%.3f sync_timing=%s",
+ slot.cache_id,
+ slot.slot_id,
+ len(suffix_token_ids),
+ input_ids.device,
+ tuple(attention_mask.shape),
+ tuple(cache_position.shape),
+ input_prepare_ms,
+ _sync_timing_enabled(),
+ )
+ suffix_prefill_started = perf_counter()
+ _sync_device_for_timing(input_ids.device)
+ with torch.inference_mode():
+ suffix_outputs = _forward_keep_last_logits(
+ self.model,
+ input_ids=input_ids,
+ past_key_values=slot.static_cache,
+ attention_mask=attention_mask,
+ cache_position=cache_position,
+ use_cache=True,
+ )
+ _sync_device_for_timing(input_ids.device)
+ suffix_prefill_ms = (perf_counter() - suffix_prefill_started) * 1000.0
+ slot.static_cache = getattr(suffix_outputs, "past_key_values", slot.static_cache)
+ first_token_started = perf_counter()
+ first_token_id = _select_next_token_from_logits(
+ getattr(suffix_outputs, "logits", None),
+ generation_config=generation_config,
+ device=input_ids.device,
+ )
+ first_token_select_ms = (perf_counter() - first_token_started) * 1000.0
+ suffix_active_len = slot.prefix_len + len(suffix_token_ids)
+ logger.debug(
+ "prefix generation suffix prefill complete cache_id=%s slot_id=%s suffix_tokens=%s "
+ "suffix_prefill_ms=%.3f first_token_id=%s first_token_select_ms=%.3f",
+ slot.cache_id,
+ slot.slot_id,
+ len(suffix_token_ids),
+ suffix_prefill_ms,
+ first_token_id,
+ first_token_select_ms,
+ )
+ first_token_input_ids = torch.tensor([[int(first_token_id)]], dtype=torch.long, device=input_ids.device)
+ continuation_attention_mask = torch.ones(
+ (1, suffix_active_len + 1),
+ dtype=torch.long,
+ device=input_ids.device,
+ )
+ continuation_cache_position = torch.tensor([suffix_active_len], dtype=torch.long, device=input_ids.device)
+ continuation_max_new_tokens = max(0, int(max_new_tokens) - 1)
+ generate_kwargs: dict[str, Any] = {
+ "input_ids": first_token_input_ids,
+ "past_key_values": slot.static_cache,
+ "attention_mask": continuation_attention_mask,
+ "cache_position": continuation_cache_position,
+ "max_new_tokens": max(1, continuation_max_new_tokens),
+ "use_cache": True,
+ "return_dict_in_generate": False,
+ }
+ logger.debug(
+ "prefix generation official generate kwargs ready cache_id=%s slot_id=%s "
+ "passes_cache_position=%s cache_position_shape=%s prompt_tokens=%s "
+ "continuation_max_new_tokens=%s reason=%s",
+ slot.cache_id,
+ slot.slot_id,
+ True,
+ tuple(continuation_cache_position.shape),
+ 1,
+ continuation_max_new_tokens,
+ "suffix is prefilled explicitly; generate continues from the first selected token",
+ )
+ if float(generation_config.temperature) > 0.0:
+ generate_kwargs["do_sample"] = True
+ generate_kwargs["temperature"] = max(1e-6, float(generation_config.temperature))
+ generate_kwargs["top_p"] = float(generation_config.top_p)
+ if generation_config.seed is not None:
+ generator = torch.Generator(device=input_ids.device)
+ generator.manual_seed(int(generation_config.seed))
+ generate_kwargs["generator"] = generator
+ else:
+ generate_kwargs["do_sample"] = False
+ pad_token_id = getattr(self.tokenizer, "pad_token_id", None)
+ eos_token_id = getattr(self.tokenizer, "eos_token_id", None)
+ if pad_token_id is None and eos_token_id is not None:
+ generate_kwargs["pad_token_id"] = eos_token_id
+ if eos_token_id is not None:
+ generate_kwargs["eos_token_id"] = eos_token_id
+ if generation_config.constraints.trie is not None:
+ raise ValueError("transformers prefix cached generation does not support trie decoding")
+ generate_started = perf_counter()
+ if continuation_max_new_tokens > 0:
+ _sync_device_for_timing(input_ids.device)
+ with torch.inference_mode():
+ output_ids = self.model.generate(**generate_kwargs)
+ _sync_device_for_timing(input_ids.device)
+ continuation_ids = _slice_generated_ids(output_ids, suffix_len=1)
+ else:
+ output_ids = first_token_input_ids
+ continuation_ids = ()
+ official_generate_ms = (perf_counter() - generate_started) * 1000.0
+ _log_memory_snapshot(
+ "after_official_generate",
+ model=self.model,
+ cache_id=slot.cache_id,
+ slot_id=slot.slot_id,
+ prefix_len=slot.prefix_len,
+ max_cache_len=slot.max_cache_len,
+ execution_device=device,
+ )
+ logger.debug(
+ "prefix generation official generate complete cache_id=%s slot_id=%s "
+ "suffix_tokens=%s official_generate_ms=%.3f",
+ slot.cache_id,
+ slot.slot_id,
+ len(suffix_token_ids),
+ official_generate_ms,
+ )
+ generated_ids = _concat_generated_token_ids(first_token_id, continuation_ids)
+ generated_count = _token_count(generated_ids)
+ slot.active_len = slot.prefix_len + len(suffix_token_ids) + generated_count
+ text_decode_started = perf_counter()
+ text = self.tokenizer.decode(_to_token_id_list(generated_ids), skip_special_tokens=True)
+ text_decode_ms = (perf_counter() - text_decode_started) * 1000.0
+ if text and on_text is not None:
+ on_text(str(text))
+ stop_sequence_started = perf_counter()
+ for stop in stop_sequences or ():
+ if stop and stop in text:
+ text = text.split(stop, 1)[0]
+ stop_sequence_ms = (perf_counter() - stop_sequence_started) * 1000.0
+ elapsed_ms = (perf_counter() - started) * 1000.0
+ decode_ms = official_generate_ms
+ logger.debug(
+ "prefix generation official timing summary cache_id=%s slot_id=%s completion_tokens=%s "
+ "official_generate_ms=%.3f text_decode_ms=%.3f stop_sequence_ms=%.3f sync_timing=%s",
+ slot.cache_id,
+ slot.slot_id,
+ generated_count,
+ official_generate_ms,
+ text_decode_ms,
+ stop_sequence_ms,
+ _sync_timing_enabled(),
+ )
+ logger.debug(
+ "prefix generation complete cache_id=%s slot_id=%s completion_tokens=%s "
+ "total_ms=%.3f decode_ms=%.3f active_len=%s",
+ slot.cache_id,
+ slot.slot_id,
+ generated_count,
+ elapsed_ms,
+ decode_ms,
+ slot.active_len,
+ )
+ _log_memory_snapshot(
+ "after_generation",
+ model=self.model,
+ cache_id=slot.cache_id,
+ slot_id=slot.slot_id,
+ prefix_len=slot.prefix_len,
+ max_cache_len=slot.max_cache_len,
+ execution_device=device,
+ )
+ return PrefixGenerationResult(
+ text=text,
+ usage={
+ "cached_prefix_tokens": int(slot.prefix_len),
+ "suffix_tokens": len(tuple(suffix_token_ids)),
+ "completion_tokens": generated_count,
+ "generation_path": "transformers.generate",
+ },
+ latency={
+ "total_ms": round(elapsed_ms, 3),
+ "input_prepare_ms": round(input_prepare_ms, 3),
+ "suffix_prefill_ms": round(suffix_prefill_ms, 3),
+ "first_decode_ms": round(official_generate_ms, 3) if generated_count else 0.0,
+ "decode_ms": round(decode_ms, 3),
+ "official_generate_ms": round(official_generate_ms, 3),
+ "decode_trie_ms": 0.0,
+ "decode_sample_ms": round(first_token_select_ms, 3),
+ "decode_token_decode_ms": 0.0,
+ "decode_callback_ms": 0.0,
+ "decode_stop_check_ms": 0.0,
+ "decode_tensor_prepare_ms": 0.0,
+ "decode_model_forward_ms": round(official_generate_ms + suffix_prefill_ms, 3),
+ "decode_cache_update_ms": 0.0,
+ "decode_text_decode_ms": round(text_decode_ms, 3),
+ "decode_stop_sequence_ms": round(stop_sequence_ms, 3),
+ "decode_loop_overhead_ms": 0.0,
+ "sampler_prepare_ms": 0.0,
+ },
+ )
+
+
+def _slice_generated_ids(output_ids: Any, *, suffix_len: int) -> Any:
+ sequences = getattr(output_ids, "sequences", output_ids)
+ try:
+ return sequences[(0, slice(int(suffix_len), None))]
+ except Exception:
+ row = sequences[0] if sequences and isinstance(sequences, (list, tuple)) else sequences
+ return row[slice(int(suffix_len), None)]
+
+
+def _token_count(token_ids: Any) -> int:
+ shape = getattr(token_ids, "shape", None)
+ if shape is not None:
+ try:
+ return int(shape[-1])
+ except Exception:
+ return len(_to_token_id_list(token_ids))
+ try:
+ return len(token_ids)
+ except Exception:
+ return len(_to_token_id_list(token_ids))
+
+
+def _to_token_id_list(token_ids: Any) -> list[int]:
+ if hasattr(token_ids, "detach"):
+ token_ids = token_ids.detach()
+ if hasattr(token_ids, "cpu"):
+ token_ids = token_ids.cpu()
+ if hasattr(token_ids, "tolist"):
+ values = token_ids.tolist()
+ else:
+ values = list(token_ids)
+ if values and isinstance(values[0], list):
+ values = values[0]
+ return [int(item) for item in values]
+
+
+def _concat_generated_token_ids(first_token_id: int, continuation_ids: Any) -> list[int]:
+ return [int(first_token_id), *_to_token_id_list(continuation_ids)]
+
+
+def _select_next_token_from_logits(
+ logits: Any,
+ *,
+ generation_config: GenerationConfig,
+ device: Any,
+) -> int:
+ if logits is None:
+ raise RuntimeError("transformers prefix generation did not return logits for suffix prefill")
+ selected_token_id = getattr(logits, "selected_token_id", None)
+ if selected_token_id is not None:
+ return int(selected_token_id)
+ try:
+ import torch
+ except ImportError as exc:
+ raise RuntimeError("torch is required for transformers prefix generation sampling") from exc
+ next_token_logits = logits[(slice(None), -1, slice(None))]
+ temperature = float(generation_config.temperature)
+ if temperature <= 0.0:
+ return int(torch.argmax(next_token_logits, dim=-1).item())
+ scores = next_token_logits / max(1e-6, temperature)
+ top_p = float(generation_config.top_p)
+ if 0.0 < top_p < 1.0:
+ sorted_scores, sorted_indices = torch.sort(scores, descending=True, dim=-1)
+ cumulative_probs = torch.cumsum(torch.softmax(sorted_scores, dim=-1), dim=-1)
+ sorted_indices_to_remove = cumulative_probs > top_p
+ sorted_indices_to_remove[(Ellipsis, slice(1, None))] = sorted_indices_to_remove[
+ (Ellipsis, slice(None, -1))
+ ].clone()
+ sorted_indices_to_remove[..., 0] = False
+ sorted_scores = sorted_scores.masked_fill(sorted_indices_to_remove, float("-inf"))
+ probs = torch.softmax(sorted_scores, dim=-1)
+ generator = None
+ if generation_config.seed is not None:
+ generator = torch.Generator(device=device)
+ generator.manual_seed(int(generation_config.seed))
+ sampled_sorted = torch.multinomial(probs, num_samples=1, generator=generator)
+ return int(sorted_indices.gather(-1, sampled_sorted).item())
+ probs = torch.softmax(scores, dim=-1)
+ generator = None
+ if generation_config.seed is not None:
+ generator = torch.Generator(device=device)
+ generator.manual_seed(int(generation_config.seed))
+ return int(torch.multinomial(probs, num_samples=1, generator=generator).item())
+
+
+def _forward_keep_last_logits(model: Any, **kwargs: Any) -> Any:
+ try:
+ parameters = signature(model.forward).parameters
+ except (AttributeError, TypeError, ValueError):
+ parameters = {}
+ accepts_kwargs = any(parameter.kind == Parameter.VAR_KEYWORD for parameter in parameters.values())
+ if "logits_to_keep" in parameters or accepts_kwargs:
+ kwargs.setdefault("logits_to_keep", 1)
+ elif "num_logits_to_keep" in parameters:
+ kwargs.setdefault("num_logits_to_keep", 1)
+ return model(**kwargs)
+
+
+def _prefill_static_cache_in_chunks(*, model: Any, input_ids: Any, static_cache: Any, chunk_size: int) -> Any:
+ try:
+ import torch
+ except ImportError:
+ return _forward_keep_last_logits(model, input_ids=input_ids, past_key_values=static_cache, use_cache=True)
+ seq_len = int(input_ids.shape[-1])
+ resolved_chunk_size = max(1, int(chunk_size))
+ outputs = None
+ for start in range(0, seq_len, resolved_chunk_size):
+ end = min(seq_len, start + resolved_chunk_size)
+ chunk_input_ids = input_ids[:, start:end]
+ cache_position = torch.arange(start, end, device=chunk_input_ids.device)
+ attention_mask = torch.ones((1, end), dtype=torch.long, device=chunk_input_ids.device)
+ logger.debug(
+ "prefix cache prefill chunk start=%s end=%s seq_len=%s chunk_tokens=%s",
+ start,
+ end,
+ seq_len,
+ end - start,
+ )
+ outputs = _forward_keep_last_logits(
+ model,
+ input_ids=chunk_input_ids,
+ past_key_values=static_cache,
+ attention_mask=attention_mask,
+ cache_position=cache_position,
+ use_cache=True,
+ )
+ static_cache = getattr(outputs, "past_key_values", static_cache)
+ return outputs
+
+
+def _prefix_prefill_chunk_size() -> int:
+ return _PREFIX_PREFILL_CHUNK_TOKENS
+
+
+def _sync_timing_enabled() -> bool:
+ return False
+
+
+def _sync_device_for_timing(device: Any) -> None:
+ if not _sync_timing_enabled():
+ return
+ device_text = str(device or "")
+ try:
+ import torch
+
+ if device_text.startswith("cuda") and hasattr(torch, "cuda") and torch.cuda.is_available():
+ torch.cuda.synchronize(device)
+ return
+ except Exception:
+ logger.debug("failed to synchronize cuda device for timing device=%s", device, exc_info=True)
+ try:
+ import torch_npu
+
+ npu = getattr(torch_npu, "npu", None)
+ synchronize = getattr(npu, "synchronize", None)
+ if device_text.startswith("npu") and callable(synchronize):
+ synchronize(device)
+ except Exception:
+ logger.debug("failed to synchronize npu device for timing device=%s", device, exc_info=True)
+
+
+def _build_static_cache(
+ static_cache_cls: Any,
+ *,
+ model: Any,
+ input_ids: Any,
+ max_cache_len: int,
+ device: Any | None = None,
+) -> Any:
+ kwargs: dict[str, Any] = {
+ "config": model.config,
+ "max_cache_len": int(max_cache_len),
+ }
+ try:
+ parameters = signature(static_cache_cls).parameters
+ except (TypeError, ValueError):
+ parameters = {}
+ batch_size = int(getattr(input_ids, "shape", (1,))[0] or 1)
+ if "max_batch_size" in parameters:
+ kwargs["max_batch_size"] = batch_size
+ elif "batch_size" in parameters:
+ kwargs["batch_size"] = batch_size
+ layer_device_map = _infer_static_cache_layer_device_map(model)
+ if "layer_device_map" in parameters and layer_device_map:
+ kwargs["layer_device_map"] = layer_device_map
+ resolved_device = _infer_model_execution_device(model) or device or getattr(input_ids, "device", None)
+ if "device" in parameters and resolved_device is not None and "layer_device_map" not in kwargs:
+ kwargs["device"] = resolved_device
+ dtype = _infer_model_cache_dtype(model)
+ if "dtype" in parameters and dtype is not None:
+ kwargs["dtype"] = dtype
+ estimated_bytes = _estimate_static_cache_bytes(model=model, max_cache_len=max_cache_len, dtype=dtype)
+ logger.debug(
+ "prefix cache StaticCache init kwargs max_cache_len=%s batch_size=%s device=%s dtype=%s layer_device_map=%s "
+ "estimated_bytes=%s estimated_gib=%.3f",
+ max_cache_len,
+ batch_size,
+ resolved_device,
+ dtype,
+ layer_device_map,
+ estimated_bytes,
+ estimated_bytes / (1024**3) if estimated_bytes else 0.0,
+ )
+ try:
+ return static_cache_cls(**kwargs)
+ except TypeError as exc:
+ if "max_batch_size" not in str(exc) and "batch_size" not in str(exc):
+ raise
+ kwargs.pop("max_batch_size", None)
+ kwargs.pop("batch_size", None)
+ logger.debug("retrying StaticCache init without batch size after TypeError: %s", exc)
+ return static_cache_cls(**kwargs)
+
+
+def _infer_model_execution_device(model: Any) -> Any | None:
+ layer_device_map = _infer_static_cache_layer_device_map(model)
+ if layer_device_map:
+ return layer_device_map[min(layer_device_map)]
+ hf_device_map = getattr(model, "hf_device_map", None)
+ if isinstance(hf_device_map, dict):
+ for value in hf_device_map.values():
+ device = _normalize_runtime_device(value)
+ if device is not None:
+ return device
+ device = _normalize_runtime_device(getattr(model, "device", None))
+ if device is not None:
+ return device
+ try:
+ parameter = next(model.parameters())
+ except Exception:
+ return None
+ return _normalize_runtime_device(getattr(parameter, "device", None))
+
+
+def _infer_model_cache_dtype(model: Any) -> Any | None:
+ for attr in ("dtype", "torch_dtype"):
+ dtype = getattr(model, attr, None)
+ if dtype is not None and "float32" not in str(dtype).lower():
+ return dtype
+ try:
+ for parameter in model.parameters():
+ dtype = getattr(parameter, "dtype", None)
+ if dtype is not None:
+ return dtype
+ except Exception:
+ return getattr(model, "dtype", None)
+ return getattr(model, "dtype", None)
+
+
+def _infer_static_cache_layer_device_map(model: Any) -> dict[int, Any]:
+ hf_device_map = getattr(model, "hf_device_map", None)
+ if not isinstance(hf_device_map, dict):
+ return {}
+ layer_devices: dict[int, Any] = {}
+ for name, value in hf_device_map.items():
+ match = re.search(r"(?:^|\.)(?:layers|h|blocks)\.(\d+)(?:\.|$)", str(name))
+ if match is None:
+ continue
+ device = _normalize_runtime_device(value)
+ if device is None:
+ continue
+ layer_devices.setdefault(int(match.group(1)), device)
+ return dict(sorted(layer_devices.items()))
+
+
+def _normalize_runtime_device(value: Any) -> Any | None:
+ if value is None:
+ return None
+ text = str(value)
+ lowered = text.lower()
+ if lowered in {"cpu", "disk", "meta"}:
+ return None
+ if lowered.startswith("cuda") or lowered.startswith("npu"):
+ return value
+ if lowered.isdigit():
+ return f"cuda:{lowered}"
+ return value
+
+
+def _estimate_static_cache_bytes(*, model: Any, max_cache_len: int, dtype: Any | None) -> int:
+ config = getattr(model, "config", None)
+ if config is None:
+ return 0
+ layers = int(getattr(config, "num_hidden_layers", 0) or getattr(config, "n_layer", 0) or 0)
+ hidden_size = int(getattr(config, "hidden_size", 0) or getattr(config, "n_embd", 0) or 0)
+ heads = int(getattr(config, "num_attention_heads", 0) or getattr(config, "n_head", 0) or 0)
+ kv_heads = int(getattr(config, "num_key_value_heads", 0) or heads or 0)
+ head_dim = int(getattr(config, "head_dim", 0) or (hidden_size // heads if heads else 0))
+ bytes_per_value = _dtype_nbytes(dtype)
+ cache_shape_complete = bool(layers and kv_heads and head_dim)
+ if not cache_shape_complete or not bytes_per_value:
+ return 0
+ return int(layers * 2 * int(max_cache_len) * kv_heads * head_dim * bytes_per_value)
+
+
+def _dtype_nbytes(dtype: Any | None) -> int:
+ text = str(dtype or "").lower()
+ if "float64" in text or "double" in text:
+ return 8
+ if "float32" in text or text.endswith("float"):
+ return 4
+ if "float16" in text or "bfloat16" in text or "half" in text:
+ return 2
+ if "int8" in text:
+ return 1
+ return 0
+
+
+def _log_memory_snapshot(phase: str, *, model: Any, **context: Any) -> None:
+ if not logger.isEnabledFor(logging.DEBUG):
+ return
+ devices = _memory_snapshot_devices(model=model, extra_device=context.get("execution_device"))
+ snapshots = []
+ for device in devices:
+ snapshot = _device_memory_snapshot(device)
+ if snapshot:
+ snapshots.append(snapshot)
+ logger.debug("prefix cache memory phase=%s context=%s snapshots=%s", phase, context, snapshots)
+
+
+def log_runtime_memory_snapshot(
+ phase: str,
+ *,
+ model: Any | None = None,
+ devices: Sequence[Any] = (),
+ context: dict[str, Any] | None = None,
+) -> None:
+ if not logger.isEnabledFor(logging.DEBUG):
+ return
+ resolved_devices = list(devices)
+ if model is not None:
+ resolved_devices.extend(_memory_snapshot_devices(model=model))
+ snapshots = []
+ seen: set[str] = set()
+ for device in resolved_devices:
+ normalized = _normalize_runtime_device(device)
+ if normalized is None:
+ continue
+ key = str(normalized)
+ if key in seen:
+ continue
+ seen.add(key)
+ snapshot = _device_memory_snapshot(normalized)
+ if snapshot:
+ snapshots.append(snapshot)
+ logger.debug("prefix cache runtime memory phase=%s context=%s snapshots=%s", phase, context or {}, snapshots)
+
+
+def _memory_snapshot_devices(*, model: Any, extra_device: Any | None = None) -> tuple[Any, ...]:
+ devices: list[Any] = []
+ if extra_device is not None:
+ devices.append(extra_device)
+ layer_device_map = _infer_static_cache_layer_device_map(model)
+ devices.extend(layer_device_map.values())
+ inferred = _infer_model_execution_device(model)
+ if inferred is not None:
+ devices.append(inferred)
+ deduped: list[Any] = []
+ seen: set[str] = set()
+ for device in devices:
+ normalized = _normalize_runtime_device(device)
+ if normalized is None:
+ continue
+ key = str(normalized)
+ if key in seen:
+ continue
+ seen.add(key)
+ deduped.append(normalized)
+ return tuple(deduped)
+
+
+def _device_memory_snapshot(device: Any) -> dict[str, Any]:
+ text = str(device)
+ if text.startswith("cuda"):
+ return _cuda_memory_snapshot(text)
+ if text.startswith("npu"):
+ return _npu_memory_snapshot(text)
+ return {}
+
+
+def _cuda_memory_snapshot(device: str) -> dict[str, Any]:
+ try:
+ import torch
+
+ if not torch.cuda.is_available():
+ return {}
+ index = int(str(device).split(":", 1)[1]) if ":" in str(device) else torch.cuda.current_device()
+ free_bytes, total_bytes = torch.cuda.mem_get_info(index)
+ return {
+ "device": f"cuda:{index}",
+ "allocated_gib": round(torch.cuda.memory_allocated(index) / (1024**3), 3),
+ "reserved_gib": round(torch.cuda.memory_reserved(index) / (1024**3), 3),
+ "free_gib": round(free_bytes / (1024**3), 3),
+ "total_gib": round(total_bytes / (1024**3), 3),
+ }
+ except Exception as exc:
+ return {"device": device, "error": str(exc)}
+
+
+def _npu_memory_snapshot(device: str) -> dict[str, Any]:
+ try:
+ import torch_npu
+
+ npu = getattr(torch_npu, "npu", None)
+ memory_allocated = getattr(npu, "memory_allocated", None)
+ memory_reserved = getattr(npu, "memory_reserved", None)
+ mem_get_info = getattr(npu, "mem_get_info", None)
+ index = int(str(device).split(":", 1)[1]) if ":" in str(device) else 0
+ snapshot: dict[str, Any] = {"device": f"npu:{index}"}
+ if callable(memory_allocated):
+ snapshot["allocated_gib"] = round(memory_allocated(index) / (1024**3), 3)
+ if callable(memory_reserved):
+ snapshot["reserved_gib"] = round(memory_reserved(index) / (1024**3), 3)
+ if callable(mem_get_info):
+ free_bytes, total_bytes = mem_get_info(index)
+ snapshot["free_gib"] = round(free_bytes / (1024**3), 3)
+ snapshot["total_gib"] = round(total_bytes / (1024**3), 3)
+ return snapshot
+ except Exception as exc:
+ return {"device": device, "error": str(exc)}
+
+
+__all__ = [
+ "PrefixGenerationDecoder",
+ "PrefixGenerationResult",
+ "TransformersForwardDecoder",
+ "log_runtime_memory_snapshot",
+]
diff --git a/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/warmup.py b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/warmup.py
new file mode 100644
index 0000000000..6f9b5c8943
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/transformers_prefix_cached_generation/warmup.py
@@ -0,0 +1,148 @@
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any
+
+from models.retrieval import RetrieverNode
+from ..base import PrefixCacheRuntimeOOM
+from ...tree.render.disclosure import (
+ DisclosureConfig,
+ build_disclosure_prompt_parts,
+ build_exposed_fragment,
+)
+from ...tree.types import ProgressiveRetrieverConfig
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class PrefixCacheWarmupResult:
+ attempted: int = 0
+ prepared: int = 0
+ skipped: int = 0
+
+
+def warmup_progressive_prefix_cache(
+ *,
+ client: Any,
+ root: RetrieverNode,
+ config: ProgressiveRetrieverConfig,
+) -> PrefixCacheWarmupResult:
+ if not getattr(getattr(client, "capabilities", None), "progressive_prefix_kv_cache", False):
+ logger.debug("prefix cache warmup skipped: client capability disabled")
+ return PrefixCacheWarmupResult(skipped=1)
+ prepare = getattr(client, "prepare_prefix_cache", None)
+ if not callable(prepare):
+ logger.debug("prefix cache warmup skipped: client has no prepare_prefix_cache")
+ return PrefixCacheWarmupResult(skipped=1)
+ disclosure_config = DisclosureConfig(
+ max_exposure_depth_per_call=max(0, int(config.max_exposure_depth_per_call)),
+ exposure_threshold=max(0, int(config.exposure_threshold)),
+ compact_boundary_codes_enabled=bool(config.compact_boundary_codes_enabled),
+ compact_boundary_codebook=tuple(str(code) for code in config.compact_boundary_codebook),
+ flatten_full_tree_in_prompt=bool(config.flatten_full_tree_in_prompt),
+ )
+ default_top_k = max(1, int(config.top_k))
+ attempted = 0
+ prepared = 0
+ skipped = 0
+ seen: set[str] = set()
+ logger.debug(
+ "prefix cache warmup start root=%s default_top_k=%s",
+ root.node_id,
+ default_top_k,
+ )
+
+ for node, branch_path in _iter_nodes(root, (root.node_id,)):
+ fragment = build_exposed_fragment(
+ root=node,
+ branch_path=branch_path,
+ config=disclosure_config,
+ subtree_item_count=_count_items,
+ )
+ if len(fragment.code_to_resolution) <= 1:
+ skipped += 1
+ logger.debug(
+ "prefix cache warmup skipped node=%s branch_path=%s reason=insufficient_candidates candidates=%s",
+ node.node_id,
+ branch_path,
+ len(fragment.code_to_resolution),
+ )
+ continue
+ parts = build_disclosure_prompt_parts(fragment=fragment, query_messages=(), top_k=default_top_k)
+ if parts.cache_id in seen:
+ skipped += 1
+ logger.debug(
+ "prefix cache warmup skipped duplicate cache_id=%s node=%s top_k=%s",
+ parts.cache_id,
+ node.node_id,
+ default_top_k,
+ )
+ continue
+ seen.add(parts.cache_id)
+ attempted += 1
+ logger.debug(
+ "prefix cache warmup preparing cache_id=%s node=%s branch_path=%s default_top_k=%s candidates=%s",
+ parts.cache_id,
+ node.node_id,
+ branch_path,
+ default_top_k,
+ len(fragment.code_to_resolution),
+ )
+ try:
+ prepare(
+ cache_id=parts.cache_id,
+ prefix_messages=parts.prefix_messages,
+ prefix_token_hash=parts.prefix_token_hash,
+ metadata={
+ "node_id": node.node_id,
+ "branch_path": tuple(branch_path),
+ "top_k": int(default_top_k),
+ "fragment_fingerprint": fragment.fragment_fingerprint,
+ },
+ )
+ except PrefixCacheRuntimeOOM as exc:
+ logger.warning(
+ "prefix cache warmup stopped after OOM attempted=%s prepared=%s skipped=%s "
+ "cache_id=%s node=%s top_k=%s error=%s",
+ attempted,
+ prepared,
+ skipped,
+ parts.cache_id,
+ node.node_id,
+ default_top_k,
+ exc,
+ )
+ return PrefixCacheWarmupResult(attempted=attempted, prepared=prepared, skipped=skipped)
+ prepared += 1
+ logger.debug(
+ "prefix cache warmup prepared cache_id=%s attempted=%s prepared=%s skipped=%s",
+ parts.cache_id,
+ attempted,
+ prepared,
+ skipped,
+ )
+ logger.debug(
+ "prefix cache warmup complete attempted=%s prepared=%s skipped=%s",
+ attempted,
+ prepared,
+ skipped,
+ )
+ return PrefixCacheWarmupResult(attempted=attempted, prepared=prepared, skipped=skipped)
+
+
+def _iter_nodes(node: RetrieverNode, branch_path: tuple[str, ...]):
+ yield node, branch_path
+ for child in node.children:
+ yield from _iter_nodes(child, branch_path + (child.node_id,))
+
+
+def _count_items(node: RetrieverNode) -> int:
+ total = len(node.items)
+ for child in node.children:
+ total += _count_items(child)
+ return total
+
+
+__all__ = ["PrefixCacheWarmupResult", "warmup_progressive_prefix_cache"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/vllm/__init__.py b/jiuwenswarm/symphony/retrieval/llm/vllm/__init__.py
new file mode 100644
index 0000000000..0da458f5d8
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/vllm/__init__.py
@@ -0,0 +1,3 @@
+from .client import LocalVLLMClient, LocalVLLMPrefixCacheHandle
+
+__all__ = ["LocalVLLMClient", "LocalVLLMPrefixCacheHandle"]
diff --git a/jiuwenswarm/symphony/retrieval/llm/vllm/client.py b/jiuwenswarm/symphony/retrieval/llm/vllm/client.py
new file mode 100644
index 0000000000..b85a885a78
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/llm/vllm/client.py
@@ -0,0 +1,886 @@
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import inspect
+import logging
+import threading
+import uuid
+from dataclasses import dataclass, field
+from time import perf_counter
+from typing import Any, Mapping, Sequence
+
+from ..base import (
+ GenerationConfig,
+ LLMClientCapabilities,
+ LLMRequestError,
+ LLMStreamChunk,
+ MaxNewTokensTooLarge,
+ Message,
+ PrefixCacheUnavailable,
+ ProgressiveLLMClient,
+ UnsupportedCapability,
+)
+
+LOGGER = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class LocalVLLMPrefixCacheHandle:
+ cache_id: str
+ prefix_token_ids: tuple[int, ...]
+ prefix_len: int
+ prefix_token_hash: str
+ model_fingerprint: str
+ tokenizer_fingerprint: str
+ prefix_text: str = ""
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+ @property
+ def dp_replica_id(self) -> int | None:
+ return None
+
+
+class _AsyncLoopRunner:
+ def __init__(self) -> None:
+ self._loop = asyncio.new_event_loop()
+ self._thread = threading.Thread(target=self._run, name="local-vllm-async-loop", daemon=True)
+ self._thread.start()
+
+ def submit(self, coro: Any, *, timeout: float | None = None) -> Any:
+ future = asyncio.run_coroutine_threadsafe(coro, self._loop)
+ return future.result(timeout=timeout)
+
+ def close(self) -> None:
+ if not self._loop.is_closed():
+ self._loop.call_soon_threadsafe(self._loop.stop)
+ self._thread.join(timeout=5.0)
+
+ def _run(self) -> None:
+ asyncio.set_event_loop(self._loop)
+ self._loop.run_forever()
+ pending = asyncio.all_tasks(self._loop)
+ for task in pending:
+ task.cancel()
+ if pending:
+ self._loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
+ self._loop.close()
+
+
+@dataclass
+class LocalVLLMClient(ProgressiveLLMClient):
+ engine: object
+ model_name: str
+ model_path: str = ""
+ tokenizer_path: str = ""
+ warmup_max_tokens: int = 128
+ max_new_tokens: int = 128
+ request_timeout: float | None = None
+ sampling_params_cls: object | None = None
+ health_check_timeout: float | None = None
+ health_check_interval: float = 1.0
+ tokenizer_fingerprint: str = ""
+ chat_template_tokenizer: object | None = None
+ _handles: dict[str, LocalVLLMPrefixCacheHandle] = field(default_factory=dict)
+ _loop_runner: _AsyncLoopRunner = field(default_factory=_AsyncLoopRunner)
+
+ name = "local_vllm"
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ *,
+ model_path: str,
+ tokenizer_path: str | None = None,
+ device: str = "auto",
+ dtype: str = "auto",
+ vllm_kwargs: Mapping[str, Any] | None = None,
+ generation_client: ProgressiveLLMClient | None = None,
+ max_new_tokens: int = 128,
+ ) -> "LocalVLLMClient":
+ del generation_client
+ try:
+ from vllm import AsyncEngineArgs, AsyncLLMEngine, SamplingParams
+ from vllm.global_consts import EngineRole
+ except ImportError as exc:
+ raise RuntimeError("custom vllm is required for LocalVLLMClient") from exc
+
+ resolved_tokenizer_path = tokenizer_path or model_path
+ options = dict(vllm_kwargs or {})
+ request_model_name = (
+ str(options.pop("request_model", "") or options.pop("model_name", "") or model_path).strip() or model_path
+ )
+ warmup_max_tokens = max(1, int(max_new_tokens))
+ trust_remote_code = bool(options.pop("trust_remote_code", True))
+ health_check_timeout = _pop_float_optional(options, "health_check_timeout")
+ health_check_interval = max(0.1, float(options.pop("health_check_interval", 1.0)))
+ chat_template_tokenizer = _load_chat_template_tokenizer(
+ tokenizer_path=str(resolved_tokenizer_path),
+ trust_remote_code=trust_remote_code,
+ )
+ engine_kwargs = _build_custom_engine_kwargs(
+ model_path=model_path,
+ tokenizer_path=resolved_tokenizer_path,
+ dtype=dtype,
+ trust_remote_code=trust_remote_code,
+ engine_role=EngineRole.M,
+ options=options,
+ )
+
+ LOGGER.info(
+ "initializing custom local vllm async client model=%s tokenizer=%s dtype=%s "
+ "device=%s kwargs=%s",
+ model_path,
+ resolved_tokenizer_path,
+ dtype,
+ device,
+ sorted(engine_kwargs.keys()),
+ )
+ engine_args = build_engine_args(AsyncEngineArgs, **engine_kwargs)
+ engine = AsyncLLMEngine.from_engine_args(engine_args)
+ loop_runner = _AsyncLoopRunner()
+ loop_runner.submit(
+ _start_custom_engine(
+ engine=engine,
+ health_check_interval=health_check_interval,
+ health_check_timeout=health_check_timeout,
+ ),
+ timeout=health_check_timeout,
+ )
+ return cls(
+ engine=engine,
+ model_name=request_model_name,
+ model_path=str(model_path),
+ tokenizer_path=str(resolved_tokenizer_path),
+ warmup_max_tokens=warmup_max_tokens,
+ max_new_tokens=max(1, int(max_new_tokens)),
+ sampling_params_cls=SamplingParams,
+ health_check_timeout=health_check_timeout,
+ health_check_interval=health_check_interval,
+ tokenizer_fingerprint=str(resolved_tokenizer_path),
+ chat_template_tokenizer=chat_template_tokenizer,
+ _loop_runner=loop_runner,
+ )
+
+ @property
+ def capabilities(self) -> LLMClientCapabilities:
+ return LLMClientCapabilities(
+ completion=True,
+ streaming=False,
+ candidate_scoring=False,
+ trie_constrained_decoding=False,
+ progressive_prefix_kv_cache=True,
+ thread_safe=True,
+ local_resources=True,
+ )
+
+ def prepare_prefix_cache(
+ self,
+ *,
+ cache_id: str,
+ prefix_messages: Sequence[Message],
+ prefix_token_hash: str = "",
+ metadata: dict[str, object] | None = None,
+ ) -> LocalVLLMPrefixCacheHandle:
+ started = perf_counter()
+ resolved_cache_id = str(cache_id)
+ cached = self._handles.get(resolved_cache_id)
+ if cached is not None:
+ LOGGER.debug(
+ "local vllm prefix cache already prepared cache_id=%s prefix_len=%s", cache_id, cached.prefix_len
+ )
+ return cached
+ token_ids, prefix_text = self._encode_prefix_messages(prefix_messages)
+ handle = LocalVLLMPrefixCacheHandle(
+ cache_id=resolved_cache_id,
+ prefix_token_ids=token_ids,
+ prefix_len=len(token_ids),
+ prefix_token_hash=str(prefix_token_hash or _hash_token_ids(token_ids)),
+ model_fingerprint=str(self.model_name),
+ tokenizer_fingerprint=str(self.tokenizer_fingerprint or self.tokenizer_path),
+ prefix_text=prefix_text,
+ metadata=dict(metadata or {}),
+ )
+ if token_ids:
+ try:
+ self._warmup_prefix(handle)
+ except Exception:
+ self._handles.pop(resolved_cache_id, None)
+ raise
+ self._handles[resolved_cache_id] = handle
+ LOGGER.debug(
+ "local vllm prefix cache prepared cache_id=%s prefix_len=%s elapsed_ms=%.3f metadata=%s",
+ handle.cache_id,
+ handle.prefix_len,
+ (perf_counter() - started) * 1000.0,
+ handle.metadata,
+ )
+ return handle
+
+ def get_prompt_cache_handle(self, cache_id: str) -> LocalVLLMPrefixCacheHandle | None:
+ handle = self._handles.get(str(cache_id))
+ LOGGER.debug("local vllm prefix cache handle lookup cache_id=%s hit=%s", cache_id, handle is not None)
+ return handle
+
+ def complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ n: int = 1,
+ request_timeout: float | None = None,
+ ) -> list[str]:
+ del model
+ if n != 1:
+ raise UnsupportedCapability("LocalVLLMClient supports n=1 only")
+ config = generation_config or GenerationConfig()
+ if config.constraints.trie is not None:
+ raise UnsupportedCapability("LocalVLLMClient does not support trie constrained decoding")
+ resolved_max_tokens = max(1, int(max_tokens or self.max_new_tokens))
+ if resolved_max_tokens > self.max_new_tokens:
+ raise MaxNewTokensTooLarge(
+ f"requested max_tokens={resolved_max_tokens} exceeds local vllm "
+ f"prefix-cache budget={self.max_new_tokens}"
+ )
+ prompt_text, prompt_ids, cached_token_count, new_token_count = self._resolve_prompt(
+ messages=messages,
+ generation_config=config,
+ )
+ sampling_params = self._sampling_params(
+ max_tokens=resolved_max_tokens,
+ generation_config=config,
+ )
+ started = perf_counter()
+ try:
+ text = self._generate_sync(
+ prompt=prompt_text,
+ prompt_ids=prompt_ids,
+ cached_token_count=cached_token_count,
+ new_token_count=new_token_count,
+ request_phase="complete",
+ sampling_params=sampling_params,
+ request_timeout=request_timeout,
+ )
+ except Exception as exc:
+ raise LLMRequestError(f"local vLLM generation failed: {exc}") from exc
+ LOGGER.debug(
+ "local vllm completion complete prompt_tokens=%s max_tokens=%s elapsed_ms=%.3f",
+ len(prompt_ids),
+ resolved_max_tokens,
+ (perf_counter() - started) * 1000.0,
+ )
+ return [text]
+
+ def stream_complete(
+ self,
+ model: str,
+ messages: list[Message],
+ *,
+ max_tokens: int | None = None,
+ stop_sequences: Sequence[str] | None = None,
+ generation_config: GenerationConfig | None = None,
+ request_timeout: float | None = None,
+ early_stop: object | None = None,
+ ):
+ del early_stop
+ started = perf_counter()
+ outputs = self.complete(
+ model=model,
+ messages=messages,
+ max_tokens=max_tokens,
+ stop_sequences=stop_sequences,
+ generation_config=generation_config,
+ n=1,
+ request_timeout=request_timeout,
+ )
+ yield LLMStreamChunk(
+ outputs[0] if outputs else "",
+ usage={"latency": {"total_client_ms": round((perf_counter() - started) * 1000.0, 3)}},
+ )
+
+ def _warmup_prefix(self, handle: LocalVLLMPrefixCacheHandle) -> None:
+ sampling_params = self._sampling_params(
+ max_tokens=self.warmup_max_tokens,
+ generation_config=GenerationConfig(),
+ )
+ try:
+ self._generate_sync(
+ prompt=handle.prefix_text,
+ prompt_ids=handle.prefix_token_ids,
+ cached_token_count=handle.prefix_len,
+ new_token_count=0,
+ request_phase="warmup",
+ sampling_params=sampling_params,
+ request_timeout=self.request_timeout,
+ )
+ except Exception as exc:
+ raise LLMRequestError(f"local vLLM prefix-cache warmup failed: {exc}") from exc
+
+ def _resolve_prompt(
+ self,
+ *,
+ messages: list[Message],
+ generation_config: GenerationConfig,
+ ) -> tuple[str, tuple[int, ...], int, int]:
+ hint = generation_config.prompt_cache
+ if hint is None or hint.handle is None:
+ prompt, prompt_ids = self._render_and_tokenize_messages(messages)
+ return prompt, prompt_ids, 0, len(prompt_ids)
+ handle = hint.handle
+ if not isinstance(handle, LocalVLLMPrefixCacheHandle):
+ raise PrefixCacheUnavailable(f"unsupported local vllm prefix cache handle: {type(handle).__name__}")
+ if hint.expected_prefix_len is not None and int(hint.expected_prefix_len) != int(handle.prefix_len):
+ raise PrefixCacheUnavailable(
+ f"prefix length mismatch: expected={hint.expected_prefix_len} actual={handle.prefix_len}"
+ )
+ if hint.suffix_token_ids is not None:
+ suffix_ids = tuple(int(token_id) for token_id in hint.suffix_token_ids)
+ suffix_text = str(hint.suffix_text or "")
+ suffix_source = "hint_token_ids"
+ else:
+ suffix_text, suffix_ids = self._encode_cached_suffix(
+ messages=messages,
+ handle=handle,
+ suffix_text=hint.suffix_text,
+ )
+ suffix_source = "rendered_chat_suffix"
+ prompt_ids = handle.prefix_token_ids + suffix_ids
+ prompt_text = f"{handle.prefix_text}{suffix_text}" if handle.prefix_text else self._render_messages(messages)
+ LOGGER.debug(
+ "local vllm using prefix cache cache_id=%s prefix_len=%s suffix_tokens=%s "
+ "suffix_source=%s prompt_tokens=%s prefix_tail=%s suffix_head=%s prompt_tail=%s",
+ handle.cache_id,
+ handle.prefix_len,
+ len(suffix_ids),
+ suffix_source,
+ len(prompt_ids),
+ list(handle.prefix_token_ids[-16:]),
+ list(suffix_ids[:16]),
+ list(prompt_ids[-32:]),
+ )
+ return prompt_text, prompt_ids, handle.prefix_len, len(suffix_ids)
+
+ def _generate_sync(
+ self,
+ *,
+ prompt: str,
+ prompt_ids: Sequence[int],
+ cached_token_count: int,
+ new_token_count: int,
+ request_phase: str,
+ sampling_params: object,
+ request_timeout: float | None,
+ ) -> str:
+ timeout = request_timeout if request_timeout is not None else self.request_timeout
+ LOGGER.info(
+ "local vllm request tokens phase=%s cached_token_ids=%s new_token_ids=%s prompt_tokens=%s",
+ request_phase,
+ max(0, int(cached_token_count)),
+ max(0, int(new_token_count)),
+ len(prompt_ids),
+ )
+ return self._loop_runner.submit(
+ _generate_on_loop(
+ engine=self.engine,
+ tokenizer=self.chat_template_tokenizer,
+ prompt=prompt,
+ prompt_token_ids=prompt_ids,
+ sampling_params=sampling_params,
+ ),
+ timeout=timeout,
+ )
+
+ def _sampling_params(
+ self,
+ *,
+ max_tokens: int,
+ generation_config: GenerationConfig,
+ ):
+ sampling_params_cls = self.sampling_params_cls
+ if sampling_params_cls is None:
+ raise RuntimeError("custom vllm SamplingParams is not initialized")
+ kwargs = {
+ "temperature": float(generation_config.temperature),
+ "max_tokens": max(1, int(max_tokens)),
+ }
+ return sampling_params_cls(**_filter_callable_kwargs(sampling_params_cls, kwargs))
+
+ def _encode_prefix_messages(self, messages: Sequence[Message]) -> tuple[tuple[int, ...], str]:
+ rendered_prefix = self._render_messages(messages, add_generation_prompt=False)
+ open_prefix = _strip_final_turn_end(rendered_prefix, tokenizer=self.chat_template_tokenizer)
+ token_ids = tuple(self._encode_text(open_prefix))
+ LOGGER.debug(
+ "local vllm encoded open prefix messages=%s rendered_chars=%s "
+ "open_prefix_chars=%s prefix_tokens=%s prefix_text_tail=%r",
+ len(tuple(messages)),
+ len(rendered_prefix),
+ len(open_prefix),
+ len(token_ids),
+ open_prefix[-240:],
+ )
+ return token_ids, open_prefix
+
+ def _encode_cached_suffix(
+ self,
+ *,
+ messages: Sequence[Message],
+ handle: LocalVLLMPrefixCacheHandle,
+ suffix_text: str,
+ ) -> tuple[str, tuple[int, ...]]:
+ if not handle.prefix_text:
+ return str(suffix_text or ""), tuple(self._encode_text(suffix_text))
+ full_text = self._render_messages(messages)
+ if full_text.startswith(handle.prefix_text):
+ suffix_rendered = full_text[len(handle.prefix_text):]
+ if not suffix_rendered and str(suffix_text or ""):
+ LOGGER.warning(
+ "local vllm rendered chat suffix is empty despite non-empty suffix_text "
+ "cache_id=%s; falling back to raw suffix encode",
+ handle.cache_id,
+ )
+ fallback_text = str(suffix_text or "")
+ return fallback_text, tuple(self._encode_text(fallback_text))
+ suffix_ids = tuple(self._encode_text(suffix_rendered))
+ LOGGER.debug(
+ "local vllm encoded cached suffix from full chat template cache_id=%s "
+ "full_chars=%s prefix_chars=%s suffix_chars=%s suffix_tokens=%s suffix_text_head=%r",
+ handle.cache_id,
+ len(full_text),
+ len(handle.prefix_text),
+ len(suffix_rendered),
+ len(suffix_ids),
+ suffix_rendered[:240],
+ )
+ return suffix_rendered, suffix_ids
+ LOGGER.warning(
+ "local vllm prefix cache prompt mismatch cache_id=%s full_chars=%s "
+ "prefix_chars=%s prefix_len=%s; falling back to raw suffix encode",
+ handle.cache_id,
+ len(full_text),
+ len(handle.prefix_text),
+ handle.prefix_len,
+ )
+ fallback_text = str(suffix_text or "")
+ return fallback_text, tuple(self._encode_text(fallback_text))
+
+ def _encode_text(self, text: str) -> tuple[int, ...]:
+ return _encode_text_with_transformers(tokenizer=self.chat_template_tokenizer, text=str(text or ""))
+
+ def _render_messages(self, messages: Sequence[Message], *, add_generation_prompt: bool = True) -> str:
+ return _render_qwen_chat_template(
+ tokenizer=self.chat_template_tokenizer,
+ messages=messages,
+ add_generation_prompt=add_generation_prompt,
+ )
+
+ def _render_and_tokenize_messages(
+ self,
+ messages: Sequence[Message],
+ *,
+ add_generation_prompt: bool = True,
+ ) -> tuple[str, tuple[int, ...]]:
+ return _render_and_tokenize_qwen_chat_template(
+ tokenizer=self.chat_template_tokenizer,
+ messages=messages,
+ add_generation_prompt=add_generation_prompt,
+ )
+
+ def close(self) -> None:
+ shutdown = getattr(self.engine, "shutdown_background_loop", None)
+ if callable(shutdown):
+ shutdown()
+ shutdown_engine = getattr(getattr(self.engine, "llm_engine", None), "shutdown", None)
+ if callable(shutdown_engine):
+ shutdown_engine()
+ self._loop_runner.close()
+
+
+async def _generate_on_loop(
+ *,
+ engine: object,
+ tokenizer: object | None,
+ prompt: str,
+ prompt_token_ids: Sequence[int],
+ sampling_params: object,
+) -> str:
+ results_generator = engine.generate(
+ prompt=prompt,
+ sampling_params=sampling_params,
+ request_id=str(uuid.uuid4()),
+ prompt_token_ids=[int(token_id) for token_id in prompt_token_ids],
+ tag=None,
+ arrival_time=None,
+ multi_modal_data=None,
+ scheduler_result=None,
+ is_stream=False,
+ )
+ final_output = None
+ async for request_output in results_generator:
+ final_output = request_output
+ if final_output is None:
+ raise RuntimeError("local vLLM returned no request outputs")
+ return _extract_generation_text(final_output, tokenizer=tokenizer)
+
+
+async def _start_custom_engine(
+ *,
+ engine: object,
+ health_check_interval: float,
+ health_check_timeout: float | None,
+) -> None:
+ load_model = getattr(getattr(engine, "engine", None), "load_model", None)
+ if callable(load_model):
+ load_model()
+ start_background_loop = getattr(engine, "start_background_loop", None)
+ if callable(start_background_loop):
+ start_background_loop()
+ is_health = getattr(engine, "is_health", None)
+ if not callable(is_health):
+ return
+ started = perf_counter()
+ while not await is_health():
+ if health_check_timeout is not None and (perf_counter() - started) > float(health_check_timeout):
+ raise TimeoutError("custom vLLM engine health check timed out")
+ await asyncio.sleep(max(0.1, float(health_check_interval)))
+
+
+def _encode_text_with_transformers(*, tokenizer: object | None, text: str) -> tuple[int, ...]:
+ if tokenizer is None:
+ raise RuntimeError("Qwen tokenizer is not initialized")
+ encode = getattr(tokenizer, "encode", None)
+ if not callable(encode):
+ raise RuntimeError("Qwen tokenizer does not expose encode(...)")
+ return tuple(int(token_id) for token_id in encode(str(text or ""), add_special_tokens=False))
+
+
+def _build_custom_engine_kwargs(
+ *,
+ model_path: str,
+ tokenizer_path: str,
+ dtype: str,
+ trust_remote_code: bool,
+ engine_role: object,
+ options: Mapping[str, Any],
+) -> dict[str, Any]:
+ normalized_options = dict(options or {})
+ resolved_dtype = str(dtype or "").strip()
+ if not resolved_dtype or resolved_dtype.lower() == "auto":
+ resolved_dtype = "bfloat16"
+ kwargs: dict[str, Any] = {
+ "model": model_path,
+ "model_vision": "facebook/opt-125m",
+ "architectures": "Qwen3_5MoeForConditionalGeneration_OnlyLLM",
+ "tokenizer": tokenizer_path,
+ "tokenizer_mode": "auto",
+ "trust_remote_code": bool(trust_remote_code),
+ "download_dir": None,
+ "load_format": "auto",
+ "dtype": resolved_dtype,
+ "seed": 0,
+ "max_model_len": None,
+ "rope_scaling_type": None,
+ "rope_scaling_factor": 1.0,
+ "pipeline_parallel_size": 1,
+ "tensor_parallel_size": 2,
+ "data_parallel_size": 1,
+ "context_parallel_size": 1,
+ "pipeline_parallel_layer_partitions": "",
+ "mla_wo_tensor_parallel_size": -1,
+ "enable_expert_parallel": False,
+ "decode_enable_expert_parallel": False,
+ "decode_pipeline_parallel_size": 1,
+ "decode_tensor_parallel_size": 2,
+ "decode_data_parallel_size": 1,
+ "decode_context_parallel_size": 1,
+ "block_size": 128,
+ "kernel_block_size": 128,
+ "prefix_sharing_chunk_size": 128,
+ "scheduler_budget_len": 102400,
+ "prefix_sharing_type": "auto",
+ "prefix_sharing_kwargs": {"gpu_usage_threshold": 0.7},
+ "enable_datasystem": True,
+ "multipath_devices": "",
+ "swap_space": 0,
+ "gpu_memory_utilization": 0.9,
+ "max_num_batched_tokens": None,
+ "max_num_seqs": 8,
+ "disable_log_stats": False,
+ "revision": None,
+ "tokenizer_revision": None,
+ "quantization": None,
+ "block_sliding_window": None,
+ "sink_block_num": 0,
+ "schedule_policy": "fcfs",
+ "schedule_policy_kwargs": None,
+ "first_token_timeout": 300.0,
+ "max_swapped_req_num": 128,
+ "sys_prefix_prompts": None,
+ "ops_dev_mode": None,
+ "speculate_type": None,
+ "speculate_kwargs": None,
+ "disaggregate_prefill_decoding": False,
+ "dispd_args": None,
+ "ranks": None,
+ "engine_name": "",
+ "sparse_mode": "",
+ "sparse_threshold_len": 4096,
+ "sparse_minimum_len": 2048,
+ "sparse_budget_len": 4096,
+ "sparse_compress_ratio": 0.5,
+ "cluster_window_size": 32,
+ "cluster_sink_size": 64,
+ "cluster_recent_size": 128,
+ "cluster_kernel_size": 9,
+ "cluster_block_size": 64,
+ "inf_prefix_len": 64,
+ "inf_query_len": 32,
+ "inf_window_size": 1024,
+ "inf_overlap_size": 32,
+ "turbo_share_sysprefix": False,
+ "turbo_sysprefix_num": 0,
+ "turbo_separator_set": None,
+ "speculative_config": None,
+ "enable_chunked_prefill": True,
+ "enable_batching_prefill": False,
+ "enable_fuse_prefill_and_decode": False,
+ "enable_lookahead_scheduling": False,
+ "need_kv_transfer": False,
+ "prefill_group_num": 1,
+ "decode_group_num": 1,
+ "global_group_meta": None,
+ "stage_id": None,
+ "engine_role": engine_role,
+ "head_candidate_role_set": None,
+ "need_bypass_balancer": False,
+ "group_name": "",
+ "dllm_blockwise_type": None,
+ "dllm_blockwise_kwargs": None,
+ "dense_prefetch_config": None,
+ "tokenizer_group_mode": "process",
+ "tokenizer_group_workers": 4,
+ "disable_log_requests": True,
+ "max_log_len": None,
+ "new_requests_que_size": 128,
+ "finished_requests_que_size": 1024,
+ "detokenizer_group_mode": None,
+ "detokenizer_group_workers": 1,
+ }
+ kwargs.update(normalized_options)
+ return kwargs
+
+
+def build_engine_args(async_engine_args_cls: object, **kwargs: Any) -> Any:
+ filtered = _filter_callable_kwargs(async_engine_args_cls, kwargs)
+ skipped = sorted(set(kwargs).difference(filtered))
+ if skipped:
+ LOGGER.warning("current vLLM AsyncEngineArgs does not support options; skipped=%s", skipped)
+ return async_engine_args_cls(**filtered)
+
+
+def _filter_callable_kwargs(callable_obj: object, kwargs: Mapping[str, Any]) -> dict[str, Any]:
+ try:
+ sig = inspect.signature(callable_obj)
+ except (TypeError, ValueError):
+ return dict(kwargs)
+ supported = set(sig.parameters.keys())
+ if any(param.kind == inspect.Parameter.VAR_KEYWORD for param in sig.parameters.values()):
+ return dict(kwargs)
+ return {key: value for key, value in kwargs.items() if key in supported}
+
+
+def _load_chat_template_tokenizer(*, tokenizer_path: str, trust_remote_code: bool) -> object:
+ try:
+ from transformers import AutoTokenizer
+ except ImportError as exc:
+ raise RuntimeError("transformers is required to render Qwen chat templates") from exc
+ tokenizer = AutoTokenizer.from_pretrained(str(tokenizer_path), trust_remote_code=bool(trust_remote_code))
+ if not hasattr(tokenizer, "apply_chat_template"):
+ raise RuntimeError("Qwen tokenizer does not expose apply_chat_template(...)")
+ return tokenizer
+
+
+def _render_qwen_chat_template(
+ *,
+ tokenizer: object | None,
+ messages: Sequence[Message],
+ add_generation_prompt: bool,
+) -> str:
+ if tokenizer is None:
+ raise RuntimeError("Qwen chat template tokenizer is not initialized")
+ rendered = tokenizer.apply_chat_template(
+ [dict(message) for message in messages],
+ add_generation_prompt=bool(add_generation_prompt),
+ tokenize=False,
+ enable_thinking=False,
+ )
+ return str(rendered)
+
+
+def _render_and_tokenize_qwen_chat_template(
+ *,
+ tokenizer: object | None,
+ messages: Sequence[Message],
+ add_generation_prompt: bool,
+) -> tuple[str, tuple[int, ...]]:
+ if tokenizer is None:
+ raise RuntimeError("Qwen chat template tokenizer is not initialized")
+ normalized_messages = [dict(message) for message in messages]
+ rendered = tokenizer.apply_chat_template(
+ normalized_messages,
+ add_generation_prompt=bool(add_generation_prompt),
+ tokenize=False,
+ enable_thinking=False,
+ )
+ tokenized = tokenizer.apply_chat_template(
+ normalized_messages,
+ add_generation_prompt=bool(add_generation_prompt),
+ tokenize=True,
+ enable_thinking=False,
+ )
+ return str(rendered), _extract_chat_template_input_ids(tokenized)
+
+
+def _extract_chat_template_input_ids(tokenized: Any) -> tuple[int, ...]:
+ input_ids = tokenized.get("input_ids") if isinstance(tokenized, Mapping) else tokenized
+ if hasattr(input_ids, "tolist"):
+ input_ids = input_ids.tolist()
+ if input_ids and isinstance(input_ids, list) and isinstance(input_ids[0], list):
+ input_ids = input_ids[0]
+ return tuple(int(token_id) for token_id in input_ids or ())
+
+
+def _strip_final_turn_end(rendered: str, *, tokenizer: object | None) -> str:
+ text = str(rendered or "")
+ candidates: list[str] = []
+ for attr in ("eos_token", "im_end_token", "eot_token"):
+ token = getattr(tokenizer, attr, None) if tokenizer is not None else None
+ if token and str(token) not in candidates:
+ candidates.append(str(token))
+ for token in ("<|im_end|>", "<eot>", "</s>", "<|endoftext|>"):
+ if token not in candidates:
+ candidates.append(token)
+ for token in candidates:
+ index = text.rfind(token)
+ if index < 0:
+ continue
+ tail = text[index + len(token):]
+ if tail.strip():
+ continue
+ return text[:index]
+ return text
+
+
+def _extract_generation_text(outputs: Any, *, tokenizer: object | None = None) -> str:
+ first = _first_request_output(outputs)
+ completion = _first_completion_output(first)
+ text = getattr(completion, "text", None)
+ if text is None and isinstance(completion, Mapping):
+ text = completion.get("text")
+ resolved_text = str(text or "")
+ raw_summary = _summarize_generation_outputs(first, completion)
+ if not resolved_text:
+ fallback_text = _decode_completion_token_ids(completion, tokenizer=tokenizer)
+ if fallback_text:
+ LOGGER.warning(
+ "local vllm generated empty text; decoded token_ids fallback raw=%s decoded=%r",
+ raw_summary,
+ fallback_text,
+ )
+ return fallback_text
+ if resolved_text:
+ LOGGER.debug("local vllm raw generation output=%s", raw_summary)
+ else:
+ LOGGER.warning("local vllm generated empty text raw=%s", raw_summary)
+ return resolved_text
+
+
+def _decode_completion_token_ids(completion: Any, *, tokenizer: object | None) -> str:
+ token_ids = getattr(completion, "token_ids", None)
+ if token_ids is None and isinstance(completion, Mapping):
+ token_ids = completion.get("token_ids")
+ safe_token_ids = _safe_int_list(token_ids) or []
+ if not safe_token_ids or tokenizer is None:
+ return ""
+ decode = getattr(tokenizer, "decode", None)
+ if not callable(decode):
+ return ""
+ try:
+ return str(decode(safe_token_ids, skip_special_tokens=True) or "")
+ except TypeError:
+ return str(decode(safe_token_ids) or "")
+
+
+def _first_request_output(outputs: Any) -> Any:
+ if isinstance(outputs, Sequence) and not isinstance(outputs, (str, bytes, bytearray)) and outputs:
+ return outputs[0]
+ return outputs
+
+
+def _first_completion_output(request_output: Any) -> Any:
+ completions = getattr(request_output, "outputs", None)
+ if completions is None and isinstance(request_output, Mapping):
+ completions = request_output.get("outputs")
+ if isinstance(completions, Sequence) and not isinstance(completions, (str, bytes, bytearray)) and completions:
+ return completions[0]
+ raise RuntimeError(f"local vLLM returned no completion outputs: {request_output!r}")
+
+
+def _summarize_generation_outputs(request_output: Any, completion: Any) -> dict[str, Any]:
+ prompt_token_ids = getattr(request_output, "prompt_token_ids", None)
+ if prompt_token_ids is None and isinstance(request_output, Mapping):
+ prompt_token_ids = request_output.get("prompt_token_ids")
+ token_ids = getattr(completion, "token_ids", None)
+ if token_ids is None and isinstance(completion, Mapping):
+ token_ids = completion.get("token_ids")
+ return {
+ "request_id": _output_attr(request_output, "request_id"),
+ "finished": _output_attr(request_output, "finished"),
+ "prompt_tokens": _safe_len(prompt_token_ids),
+ "token_ids": _safe_int_list(token_ids),
+ "text": _output_attr(completion, "text"),
+ "finish_reason": _output_attr(completion, "finish_reason"),
+ "stop_reason": _output_attr(completion, "stop_reason"),
+ "cumulative_logprob": _output_attr(completion, "cumulative_logprob"),
+ }
+
+
+def _output_attr(obj: Any, name: str) -> Any:
+ if isinstance(obj, Mapping):
+ return obj.get(name)
+ return getattr(obj, name, None)
+
+
+def _safe_len(value: Any) -> int | None:
+ try:
+ return len(value)
+ except TypeError:
+ return None
+
+
+def _safe_int_list(value: Any) -> list[int] | None:
+ if value is None:
+ return None
+ try:
+ return [int(item) for item in value]
+ except TypeError:
+ return None
+
+
+def _hash_token_ids(token_ids: Sequence[int]) -> str:
+ digest = hashlib.sha256()
+ for token_id in token_ids:
+ digest.update(int(token_id).to_bytes(8, "little", signed=True))
+ return digest.hexdigest()
+
+
+def _pop_float_optional(options: dict[str, Any], key: str) -> float | None:
+ value = options.pop(key, None)
+ if value is None or not str(value).strip():
+ return None
+ return float(value)
+
+
+__all__ = ["LocalVLLMClient", "LocalVLLMPrefixCacheHandle", "build_engine_args"]
diff --git a/jiuwenswarm/symphony/retrieval/merge/__init__.py b/jiuwenswarm/symphony/retrieval/merge/__init__.py
new file mode 100644
index 0000000000..07fba76cac
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/merge/__init__.py
@@ -0,0 +1,5 @@
+from .append import hits_to_search_result
+
+__all__ = [
+ "hits_to_search_result",
+]
diff --git a/jiuwenswarm/symphony/retrieval/merge/append.py b/jiuwenswarm/symphony/retrieval/merge/append.py
new file mode 100644
index 0000000000..b5d9d9ac25
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/merge/append.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+from typing import Dict, List, Sequence
+
+from models.retrieval import RetrieverCandidate, RetrieverTrace
+from ..tree.types import ProgressiveRetrieverResult
+
+from ..service.models import SearchResult
+
+
+def hits_to_search_result(
+ *,
+ method: str,
+ source: str,
+ elapsed_ms: float,
+ trace_events: List[Dict[str, object]],
+ candidate_records: List[Dict[str, object]],
+) -> SearchResult:
+ payloads = [str(record.get("resolved_payload") or "") for record in candidate_records]
+ return SearchResult(
+ method=method,
+ payloads=payloads,
+ candidate_records=candidate_records,
+ summary_lines=[
+ _format_append_summary_line(index, record, source)
+ for index, record in enumerate(candidate_records, start=1)
+ ],
+ selected_payload=payloads[0] if payloads else None,
+ selected_rank=1 if payloads else -1,
+ elapsed_ms=float(elapsed_ms),
+ trace_events=trace_events,
+ )
+
+
+def _format_append_summary_line(index: int, record: dict[str, object], source: str) -> str:
+ choice_id = record.get("choice_id") or record.get("raw_output") or ""
+ resolved_payload = record.get("resolved_payload") or ""
+ return f"{index}. {choice_id} -> {resolved_payload} (source={source})"
+
+
+__all__ = [
+ "hits_to_search_result",
+]
diff --git a/jiuwenswarm/symphony/retrieval/protocols/__init__.py b/jiuwenswarm/symphony/retrieval/protocols/__init__.py
new file mode 100644
index 0000000000..3f6413c504
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/protocols/__init__.py
@@ -0,0 +1,5 @@
+from .display_name import to_pascal_case
+from .parsing import parse_ids
+from .prompts import build_retriever_catalog_prompt, build_retriever_system_prompt
+
+__all__ = ["build_retriever_catalog_prompt", "build_retriever_system_prompt", "parse_ids", "to_pascal_case"]
diff --git a/jiuwenswarm/symphony/retrieval/protocols/display_name.py b/jiuwenswarm/symphony/retrieval/protocols/display_name.py
new file mode 100644
index 0000000000..0de9fc542d
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/protocols/display_name.py
@@ -0,0 +1,24 @@
+from __future__ import annotations
+
+import re
+
+
+_CAMEL_BOUNDARY_RE = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
+_NON_ALNUM_RE = re.compile(r"[^A-Za-z0-9]+")
+
+
+def to_pascal_case(value: str) -> str:
+ text = str(value or "").strip()
+ if not text:
+ return ""
+ text = _CAMEL_BOUNDARY_RE.sub("-", text)
+ text = text.replace("_", "-")
+ text = _NON_ALNUM_RE.sub("-", text)
+ text = re.sub(r"-{2,}", "-", text)
+ parts = [part.lower() for part in text.strip("-").split("-") if part]
+ if not parts:
+ return ""
+ return "".join(part[:1].upper() + part[1:] for part in parts)
+
+
+__all__ = ["to_pascal_case"]
diff --git a/jiuwenswarm/symphony/retrieval/protocols/parsing.py b/jiuwenswarm/symphony/retrieval/protocols/parsing.py
new file mode 100644
index 0000000000..92f4e7e34e
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/protocols/parsing.py
@@ -0,0 +1,18 @@
+from __future__ import annotations
+
+import re
+
+
+def parse_ids(output: str) -> list[str]:
+ values: list[str] = []
+ for line in str(output or "").splitlines():
+ cleaned = re.sub(r"^\s*(?:\d+[\).\s:-]+|[-*]\s+)", "", line.strip())
+ if not cleaned:
+ continue
+ values.append(cleaned.split("|", 1)[0].strip())
+ if values:
+ return values
+ return re.findall(r"[A-Za-z][A-Za-z0-9_./-]*", str(output or ""))
+
+
+__all__ = ["parse_ids"]
diff --git a/jiuwenswarm/symphony/retrieval/protocols/prompts.py b/jiuwenswarm/symphony/retrieval/protocols/prompts.py
new file mode 100644
index 0000000000..d6a79a19a1
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/protocols/prompts.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+
+_TOP1_TEMPLATE = """\
+# Role
+- You are a retriever.
+- Select exactly one executable worker from the candidate tree.
+- Do not explain your reasoning.
+
+# Goal
+- Choose the single best worker for the user request.
+- The result must be an executable worker id from the tree.
+
+# Output Rules
+- Output exactly 1 line.
+- Output exactly 1 worker id from the tree.
+- Do not output category ids.
+- Do not output explanations, numbering, JSON, or Markdown.
+
+Node Name Hierarchy:
+{tree_cid_hierarchy}
+"""
+
+
+_TOPK_TEMPLATE = """\
+# Role
+- You are a retriever.
+- Rank candidate workers for the current user query.
+- Do not explain your reasoning.
+
+# Goal
+- Select the best {top_k} executable workers for the user request.
+
+# Output Rules
+- Output up to {top_k} lines.
+- Each line must contain exactly 1 worker id from the tree.
+- Do not output category ids.
+- Do not output explanations, numbering, JSON, or Markdown.
+
+Node Name Hierarchy:
+{tree_cid_hierarchy}
+"""
+
+
+def build_retriever_system_prompt(*, tree_cid_hierarchy: str, top_k: int) -> str:
+ resolved_top_k = max(1, int(top_k or 1))
+ template = _TOPK_TEMPLATE if resolved_top_k > 1 else _TOP1_TEMPLATE
+ return template.format(
+ top_k=resolved_top_k,
+ tree_cid_hierarchy=str(tree_cid_hierarchy or "").strip() or "(no candidates)",
+ )
+
+
+def build_retriever_catalog_prompt(*, choices, top_k: int) -> str:
+ resolved_top_k = max(1, int(top_k or 1))
+ lines = [
+ "# Role",
+ "- You are a retriever.",
+ "- Rank candidate workers for the current user query.",
+ "- Do not explain your reasoning.",
+ "",
+ "# Goal",
+ f"- Select the best {resolved_top_k} workers from the candidate list.",
+ "",
+ "# Output Rules",
+ f"- Output up to {resolved_top_k} lines.",
+ "- Each line must contain exactly 1 worker id from the candidate list.",
+ "- Do not output explanations, numbering, JSON, or Markdown.",
+ "",
+ "# Candidates",
+ ]
+ has_choice = False
+ for choice in choices:
+ choice_id = str(getattr(choice, "choice_id", "") or "").strip()
+ if not choice_id:
+ continue
+ description = " ".join(str(getattr(choice, "description", "") or "").split())
+ line = f"- {choice_id}"
+ if description:
+ line += f": {description}"
+ lines.append(line)
+ has_choice = True
+ if not has_choice:
+ lines.append("- (no candidates)")
+ return "\n".join(lines)
+
+
+__all__ = ["build_retriever_catalog_prompt", "build_retriever_system_prompt"]
diff --git a/jiuwenswarm/symphony/retrieval/service/__init__.py b/jiuwenswarm/symphony/retrieval/service/__init__.py
new file mode 100644
index 0000000000..e2c25719d9
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/service/__init__.py
@@ -0,0 +1,25 @@
+from .models import (
+ GenerationConfig,
+ OpenAIClientConfig,
+ RenderConfig,
+ RequestConfig,
+ RetrieverConfig,
+ SearchResult,
+ TransformersClientConfig,
+ TraversalConfig,
+ VLLMClientConfig,
+)
+from .retriever import Retriever
+
+__all__ = [
+ "GenerationConfig",
+ "OpenAIClientConfig",
+ "RequestConfig",
+ "RenderConfig",
+ "Retriever",
+ "RetrieverConfig",
+ "SearchResult",
+ "TransformersClientConfig",
+ "TraversalConfig",
+ "VLLMClientConfig",
+]
diff --git a/jiuwenswarm/symphony/retrieval/service/defaults.py b/jiuwenswarm/symphony/retrieval/service/defaults.py
new file mode 100644
index 0000000000..610a42453c
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/service/defaults.py
@@ -0,0 +1,29 @@
+from __future__ import annotations
+
+from typing import Dict
+
+from models.retrieval import RetrieverTraceEvent
+
+
+def serialize_trace_event(event: RetrieverTraceEvent) -> Dict[str, object]:
+ return {
+ "event_type": str(event.event_type),
+ "node_id": str(event.node_id),
+ "depth": int(event.depth),
+ "detail": dict(event.detail or {}),
+ }
+
+
+def serialize_hit_summary(choice_id: str, payload: str, rank: int, score: float) -> Dict[str, object]:
+ return {
+ "choice_id": str(choice_id),
+ "payload": str(payload),
+ "rank": int(rank),
+ "score": float(score),
+ }
+
+
+__all__ = [
+ "serialize_hit_summary",
+ "serialize_trace_event",
+]
diff --git a/jiuwenswarm/symphony/retrieval/service/models.py b/jiuwenswarm/symphony/retrieval/service/models.py
new file mode 100644
index 0000000000..5fc7acadf1
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/service/models.py
@@ -0,0 +1,200 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Dict, List, Literal
+
+from ..llm.config import LLMClientConfig, OpenAIClientConfig, TransformersClientConfig, VLLMClientConfig
+from ..tree.codebooks import DEFAULT_COMPACT_BOUNDARY_CODEBOOK
+from ..tree.types import ProgressiveRetrieverConfig
+
+
+@dataclass(frozen=True)
+class TraversalConfig:
+ """Progressive traversal and branch-search controls."""
+
+ # Maximum number of child branches considered at a node.
+ max_branch_choices: int = 6
+
+ # Maximum number of branches searched in parallel.
+ max_parallel_branches: int = 3
+
+ # Whether branch-level parallel search is enabled.
+ enable_parallel_branches: bool = True
+
+ # Extra child branches to consider beyond top_k.
+ branch_choice_slack: int = 2
+
+ # Extra candidates to keep per selected branch.
+ branch_candidate_slack: int = 1
+
+ # Whether multi-branch candidates are merged round-robin.
+ round_robin_branch_reduce: bool = True
+
+
+@dataclass(frozen=True)
+class RenderConfig:
+ """Prompt rendering and tree disclosure controls."""
+
+ # Whether compact numeric candidate codes are exposed to the LLM.
+ compact_codes_enabled: bool = True
+
+ # Codebook for compact candidate code rendering.
+ compact_codebook: tuple[str, ...] = DEFAULT_COMPACT_BOUNDARY_CODEBOOK
+
+ # Whether the current candidate tree is rendered as a flat prompt payload.
+ flatten_tree: bool = True
+
+ # Maximum candidate tree depth exposed in one LLM call.
+ max_exposure_depth: int = 99
+
+ # Node expansion / exposure threshold.
+ exposure_threshold: int = 1_000_000_000
+
+
+@dataclass(frozen=True)
+class GenerationConfig:
+ """LLM candidate generation and logit-selection controls."""
+
+ # Selection mode: generated compact codes or logit-based candidate scoring.
+ mode: Literal["generate", "logit_selection"] = "generate"
+
+ # Default generation token limit for selection requests.
+ max_tokens: int = 96
+
+ # Per-request timeout in seconds.
+ request_timeout_seconds: float | None = 120.0
+
+ # Whether trie constrained decoding is enabled for supporting clients.
+ trie_constrained_decoding_enabled: bool = False
+
+ # Whether logit-selection candidate codes must be single tokenizer tokens.
+ logit_require_single_token_codes: bool = True
+
+ # Whether logit-selection returns probabilities in traces.
+ logit_return_probabilities: bool = True
+
+ # Logit-selection fallback behavior.
+ logit_fallback_mode: str = "error"
+
+ # Maximum number of candidates scored in logit-selection mode.
+ logit_max_candidates: int = 512
+
+ # Optional minimum probability threshold for logit-selected candidates.
+ logit_min_probability: float | None = None
+
+ # Number of top scoring candidates included in trace debug output.
+ logit_trace_top_n: int = 10
+
+
+@dataclass(frozen=True)
+class RetrieverConfig:
+ """Public retriever initialization configuration."""
+
+ # Maximum number of skills returned by the initialized retriever.
+ top_k: int = 10
+
+ # LLM client configuration. Defaults to OpenAI-compatible external-client mode.
+ llm_client_config: LLMClientConfig = field(default_factory=OpenAIClientConfig)
+
+ # Progressive traversal configuration.
+ traversal_config: TraversalConfig = field(default_factory=TraversalConfig)
+
+ # Prompt rendering configuration.
+ render_config: RenderConfig = field(default_factory=RenderConfig)
+
+ # Candidate generation / scoring configuration.
+ generation_config: GenerationConfig = field(default_factory=GenerationConfig)
+
+
+@dataclass(frozen=True)
+class RequestConfig:
+ """Per-search overrides that do not rebuild retriever runtime."""
+
+ # Requested result count. None means using RetrieverConfig.top_k.
+ top_k: int | None = None
+
+
+@dataclass(frozen=True)
+class _RuntimeRetrieverConfig:
+ """Internal runtime configuration consumed by the retrieval engine."""
+
+ top_k: int = 10
+ progressive: ProgressiveRetrieverConfig = field(default_factory=ProgressiveRetrieverConfig)
+
+
+@dataclass
+class SearchResult:
+ method: str
+ payloads: List[str]
+ candidate_records: List[Dict[str, object]]
+ summary_lines: List[str]
+ selected_payload: str | None
+ selected_rank: int
+ elapsed_ms: float = 0.0
+ trace_events: List[Dict[str, object]] = field(default_factory=list)
+
+
+def runtime_retriever_config_from_config(config: RetrieverConfig | None = None) -> _RuntimeRetrieverConfig:
+ """Convert public retrieval config into the internal runtime config.
+
+ Args:
+ config: Public retriever configuration.
+
+ Returns:
+ Internal config passed to the progressive retriever implementation.
+ """
+
+ config = config or RetrieverConfig()
+ resolved_top_k = max(1, int(config.top_k))
+ traversal = config.traversal_config or TraversalConfig()
+ render = config.render_config or RenderConfig()
+ generation = config.generation_config or GenerationConfig()
+
+ return _RuntimeRetrieverConfig(
+ top_k=resolved_top_k,
+ progressive=ProgressiveRetrieverConfig(
+ top_k=resolved_top_k,
+ llm_client_config=config.llm_client_config or OpenAIClientConfig(),
+ max_tokens=max(1, int(generation.max_tokens)),
+ trie_constrained_decoding_enabled=bool(generation.trie_constrained_decoding_enabled),
+ max_branch_choices=max(1, int(traversal.max_branch_choices)),
+ max_parallel_branches=max(1, int(traversal.max_parallel_branches)),
+ enable_parallel_branches=bool(traversal.enable_parallel_branches),
+ branch_choice_slack=max(0, int(traversal.branch_choice_slack)),
+ branch_candidate_slack=max(0, int(traversal.branch_candidate_slack)),
+ round_robin_branch_reduce=bool(traversal.round_robin_branch_reduce),
+ request_timeout=generation.request_timeout_seconds,
+ compact_boundary_codes_enabled=bool(render.compact_codes_enabled),
+ compact_boundary_codebook=tuple(str(code) for code in render.compact_codebook),
+ flatten_full_tree_in_prompt=bool(render.flatten_tree),
+ max_exposure_depth_per_call=max(0, int(render.max_exposure_depth)),
+ exposure_threshold=max(0, int(render.exposure_threshold)),
+ selection_mode=_normalize_selection_mode(generation.mode),
+ scoring_require_single_token_codes=bool(generation.logit_require_single_token_codes),
+ scoring_return_probabilities=bool(generation.logit_return_probabilities),
+ scoring_fallback_mode=str(generation.logit_fallback_mode or "error"),
+ scoring_max_candidates=max(1, int(generation.logit_max_candidates)),
+ scoring_min_probability=generation.logit_min_probability,
+ scoring_trace_top_n=max(1, int(generation.logit_trace_top_n)),
+ ),
+ )
+
+
+def _normalize_selection_mode(value: str | None) -> str:
+ normalized = str(value or "generate").strip().lower()
+ return normalized or "generate"
+
+
+__all__ = [
+ "GenerationConfig",
+ "LLMClientConfig",
+ "OpenAIClientConfig",
+ "RequestConfig",
+ "RenderConfig",
+ "RetrieverConfig",
+ "SearchResult",
+ "TransformersClientConfig",
+ "TraversalConfig",
+ "VLLMClientConfig",
+ "runtime_retriever_config_from_config",
+]
diff --git a/jiuwenswarm/symphony/retrieval/service/retriever.py b/jiuwenswarm/symphony/retrieval/service/retriever.py
new file mode 100644
index 0000000000..dff1d81576
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/service/retriever.py
@@ -0,0 +1,667 @@
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Sequence
+
+from ..llm import (
+ LLMClientCapabilities,
+ LLMClientConfig,
+ OpenAICompatibleClient,
+ OpenAIClientConfig,
+ ProgressiveLLMClient,
+ TransformersClientConfig,
+ VLLMClientConfig,
+ coerce_generation_client,
+ create_progressive_client,
+ progressive_client_cache_key,
+)
+from ..llm.transformers_prefix_cached_generation import warmup_progressive_prefix_cache
+from ..tree.progressive import ProgressiveRetriever
+
+from .defaults import serialize_trace_event
+from .models import (
+ RequestConfig,
+ RetrieverConfig,
+ SearchResult,
+ _RuntimeRetrieverConfig,
+ runtime_retriever_config_from_config,
+)
+
+from ..io.loading import LoadedRetrieverIndex, load_retriever_index
+
+LOGGER = logging.getLogger("retriever")
+
+
+class _UnavailableProgressiveLLMClient(ProgressiveLLMClient):
+ name = "unavailable"
+
+ @property
+ def capabilities(self) -> LLMClientCapabilities:
+ return LLMClientCapabilities(completion=False, streaming=False, candidate_scoring=False)
+
+ def complete(self, *args, **kwargs):
+ raise RuntimeError("LLM completion client is unavailable for generation fallback")
+
+
+class Retriever:
+ """Unified online retrieval API."""
+
+ def __init__(
+ self,
+ *,
+ loaded_index: LoadedRetrieverIndex,
+ config: RetrieverConfig | None = None,
+ llm: ProgressiveLLMClient | None = None,
+ llm_model: str = "",
+ debug_event_hook: Callable[[Dict[str, object]], None] | None = None,
+ prefix_audit_hook: Callable[[str, str, List[Dict[str, str]]], None] | None = None,
+ before_llm_call_hook: Callable[[], None] | None = None,
+ ) -> None:
+ self._loaded_index = loaded_index
+ configured_llm, configured_model = _llm_from_retriever_config(config)
+ self._config = _coerce_retriever_config(config)
+ self._llm = llm if llm is not None else configured_llm
+ self._llm_model = str(llm_model or configured_model or "").strip()
+ self._debug_event_hook = debug_event_hook
+ self._prefix_audit_hook = prefix_audit_hook
+ self._before_llm_call_hook = before_llm_call_hook
+ self._progressive_runtime_cache: dict[tuple[object, ...], ProgressiveLLMClient] = {}
+ self._progressive_retriever_cache: dict[tuple[object, ...], ProgressiveRetriever] = {}
+ self._public_name_by_payload: dict[str, str] = {}
+ self._public_name_by_choice_id: dict[str, str] = {}
+ self._description_by_payload: dict[str, str] = {}
+ self._description_by_choice_id: dict[str, str] = {}
+ self._worker_id_by_payload: dict[str, str] = {}
+ self._worker_id_by_choice_id: dict[str, str] = {}
+ for record in self._loaded_index.catalog_records:
+ payload = str(getattr(record, "payload", "") or getattr(record, "cid", "") or "").strip()
+ choice_id = str(
+ getattr(record, "choice_id", "")
+ or getattr(record, "worker_id", "")
+ or getattr(record, "skill_id", "")
+ or ""
+ ).strip()
+ metadata = getattr(record, "metadata", {}) or {}
+ worker_id = str(getattr(record, "worker_id", "") or "").strip()
+ if not worker_id and isinstance(metadata, dict):
+ worker_id = str(metadata.get("worker_id") or "").strip()
+ public_name = str(getattr(record, "name", "") or choice_id or payload).strip()
+ description = str(getattr(record, "description", "") or "").strip()
+ if payload:
+ self._public_name_by_payload[payload] = public_name or payload
+ self._worker_id_by_payload[payload] = worker_id or payload
+ if description:
+ self._description_by_payload[payload] = description
+ if choice_id:
+ self._public_name_by_choice_id[choice_id] = public_name or choice_id
+ self._worker_id_by_choice_id[choice_id] = worker_id or choice_id
+ if description:
+ self._description_by_choice_id[choice_id] = description
+
+ def _record_debug_event(self, event: Dict[str, object]) -> None:
+ if self._debug_event_hook is None:
+ return
+ try:
+ self._debug_event_hook(dict(event))
+ except Exception as exc:
+ LOGGER.debug("debug event hook failed: %s", exc)
+
+ def _emit_runtime_event(self, **event: object) -> None:
+ self._record_debug_event({"type": "progressive_runtime", **event})
+
+ def _progressive_unavailable_reason(self, runtime_config: _RuntimeRetrieverConfig | None = None) -> str | None:
+ if runtime_config is None:
+ return "llm client is unavailable"
+ progressive = runtime_config.progressive
+ if _progressive_fixed_prefix_cache_requested(progressive):
+ if not bool(_progressive_local_model_path(progressive)):
+ return "progressive prefix-cached generation model path is empty"
+ return None
+ if self._llm is not None and bool(self._llm_model) and self._llm.capabilities.completion:
+ return None
+ if not _progressive_logit_selection_enabled(progressive):
+ return "llm client is unavailable and progressive logit selection is disabled"
+ if not bool(progressive.compact_boundary_codes_enabled):
+ return "llm client is unavailable and compact boundary codes are disabled"
+ generation_fallback_requested = str(progressive.scoring_fallback_mode or "error").strip().lower() == "generate"
+ completion_client_unavailable = (
+ self._llm is None or not bool(self._llm_model) or not self._llm.capabilities.completion
+ )
+ if generation_fallback_requested and completion_client_unavailable:
+ return "llm client is unavailable and progressive scoring fallback mode is generate"
+ if not bool(_progressive_local_model_path(progressive)):
+ return "llm client is unavailable and progressive local model path is empty"
+ return None
+
+ def _emit_fallback_event(
+ self,
+ *,
+ requested_method: str,
+ fallback_method: str,
+ reason: str,
+ ) -> None:
+ self._record_debug_event(
+ {
+ "type": "retriever_fallback",
+ "requested_method": str(requested_method or ""),
+ "fallback_method": str(fallback_method or ""),
+ "reason": str(reason or "").strip(),
+ }
+ )
+
+ @classmethod
+ def from_index(
+ cls,
+ index_dir: str | Path,
+ *,
+ config: RetrieverConfig | None = None,
+ llm_openai_client: Any | None = None,
+ llm_model: str = "",
+ debug_event_hook: Callable[[Dict[str, object]], None] | None = None,
+ prefix_audit_hook: Callable[[str, str, List[Dict[str, str]]], None] | None = None,
+ before_llm_call_hook: Callable[[], None] | None = None,
+ ) -> "Retriever":
+ loaded_index = load_retriever_index(index_dir)
+ return cls(
+ loaded_index=loaded_index,
+ config=config,
+ llm=_coerce_llm_client(llm_openai_client),
+ llm_model=str(llm_model or "").strip(),
+ debug_event_hook=debug_event_hook,
+ prefix_audit_hook=prefix_audit_hook,
+ before_llm_call_hook=before_llm_call_hook,
+ )
+
+ def search(self, query: str, *, search_config: RequestConfig | None = None) -> List[str]:
+ return list(self.search_details(query, search_config=search_config).payloads)
+
+ def close(self) -> None:
+ clients: list[object] = list(self._progressive_runtime_cache.values())
+ if self._llm is not None:
+ clients.append(self._llm)
+ seen: set[int] = set()
+ for client in clients:
+ client_id = id(client)
+ if client_id in seen:
+ continue
+ seen.add(client_id)
+ close = getattr(client, "close", None)
+ if not callable(close):
+ continue
+ try:
+ close()
+ except Exception:
+ LOGGER.exception("failed to close retriever llm client")
+ self._progressive_runtime_cache.clear()
+ self._progressive_retriever_cache.clear()
+
+ def search_details(
+ self,
+ query: str | Sequence[Dict[str, str]],
+ *,
+ search_config: RequestConfig | None = None,
+ ) -> SearchResult:
+ runtime_config = self._config
+ request_top_k = _resolve_request_top_k(runtime_config=runtime_config, search_config=search_config)
+ _validate_search_request_config(runtime_config=runtime_config, request_top_k=request_top_k)
+ result = self._search_progressive(
+ query=query,
+ top_k=request_top_k,
+ runtime_config=runtime_config,
+ )
+ return self._trim_public_search_result(self._publicize_search_result(result), top_k=request_top_k)
+
+ def _can_run_progressive(self, runtime_config: _RuntimeRetrieverConfig | None = None) -> bool:
+ return self._progressive_unavailable_reason(runtime_config) is None
+
+ @staticmethod
+ def _build_scored_candidate_records(*, hits: Sequence[object], source: str) -> List[Dict[str, object]]:
+ return [
+ {
+ "rank": int(getattr(hit, "rank", 0) or 0),
+ "raw_output": str(getattr(hit, "choice_id", "") or ""),
+ "resolved_payload": str(getattr(hit, "payload", "") or ""),
+ "valid": True,
+ "selected": int(getattr(hit, "rank", 0) or 0) == 1,
+ "choice_id": str(getattr(hit, "choice_id", "") or ""),
+ "description": str(getattr(hit, "description", "") or ""),
+ "score": float(getattr(hit, "score", 0.0) or 0.0),
+ "source": str(source or "unknown"),
+ }
+ for hit in hits
+ ]
+
+ @staticmethod
+ def _normalize_candidate_records(
+ candidate_records: Sequence[Dict[str, object]],
+ *,
+ source: str,
+ ) -> List[Dict[str, object]]:
+ normalized: List[Dict[str, object]] = []
+ for index, item in enumerate(candidate_records, start=1):
+ record = dict(item)
+ record["rank"] = max(1, int(record.get("rank") or index))
+ record["raw_output"] = str(record.get("raw_output") or record.get("choice_id") or "")
+ record["resolved_payload"] = str(record.get("resolved_payload") or "")
+ record["valid"] = bool(record.get("valid", True))
+ record["selected"] = bool(record.get("selected", False))
+ record["choice_id"] = str(record.get("choice_id") or record["raw_output"] or "")
+ record.setdefault("score", None)
+ record["source"] = str(record.get("source") or source or "unknown")
+ normalized.append(record)
+ return normalized
+
+ def _search_progressive(
+ self,
+ *,
+ query: str | Sequence[Dict[str, str]],
+ top_k: int,
+ runtime_config: _RuntimeRetrieverConfig,
+ ) -> SearchResult:
+ backend_name = _progressive_search_backend_name(runtime_config.progressive)
+ LOGGER.info(
+ "progressive search started top_k=%d backend=%s logit_selection=%s",
+ int(top_k),
+ backend_name,
+ _progressive_logit_selection_enabled(runtime_config.progressive),
+ )
+ self._emit_runtime_event(
+ phase="search_started",
+ backend=backend_name,
+ top_k=int(top_k),
+ logit_selection_enabled=_progressive_logit_selection_enabled(runtime_config.progressive),
+ )
+ if not self._can_run_progressive(runtime_config):
+ reason = self._progressive_unavailable_reason(runtime_config) or "unknown reason"
+ raise RuntimeError(f"progressive retrieval is unavailable: {reason}")
+ try:
+ progressive_client = self._get_progressive_client(runtime_config)
+ except Exception as exc:
+ LOGGER.exception("progressive runtime initialization failed")
+ self._emit_runtime_event(
+ phase="runtime_init_failed",
+ backend=backend_name,
+ error=str(exc),
+ )
+ raise RuntimeError(f"progressive runtime initialization failed: {exc}") from exc
+ if progressive_client is None:
+ progressive_client = _UnavailableProgressiveLLMClient()
+ retriever = self._get_progressive_retriever(
+ progressive_client=progressive_client,
+ runtime_config=runtime_config,
+ root=self._loaded_index.tree_root,
+ )
+ result = retriever.search(
+ model=_progressive_model_name(self._llm_model, runtime_config.progressive),
+ query=query,
+ root=self._loaded_index.tree_root,
+ top_k=top_k,
+ before_llm_call_hook=self._before_llm_call_hook,
+ )
+ LOGGER.info(
+ "progressive search completed backend=%s hits=%d elapsed_ms=%.2f",
+ backend_name,
+ len(result.candidates),
+ float(result.elapsed_ms),
+ )
+ self._emit_runtime_event(
+ phase="search_completed",
+ backend=backend_name,
+ candidate_count=len(result.candidates),
+ elapsed_ms=float(result.elapsed_ms),
+ )
+ candidate_records = self._normalize_candidate_records(result.candidate_records, source="progressive")
+ return SearchResult(
+ method="progressive",
+ payloads=[candidate.payload for candidate in result.candidates],
+ candidate_records=candidate_records,
+ summary_lines=list(result.summary_lines),
+ selected_payload=result.selected_payload,
+ selected_rank=result.selected_rank,
+ elapsed_ms=float(result.elapsed_ms),
+ trace_events=[serialize_trace_event(event) for event in result.trace.events],
+ )
+
+ def _get_progressive_retriever(
+ self,
+ *,
+ progressive_client: ProgressiveLLMClient,
+ runtime_config: _RuntimeRetrieverConfig,
+ root: object,
+ ) -> ProgressiveRetriever:
+ cache_key = (
+ id(progressive_client),
+ id(runtime_config.progressive),
+ id(root),
+ id(self._debug_event_hook),
+ )
+ cached = self._progressive_retriever_cache.get(cache_key)
+ if cached is not None:
+ return cached
+ retriever = ProgressiveRetriever(
+ llm=progressive_client,
+ config=runtime_config.progressive,
+ debug_event_hook=self._debug_event_hook,
+ )
+ retriever.prepare_root(
+ root=root,
+ top_k=runtime_config.progressive.top_k,
+ )
+ self._progressive_retriever_cache[cache_key] = retriever
+ return retriever
+
+ def _get_progressive_client(self, runtime_config: _RuntimeRetrieverConfig) -> ProgressiveLLMClient | None:
+ progressive = runtime_config.progressive
+ cache_key = progressive_client_cache_key(progressive)
+ if cache_key is None:
+ return self._llm
+ backend_name, model_path, tokenizer_path = _progressive_runtime_log_identity(progressive)
+ cached = self._progressive_runtime_cache.get(cache_key)
+ if cached is not None:
+ LOGGER.info("progressive runtime cache hit backend=%s model=%s", backend_name, model_path)
+ self._emit_runtime_event(
+ phase="runtime_cache_hit",
+ backend=backend_name,
+ model_path=model_path,
+ tokenizer_path=tokenizer_path,
+ )
+ return cached
+ LOGGER.info("progressive runtime initializing backend=%s model=%s", backend_name, model_path)
+ self._emit_runtime_event(
+ phase="runtime_initializing",
+ backend=backend_name,
+ model_path=model_path,
+ tokenizer_path=tokenizer_path,
+ )
+ client = create_progressive_client(generation_client=self._llm, config=progressive)
+ if client is None:
+ return self._llm
+ if bool(client.capabilities.progressive_prefix_kv_cache):
+ warmup_result = warmup_progressive_prefix_cache(
+ client=client,
+ root=self._loaded_index.tree_root,
+ config=progressive,
+ )
+ self._emit_runtime_event(
+ phase="prefix_cache_warmup_completed",
+ attempted=int(warmup_result.attempted),
+ prepared=int(warmup_result.prepared),
+ skipped=int(warmup_result.skipped),
+ )
+ self._progressive_runtime_cache[cache_key] = client
+ LOGGER.info("progressive runtime ready backend=%s model=%s", backend_name, model_path)
+ self._emit_runtime_event(
+ phase="runtime_ready",
+ backend=backend_name,
+ model_path=model_path,
+ tokenizer_path=tokenizer_path,
+ )
+ return client
+
+ def _public_name_for(self, *, payload: object = "", choice_id: object = "", fallback: object = "") -> str:
+ payload_text = str(payload or "").strip()
+ choice_id_text = str(choice_id or "").strip()
+ fallback_text = str(fallback or "").strip()
+ if payload_text and payload_text in self._public_name_by_payload:
+ return str(self._public_name_by_payload[payload_text]).strip() or payload_text
+ if choice_id_text and choice_id_text in self._public_name_by_choice_id:
+ return str(self._public_name_by_choice_id[choice_id_text]).strip() or choice_id_text
+ if fallback_text and fallback_text in self._public_name_by_choice_id:
+ return str(self._public_name_by_choice_id[fallback_text]).strip() or fallback_text
+ if fallback_text and fallback_text in self._public_name_by_payload:
+ return str(self._public_name_by_payload[fallback_text]).strip() or fallback_text
+ return fallback_text or choice_id_text or payload_text
+
+ def _worker_id_for(self, *, payload: object = "", choice_id: object = "", fallback: object = "") -> str:
+ payload_text = str(payload or "").strip()
+ choice_id_text = str(choice_id or "").strip()
+ fallback_text = str(fallback or "").strip()
+ if payload_text and payload_text in self._worker_id_by_payload:
+ return str(self._worker_id_by_payload[payload_text]).strip() or payload_text
+ if choice_id_text and choice_id_text in self._worker_id_by_choice_id:
+ return str(self._worker_id_by_choice_id[choice_id_text]).strip() or choice_id_text
+ if fallback_text and fallback_text in self._worker_id_by_choice_id:
+ return str(self._worker_id_by_choice_id[fallback_text]).strip() or fallback_text
+ if fallback_text and fallback_text in self._worker_id_by_payload:
+ return str(self._worker_id_by_payload[fallback_text]).strip() or fallback_text
+ return fallback_text or payload_text or choice_id_text
+
+ def _publicize_candidate_record(self, record: Dict[str, object]) -> Dict[str, object]:
+ public_record = dict(record)
+ resolved_payload = str(record.get("resolved_payload") or "").strip()
+ choice_id = str(record.get("choice_id") or "").strip()
+ raw_output = str(record.get("raw_output") or "").strip()
+ public_name = self._public_name_for(payload=resolved_payload, choice_id=choice_id, fallback=raw_output)
+ worker_id = self._worker_id_for(
+ payload=resolved_payload,
+ choice_id=choice_id,
+ fallback=resolved_payload or raw_output,
+ )
+ description = (
+ str(self._description_by_payload.get(resolved_payload, "")).strip()
+ or str(self._description_by_choice_id.get(choice_id, "")).strip()
+ or str(record.get("description") or "").strip()
+ )
+ if resolved_payload:
+ public_record["resolved_cid"] = resolved_payload
+ public_record["resolved_payload"] = worker_id
+ if choice_id:
+ public_record["choice_id"] = self._public_name_for(
+ payload=resolved_payload, choice_id=choice_id, fallback=choice_id
+ )
+ if raw_output and (raw_output == resolved_payload or raw_output == choice_id):
+ public_record["raw_output"] = public_name
+ public_record["skill_name"] = public_name
+ if worker_id:
+ public_record["worker_id"] = worker_id
+ if description:
+ public_record["description"] = description
+ return public_record
+
+ @staticmethod
+ def _build_public_summary_lines(candidate_records: Sequence[Dict[str, object]]) -> List[str]:
+ lines: List[str] = []
+ for index, record in enumerate(candidate_records, start=1):
+ resolved_payload = str(record.get("resolved_payload") or "").strip()
+ raw_output = str(record.get("raw_output") or "").strip()
+ label = resolved_payload or raw_output or "-"
+ source = str(record.get("source") or "unknown").strip() or "unknown"
+ score = record.get("score")
+ if score is None:
+ lines.append(f"{index}. {label} (source={source})")
+ continue
+ try:
+ lines.append(f"{index}. {label} (source={source}, score={float(score):.4f})")
+ except Exception:
+ lines.append(f"{index}. {label} (source={source}, score={score})")
+ return lines
+
+ @staticmethod
+ def _dedupe_public_candidate_records(candidate_records: Sequence[Dict[str, object]]) -> List[Dict[str, object]]:
+ deduped: List[Dict[str, object]] = []
+ seen: set[str] = set()
+ for record in candidate_records:
+ dedupe_key = str(
+ record.get("resolved_payload")
+ or record.get("worker_id")
+ or record.get("skill_name")
+ or record.get("raw_output")
+ or ""
+ ).strip()
+ if not dedupe_key or dedupe_key in seen:
+ continue
+ seen.add(dedupe_key)
+ deduped.append(dict(record))
+ for index, record in enumerate(deduped, start=1):
+ record["rank"] = index
+ record["selected"] = index == 1
+ return deduped
+
+ @staticmethod
+ def _trim_public_search_result(result: SearchResult, *, top_k: int) -> SearchResult:
+ resolved_top_k = max(1, int(top_k))
+ candidate_records = [dict(record) for record in list(result.candidate_records)[:resolved_top_k]]
+ for index, record in enumerate(candidate_records, start=1):
+ record["rank"] = index
+ record["selected"] = index == 1
+ payloads = [
+ str(record.get("resolved_payload") or record.get("worker_id") or record.get("skill_name") or "").strip()
+ for record in candidate_records
+ ]
+ payloads = [payload for payload in payloads if payload]
+ return SearchResult(
+ method=result.method,
+ payloads=payloads,
+ candidate_records=candidate_records,
+ summary_lines=Retriever._build_public_summary_lines(candidate_records),
+ selected_payload=payloads[0] if payloads else None,
+ selected_rank=1 if payloads else -1,
+ elapsed_ms=result.elapsed_ms,
+ trace_events=list(result.trace_events),
+ )
+
+ def _publicize_search_result(self, result: SearchResult) -> SearchResult:
+ candidate_records = [self._publicize_candidate_record(record) for record in result.candidate_records]
+ candidate_records = self._dedupe_public_candidate_records(candidate_records)
+ payloads = [
+ str(record.get("resolved_payload") or record.get("worker_id") or record.get("skill_name") or "").strip()
+ for record in candidate_records
+ ]
+ payloads = [payload for payload in payloads if payload]
+ selected_payload = (
+ payloads[0]
+ if payloads
+ else self._worker_id_for(payload=result.selected_payload or "", fallback=result.selected_payload or "")
+ )
+ return SearchResult(
+ method=result.method,
+ payloads=payloads,
+ candidate_records=candidate_records,
+ summary_lines=self._build_public_summary_lines(candidate_records),
+ selected_payload=selected_payload if selected_payload else None,
+ selected_rank=1 if payloads else result.selected_rank,
+ elapsed_ms=result.elapsed_ms,
+ trace_events=list(result.trace_events),
+ )
+
+
+def _coerce_llm_client(client: Any | None) -> Any | None:
+ return coerce_generation_client(client)
+
+
+def _coerce_retriever_config(config: RetrieverConfig | None) -> _RuntimeRetrieverConfig:
+ if config is None:
+ return runtime_retriever_config_from_config()
+ if isinstance(config, RetrieverConfig):
+ return runtime_retriever_config_from_config(config)
+ raise TypeError(f"Unsupported retriever config type: {type(config).__name__}")
+
+
+def _llm_from_retriever_config(config: object) -> tuple[ProgressiveLLMClient | None, str]:
+ if not isinstance(config, RetrieverConfig):
+ return None, ""
+ llm_client_config = config.llm_client_config
+ if isinstance(llm_client_config, OpenAIClientConfig):
+ raw_client = llm_client_config.client
+ if isinstance(raw_client, ProgressiveLLMClient):
+ return raw_client, str(llm_client_config.model or "").strip()
+ if raw_client is not None:
+ return OpenAICompatibleClient(
+ raw_client,
+ seed=llm_client_config.seed,
+ extra_body=llm_client_config.extra_body,
+ ), str(llm_client_config.model or "").strip()
+ if str(llm_client_config.api_key or "").strip() or str(llm_client_config.base_url or "").strip():
+ try:
+ from openai import OpenAI
+ except ImportError as exc:
+ raise RuntimeError("openai package is required to create an OpenAI-compatible client") from exc
+ raw_client = OpenAI(
+ api_key=str(llm_client_config.api_key or "").strip() or None,
+ base_url=str(llm_client_config.base_url or "").strip() or None,
+ )
+ return OpenAICompatibleClient(
+ raw_client,
+ seed=llm_client_config.seed,
+ extra_body=llm_client_config.extra_body,
+ ), str(llm_client_config.model or "").strip()
+ return None, str(llm_client_config.model or "").strip()
+ return None, ""
+
+
+def _resolve_request_top_k(*, runtime_config: _RuntimeRetrieverConfig, search_config: RequestConfig | None) -> int:
+ if search_config is not None and not isinstance(search_config, RequestConfig):
+ raise TypeError(f"search_config must be RequestConfig, got {type(search_config).__name__}")
+ if search_config is None or search_config.top_k is None:
+ return max(1, int(runtime_config.top_k))
+ return max(1, int(search_config.top_k))
+
+
+def _validate_search_request_config(*, runtime_config: _RuntimeRetrieverConfig, request_top_k: int) -> None:
+ initialized_top_k = max(1, int(runtime_config.top_k))
+ if request_top_k == initialized_top_k:
+ return
+ if _progressive_fixed_prefix_cache_requested(runtime_config.progressive):
+ raise ValueError(
+ "search-time top_k override is not supported with progressive fixed-prefix cache; "
+ "initialize the retriever with the target top_k so prefix caches are prepared deterministically"
+ )
+
+
+def _progressive_fixed_prefix_cache_requested(config: Any) -> bool:
+ backend = _progressive_client_backend(config)
+ return backend in {"transformers_prefix_cached", "transformers_prefix_cached_generation", "vllm", "local_vllm"}
+
+
+def _progressive_model_name(llm_model: str, config: Any) -> str:
+ return _progressive_local_model_path(config) or str(llm_model or "").strip()
+
+
+def _progressive_runtime_log_identity(config: Any) -> tuple[str, str, str]:
+ backend = _progressive_client_backend(config)
+ model_path = _progressive_local_model_path(config)
+ tokenizer_path = _progressive_local_tokenizer_path(config)
+ if model_path:
+ return backend, model_path, tokenizer_path
+ llm_config = _progressive_llm_client_config(config)
+ return backend, str(getattr(llm_config, "model", "") or "").strip(), ""
+
+
+def _progressive_search_backend_name(config: Any) -> str:
+ backend = _progressive_client_backend(config)
+ if backend in {"transformers_prefix_cached", "transformers_prefix_cached_generation", "vllm", "local_vllm"}:
+ return backend
+ if _progressive_logit_selection_enabled(config):
+ return backend or "logit_selection"
+ return backend or "generate"
+
+
+def _progressive_logit_selection_enabled(config: Any) -> bool:
+ return str(getattr(config, "selection_mode", "") or "").strip().lower() == "logit_selection"
+
+
+def _progressive_llm_client_config(config: Any) -> LLMClientConfig:
+ llm_config = getattr(config, "llm_client_config", None)
+ if isinstance(llm_config, (OpenAIClientConfig, TransformersClientConfig, VLLMClientConfig)):
+ return llm_config
+ return OpenAIClientConfig()
+
+
+def _progressive_client_backend(config: Any) -> str:
+ llm_config = _progressive_llm_client_config(config)
+ return str(getattr(llm_config, "backend", "openai") or "openai").strip().lower() or "openai"
+
+
+def _progressive_local_model_path(config: Any) -> str:
+ llm_config = _progressive_llm_client_config(config)
+ return str(getattr(llm_config, "model_path", "") or "").strip()
+
+
+def _progressive_local_tokenizer_path(config: Any) -> str:
+ llm_config = _progressive_llm_client_config(config)
+ model_path = _progressive_local_model_path(config)
+ return str(getattr(llm_config, "tokenizer_path", "") or model_path).strip()
+
+
+__all__ = ["Retriever"]
diff --git a/jiuwenswarm/symphony/retrieval/tree/__init__.py b/jiuwenswarm/symphony/retrieval/tree/__init__.py
new file mode 100644
index 0000000000..c5b8bf8635
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/__init__.py
@@ -0,0 +1,24 @@
+from models.retrieval import (
+ RetrieverCandidate,
+ RetrieverItem,
+ RetrieverNode,
+ RetrieverTrace,
+ RetrieverTraceEvent,
+ RetrieverChoice,
+)
+from .flat import FlatRetriever
+from .progressive import ProgressiveRetriever
+from .types import ProgressiveRetrieverConfig, ProgressiveRetrieverResult
+
+__all__ = [
+ "FlatRetriever",
+ "RetrieverCandidate",
+ "RetrieverItem",
+ "RetrieverNode",
+ "RetrieverTrace",
+ "RetrieverTraceEvent",
+ "ProgressiveRetriever",
+ "ProgressiveRetrieverConfig",
+ "ProgressiveRetrieverResult",
+ "RetrieverChoice",
+]
diff --git a/jiuwenswarm/symphony/retrieval/tree/codebooks.py b/jiuwenswarm/symphony/retrieval/tree/codebooks.py
new file mode 100644
index 0000000000..c36f722813
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/codebooks.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+# Single-token uppercase pair codes for qwen3.5-35b tokenizer.
+# The order is a stable hash order selected by offline retrieval experiments.
+DEFAULT_COMPACT_BOUNDARY_CODEBOOK: tuple[str, ...] = (
+ 'IU', 'BK', 'OE', 'NW', 'MU', 'AO', 'HB', 'IW', 'MA', 'VS', 'NI', 'XS', 'NE', 'BH', 'HP', 'RP',
+ 'UC', 'PB', 'LI', 'UK', 'CF', 'PW', 'WO', 'CO', 'MI', 'ON', 'FS', 'GM', 'CH', 'OA', 'NV', 'AD',
+ 'VC', 'MR', 'TB', 'KA', 'ZH', 'ZR', 'IM', 'HA', 'MO', 'PH', 'VV', 'CN', 'RA', 'DV', 'ST', 'UY',
+ 'BA', 'DN', 'IA', 'SZ', 'EA', 'LY', 'AC', 'JK', 'WD', 'MY', 'BY', 'XL', 'FM', 'LU', 'WX', 'NF',
+ 'BM', 'MP', 'SV', 'MN', 'SX', 'BT', 'ZX', 'GU', 'HO', 'AB', 'VM', 'TA', 'QC', 'IK', 'ME', 'JU',
+ 'LL', 'YA', 'LB', 'KN', 'TV', 'NQ', 'EX', 'FK', 'DK', 'PS', 'TD', 'RL', 'GV', 'FH', 'EP', 'NT',
+ 'BP', 'ZE', 'KC', 'ZO', 'TS', 'NL', 'ZI', 'KD', 'AS', 'OX', 'JP', 'MH', 'GG', 'HC', 'SM', 'BV',
+ 'AL', 'NN', 'CI', 'FN', 'UB', 'AA', 'CL', 'UM', 'KI', 'TO', 'PY', 'QB', 'ZF', 'ND', 'QP', 'NS',
+ 'KV', 'LK', 'UF', 'IV', 'GT', 'CD', 'SD', 'HG', 'RB', 'CY', 'GP', 'DL', 'WG', 'EL', 'VF', 'WK',
+ 'WT', 'HR', 'JJ', 'NR', 'QH', 'CC', 'DY', 'CG', 'QU', 'MF', 'OF', 'VL', 'PE', 'DF', 'FE', 'JS',
+ 'KL', 'UG', 'QG', 'YL', 'MJ', 'DO', 'ML', 'FP', 'JB', 'UE', 'FB', 'AV', 'MG', 'KT', 'CW', 'UI',
+ 'AK', 'OI', 'CX', 'EC', 'SP', 'FR', 'FY', 'RH', 'IH', 'IO', 'WM', 'QL', 'US', 'HF', 'LF', 'VR',
+ 'BL', 'PU', 'SC', 'MT', 'DU', 'IF', 'PF', 'QQ', 'AI', 'RJ', 'LO', 'LC', 'GA', 'PL', 'OP', 'WF',
+ 'TX', 'BW', 'HX', 'UD', 'XB', 'YG', 'LT', 'DW', 'MZ', 'SU', 'HT', 'PJ', 'DA', 'VA', 'IQ', 'JA',
+ 'PX', 'KB', 'GE', 'EB', 'AF', 'LG', 'GC', 'XE', 'OT', 'TG', 'OB', 'PD', 'IB', 'JI', 'BD', 'XR',
+ 'GR', 'HQ', 'WB', 'FC', 'KO', 'KH', 'GO', 'RV', 'BF', 'EU', 'SE', 'RO', 'YZ', 'GY', 'OS', 'TY',
+ 'ID', 'EG', 'UA', 'OR', 'BC', 'SO', 'PR', 'HK', 'XI', 'RN', 'MK', 'ZY', 'FG', 'GX', 'DX', 'EM',
+ 'FA', 'IS', 'TI', 'TU', 'PI', 'UP', 'LP', 'IR', 'EI', 'VB', 'TH', 'FU', 'TC', 'HU', 'BU', 'NU',
+ 'LR', 'SS', 'IJ', 'LA', 'PN', 'TW', 'BS', 'KG', 'CV', 'SF', 'ER', 'MM', 'AZ', 'MV', 'OD', 'LE',
+ 'MS', 'JE', 'TK', 'MQ', 'CA', 'EW', 'VO', 'XA', 'CM', 'TN', 'UN', 'RR', 'UL', 'RY', 'YW', 'FX',
+ 'OK', 'GW', 'HI', 'NM', 'EZ', 'SI', 'IZ', 'SA', 'DR', 'QA', 'JO', 'HN', 'QN', 'HZ', 'MX', 'PK',
+ 'FI', 'DC', 'RD', 'QS', 'WL', 'AJ', 'VP', 'UV', 'BB', 'AY', 'YN', 'NK', 'UR', 'OM', 'DG', 'XD',
+ 'NY', 'XM', 'DT', 'KF', 'JC', 'KR', 'TL', 'RI', 'YM', 'EN', 'OU', 'RS', 'DB', 'LD', 'NG', 'AM',
+ 'JT', 'NB', 'BJ', 'OL', 'UT', 'HD', 'WA', 'IE', 'II', 'KS', 'YP', 'VE', 'BR', 'RW', 'AU', 'SQ',
+ 'JV', 'HW', 'CS', 'IL', 'UU', 'DJ', 'SW', 'AQ', 'JM', 'TE', 'EO', 'LS', 'SB', 'CU', 'QR', 'SH',
+ 'WN', 'DH', 'ZN', 'LN', 'AW', 'SL', 'DI', 'KY', 'EF', 'ES', 'KW', 'XC', 'OV', 'CK', 'DD', 'IN',
+ 'WS', 'KE', 'PP', 'RU', 'UH', 'EH', 'RE', 'MC', 'ZA', 'SN', 'WW', 'HY', 'OW', 'BE', 'OG', 'AH',
+ 'BN', 'QE', 'NP', 'RC', 'ZZ', 'QM', 'BX', 'CT', 'WR', 'SG', 'TR', 'BI', 'MB', 'ED', 'RX', 'SJ',
+ 'NA', 'OC', 'DP', 'NO', 'JD', 'FO', 'FL', 'HH', 'FW', 'TT', 'QT', 'NZ', 'CR', 'AG', 'HL', 'TF',
+ 'VN', 'SK', 'YO', 'LV', 'GI', 'VI', 'SR', 'YT', 'CB', 'HE', 'KP', 'XT', 'PG', 'RG', 'JR', 'TP',
+ 'HM', 'AR', 'MW', 'BG', 'HS', 'AP', 'GF', 'KM', 'NJ', 'RK', 'YE', 'NX', 'AN', 'XF', 'AX', 'LM',
+ 'PM', 'GB', 'DS', 'IG', 'UX', 'GL', 'GS', 'PT', 'VD', 'FF', 'OO', 'GD', 'XY', 'IC', 'UZ', 'KU',
+)
+
+__all__ = ["DEFAULT_COMPACT_BOUNDARY_CODEBOOK"]
diff --git a/jiuwenswarm/symphony/retrieval/tree/contracts.py b/jiuwenswarm/symphony/retrieval/tree/contracts.py
new file mode 100644
index 0000000000..10597e5861
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/contracts.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+from abc import abstractmethod
+from typing import Protocol, Sequence
+
+from models.retrieval import RetrieverCandidate, RetrieverTrace
+
+from .types import (
+ CurrentSubtree,
+ ExpansionPlan,
+ NodeSearchResult,
+ PromptBundle,
+ SearchCursor,
+ SelectionProtocol,
+ SelectionResult,
+)
+
+
+class CurrentSubtreeProvider(Protocol):
+ @abstractmethod
+ def get_current_subtree(self, *, cursor: SearchCursor) -> CurrentSubtree:
+ raise NotImplementedError
+
+
+class SubtreeRenderer(Protocol):
+ @abstractmethod
+ def render_subtree(
+ self,
+ *,
+ subtree: CurrentSubtree,
+ query_messages: Sequence[dict[str, str]],
+ protocol: SelectionProtocol,
+ ) -> PromptBundle:
+ raise NotImplementedError
+
+
+class TopKSelector(Protocol):
+ @abstractmethod
+ def build_protocol(self, *, subtree: CurrentSubtree) -> SelectionProtocol:
+ raise NotImplementedError
+
+ @abstractmethod
+ def select_topk(
+ self,
+ *,
+ model: str,
+ cursor: SearchCursor,
+ query_messages: Sequence[dict[str, str]],
+ subtree: CurrentSubtree,
+ prompt: PromptBundle,
+ trace: RetrieverTrace,
+ ) -> SelectionResult:
+ raise NotImplementedError
+
+
+class TargetExpander(Protocol):
+ @abstractmethod
+ def expand_selected_targets(
+ self,
+ *,
+ cursor: SearchCursor,
+ selected_targets: Sequence,
+ ) -> ExpansionPlan:
+ raise NotImplementedError
+
+
+class BranchReducer(Protocol):
+ @abstractmethod
+ def reduce_branch_results(
+ self,
+ *,
+ cursor: SearchCursor,
+ local_leaves: Sequence[RetrieverCandidate],
+ child_results: Sequence[NodeSearchResult],
+ ) -> NodeSearchResult:
+ raise NotImplementedError
diff --git a/jiuwenswarm/symphony/retrieval/tree/engine.py b/jiuwenswarm/symphony/retrieval/tree/engine.py
new file mode 100644
index 0000000000..b04ffb3714
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/engine.py
@@ -0,0 +1,160 @@
+from __future__ import annotations
+
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from typing import Sequence
+
+from models.retrieval import RetrieverCandidate, RetrieverTrace
+
+from .contracts import BranchReducer, CurrentSubtreeProvider, SubtreeRenderer, TargetExpander, TopKSelector
+from .types import NodeSearchResult, SearchCursor
+
+
+@dataclass
+class RecursiveSearchEngine:
+ subtree_provider: CurrentSubtreeProvider
+ renderer: SubtreeRenderer
+ selector: TopKSelector
+ expander: TargetExpander
+ reducer: BranchReducer
+ enable_parallel_branches: bool = True
+ max_parallel_branches: int = 3
+
+ def search(
+ self,
+ *,
+ model: str,
+ query_messages: Sequence[dict[str, str]],
+ root_cursor: SearchCursor,
+ trace: RetrieverTrace,
+ ) -> list[RetrieverCandidate]:
+ result = self._search_node(
+ model=model,
+ query_messages=query_messages,
+ cursor=root_cursor,
+ trace=trace,
+ )
+ return list(result.candidates)
+
+ def _search_node(
+ self,
+ *,
+ model: str,
+ query_messages: Sequence[dict[str, str]],
+ cursor: SearchCursor,
+ trace: RetrieverTrace,
+ ) -> NodeSearchResult:
+ subtree = self.subtree_provider.get_current_subtree(cursor=cursor)
+ trace.record(
+ "fragment_built",
+ node_id=cursor.node.node_id,
+ depth=cursor.depth,
+ detail={
+ "selectable_count": len(subtree.selectable_targets),
+ "rendered_tree": subtree.fragment.rendered_tree,
+ },
+ )
+ if not subtree.selectable_targets:
+ return NodeSearchResult(candidates=())
+ if len(subtree.selectable_targets) == 1:
+ only = subtree.selectable_targets[0]
+ trace.record(
+ "fragment_selected",
+ node_id=cursor.node.node_id,
+ depth=cursor.depth,
+ detail={
+ "mode": "single_selectable_shortcut",
+ "selected_codes": [only.resolution.code],
+ "selected_canonical_ids": [only.resolution.canonical_id],
+ },
+ )
+ plan = self.expander.expand_selected_targets(cursor=cursor, selected_targets=subtree.selectable_targets)
+ return self._continue(cursor=cursor, trace=trace, model=model, query_messages=query_messages, plan=plan)
+
+ protocol = self.selector.build_protocol(subtree=subtree)
+ prompt = self.renderer.render_subtree(subtree=subtree, query_messages=query_messages, protocol=protocol)
+ selection = self.selector.select_topk(
+ model=model,
+ cursor=cursor,
+ query_messages=query_messages,
+ subtree=subtree,
+ prompt=prompt,
+ trace=trace,
+ )
+ trace.record(
+ "fragment_selected",
+ node_id=cursor.node.node_id,
+ depth=cursor.depth,
+ detail={
+ "selected_codes": [item.resolution.code for item in selection.selected_targets],
+ "selected_canonical_ids": [item.resolution.canonical_id for item in selection.selected_targets],
+ "raw_output": selection.raw_output,
+ },
+ )
+ if selection.is_abstain or not selection.selected_targets:
+ return NodeSearchResult(candidates=())
+ plan = self.expander.expand_selected_targets(cursor=cursor, selected_targets=selection.selected_targets)
+ return self._continue(cursor=cursor, trace=trace, model=model, query_messages=query_messages, plan=plan)
+
+ def _continue(
+ self,
+ *,
+ cursor: SearchCursor,
+ trace: RetrieverTrace,
+ model: str,
+ query_messages: Sequence[dict[str, str]],
+ plan,
+ ) -> NodeSearchResult:
+ trace.record(
+ "fragment_continue",
+ node_id=cursor.node.node_id,
+ depth=cursor.depth,
+ detail={
+ "leaf_count": len(plan.leaf_results),
+ "branch_count": len(plan.child_cursors),
+ "selected_terminal_ids": [item.item_id for item in plan.leaf_results],
+ "selected_branch_ids": [child.cursor.node.node_id for child in plan.child_cursors],
+ },
+ )
+ child_results: list[NodeSearchResult] = []
+ if plan.child_cursors:
+ if len(plan.child_cursors) > 1 and self.enable_parallel_branches:
+ max_workers = min(len(plan.child_cursors), max(1, int(self.max_parallel_branches)))
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ futures = [
+ executor.submit(
+ self._search_node,
+ model=model,
+ query_messages=query_messages,
+ cursor=child.cursor,
+ trace=trace,
+ )
+ for child in plan.child_cursors
+ ]
+ for future in futures:
+ child_results.append(future.result())
+ else:
+ for child in plan.child_cursors:
+ child_results.append(
+ self._search_node(
+ model=model,
+ query_messages=query_messages,
+ cursor=child.cursor,
+ trace=trace,
+ )
+ )
+ reduced = self.reducer.reduce_branch_results(
+ cursor=cursor,
+ local_leaves=plan.leaf_results,
+ child_results=child_results,
+ )
+ trace.record(
+ "reduce_complete",
+ node_id=cursor.node.node_id,
+ depth=cursor.depth,
+ detail={
+ "input_candidates": len(plan.leaf_results) + sum(len(result.candidates) for result in child_results),
+ "output_candidates": len(reduced.candidates),
+ },
+ )
+ return reduced
diff --git a/jiuwenswarm/symphony/retrieval/tree/expand.py b/jiuwenswarm/symphony/retrieval/tree/expand.py
new file mode 100644
index 0000000000..0c085e32fc
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/expand.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from typing import Sequence
+
+from models.retrieval import RetrieverCandidate
+
+from .contracts import TargetExpander
+from .types import ChildSearchCursor, ExpansionPlan, ProgressiveRetrieverConfig, SearchCursor, SelectableTarget
+
+
+@dataclass(frozen=True)
+class DefaultTargetExpander(TargetExpander):
+ config: ProgressiveRetrieverConfig
+
+ def expand_selected_targets(
+ self,
+ *,
+ cursor: SearchCursor,
+ selected_targets: Sequence[SelectableTarget],
+ ) -> ExpansionPlan:
+ branch_targets = [
+ target for target in selected_targets if not target.is_terminal and target.resolution.node is not None
+ ]
+ branch_top_k = self._resolve_branch_top_k(top_k=cursor.top_k, branch_count=max(1, len(selected_targets)))
+ leaf_results: list[RetrieverCandidate] = []
+ child_cursors: list[ChildSearchCursor] = []
+ for target in selected_targets:
+ resolution = target.resolution
+ if resolution.is_terminal and resolution.item is not None:
+ leaf_results.append(
+ RetrieverCandidate(
+ rank=1,
+ item_id=resolution.item.item_id,
+ payload=resolution.item.payload,
+ branch_path=resolution.branch_path,
+ label=resolution.item.label,
+ description=resolution.item.description,
+ )
+ )
+ continue
+ if resolution.node is None:
+ continue
+ child_cursors.append(
+ ChildSearchCursor(
+ cursor=SearchCursor(
+ node=resolution.node,
+ depth=cursor.depth + 1,
+ branch_path=resolution.branch_path,
+ top_k=branch_top_k,
+ ),
+ target=target,
+ )
+ )
+ return ExpansionPlan(leaf_results=tuple(leaf_results), child_cursors=tuple(child_cursors))
+
+ def _resolve_branch_top_k(self, *, top_k: int, branch_count: int) -> int:
+ if branch_count <= 0:
+ return max(1, int(top_k))
+ slack = max(0, int(self.config.branch_candidate_slack))
+ budget = math.ceil(max(1, int(top_k)) / branch_count) + slack
+ return min(max(1, int(top_k)), max(1, budget))
diff --git a/jiuwenswarm/symphony/retrieval/tree/flat.py b/jiuwenswarm/symphony/retrieval/tree/flat.py
new file mode 100644
index 0000000000..53e62587ed
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/flat.py
@@ -0,0 +1,90 @@
+from __future__ import annotations
+
+from time import perf_counter
+from typing import Callable, Dict, List, Sequence
+
+from models.retrieval import RetrieverChoice, RetrieverItem, RetrieverNode, RetrieverTrace
+
+from .progressive import ProgressiveRetriever, _normalize_query_messages
+from .types import ProgressiveRetrieverResult
+
+
+class FlatRetriever(ProgressiveRetriever):
+ def retrieve_top_k(
+ self,
+ *,
+ model: str,
+ query: str | Sequence[Dict[str, str]],
+ choices: Sequence[RetrieverChoice],
+ resolve_candidate: Callable[[str, Dict[str, str]], str],
+ system_prompt: str,
+ top_k: int | None = None,
+ prefix_audit_hook: Callable[[str, str, List[Dict[str, str]]], None] | None = None,
+ before_llm_call_hook: Callable[[], None] | None = None,
+ ) -> ProgressiveRetrieverResult:
+ started = perf_counter()
+ with self._node_stats_lock:
+ self._node_stats_cache = {}
+ resolved_top_k = max(1, int(top_k if top_k is not None else self._config.top_k))
+ query_messages = _normalize_query_messages(query)
+ messages = [{"role": "system", "content": str(system_prompt or "")}] + query_messages
+ if prefix_audit_hook is not None:
+ prefix_audit_hook("retriever", model, messages)
+ self._record_debug_event(
+ {
+ "type": "progressive_action",
+ "phase": "disclose_candidates",
+ "model": model,
+ "choice_count": len(choices),
+ "top_k": resolved_top_k,
+ "trie_constrained_decoding_enabled": bool(self._config.trie_constrained_decoding_enabled),
+ }
+ )
+ root = RetrieverNode(
+ node_id="flat_root",
+ label="Flat Root",
+ items=tuple(
+ RetrieverItem(
+ item_id=str(choice.choice_id),
+ payload=str(choice.payload),
+ label=str(choice.choice_id),
+ description=str(choice.description or ""),
+ )
+ for choice in choices
+ ),
+ )
+ trace = RetrieverTrace()
+ result = self._select_items(
+ model=model,
+ query_messages=query_messages,
+ node=root,
+ depth=0,
+ top_k=resolved_top_k,
+ trace=trace,
+ branch_path=(root.node_id,),
+ allowed_payloads={str(choice.choice_id): str(choice.payload) for choice in choices},
+ resolve_candidate=resolve_candidate,
+ system_prompt_override=str(system_prompt or ""),
+ before_llm_call_hook=before_llm_call_hook,
+ )
+ trace.record(
+ "search_complete",
+ node_id=root.node_id,
+ depth=0,
+ detail={"candidate_count": len(result.candidates), "top_k": resolved_top_k},
+ )
+ self._record_debug_event(
+ {
+ "type": "progressive_action",
+ "phase": "selection_complete",
+ "model": model,
+ "candidate_count": len(result.candidate_records),
+ "valid_candidate_count": len(result.candidates),
+ "selected_payload": result.selected_payload,
+ "selected_rank": result.selected_rank,
+ }
+ )
+ result.trace = trace
+ result.request_messages = messages
+ result.elapsed_ms = round((perf_counter() - started) * 1000, 2)
+ return result
diff --git a/jiuwenswarm/symphony/retrieval/tree/progressive.py b/jiuwenswarm/symphony/retrieval/tree/progressive.py
new file mode 100644
index 0000000000..0e47689e32
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/progressive.py
@@ -0,0 +1,1579 @@
+from __future__ import annotations
+
+import math
+import re
+import threading
+from concurrent.futures import ThreadPoolExecutor
+import hashlib
+import json
+from dataclasses import dataclass, replace
+from time import perf_counter
+from typing import Any, Callable, Dict, List, Sequence
+
+from models.retrieval import (
+ RetrieverCandidate,
+ RetrieverItem,
+ RetrieverNode,
+ RetrieverTrace,
+ RetrieverTraceEvent,
+ RetrieverChoice,
+)
+from .render.disclosure import (
+ DisclosureConfig,
+ DisclosurePromptParts,
+ ExposedFragment,
+ SelectableResolution,
+ build_disclosure_messages,
+ build_disclosure_prompt_parts,
+ build_exposed_fragment,
+ parse_selected_codes,
+)
+from ..llm import (
+ GenerationConfig,
+ GenerationConstraints,
+ PrefixCacheUnavailable,
+ ProgressiveLLMClient,
+ PromptCacheHint,
+ TrieConstraint,
+ generation_config_to_debug_dict,
+)
+from .select.selection import GenerateFragmentSelector, LogitSelectionFragmentSelector
+from .engine import RecursiveSearchEngine
+from .expand import DefaultTargetExpander
+from .reduce import DefaultBranchReducer
+from .render import DefaultSubtreeRenderer
+from .select import DefaultTopKSelector
+from .subtree import DefaultCurrentSubtreeProvider
+from .types import (
+ ProgressiveRetrieverConfig,
+ ProgressiveRetrieverResult,
+ SearchCursor,
+)
+
+_FROM_PREFIX_RE = re.compile(r"^\s*From\s+[^:]+:\s*", re.IGNORECASE)
+_CAMEL_BOUNDARY_RE = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
+_NON_ALNUM_RE = re.compile(r"[^A-Za-z0-9]+")
+
+
+@dataclass(frozen=True)
+class _RetrieverNodeStats:
+ subtree_item_count: int = 0
+ subtree_depth: int = 0
+
+
+def _scoring_enabled(config: ProgressiveRetrieverConfig) -> bool:
+ return _normalized_selection_mode(config.selection_mode) == "logit_selection"
+
+
+def _normalized_selection_mode(value: str | None) -> str:
+ normalized = str(value or "generate").strip().lower()
+ return normalized or "generate"
+
+
+def _format_sender_message(sender: str, message: str) -> str:
+ text = str(message or "").strip()
+ if not text:
+ return ""
+ if _FROM_PREFIX_RE.match(text):
+ return text
+ sender_text = str(sender or "User").strip() or "User"
+ return f"From {sender_text}: {text}"
+
+
+def _normalize_query_messages(query: str | Sequence[Dict[str, str]]) -> List[Dict[str, str]]:
+ if isinstance(query, str):
+ text = _format_sender_message("User", query)
+ return [{"role": "user", "content": text or "From User: (empty)"}]
+
+ lines: List[str] = []
+ for message in query:
+ if not isinstance(message, dict):
+ continue
+ role = str(message.get("role") or "user").strip().lower()
+ content = str(message.get("content") or "").strip()
+ if not content or role == "system":
+ continue
+ if role == "assistant":
+ sender = "Assistant"
+ elif role == "user":
+ sender = "User"
+ else:
+ sender = role[:1].upper() + role[1:] if role else "Runtime"
+ lines.append(_format_sender_message(sender, content))
+ if not lines:
+ return [{"role": "user", "content": "From User: (empty)"}]
+ return [{"role": "user", "content": "\n".join(lines)}]
+
+
+def _build_node_selection_prompt(*, node: RetrieverNode, top_k: int) -> str:
+ lines = [
+ "You are a retriever that selects the most relevant child branches from the current node.",
+ "Only choose from the direct child categories shown below.",
+ "Do not explain your reasoning.",
+ f"Current node: {node.label} ({node.node_id})",
+ ]
+ if node.description:
+ lines.append(f"Current node description: {node.description}")
+ lines.extend(
+ [
+ "",
+ "Rules:",
+ f"- Select up to {top_k} child categories.",
+ "- Prefer branches that directly match the user's object or task type.",
+ "- Output one node id per line.",
+ "- Only output node ids from the list below.",
+ "- Do not output explanations, JSON, Markdown, or numbering.",
+ "",
+ "Candidate child categories:",
+ ]
+ )
+ for child in node.children:
+ detail = f": {child.description}" if child.description else ""
+ lines.append(f"- {child.node_id} | {child.label}{detail}")
+ return "\n".join(lines)
+
+
+def _build_item_selection_prompt(*, node: RetrieverNode, items: Sequence[RetrieverItem], top_k: int) -> str:
+ lines = [
+ "You are a retriever that selects the most relevant executable items from the current node.",
+ "Only choose from the items shown below.",
+ "Do not explain your reasoning.",
+ f"Current node: {node.label} ({node.node_id})",
+ ]
+ if node.description:
+ lines.append(f"Current node description: {node.description}")
+ lines.extend(
+ [
+ "",
+ "Rules:",
+ f"- Select up to {top_k} items.",
+ "- Prefer the most directly executable items for the user request.",
+ "- Output one item id per line.",
+ "- Only output item ids from the list below.",
+ "- Do not output explanations, JSON, Markdown, or numbering.",
+ "",
+ "Candidate items:",
+ ]
+ )
+ for item in items:
+ label = item.label or item.item_id
+ detail = f": {item.description}" if item.description else ""
+ lines.append(f"- {item.item_id} | {label}{detail}")
+ return "\n".join(lines)
+
+
+@dataclass(frozen=True)
+class _VisibleOption:
+ display_name: str
+ canonical_id: str
+ label: str
+ description: str
+ kind: str
+ prompt_text: str = ""
+
+
+def _path_segments(value: str) -> List[str]:
+ text = str(value or "").strip().replace("/", ".")
+ return [part for part in text.split(".") if part]
+
+
+def _to_pascal_case(value: str) -> str:
+ text = str(value or "").strip()
+ if not text:
+ return ""
+ text = _CAMEL_BOUNDARY_RE.sub("-", text)
+ text = text.replace("_", "-")
+ text = _NON_ALNUM_RE.sub("-", text)
+ text = re.sub(r"-{2,}", "-", text)
+ parts = [part.lower() for part in text.strip("-").split("-") if part]
+ if not parts:
+ return ""
+ return "".join(part[:1].upper() + part[1:] for part in parts)
+
+
+def _encode_boundary_code(index: int, *, width: int) -> str:
+ del width
+ return str(max(0, int(index)) + 1)
+
+
+def _build_compact_boundary_codes(count: int) -> List[str]:
+ if count <= 0:
+ return []
+ return [_encode_boundary_code(index, width=0) for index in range(count)]
+
+
+def _compact_code_generation_max_tokens(top_k: int, *, generated_decimal_codes: bool) -> int:
+ code_token_budget = 8 if generated_decimal_codes else 1
+ return max(1, (code_token_budget + 1) * max(1, int(top_k)) - 1)
+
+
+def _build_visible_options(
+ *,
+ branches: Sequence[RetrieverNode] = (),
+ items: Sequence[RetrieverItem] = (),
+ compact_codes_enabled: bool = False,
+) -> List[_VisibleOption]:
+ raw_entries: List[Dict[str, str]] = []
+ for child in branches:
+ raw_entries.append(
+ {
+ "canonical_id": child.node_id,
+ "label": child.label or child.node_id,
+ "description": child.description or "",
+ "kind": "branch",
+ }
+ )
+ for item in items:
+ canonical_id = item.payload or item.item_id
+ raw_entries.append(
+ {
+ "canonical_id": canonical_id,
+ "label": item.label or canonical_id,
+ "description": item.description or "",
+ "kind": "item",
+ }
+ )
+
+ if not raw_entries:
+ return []
+
+ if compact_codes_enabled:
+ display_names = _build_compact_boundary_codes(len(raw_entries))
+ else:
+ segment_lists = [_path_segments(entry["canonical_id"]) for entry in raw_entries]
+ display_names = [
+ _initial_visible_display_name(entry=entry, segments=segments)
+ for entry, segments in zip(raw_entries, segment_lists)
+ ]
+
+ while len(set(display_names)) < len(display_names):
+ grouped: Dict[str, List[int]] = {}
+ for index, name in enumerate(display_names):
+ grouped.setdefault(name, []).append(index)
+ for indices in grouped.values():
+ if len(indices) <= 1:
+ continue
+ for index in indices:
+ segments = segment_lists[index]
+ if len(segments) > 1:
+ current_depth = len(display_names[index].split("/"))
+ next_depth = min(len(segments), current_depth + 1)
+ display_names[index] = "/".join(
+ (_to_pascal_case(segment) or segment)
+ for segment in segments[-next_depth:]
+ )
+ else:
+ display_names[index] = f"{display_names[index]}__{index + 1}"
+
+ options: List[_VisibleOption] = []
+ for entry, display_name in zip(raw_entries, display_names):
+ prompt_text = f"- {display_name} | {entry['kind']} | {entry['label']}"
+ if entry["description"]:
+ prompt_text = f"{prompt_text} | {entry['description']}"
+ options.append(
+ _VisibleOption(
+ display_name=display_name,
+ canonical_id=entry["canonical_id"],
+ label=entry["label"],
+ description=entry["description"],
+ kind=entry["kind"],
+ prompt_text=prompt_text,
+ )
+ )
+ return options
+
+
+def _initial_visible_display_name(*, entry: Dict[str, str], segments: Sequence[str]) -> str:
+ fallback = segments[-1] if segments else entry["canonical_id"]
+ return _to_pascal_case(fallback) or fallback
+
+
+def _build_visible_subtree_prompt(
+ *,
+ node: RetrieverNode,
+ options: Sequence[_VisibleOption],
+ top_k: int,
+ compact_codes_enabled: bool,
+) -> str:
+ lines = [
+ "You are a retrieval router.",
+ "You can only see the current visible subtree shown below.",
+ "Select the most relevant visible boundary nodes for the user request.",
+ f"Return at most {top_k} {'codes' if compact_codes_enabled else 'names'}.",
+ f"Output one {'code' if compact_codes_enabled else 'display name'} per line.",
+ f"Only output the {'codes' if compact_codes_enabled else 'display names'} exactly as shown.",
+ "If none are relevant, output 0.",
+ "Do not output explanations, JSON, Markdown, numbering, or full paths.",
+ "",
+ f"Current visible subtree root: {node.label} ({node.node_id})",
+ ]
+ if node.description:
+ lines.append(f"Root description: {node.description}")
+ lines.extend(["", "Visible boundary nodes:"])
+ for option in options:
+ lines.append(option.prompt_text)
+ return "\n".join(lines)
+
+
+def _is_abstain_output(output: str) -> bool:
+ text = str(output or "").strip()
+ return text == "0"
+
+
+class ProgressiveRetriever:
+ def __init__(
+ self,
+ *,
+ llm: ProgressiveLLMClient,
+ config: ProgressiveRetrieverConfig | None = None,
+ debug_event_hook: Any | None = None,
+ ) -> None:
+ self._llm = llm
+ self._config = config or ProgressiveRetrieverConfig()
+ self._debug_event_hook = debug_event_hook
+ self._node_stats_cache: Dict[int, _RetrieverNodeStats] = {}
+ self._node_stats_lock = threading.Lock()
+ self._current_subtree_cache: Dict[tuple[int, tuple[str, ...]], Any] = {}
+ self._current_subtree_cache_lock = threading.Lock()
+
+ def search(
+ self,
+ *,
+ model: str,
+ query: str | Sequence[Dict[str, str]],
+ root: RetrieverNode,
+ top_k: int | None = None,
+ before_llm_call_hook: Callable[[], None] | None = None,
+ ) -> ProgressiveRetrieverResult:
+ started = perf_counter()
+ resolved_top_k = max(1, int(top_k if top_k is not None else self._config.top_k))
+ query_messages = _normalize_query_messages(query)
+ trace = RetrieverTrace()
+ engine = self._build_recursive_search_engine(before_llm_call_hook=before_llm_call_hook)
+ candidates = engine.search(
+ model=model,
+ query_messages=query_messages,
+ root_cursor=SearchCursor(
+ node=root,
+ depth=0,
+ branch_path=(root.node_id,),
+ top_k=resolved_top_k,
+ ),
+ trace=trace,
+ )
+ ranked = [
+ RetrieverCandidate(
+ rank=index,
+ item_id=candidate.item_id,
+ payload=candidate.payload,
+ branch_path=candidate.branch_path,
+ label=candidate.label,
+ description=candidate.description,
+ )
+ for index, candidate in enumerate(self._dedupe_candidates(candidates)[:resolved_top_k], start=1)
+ ]
+ trace.record(
+ "search_complete",
+ node_id=root.node_id,
+ depth=0,
+ detail={"candidate_count": len(ranked), "top_k": resolved_top_k},
+ )
+ return ProgressiveRetrieverResult(
+ candidates=ranked,
+ trace=trace,
+ candidate_records=[
+ {
+ "rank": candidate.rank,
+ "raw_output": candidate.item_id,
+ "resolved_payload": candidate.payload,
+ "valid": True,
+ "selected": candidate.rank == 1,
+ "choice_id": candidate.item_id,
+ }
+ for candidate in ranked
+ ],
+ summary_lines=[
+ f"{candidate.rank}. {candidate.item_id} -> {candidate.payload} (ok)"
+ for candidate in ranked
+ ],
+ selected_payload=ranked[0].payload if ranked else None,
+ selected_rank=ranked[0].rank if ranked else -1,
+ raw_outputs=[],
+ request_messages=query_messages,
+ elapsed_ms=round((perf_counter() - started) * 1000, 2),
+ )
+
+ def prepare_root(self, *, root: RetrieverNode, top_k: int | None = None) -> None:
+ resolved_top_k = max(1, int(top_k if top_k is not None else self._config.top_k))
+ provider = self._build_current_subtree_provider()
+ for node, branch_path in _iter_nodes(root, (root.node_id,)):
+ subtree = provider.get_current_subtree(
+ cursor=SearchCursor(
+ node=node,
+ depth=max(0, len(branch_path) - 1),
+ branch_path=branch_path,
+ top_k=resolved_top_k,
+ )
+ )
+ if subtree.selectable_targets:
+ build_disclosure_prompt_parts(
+ fragment=subtree.fragment,
+ query_messages=(),
+ top_k=resolved_top_k,
+ )
+
+ def _build_recursive_search_engine(
+ self,
+ *,
+ before_llm_call_hook: Callable[[], None] | None = None,
+ ) -> RecursiveSearchEngine:
+ return RecursiveSearchEngine(
+ subtree_provider=self._build_current_subtree_provider(),
+ renderer=DefaultSubtreeRenderer(render_messages=False),
+ selector=DefaultTopKSelector(
+ config=self._config,
+ build_generate_selector=lambda: self._build_fragment_selector(
+ before_llm_call_hook=before_llm_call_hook,
+ ),
+ ),
+ expander=DefaultTargetExpander(config=self._config),
+ reducer=DefaultBranchReducer(config=self._config),
+ enable_parallel_branches=self._parallel_branches_enabled(),
+ max_parallel_branches=max(1, int(self._config.max_parallel_branches)),
+ )
+
+ def _build_current_subtree_provider(self) -> DefaultCurrentSubtreeProvider:
+ return DefaultCurrentSubtreeProvider(
+ config=self._config,
+ subtree_item_count=lambda current: self._analyze_node(current).subtree_item_count,
+ cache=self._current_subtree_cache,
+ cache_lock=self._current_subtree_cache_lock,
+ )
+
+ def _parallel_branches_enabled(self) -> bool:
+ return bool(self._config.enable_parallel_branches) and bool(
+ getattr(self._llm.capabilities, "thread_safe", True)
+ )
+
+ def _search_node(
+ self,
+ *,
+ model: str,
+ query_messages: List[Dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ branch_path: tuple[str, ...],
+ ) -> List[RetrieverCandidate]:
+ fragment = self._build_fragment(node=node, branch_path=branch_path)
+ trace.record(
+ "fragment_built",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "selectable_count": len(fragment.code_to_resolution),
+ "rendered_tree": fragment.rendered_tree,
+ "max_exposure_depth_per_call": int(self._config.max_exposure_depth_per_call),
+ "exposure_threshold": int(self._config.exposure_threshold),
+ },
+ )
+ selectable_resolutions = list(fragment.code_to_resolution.values())
+ if not selectable_resolutions:
+ return []
+ if len(selectable_resolutions) == 1:
+ only = selectable_resolutions[0]
+ trace.record(
+ "fragment_selected",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "mode": "single_selectable_shortcut",
+ "selected_codes": [only.code],
+ "selected_canonical_ids": [only.canonical_id],
+ },
+ )
+ return self._continue_from_resolutions(
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ selected=selectable_resolutions,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ )
+ output, selected = self._select_from_fragment(
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ fragment=fragment,
+ )
+ if not selected and _is_abstain_output(output):
+ trace.record(
+ "fragment_continue",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "selected_codes": [],
+ "selected_terminal_ids": [],
+ "selected_branch_ids": [],
+ "mode": "abstain",
+ },
+ )
+ return []
+ return self._continue_from_resolutions(
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ selected=selected,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ )
+
+ def _build_fragment(
+ self,
+ *,
+ node: RetrieverNode,
+ branch_path: tuple[str, ...],
+ ) -> ExposedFragment:
+ return build_exposed_fragment(
+ root=node,
+ branch_path=branch_path,
+ config=DisclosureConfig(
+ max_exposure_depth_per_call=max(0, int(self._config.max_exposure_depth_per_call)),
+ exposure_threshold=max(0, int(self._config.exposure_threshold)),
+ compact_boundary_codes_enabled=bool(self._config.compact_boundary_codes_enabled),
+ compact_boundary_codebook=tuple(str(code) for code in self._config.compact_boundary_codebook),
+ flatten_full_tree_in_prompt=bool(self._config.flatten_full_tree_in_prompt),
+ ),
+ subtree_item_count=lambda current: self._analyze_node(current).subtree_item_count,
+ )
+
+ def _select_from_fragment(
+ self,
+ *,
+ model: str,
+ query_messages: List[Dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ fragment: ExposedFragment,
+ ) -> tuple[str, List[SelectableResolution]]:
+ selector = self._build_fragment_selector()
+ output, selected = selector.select(
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ fragment=fragment,
+ )
+ trace.record(
+ "fragment_selected",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "selected_codes": [item.code for item in selected],
+ "selected_canonical_ids": [item.canonical_id for item in selected],
+ "raw_output": output,
+ },
+ )
+ return output, selected
+
+ def _build_fragment_selector(
+ self,
+ *,
+ before_llm_call_hook: Callable[[], None] | None = None,
+ ) -> GenerateFragmentSelector | LogitSelectionFragmentSelector:
+ def generate_fn(**kwargs):
+ return self._select_from_fragment_generate(
+ before_llm_call_hook=before_llm_call_hook,
+ **kwargs,
+ )
+
+ generate_selector = GenerateFragmentSelector(generate_fn=generate_fn)
+ if not _scoring_enabled(self._config):
+ return generate_selector
+ if _normalized_selection_mode(self._config.selection_mode) != "logit_selection":
+ return generate_selector
+ return LogitSelectionFragmentSelector(
+ client=self._llm,
+ require_single_token_codes=bool(self._config.scoring_require_single_token_codes),
+ fallback_mode=str(self._config.scoring_fallback_mode or "error"),
+ generate_selector=generate_selector,
+ max_candidates=max(1, int(self._config.scoring_max_candidates)),
+ min_probability=self._config.scoring_min_probability,
+ trace_top_n=max(1, int(self._config.scoring_trace_top_n)),
+ )
+
+ def _select_from_fragment_generate(
+ self,
+ *,
+ model: str,
+ query_messages: List[Dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ fragment: ExposedFragment,
+ before_llm_call_hook: Callable[[], None] | None = None,
+ ) -> tuple[str, List[SelectableResolution]]:
+ prompt_parts = build_disclosure_prompt_parts(
+ fragment=fragment,
+ query_messages=query_messages,
+ top_k=top_k,
+ )
+ generation_config = self._build_generation_config(
+ choice_id_to_payload={
+ code: resolution.canonical_id
+ for code, resolution in fragment.code_to_resolution.items()
+ },
+ excluded_choice_ids=[],
+ top_k=top_k,
+ )
+ generation_config = self._attach_prompt_cache_hint(
+ prompt_parts=prompt_parts,
+ generation_config=generation_config,
+ )
+ output = self._complete(
+ model=model,
+ system_prompt=str(prompt_parts.full_messages[0]["content"]),
+ query_messages=[dict(prompt_parts.full_messages[1])],
+ max_tokens=self._generate_selection_max_tokens(top_k=top_k),
+ trace=trace,
+ node_id=node.node_id,
+ depth=depth,
+ stage="select_fragment",
+ generation_config=generation_config,
+ before_llm_call_hook=before_llm_call_hook,
+ )
+ selected = parse_selected_codes(fragment=fragment, output=output)[:max(1, int(top_k))]
+ if fragment.compact_codes_enabled and selected:
+ return "\n".join(item.code for item in selected), selected
+ return output, selected
+
+ def _attach_prompt_cache_hint(
+ self,
+ *,
+ prompt_parts: DisclosurePromptParts,
+ generation_config: GenerationConfig | None,
+ ) -> GenerationConfig | None:
+ if not bool(self._llm.capabilities.progressive_prefix_kv_cache):
+ return generation_config
+ get_handle = getattr(self._llm, "get_prompt_cache_handle", None)
+ if not callable(get_handle):
+ raise PrefixCacheUnavailable("LLM client declares prefix KV cache support but exposes no handle lookup")
+ handle = get_handle(prompt_parts.cache_id)
+ if handle is None:
+ raise PrefixCacheUnavailable(f"prefix cache handle is missing: {prompt_parts.cache_id}")
+ resolved = generation_config or self._llm.default_generation_config()
+ return replace(
+ resolved,
+ prompt_cache=PromptCacheHint(
+ handle=handle,
+ suffix_text=prompt_parts.suffix_text,
+ expected_prefix_len=getattr(handle, "prefix_len", None),
+ ),
+ )
+
+ def _continue_from_resolutions(
+ self,
+ *,
+ model: str,
+ query_messages: List[Dict[str, str]],
+ node: RetrieverNode,
+ selected: Sequence[SelectableResolution],
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ ) -> List[RetrieverCandidate]:
+ trace.record(
+ "fragment_continue",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "selected_codes": [item.code for item in selected],
+ "selected_terminal_ids": [
+ item.item.item_id
+ for item in selected
+ if item.is_terminal and item.item is not None
+ ],
+ "selected_branch_ids": [
+ item.node.node_id
+ for item in selected
+ if not item.is_terminal and item.node is not None
+ ],
+ },
+ )
+ branch_top_k = self._resolve_branch_top_k(top_k=top_k, branch_count=max(1, len(selected)))
+ grouped_results: List[List[RetrieverCandidate] | None] = [None] * len(selected)
+ branch_indexes = [
+ index
+ for index, item in enumerate(selected)
+ if not item.is_terminal and item.node is not None
+ ]
+ if branch_indexes and len(branch_indexes) > 1 and self._parallel_branches_enabled():
+ max_workers = min(len(branch_indexes), max(1, int(self._config.max_parallel_branches)))
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ future_to_index = {
+ executor.submit(
+ self._search_node,
+ model=model,
+ query_messages=query_messages,
+ node=selected[index].node,
+ depth=depth + 1,
+ top_k=branch_top_k,
+ trace=trace,
+ branch_path=selected[index].branch_path,
+ ): index
+ for index in branch_indexes
+ }
+ for future, index in future_to_index.items():
+ grouped_results[index] = future.result()
+ for index, resolution in enumerate(selected):
+ if resolution.is_terminal and resolution.item is not None:
+ grouped_results[index] = [
+ RetrieverCandidate(
+ rank=1,
+ item_id=resolution.item.item_id,
+ payload=resolution.item.payload,
+ branch_path=resolution.branch_path,
+ label=resolution.item.label,
+ description=resolution.item.description,
+ )
+ ]
+ elif resolution.node is not None and grouped_results[index] is None:
+ grouped_results[index] = self._search_node(
+ model=model,
+ query_messages=query_messages,
+ node=resolution.node,
+ depth=depth + 1,
+ top_k=branch_top_k,
+ trace=trace,
+ branch_path=resolution.branch_path,
+ )
+ reduced = self._merge_branch_candidates(branch_results=grouped_results, top_k=top_k)
+ trace.record(
+ "reduce_complete",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "input_candidates": sum(len(group or []) for group in grouped_results),
+ "output_candidates": len(reduced),
+ "mode": "round_robin" if self._config.round_robin_branch_reduce else "sequential",
+ },
+ )
+ return reduced
+
+ def _search_children(
+ self,
+ *,
+ model: str,
+ query_messages: List[Dict[str, str]],
+ node: RetrieverNode,
+ selected_children: List[RetrieverNode],
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ branch_path: tuple[str, ...],
+ ) -> List[RetrieverCandidate]:
+ child_ids = [child.node_id for child in selected_children]
+ trace.record(
+ "branch_fork",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "selected_child_ids": child_ids,
+ "parallel": len(selected_children) > 1 and self._config.enable_parallel_branches,
+ "branch_top_k": self._resolve_branch_top_k(top_k=top_k, branch_count=len(selected_children)),
+ },
+ )
+ branch_top_k = self._resolve_branch_top_k(top_k=top_k, branch_count=len(selected_children))
+ if len(selected_children) <= 1 or not self._config.enable_parallel_branches:
+ branch_results = [
+ self._search_node(
+ model=model,
+ query_messages=query_messages,
+ node=child,
+ depth=depth + 1,
+ top_k=branch_top_k,
+ trace=trace,
+ branch_path=branch_path + (child.node_id,),
+ )
+ for child in selected_children
+ ]
+ else:
+ max_workers = min(len(selected_children), max(1, int(self._config.max_parallel_branches)))
+ branch_results = [None] * len(selected_children)
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ future_to_index = {
+ executor.submit(
+ self._search_node,
+ model=model,
+ query_messages=query_messages,
+ node=child,
+ depth=depth + 1,
+ top_k=branch_top_k,
+ trace=trace,
+ branch_path=branch_path + (child.node_id,),
+ ): index
+ for index, child in enumerate(selected_children)
+ }
+ for future, index in future_to_index.items():
+ branch_results[index] = future.result()
+ merged: List[RetrieverCandidate] = []
+ for branch_candidates in branch_results:
+ if branch_candidates:
+ merged.extend(branch_candidates)
+ reduced = self._merge_branch_candidates(branch_results=branch_results, top_k=top_k)
+ trace.record(
+ "reduce_complete",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "input_candidates": len(merged),
+ "output_candidates": len(reduced),
+ "mode": "round_robin" if self._config.round_robin_branch_reduce else "sequential",
+ },
+ )
+ return reduced
+
+ def _select_children(
+ self,
+ *,
+ model: str,
+ query_messages: List[Dict[str, str]],
+ node: RetrieverNode,
+ children: Sequence[RetrieverNode],
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ ) -> List[RetrieverNode]:
+ if len(children) == 1:
+ only_child = children[0]
+ trace.record(
+ "node_selection",
+ node_id=node.node_id,
+ depth=depth,
+ detail={"selected_node_ids": [only_child.node_id], "raw_output": "", "mode": "single_child_shortcut"},
+ )
+ return [only_child]
+ prompt_node = RetrieverNode(
+ node_id=node.node_id,
+ label=node.label,
+ description=node.description,
+ children=tuple(children),
+ )
+ options = _build_visible_options(
+ branches=children,
+ compact_codes_enabled=bool(self._config.compact_boundary_codes_enabled),
+ )
+ option_by_name = {option.display_name: option for option in options}
+ child_by_id = {child.node_id: child for child in children}
+ system_prompt = _build_visible_subtree_prompt(
+ node=prompt_node,
+ options=options,
+ top_k=top_k,
+ compact_codes_enabled=bool(self._config.compact_boundary_codes_enabled),
+ )
+ generation_config = self._build_generation_config(
+ choice_id_to_payload={option.display_name: option.canonical_id for option in options},
+ excluded_choice_ids=[],
+ top_k=top_k,
+ )
+ output = self._complete(
+ model=model,
+ system_prompt=system_prompt,
+ query_messages=query_messages,
+ max_tokens=self._generate_selection_max_tokens(top_k=top_k),
+ trace=trace,
+ node_id=node.node_id,
+ depth=depth,
+ stage="select_children",
+ generation_config=generation_config,
+ before_llm_call_hook=None,
+ )
+ selected_ids = self._parse_ids(output)
+ selected_children: List[RetrieverNode] = []
+ seen: set[str] = set()
+ for display_name in selected_ids:
+ option = self._resolve_option(option_by_name=option_by_name, raw_value=display_name)
+ if option is None:
+ continue
+ node_id = option.canonical_id
+ child = child_by_id.get(node_id)
+ if child is None or node_id in seen:
+ continue
+ selected_children.append(child)
+ seen.add(node_id)
+ if len(selected_children) >= top_k:
+ break
+ trace.record(
+ "node_selection",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "selected_node_ids": [child.node_id for child in selected_children],
+ "selected_display_names": [
+ option.display_name
+ for option in options
+ if option.canonical_id in {child.node_id for child in selected_children}
+ ],
+ "raw_output": output,
+ },
+ )
+ return selected_children
+
+ def _select_items(
+ self,
+ *,
+ model: str,
+ query_messages: List[Dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ branch_path: tuple[str, ...],
+ items: Sequence[RetrieverItem] | None = None,
+ item_paths: Dict[str, tuple[str, ...]] | None = None,
+ allowed_payloads: Dict[str, str] | None = None,
+ resolve_candidate: Callable[[str, Dict[str, str]], str] | None = None,
+ system_prompt_override: str | None = None,
+ before_llm_call_hook: Callable[[], None] | None = None,
+ ) -> ProgressiveRetrieverResult | List[RetrieverCandidate]:
+ candidate_items = list(items if items is not None else node.items)
+ resolved_item_paths = dict(item_paths or {})
+ visible_options = _build_visible_options(
+ items=candidate_items,
+ compact_codes_enabled=bool(self._config.compact_boundary_codes_enabled),
+ )
+ option_by_name = {option.display_name: option for option in visible_options}
+ display_name_by_payload = {option.canonical_id: option.display_name for option in visible_options}
+ subtree_prompt = _build_visible_subtree_prompt(
+ node=node,
+ options=visible_options,
+ top_k=top_k,
+ compact_codes_enabled=bool(self._config.compact_boundary_codes_enabled),
+ )
+ if not candidate_items:
+ return ProgressiveRetrieverResult(candidates=[], trace=trace) if allowed_payloads is not None else []
+ if len(candidate_items) == 1:
+ item = candidate_items[0]
+ item_branch_path = resolved_item_paths.get(item.item_id, branch_path)
+ display_name = display_name_by_payload.get(
+ item.payload or item.item_id,
+ item.payload or item.item_id,
+ )
+ trace.record(
+ "terminal_selection",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "mode": "single_item_shortcut",
+ "selected_item_ids": [item.item_id],
+ "selected_display_names": [display_name],
+ },
+ )
+ single = RetrieverCandidate(
+ rank=1,
+ item_id=item.item_id,
+ payload=item.payload,
+ branch_path=item_branch_path,
+ label=item.label,
+ description=item.description,
+ )
+ if allowed_payloads is not None:
+ return ProgressiveRetrieverResult(
+ candidates=[single],
+ trace=trace,
+ candidate_records=[
+ {
+ "rank": 1,
+ "raw_output": display_name,
+ "resolved_payload": item.payload,
+ "valid": True,
+ "selected": True,
+ "choice_id": item.item_id,
+ }
+ ],
+ summary_lines=[f"1. {display_name} -> {item.payload} (ok, shortcut)"],
+ selected_payload=item.payload,
+ selected_rank=1,
+ raw_outputs=[],
+ request_messages=[],
+ )
+ return [single]
+
+ if allowed_payloads is not None and resolve_candidate is not None:
+ return self._select_items_flat(
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ branch_path=branch_path,
+ choice_id_to_payload=allowed_payloads,
+ resolve_candidate=resolve_candidate,
+ system_prompt_prefix=str(system_prompt_override or "").strip(),
+ before_llm_call_hook=before_llm_call_hook,
+ option_by_name=option_by_name,
+ item_by_payload={item.payload: item for item in candidate_items},
+ )
+
+ system_prompt = subtree_prompt
+ generation_config = self._build_generation_config(
+ choice_id_to_payload={option.display_name: option.canonical_id for option in visible_options},
+ excluded_choice_ids=[],
+ top_k=top_k,
+ )
+ output = self._complete(
+ model=model,
+ system_prompt=system_prompt,
+ query_messages=query_messages,
+ max_tokens=self._generate_selection_max_tokens(top_k=top_k),
+ trace=trace,
+ node_id=node.node_id,
+ depth=depth,
+ stage="select_items",
+ generation_config=generation_config,
+ before_llm_call_hook=None,
+ )
+ selected_ids = self._parse_ids(output)
+ selected: List[RetrieverCandidate] = []
+ seen: set[str] = set()
+ item_by_payload = {item.payload: item for item in candidate_items}
+ for display_name in selected_ids:
+ option = self._resolve_option(option_by_name=option_by_name, raw_value=display_name)
+ if option is None:
+ continue
+ payload = option.canonical_id
+ item = item_by_payload.get(payload)
+ if item is None or item.item_id in seen:
+ continue
+ seen.add(item.item_id)
+ selected.append(
+ RetrieverCandidate(
+ rank=len(selected) + 1,
+ item_id=item.item_id,
+ payload=item.payload,
+ branch_path=resolved_item_paths.get(item.item_id, branch_path),
+ label=item.label,
+ description=item.description,
+ )
+ )
+ if len(selected) >= top_k:
+ break
+ trace.record(
+ "terminal_selection",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "selected_item_ids": [item.item_id for item in selected],
+ "selected_display_names": [
+ display_name_by_payload.get(item.payload, item.item_id)
+ for item in selected
+ ],
+ "raw_output": output,
+ },
+ )
+ if not selected and _is_abstain_output(output):
+ trace.record(
+ "terminal_selection_fallback",
+ node_id=node.node_id,
+ depth=depth,
+ detail={"selected_item_ids": [], "strategy": "abstain_no_backfill"},
+ )
+ return selected
+
+ def _select_items_flat(
+ self,
+ *,
+ model: str,
+ query_messages: List[Dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ branch_path: tuple[str, ...],
+ choice_id_to_payload: Dict[str, str],
+ resolve_candidate: Callable[[str, Dict[str, str]], str],
+ system_prompt_prefix: str,
+ before_llm_call_hook: Callable[[], None] | None,
+ option_by_name: Dict[str, _VisibleOption],
+ item_by_payload: Dict[str, RetrieverItem],
+ ) -> ProgressiveRetrieverResult:
+ candidate_records: List[Dict[str, object]] = []
+ summary_lines: List[str] = []
+ raw_outputs: List[str] = []
+ selected_payloads: set[str] = set()
+ excluded_choice_ids: List[str] = []
+ selected_payload: str | None = None
+ selected_rank = -1
+ global_rank = 0
+ max_rounds = 1
+ messages: List[Dict[str, str]] = []
+ for round_index in range(1, max_rounds + 1):
+ remaining = max(0, top_k - len(selected_payloads))
+ if remaining <= 0:
+ break
+ remaining_options = [
+ option
+ for option in option_by_name.values()
+ if option.canonical_id not in selected_payloads
+ ]
+ if not remaining_options:
+ break
+ request_k = remaining
+ round_choice_id_to_payload = {
+ option.display_name: option.canonical_id
+ for option in remaining_options
+ }
+ generation_config = self._build_generation_config(
+ choice_id_to_payload=round_choice_id_to_payload,
+ excluded_choice_ids=excluded_choice_ids,
+ top_k=request_k,
+ )
+ round_subtree_prompt = _build_visible_subtree_prompt(
+ node=node,
+ options=remaining_options,
+ top_k=request_k,
+ compact_codes_enabled=bool(self._config.compact_boundary_codes_enabled),
+ )
+ if system_prompt_prefix:
+ system_prompt = f"{system_prompt_prefix}\n\n{round_subtree_prompt}".strip()
+ else:
+ system_prompt = round_subtree_prompt
+ if not messages:
+ messages = [{"role": "system", "content": system_prompt}] + list(query_messages)
+ output = self._complete(
+ model=model,
+ system_prompt=system_prompt,
+ query_messages=query_messages,
+ max_tokens=self._generate_selection_max_tokens(top_k=request_k),
+ trace=trace,
+ node_id=node.node_id,
+ depth=depth,
+ stage="select_items",
+ generation_config=generation_config,
+ before_llm_call_hook=before_llm_call_hook,
+ io_event_type="retriever_io",
+ )
+ if output:
+ raw_outputs.append(output)
+ parsed_items = self._parse_multi_output(
+ output,
+ limit=request_k,
+ option_by_name=option_by_name,
+ item_by_payload=item_by_payload,
+ )
+ if not output:
+ self._record_debug_event(
+ {
+ "type": "retriever_iteration",
+ "model": model,
+ "round": round_index,
+ "request_k": request_k,
+ "remaining": remaining,
+ "excluded_choice_ids": list(excluded_choice_ids),
+ "outputs": [],
+ "new_valid_payloads": [],
+ "new_excluded_choice_ids": [],
+ "status": "empty",
+ }
+ )
+ break
+ round_new_valid = 0
+ round_new_valid_payloads: List[str] = []
+ round_new_excluded_choice_ids: List[str] = []
+ for raw_output, resolved_payload, matched_choice_id in parsed_items:
+ global_rank += 1
+ valid = False
+ if resolved_payload and resolved_payload not in selected_payloads:
+ valid = True
+ selected_payloads.add(resolved_payload)
+ if matched_choice_id:
+ excluded_choice_ids.append(matched_choice_id)
+ round_new_excluded_choice_ids.append(matched_choice_id)
+ round_new_valid += 1
+ round_new_valid_payloads.append(resolved_payload)
+ if selected_payload is None:
+ selected_payload = resolved_payload
+ selected_rank = global_rank
+ candidate_records.append(
+ {
+ "rank": global_rank,
+ "raw_output": raw_output,
+ "resolved_payload": resolved_payload,
+ "valid": valid,
+ "selected": False,
+ "choice_id": matched_choice_id,
+ }
+ )
+ label = resolved_payload or "-"
+ status = "ok" if valid else "invalid"
+ summary_lines.append(f"{global_rank}. {raw_output} -> {label} ({status}, round={round_index})")
+ self._record_debug_event(
+ {
+ "type": "retriever_iteration",
+ "model": model,
+ "round": round_index,
+ "request_k": request_k,
+ "remaining": remaining,
+ "excluded_choice_ids": list(excluded_choice_ids),
+ "outputs": [item[0] for item in parsed_items],
+ "raw_output": output,
+ "new_valid_payloads": round_new_valid_payloads,
+ "new_excluded_choice_ids": round_new_excluded_choice_ids,
+ "status": "ok" if round_new_valid > 0 else "stalled",
+ }
+ )
+ if round_new_valid <= 0:
+ break
+ if selected_rank > 0 and 0 <= selected_rank - 1 < len(candidate_records):
+ candidate_records[selected_rank - 1]["selected"] = True
+ candidates = [
+ RetrieverCandidate(
+ rank=int(item["rank"]),
+ item_id=str(item.get("choice_id") or item.get("raw_output") or ""),
+ payload=str(item.get("resolved_payload") or ""),
+ branch_path=branch_path,
+ label=str(item.get("choice_id") or ""),
+ description="",
+ )
+ for item in candidate_records
+ if item.get("valid")
+ ]
+ return ProgressiveRetrieverResult(
+ candidates=candidates,
+ trace=trace,
+ candidate_records=candidate_records,
+ summary_lines=summary_lines,
+ selected_payload=selected_payload,
+ selected_rank=selected_rank,
+ raw_outputs=raw_outputs,
+ request_messages=messages,
+ elapsed_ms=0.0,
+ )
+
+ def _generate_selection_max_tokens(self, *, top_k: int) -> int:
+ if (
+ bool(self._config.compact_boundary_codes_enabled)
+ and str(self._config.selection_mode or "generate").strip().lower() == "generate"
+ ):
+ return _compact_code_generation_max_tokens(
+ top_k,
+ generated_decimal_codes=not bool(self._config.compact_boundary_codebook),
+ )
+ return max(1, int(self._config.max_tokens))
+
+ def _complete(
+ self,
+ *,
+ model: str,
+ system_prompt: str,
+ query_messages: List[Dict[str, str]],
+ max_tokens: int,
+ trace: RetrieverTrace,
+ node_id: str,
+ depth: int,
+ stage: str,
+ generation_config: GenerationConfig | None,
+ before_llm_call_hook: Callable[[], None] | None,
+ io_event_type: str = "finder_io",
+ ) -> str:
+ resolved_generation_config = generation_config or self._llm.default_generation_config()
+ messages = [{"role": "system", "content": system_prompt}] + list(query_messages)
+ request_detail = {
+ "stage": stage,
+ "model": model,
+ "messages": messages,
+ "max_tokens": max_tokens,
+ "generation_config": generation_config_to_debug_dict(resolved_generation_config),
+ }
+ trace.record("llm_request", node_id=node_id, depth=depth, detail=request_detail)
+ if self._debug_event_hook is not None:
+ self._debug_event_hook({"type": io_event_type, "phase": "request", **request_detail})
+ if before_llm_call_hook is not None:
+ before_llm_call_hook()
+ llm_started = perf_counter()
+ ttft_ms: float | None = None
+ use_stream = bool(self._llm.capabilities.streaming)
+ usage: Dict[str, Any] = {}
+ if use_stream:
+ chunks: list[str] = []
+ for chunk in self._llm.stream_complete(
+ model=model,
+ messages=messages,
+ max_tokens=max_tokens,
+ stop_sequences=None,
+ generation_config=resolved_generation_config,
+ request_timeout=self._config.request_timeout,
+ ):
+ chunk_usage = getattr(chunk, "usage", None)
+ if isinstance(chunk_usage, dict) and chunk_usage:
+ usage = dict(chunk_usage)
+ text = str(chunk or "")
+ if not text:
+ continue
+ if ttft_ms is None:
+ ttft_ms = (perf_counter() - llm_started) * 1000.0
+ chunks.append(text)
+ outputs = ["".join(chunks)]
+ else:
+ outputs = self._llm.complete(
+ model=model,
+ messages=messages,
+ max_tokens=max_tokens,
+ stop_sequences=None,
+ generation_config=resolved_generation_config,
+ n=1,
+ request_timeout=self._config.request_timeout,
+ )
+ elapsed_ms = (perf_counter() - llm_started) * 1000.0
+ output = outputs[0] if outputs else ""
+ response_detail = {
+ "stage": stage,
+ "model": model,
+ "outputs": list(outputs),
+ "usage": dict(usage),
+ "latency": {
+ "elapsed_ms": round(elapsed_ms, 3),
+ "ttft_ms": None if ttft_ms is None else round(ttft_ms, 3),
+ "decode_ms": None if ttft_ms is None else round(max(0.0, elapsed_ms - ttft_ms), 3),
+ "stream": use_stream,
+ },
+ }
+ trace.record("llm_response", node_id=node_id, depth=depth, detail=response_detail)
+ if self._debug_event_hook is not None:
+ self._debug_event_hook({"type": io_event_type, "phase": "response", **response_detail})
+ return output
+
+ def _build_generation_config(
+ self,
+ *,
+ choice_id_to_payload: Dict[str, str],
+ excluded_choice_ids: List[str] | None,
+ top_k: int,
+ ) -> GenerationConfig | None:
+ if not self._config.trie_constrained_decoding_enabled:
+ return None
+ if not bool(self._llm.capabilities.trie_constrained_decoding):
+ return None
+ choice_ids = list(choice_id_to_payload.keys())
+ excluded = [str(item).strip() for item in (excluded_choice_ids or []) if str(item).strip()]
+ digest = hashlib.sha256(json.dumps(choice_ids, ensure_ascii=False).encode("utf-8")).hexdigest()
+ return GenerationConfig(
+ constraints=GenerationConstraints(
+ trie=TrieConstraint(
+ allowed_output_ids=tuple(choice_ids),
+ excluded_output_ids=tuple(excluded),
+ top_k=max(1, int(top_k)),
+ version=digest,
+ )
+ )
+ )
+
+ @staticmethod
+ def _collapse_unique_chain(node: RetrieverNode) -> tuple[RetrieverNode, List[str]]:
+ current = node
+ collapsed: List[str] = []
+ while len(current.children) == 1 and not current.items:
+ current = current.children[0]
+ collapsed.append(current.node_id)
+ return current, collapsed
+
+ @staticmethod
+ def _parse_ids(output: str) -> List[str]:
+ values: List[str] = []
+ for line in str(output or "").splitlines():
+ cleaned = re.sub(r"^\s*(?:\d+[\).\s:-]+|[-*]\s+)", "", line.strip())
+ if not cleaned:
+ continue
+ values.append(cleaned.split("|", 1)[0].strip())
+ if values:
+ return values
+ return re.findall(r"[A-Za-z][A-Za-z0-9_./-]*", str(output or ""))
+
+ def _parse_multi_output(
+ self,
+ content: str,
+ *,
+ limit: int,
+ option_by_name: Dict[str, _VisibleOption],
+ item_by_payload: Dict[str, RetrieverItem],
+ ) -> List[tuple[str, str, str]]:
+ raw_candidates = self._parse_ids((content or "").strip())
+ parsed: List[tuple[str, str, str]] = []
+ for raw in raw_candidates:
+ option = self._resolve_option(option_by_name=option_by_name, raw_value=raw)
+ if option is None:
+ continue
+ resolved_payload = option.canonical_id
+ item = item_by_payload.get(resolved_payload)
+ if item is None:
+ continue
+ parsed.append((raw, resolved_payload, item.item_id))
+ if len(parsed) >= max(1, int(limit)):
+ break
+ return parsed
+
+ @staticmethod
+ def _resolve_choice_id(raw_candidate: str, choice_id_to_payload: Dict[str, str], resolved_payload: str) -> str:
+ raw = str(raw_candidate or "").strip().strip("`").strip("<>").strip()
+ if raw in choice_id_to_payload and choice_id_to_payload[raw] == resolved_payload:
+ return raw
+ for choice_id, payload in choice_id_to_payload.items():
+ if payload == resolved_payload:
+ return choice_id
+ return ""
+
+ @staticmethod
+ def _resolve_option(*, option_by_name: Dict[str, _VisibleOption], raw_value: str) -> _VisibleOption | None:
+ option = option_by_name.get(str(raw_value or "").strip())
+ if option is not None:
+ return option
+ text = str(raw_value or "").strip()
+ if not text.isdigit():
+ return None
+ index = int(text) - 1
+ if index < 0:
+ return None
+ ordered = list(option_by_name.values())
+ if index >= len(ordered):
+ return None
+ return ordered[index]
+
+ def _record_debug_event(self, event: Dict[str, object]) -> None:
+ if self._debug_event_hook is None:
+ return
+ self._debug_event_hook(dict(event))
+
+ def _resolve_branch_limit(self, *, child_count: int, top_k: int) -> int:
+ limit_with_slack = int(top_k) + max(0, int(self._config.branch_choice_slack))
+ return min(
+ max(1, int(child_count)),
+ max(1, min(int(self._config.max_branch_choices), limit_with_slack)),
+ )
+
+ def _resolve_branch_top_k(self, *, top_k: int, branch_count: int) -> int:
+ if branch_count <= 0:
+ return max(1, int(top_k))
+ slack = max(0, int(self._config.branch_candidate_slack))
+ budget = math.ceil(max(1, int(top_k)) / branch_count) + slack
+ return min(max(1, int(top_k)), max(1, budget))
+
+ def _analyze_node(self, node: RetrieverNode) -> _RetrieverNodeStats:
+ cache_key = id(node)
+ cached = self._node_stats_cache.get(cache_key)
+ if cached is not None:
+ return cached
+ subtree_item_count = len(node.items)
+ subtree_depth = 0
+ for child in node.children:
+ child_stats = self._analyze_node(child)
+ subtree_item_count += child_stats.subtree_item_count
+ subtree_depth = max(subtree_depth, child_stats.subtree_depth + 1)
+ stats = _RetrieverNodeStats(subtree_item_count=subtree_item_count, subtree_depth=subtree_depth)
+ with self._node_stats_lock:
+ self._node_stats_cache.setdefault(cache_key, stats)
+ return stats
+
+ def _collect_subtree_items(
+ self,
+ node: RetrieverNode,
+ branch_path: tuple[str, ...],
+ ) -> List[tuple[RetrieverItem, tuple[str, ...]]]:
+ collected: List[tuple[RetrieverItem, tuple[str, ...]]] = [(item, branch_path) for item in node.items]
+ for child in node.children:
+ collected.extend(self._collect_subtree_items(child, branch_path + (child.node_id,)))
+ return collected
+
+ def _merge_branch_candidates(
+ self,
+ *,
+ branch_results: Sequence[List[RetrieverCandidate] | None],
+ top_k: int,
+ ) -> List[RetrieverCandidate]:
+ if not self._config.round_robin_branch_reduce:
+ merged: List[RetrieverCandidate] = []
+ for branch_candidates in branch_results:
+ if branch_candidates:
+ merged.extend(branch_candidates)
+ return self._dedupe_candidates(merged)[:top_k]
+ reduced: List[RetrieverCandidate] = []
+ seen: set[str] = set()
+ index = 0
+ while len(reduced) < top_k:
+ added = False
+ for branch_candidates in branch_results:
+ if not branch_candidates or index >= len(branch_candidates):
+ continue
+ candidate = branch_candidates[index]
+ dedupe_key = candidate.payload or candidate.item_id
+ if dedupe_key in seen:
+ continue
+ seen.add(dedupe_key)
+ reduced.append(candidate)
+ added = True
+ if len(reduced) >= top_k:
+ break
+ if not added:
+ break
+ index += 1
+ if len(reduced) >= top_k:
+ return reduced[:top_k]
+ merged: List[RetrieverCandidate] = []
+ for branch_candidates in branch_results:
+ if branch_candidates:
+ merged.extend(branch_candidates)
+ for candidate in self._dedupe_candidates(merged):
+ dedupe_key = candidate.payload or candidate.item_id
+ if dedupe_key in seen:
+ continue
+ seen.add(dedupe_key)
+ reduced.append(candidate)
+ if len(reduced) >= top_k:
+ break
+ return reduced[:top_k]
+
+ @staticmethod
+ def _dedupe_candidates(candidates: List[RetrieverCandidate]) -> List[RetrieverCandidate]:
+ reduced: List[RetrieverCandidate] = []
+ seen: set[str] = set()
+ for candidate in candidates:
+ dedupe_key = candidate.payload or candidate.item_id
+ if dedupe_key in seen:
+ continue
+ seen.add(dedupe_key)
+ reduced.append(candidate)
+ return reduced
+
+
+def _iter_nodes(
+ root: RetrieverNode,
+ branch_path: tuple[str, ...],
+) -> Sequence[tuple[RetrieverNode, tuple[str, ...]]]:
+ nodes: list[tuple[RetrieverNode, tuple[str, ...]]] = [(root, branch_path)]
+ for child in root.children:
+ nodes.extend(_iter_nodes(child, branch_path + (child.node_id,)))
+ return nodes
+
+
+__all__ = [
+ "RetrieverCandidate",
+ "RetrieverItem",
+ "RetrieverNode",
+ "RetrieverTrace",
+ "RetrieverTraceEvent",
+ "RetrieverChoice",
+ "ProgressiveRetriever",
+ "ProgressiveRetrieverConfig",
+ "ProgressiveRetrieverResult",
+]
diff --git a/jiuwenswarm/symphony/retrieval/tree/reduce.py b/jiuwenswarm/symphony/retrieval/tree/reduce.py
new file mode 100644
index 0000000000..2a12834ee7
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/reduce.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Sequence
+
+from models.retrieval import RetrieverCandidate
+
+from .contracts import BranchReducer
+from .types import NodeSearchResult, ProgressiveRetrieverConfig, SearchCursor
+
+
+@dataclass(frozen=True)
+class DefaultBranchReducer(BranchReducer):
+ config: ProgressiveRetrieverConfig
+
+ def reduce_branch_results(
+ self,
+ *,
+ cursor: SearchCursor,
+ local_leaves: Sequence[RetrieverCandidate],
+ child_results: Sequence[NodeSearchResult],
+ ) -> NodeSearchResult:
+ branch_results = [list(local_leaves)] + [list(result.candidates) for result in child_results]
+ reduced = self._merge_branch_candidates(branch_results=branch_results, top_k=cursor.top_k)
+ return NodeSearchResult(candidates=tuple(reduced))
+
+ def _merge_branch_candidates(
+ self,
+ *,
+ branch_results: Sequence[Sequence[RetrieverCandidate] | None],
+ top_k: int,
+ ) -> list[RetrieverCandidate]:
+ if not self.config.round_robin_branch_reduce:
+ merged: list[RetrieverCandidate] = []
+ for branch_candidates in branch_results:
+ if branch_candidates:
+ merged.extend(branch_candidates)
+ return self._dedupe_candidates(merged)[:top_k]
+ reduced: list[RetrieverCandidate] = []
+ seen: set[str] = set()
+ index = 0
+ while len(reduced) < top_k:
+ added = False
+ for branch_candidates in branch_results:
+ if not branch_candidates or index >= len(branch_candidates):
+ continue
+ candidate = branch_candidates[index]
+ dedupe_key = candidate.payload or candidate.item_id
+ if dedupe_key in seen:
+ continue
+ seen.add(dedupe_key)
+ reduced.append(candidate)
+ added = True
+ if len(reduced) >= top_k:
+ break
+ if not added:
+ break
+ index += 1
+ if len(reduced) >= top_k:
+ return reduced[:top_k]
+ merged: list[RetrieverCandidate] = []
+ for branch_candidates in branch_results:
+ if branch_candidates:
+ merged.extend(branch_candidates)
+ for candidate in self._dedupe_candidates(merged):
+ dedupe_key = candidate.payload or candidate.item_id
+ if dedupe_key in seen:
+ continue
+ seen.add(dedupe_key)
+ reduced.append(candidate)
+ if len(reduced) >= top_k:
+ break
+ return reduced[:top_k]
+
+ @staticmethod
+ def _dedupe_candidates(candidates: Sequence[RetrieverCandidate]) -> list[RetrieverCandidate]:
+ reduced: list[RetrieverCandidate] = []
+ seen: set[str] = set()
+ for candidate in candidates:
+ dedupe_key = candidate.payload or candidate.item_id
+ if dedupe_key in seen:
+ continue
+ seen.add(dedupe_key)
+ reduced.append(candidate)
+ return reduced
diff --git a/jiuwenswarm/symphony/retrieval/tree/render/__init__.py b/jiuwenswarm/symphony/retrieval/tree/render/__init__.py
new file mode 100644
index 0000000000..868959c164
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/render/__init__.py
@@ -0,0 +1,21 @@
+from .default import DefaultSubtreeRenderer
+from .disclosure import (
+ DisclosureConfig,
+ ExposedFragment,
+ ExposedNode,
+ SelectableResolution,
+ build_disclosure_messages,
+ build_exposed_fragment,
+ parse_selected_codes,
+)
+
+__all__ = [
+ "DefaultSubtreeRenderer",
+ "DisclosureConfig",
+ "ExposedFragment",
+ "ExposedNode",
+ "SelectableResolution",
+ "build_disclosure_messages",
+ "build_exposed_fragment",
+ "parse_selected_codes",
+]
diff --git a/jiuwenswarm/symphony/retrieval/tree/render/default.py b/jiuwenswarm/symphony/retrieval/tree/render/default.py
new file mode 100644
index 0000000000..2f754e4e3d
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/render/default.py
@@ -0,0 +1,35 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Sequence
+
+from .disclosure import build_disclosure_messages
+
+from ..contracts import SubtreeRenderer
+from ..types import CurrentSubtree, PromptBundle, SelectionProtocol
+
+
+@dataclass(frozen=True)
+class DefaultSubtreeRenderer(SubtreeRenderer):
+ render_messages: bool = True
+
+ def render_subtree(
+ self,
+ *,
+ subtree: CurrentSubtree,
+ query_messages: Sequence[dict[str, str]],
+ protocol: SelectionProtocol,
+ ) -> PromptBundle:
+ messages = ()
+ if self.render_messages:
+ disclosure_messages = build_disclosure_messages(
+ fragment=subtree.fragment,
+ query_messages=query_messages,
+ top_k=subtree.cursor.top_k,
+ )
+ messages = tuple(dict(message) for message in disclosure_messages)
+ return PromptBundle(
+ fragment=subtree.fragment,
+ protocol=protocol,
+ messages=messages,
+ )
diff --git a/jiuwenswarm/symphony/retrieval/tree/render/disclosure.py b/jiuwenswarm/symphony/retrieval/tree/render/disclosure.py
new file mode 100644
index 0000000000..db1429099e
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/render/disclosure.py
@@ -0,0 +1,1225 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from pathlib import Path
+from typing import Dict, Iterable, List, Sequence
+
+import yaml
+
+from models.retrieval import RetrieverItem, RetrieverNode
+from ...protocols.display_name import to_pascal_case
+
+_PROMPT_FILE = Path(__file__).with_name("prompts.yaml")
+_LEGACY_FLAT_NON_COMPACT_SYSTEM_PROMPT = (
+ "\n# 背景与目标:\n"
+ "- 系统的最终目标是解决用户的问题。\n"
+ "- 系统通过调用 Candidate skill 来执行任务。\n"
+ "- 你的职责是:组建一个最优 skill 小组,以端到端闭环用户的任务。\n"
+ "\n"
+ "注意:\n"
+ "- 你只做“候选筛选”,不做规划、不做执行。\n"
+ "\n\n"
+ "# 输出规则:\n"
+ "\n"
+ "1. 总共输出至多 5 个 Candidate skill 节点 id\n"
+ "\n"
+ "2. 该结果必须是:\n"
+ " - 最优 Candidate skill 组合\n"
+ " - 该组合能够完整闭环用户任务\n"
+ "\n"
+ "3. 至多输出 5 行\n"
+ "\n\n"
+ "# 选择规则:\n"
+ "\n"
+ "- 必须严格遵守用户的显式约束(如时间、范围、条件等)\n"
+ "- 要选出**能够完整闭环用户意图的 skill 组合**,包括用户的显式意图和隐式意图。\n"
+ " - 例如,用户有出行意图时,不仅考虑出行规划,也要选择查询天气相关skill\n"
+ " - 用户有饮食、购物等意图时,不仅直接选择对应的出行助手,也要选择美团红包优惠\n"
+ " - 用户要搭建网站时,不仅直接选择html生成与前端开发,也可以考虑艺术创作\n"
+ " - 务必确认用户的真实隐含意图,例如“生成一张地图”实质上对应于基于AI的图像生成,而非查询地图。\n"
+ " - 不要附带任何无关的skill,例如,用户不需要ppt时不要选择ppt相关技能。用户需要生成地图而非查询地点时,不要选择地图相关技能。\n"
+ " - 用户明确不要某类skill时,不要选择对应的skill。\n"
+ "\n\n"
+ "{candidate_block}\n"
+ "\n\n"
+ "# 输出 id 说明:\n"
+ "\n"
+ "- 仅输出驼峰格式的节点 id, 不要附带任何其他内容\n"
+)
+
+
+@lru_cache(maxsize=1)
+def _load_progressive_prompt_bank() -> dict[str, str]:
+ raw = yaml.safe_load(_PROMPT_FILE.read_text(encoding="utf-8"))
+ if not isinstance(raw, dict):
+ raise ValueError(f"invalid prompt yaml: {_PROMPT_FILE}")
+ bank = raw.get("progressive_system_prompt")
+ if not isinstance(bank, dict):
+ raise ValueError(f"missing progressive_system_prompt in prompt yaml: {_PROMPT_FILE}")
+ required_keys = {
+ "shared",
+ "shared_top2",
+ "structure_codes",
+ "structure_names",
+ "structure_codes_flat",
+ "structure_names_flat",
+ "output_codes",
+ "output_codes_flat",
+ "output_names_tree",
+ "output_names_flat",
+ }
+ missing = sorted(required_keys.difference(bank))
+ if missing:
+ raise ValueError(f"missing progressive prompt keys in {_PROMPT_FILE}: {missing}")
+ return {key: str(value).rstrip("\n") for key, value in bank.items()}
+
+
+def _build_system_prompt(
+ *,
+ compact_codes_enabled: bool,
+ flat_list_mode: bool,
+ top_k: int,
+ candidate_block: str = "",
+) -> str:
+ resolved_top_k = max(1, int(top_k))
+ if not compact_codes_enabled and flat_list_mode and resolved_top_k != 2:
+ return _LEGACY_FLAT_NON_COMPACT_SYSTEM_PROMPT.format(
+ candidate_block=str(candidate_block or "").rstrip()
+ )
+ bank = _load_progressive_prompt_bank()
+ candidate_region = "<CANDIDATE_LIST>" if flat_list_mode else "<CANDIDATE_TREE>"
+ if compact_codes_enabled and flat_list_mode:
+ structure_block = bank["structure_codes_flat"]
+ output_block = _compact_flat_output_block()
+ elif compact_codes_enabled:
+ structure_block = bank["structure_codes"]
+ output_block = bank["output_codes"]
+ elif flat_list_mode:
+ structure_block = bank["structure_names_flat"]
+ output_block = bank["output_names_flat"]
+ else:
+ structure_block = bank["structure_names"]
+ output_block = bank["output_names_tree"]
+ shared_key = "shared_top2" if resolved_top_k == 2 else "shared"
+ return bank[shared_key].format(
+ top_k=resolved_top_k,
+ candidate_region=candidate_region,
+ structure_block=structure_block,
+ candidate_block=str(candidate_block or "").rstrip(),
+ output_block=output_block.format(top_k=resolved_top_k),
+ )
+
+
+_SELECTION_LINE_RE = re.compile(r"^\s*(?:\d+[\).:-]+\s*|[-*]\s+)?(.+?)\s*$")
+_COMPACT_ID_HANDLE_RE = re.compile(r"\[\s*id\s*:\s*([^\]\s|,:;]+)\s*\]", re.IGNORECASE)
+_COMPACT_JSON_ID_FIELD_RE = re.compile(r"""["'](?:id|c|code)["']\s*:\s*["']([^"'\]\s|,:;{}]+)["']""", re.IGNORECASE)
+_COMPACT_BRACKET_PREFIX_RE = re.compile(r"^\[\s*([^\]\s|,:;]+)\s*\]\s*\.")
+_QUERY_FROM_PREFIX_RE = re.compile(r"^\s*From\s+[^:]+:\s*", re.IGNORECASE)
+_REPRESENTATIVE_DESCENDANTS_RE = re.compile(
+ r"(?:\n\s*|\s+)Representative descendants:\s*.+$",
+ re.IGNORECASE | re.DOTALL,
+)
+_FLAT_COMPACT_DESCRIPTION_MAX_CHARS_DEFAULT = 150
+_FLAT_COMPACT_FIELD_ORDER_DEFAULT = ("category", "name", "raw_name", "description", "id")
+
+
+@dataclass(frozen=True)
+class DisclosureConfig:
+ max_exposure_depth_per_call: int = 2
+ exposure_threshold: int = 12
+ compact_boundary_codes_enabled: bool = False
+ compact_boundary_codebook: tuple[str, ...] = ()
+ flatten_full_tree_in_prompt: bool = False
+
+
+@dataclass(frozen=True)
+class SelectableResolution:
+ code: str
+ canonical_id: str
+ display_name: str
+ label: str
+ description: str
+ is_terminal: bool
+ branch_path: tuple[str, ...]
+ score_key: str = ""
+ token_id: int | None = None
+ node: RetrieverNode | None = None
+ item: RetrieverItem | None = None
+
+
+@dataclass(frozen=True)
+class ExposedNode:
+ canonical_id: str
+ label: str
+ description: str
+ is_selectable: bool
+ selectable_canonical_id: str | None = None
+ children: tuple["ExposedNode", ...] = ()
+
+
+_SelectableEntry = tuple[
+ str,
+ str,
+ str,
+ str,
+ bool,
+ tuple[str, ...],
+ RetrieverNode | None,
+ RetrieverItem | None,
+]
+
+
+@dataclass(frozen=True)
+class ExposedFragment:
+ root: ExposedNode
+ rendered_tree: str
+ code_to_resolution: Dict[str, SelectableResolution]
+ selectable_nodes: tuple[ExposedNode, ...] = ()
+ candidate_codes: tuple[str, ...] = ()
+ fragment_fingerprint: str = ""
+ code_width: int = 1
+ compact_codes_enabled: bool = False
+ flat_list_mode: bool = False
+
+ def build_system_prompt(self, *, top_k: int | None = None) -> str:
+ resolved_top_k = max(1, int(top_k if top_k is not None else (len(self.code_to_resolution) or 1)))
+ return _build_system_prompt(
+ compact_codes_enabled=bool(self.compact_codes_enabled),
+ flat_list_mode=bool(self.flat_list_mode),
+ top_k=resolved_top_k,
+ )
+
+ @property
+ def system_prompt(self) -> str:
+ return self.build_system_prompt()
+
+ @property
+ def user_prefix(self) -> str:
+ if self.flat_list_mode:
+ return f"Available options:\n{self.rendered_tree}\n\nUser request:\n"
+ return f"<CANDIDATE_TREE>\n{self.rendered_tree}\n</CANDIDATE_TREE>\n\n<USER_REQUEST>\n"
+
+
+@dataclass(frozen=True)
+class DisclosurePromptParts:
+ full_messages: tuple[Dict[str, str], ...]
+ prefix_messages: tuple[Dict[str, str], ...]
+ suffix_text: str
+ cache_id: str
+ prefix_token_hash: str
+
+
+def build_exposed_fragment(
+ *,
+ root: RetrieverNode,
+ branch_path: tuple[str, ...],
+ config: DisclosureConfig,
+ subtree_item_count: callable,
+) -> ExposedFragment:
+ selectable_entries: List[_SelectableEntry] = []
+ root_node = _expand_node(
+ node=root,
+ current_path=branch_path,
+ remaining_depth=max(0, int(config.max_exposure_depth_per_call)),
+ is_root=True,
+ config=config,
+ subtree_item_count=subtree_item_count,
+ selectable_entries=selectable_entries,
+ )
+ if bool(config.flatten_full_tree_in_prompt):
+ return _build_flat_fragment_from_exposed_subtree(
+ root_node=root_node,
+ selectable_entries=selectable_entries,
+ config=config,
+ )
+ codes = _build_codes(
+ selectable_entries,
+ compact_codes_enabled=bool(config.compact_boundary_codes_enabled),
+ compact_codebook=config.compact_boundary_codebook,
+ )
+ display_names = _build_boundary_names(selectable_entries)
+ resolution_by_code: Dict[str, SelectableResolution] = {}
+ resolution_by_canonical_id: Dict[str, SelectableResolution] = {}
+ for code, display_name, entry in zip(codes, display_names, selectable_entries):
+ (
+ canonical_id,
+ label,
+ description,
+ selectable_canonical_id,
+ is_terminal,
+ selectable_path,
+ node_ref,
+ item_ref,
+ ) = entry
+ resolution = SelectableResolution(
+ code=code,
+ canonical_id=selectable_canonical_id,
+ display_name=display_name,
+ label=label,
+ description=description,
+ is_terminal=is_terminal,
+ branch_path=selectable_path,
+ score_key=code,
+ node=node_ref,
+ item=item_ref,
+ )
+ resolution_by_code[code] = resolution
+ resolution_by_canonical_id[canonical_id] = resolution
+ rendered_tree = _render_tree(
+ root_node,
+ resolution_by_canonical_id=resolution_by_canonical_id,
+ compact_codes_enabled=bool(config.compact_boundary_codes_enabled),
+ )
+ candidate_codes = tuple(codes)
+ return ExposedFragment(
+ root=root_node,
+ rendered_tree=rendered_tree,
+ code_to_resolution=resolution_by_code,
+ selectable_nodes=tuple(_iter_selectable_nodes(root_node)),
+ candidate_codes=candidate_codes,
+ fragment_fingerprint=_build_fragment_fingerprint(root_node=root_node, candidate_codes=candidate_codes),
+ code_width=_resolve_code_width(codes),
+ compact_codes_enabled=bool(config.compact_boundary_codes_enabled),
+ flat_list_mode=False,
+ )
+
+
+def build_disclosure_messages(
+ *,
+ fragment: ExposedFragment,
+ query_messages: Sequence[Dict[str, str]],
+ top_k: int | None = None,
+) -> List[Dict[str, str]]:
+ return list(
+ build_disclosure_prompt_parts(
+ fragment=fragment,
+ query_messages=query_messages,
+ top_k=top_k,
+ ).full_messages
+ )
+
+
+def build_disclosure_prompt_parts(
+ *,
+ fragment: ExposedFragment,
+ query_messages: Sequence[Dict[str, str]],
+ top_k: int | None = None,
+) -> DisclosurePromptParts:
+ query_text = "\n".join(
+ _normalize_query_content(str(message.get("content") or "").strip())
+ for message in query_messages
+ if str(message.get("content") or "").strip()
+ ).strip()
+ resolved_top_k = None if top_k is None else max(1, int(top_k))
+ system_prompt, user_prefix, prefix_token_hash, cache_id = _build_disclosure_prompt_static(
+ rendered_tree=fragment.rendered_tree,
+ fragment_fingerprint=fragment.fragment_fingerprint,
+ candidate_codes=tuple(str(code) for code in fragment.candidate_codes),
+ compact_codes_enabled=bool(fragment.compact_codes_enabled),
+ flat_list_mode=bool(fragment.flat_list_mode),
+ top_k=resolved_top_k,
+ )
+ if fragment.flat_list_mode:
+ suffix_text = query_text
+ else:
+ suffix_text = f"{query_text}\n</USER_REQUEST>".rstrip()
+ user_content = f"{user_prefix}{suffix_text}".rstrip()
+ prefix_messages = (
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": user_prefix},
+ )
+ full_messages = (
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": user_content},
+ )
+ return DisclosurePromptParts(
+ full_messages=full_messages,
+ prefix_messages=prefix_messages,
+ suffix_text=suffix_text,
+ cache_id=cache_id,
+ prefix_token_hash=prefix_token_hash,
+ )
+
+
+@lru_cache(maxsize=4096)
+def _build_disclosure_prompt_static(
+ *,
+ rendered_tree: str,
+ fragment_fingerprint: str,
+ candidate_codes: tuple[str, ...],
+ compact_codes_enabled: bool,
+ flat_list_mode: bool,
+ top_k: int | None,
+) -> tuple[str, str, str, str]:
+ candidate_text = (
+ f"Available options:\n{rendered_tree}"
+ if flat_list_mode
+ else f"<CANDIDATE_TREE>\n{rendered_tree}\n</CANDIDATE_TREE>"
+ )
+ candidate_block = f"# 候选列表\n{candidate_text}"
+ system_prompt = _build_system_prompt(
+ compact_codes_enabled=bool(compact_codes_enabled),
+ flat_list_mode=bool(flat_list_mode),
+ top_k=max(1, int(top_k if top_k is not None else (len(candidate_codes) or 1))),
+ candidate_block=candidate_block,
+ )
+ if flat_list_mode:
+ user_prefix = "User request:\n"
+ else:
+ user_prefix = "<USER_REQUEST>\n"
+ prefix_payload = (
+ f"{system_prompt}\n"
+ f"{user_prefix}\n"
+ f"{fragment_fingerprint}\n"
+ f"{top_k or ''}\n"
+ f"{int(compact_codes_enabled)}\n"
+ f"{int(flat_list_mode)}"
+ )
+ prefix_token_hash = hashlib.sha256(prefix_payload.encode("utf-8")).hexdigest()
+ cache_id = hashlib.sha256(
+ (
+ "progressive-disclosure-v1\n"
+ f"{prefix_token_hash}\n"
+ f"{'/'.join(str(code) for code in candidate_codes)}"
+ ).encode("utf-8")
+ ).hexdigest()[:32]
+ return system_prompt, user_prefix, prefix_token_hash, cache_id
+
+
+def _normalize_query_content(text: str) -> str:
+ lines = []
+ for raw in str(text or "").splitlines():
+ cleaned = _QUERY_FROM_PREFIX_RE.sub("", raw.strip())
+ if cleaned:
+ lines.append(cleaned)
+ return "\n".join(lines)
+
+
+def _compact_flat_output_block() -> str:
+ return (
+ "- 只输出候选 JSON 对象中的两个大写字母 id,每行一个 id。\n"
+ "- 不要输出 JSON、字段名、候选名称、解释、编号、冒号、标点或整个候选对象。\n"
+ "- 如果想复制某个候选 JSON 对象,必须改为只输出该对象的两个大写字母 id。\n"
+ "- id 是无语义句柄,只能根据候选名称和能力说明判断相关性。"
+ )
+
+
+def parse_selected_codes(*, fragment: ExposedFragment, output: str) -> List[SelectableResolution]:
+ text = str(output or "").strip()
+ if not text or text == "0":
+ return []
+ lines = _parse_selection_lines(text)
+ if fragment.compact_codes_enabled:
+ parsed_codes = _parse_compact_codes(fragment=fragment, lines=lines)
+ else:
+ parsed_codes = _parse_non_compact_codes(fragment=fragment, lines=lines)
+ if _can_parse_joined_compact_codes(fragment=fragment, parsed_codes=parsed_codes, text=text):
+ compact = text.strip()
+ if compact != "0" and len(compact) % fragment.code_width == 0:
+ compact_codes = [
+ compact[index: index + fragment.code_width]
+ for index in range(0, len(compact), fragment.code_width)
+ ]
+ if all(code in fragment.code_to_resolution for code in compact_codes):
+ parsed_codes = compact_codes
+ selected: List[SelectableResolution] = []
+ seen: set[str] = set()
+ for code in parsed_codes:
+ resolution = fragment.code_to_resolution.get(code)
+ if resolution is None and not fragment.compact_codes_enabled:
+ resolution = _match_numeric_code(fragment=fragment, code=code)
+ if resolution is None and not fragment.compact_codes_enabled:
+ resolution = _match_label_code(fragment=fragment, code=code)
+ if resolution is None:
+ continue
+ dedupe_key = resolution.canonical_id
+ if dedupe_key in seen:
+ continue
+ seen.add(dedupe_key)
+ selected.append(resolution)
+ return selected
+
+
+def _parse_selection_lines(text: str) -> List[str]:
+ lines: List[str] = []
+ for raw in str(text or "").splitlines():
+ if not raw.strip():
+ continue
+ match = _SELECTION_LINE_RE.match(raw)
+ if match:
+ lines.append(match.group(1).strip())
+ return lines
+
+
+def _can_parse_joined_compact_codes(
+ *,
+ fragment: ExposedFragment,
+ parsed_codes: Sequence[str],
+ text: str,
+) -> bool:
+ return (
+ not parsed_codes
+ and fragment.compact_codes_enabled
+ and fragment.code_width > 0
+ and "\n" not in text
+ and " " not in text
+ )
+
+
+def _parse_non_compact_codes(*, fragment: ExposedFragment, lines: Sequence[str]) -> List[str]:
+ parsed: List[str] = []
+ for line in lines:
+ normalized = str(line or "").strip().strip("`").strip().strip("\"'")
+ if not normalized:
+ continue
+ candidates = [normalized]
+ if normalized.lower().startswith("candidate "):
+ candidates.append(normalized[len("candidate "):].strip())
+ if normalized.lower().startswith("name:"):
+ candidates.append(normalized.split(":", 1)[1].split("|", 1)[0].strip())
+ if ":" in normalized:
+ candidates.append(normalized.split(":", 1)[0].strip())
+ for candidate in candidates:
+ matched_code = _match_non_compact_candidate_code(fragment=fragment, candidate=candidate)
+ if matched_code:
+ parsed.append(matched_code)
+ break
+ else:
+ if re.fullmatch(r"\d+", normalized):
+ parsed.append(normalized)
+ continue
+ listed_codes = _parse_non_compact_code_list(normalized, fragment)
+ if listed_codes:
+ parsed.extend(listed_codes)
+ return parsed
+
+
+def _match_non_compact_candidate_code(*, fragment: ExposedFragment, candidate: str) -> str:
+ text = str(candidate or "").strip().strip("`").strip().strip("\"'")
+ if not text:
+ return ""
+ if text in fragment.code_to_resolution:
+ return text
+ folded = text.casefold()
+ code_matches = [code for code in fragment.code_to_resolution if str(code).casefold() == folded]
+ if len(code_matches) == 1:
+ return code_matches[0]
+ label_matches = [
+ resolution.code
+ for resolution in fragment.code_to_resolution.values()
+ if str(resolution.label or "").strip().casefold() == folded
+ ]
+ if len(label_matches) == 1:
+ return label_matches[0]
+
+ # Fallback: fuzzy match LLM output against display_name/label tokens
+ hits = [r.code for r in fragment.code_to_resolution.values() if _tokens_overlap(r, folded)]
+ if len(hits) == 1:
+ return hits[0]
+
+ return ""
+
+
+def _tokens_overlap(resolution: SelectableResolution, folded: str) -> bool:
+ for s in (resolution.display_name or "", resolution.label or ""):
+ if any(t in folded for t in _tokenize_camel(s) if len(t) > 2):
+ return True
+ return False
+
+
+def _tokenize_camel(s: str) -> List[str]:
+ """Split a camelCase string into its constituent tokens."""
+ parts = re.findall(r"[A-Z]?[a-z]+|[A-Z]+(?=[A-Z]|$)|\d+", s)
+ return [p.lower() for p in parts if p]
+
+
+def _parse_non_compact_code_list(line: str, fragment: ExposedFragment) -> List[str]:
+ text = str(line or "").strip()
+ if not text or ":" in text:
+ return []
+ tokens = [
+ token.strip().strip("`").strip().strip("\"'")
+ for token in re.split(r"[\s,;|]+", text.strip("[](){}"))
+ if token.strip()
+ ]
+ meaningful_tokens = [
+ token
+ for token in tokens
+ if not re.fullmatch(r"\d+[\).]?", token)
+ ]
+ if not meaningful_tokens or len(meaningful_tokens) <= 1:
+ return []
+ resolved_codes = [
+ _match_non_compact_candidate_code(fragment=fragment, candidate=token)
+ for token in meaningful_tokens
+ ]
+ if all(resolved_codes):
+ return resolved_codes
+ return []
+
+
+def _parse_compact_codes(*, fragment: ExposedFragment, lines: Sequence[str]) -> List[str]:
+ parsed: List[str] = []
+ codes = sorted((str(code) for code in fragment.code_to_resolution), key=len, reverse=True)
+ for line in lines:
+ raw_line = str(line or "").strip()
+ json_codes = _parse_compact_json_id_fields(raw_line, fragment.code_to_resolution)
+ if json_codes:
+ parsed.extend(json_codes)
+ continue
+ normalized = raw_line.strip("`").strip().strip("\"'")
+ if normalized.lower().startswith("candidate "):
+ normalized = normalized[len("candidate "):].strip()
+ if normalized.lower().startswith(("id:", "c:", "code:")):
+ normalized = normalized.split(":", 1)[1].strip()
+ if normalized in fragment.code_to_resolution:
+ parsed.append(normalized)
+ continue
+ bracketed_prefix = _parse_compact_bracket_prefix(normalized, fragment.code_to_resolution)
+ if bracketed_prefix:
+ parsed.append(bracketed_prefix)
+ continue
+ handled_codes = _parse_compact_id_handles(normalized, fragment.code_to_resolution)
+ if handled_codes:
+ parsed.extend(handled_codes)
+ continue
+ listed_codes = _parse_compact_code_list(normalized, fragment.code_to_resolution)
+ if listed_codes:
+ parsed.extend(listed_codes)
+ continue
+ matched_prefix = _match_compact_code_prefix(normalized, codes)
+ if matched_prefix:
+ parsed.append(matched_prefix)
+ continue
+ return parsed
+
+
+def _parse_compact_json_id_fields(line: str, code_to_resolution: Dict[str, SelectableResolution]) -> List[str]:
+ parsed: List[str] = []
+ for match in _COMPACT_JSON_ID_FIELD_RE.finditer(str(line or "")):
+ code = str(match.group(1) or "").strip().strip("`").strip().strip("\"'")
+ if code in code_to_resolution:
+ parsed.append(code)
+ return parsed
+
+
+def _parse_compact_bracket_prefix(line: str, code_to_resolution: Dict[str, SelectableResolution]) -> str:
+ match = _COMPACT_BRACKET_PREFIX_RE.match(str(line or ""))
+ if not match:
+ return ""
+ code = str(match.group(1) or "").strip().strip("`").strip().strip("\"'")
+ if code in code_to_resolution:
+ return code
+ return ""
+
+
+def _parse_compact_id_handles(line: str, code_to_resolution: Dict[str, SelectableResolution]) -> List[str]:
+ parsed: List[str] = []
+ for match in _COMPACT_ID_HANDLE_RE.finditer(str(line or "")):
+ code = str(match.group(1) or "").strip().strip("`").strip().strip("\"'")
+ if code in code_to_resolution:
+ parsed.append(code)
+ return parsed
+
+
+def _match_compact_code_prefix(line: str, codes: Sequence[str]) -> str:
+ for code in codes:
+ if not line.startswith(code):
+ continue
+ if len(line) == len(code):
+ return code
+ if line[len(code)] in {" ", "\t", "|", ":", "-", ",", ";", "]", "}", ")", "\"", "'"}:
+ return code
+ return ""
+
+
+def _parse_compact_code_list(line: str, code_to_resolution: Dict[str, SelectableResolution]) -> List[str]:
+ text = str(line or "").strip()
+ if not text or "|" in text or ":" in text:
+ return []
+ tokens = [token for token in re.split(r"[\s,;]+", text.strip("[](){}")) if token]
+ if not tokens:
+ return []
+ if all(token in code_to_resolution for token in tokens):
+ return tokens
+ return []
+
+
+def _match_numeric_code(*, fragment: ExposedFragment, code: str) -> SelectableResolution | None:
+ text = str(code or "").strip()
+ if not text.isdigit():
+ return None
+ numeric_value = str(int(text))
+ for candidate, resolution in fragment.code_to_resolution.items():
+ candidate_text = str(candidate or "").strip()
+ if not candidate_text.isdigit():
+ continue
+ if str(int(candidate_text)) == numeric_value:
+ return resolution
+ index = int(numeric_value) - 1
+ ordered = list(fragment.code_to_resolution.values())
+ if 0 <= index < len(ordered):
+ return ordered[index]
+ return None
+
+
+def _match_label_code(*, fragment: ExposedFragment, code: str) -> SelectableResolution | None:
+ text = str(code or "").strip()
+ if not text:
+ return None
+ matches = [
+ resolution
+ for resolution in fragment.code_to_resolution.values()
+ if str(resolution.label or "").strip() == text
+ ]
+ if len(matches) == 1:
+ return matches[0]
+ return None
+
+
+def _expand_node(
+ *,
+ node: RetrieverNode,
+ current_path: tuple[str, ...],
+ remaining_depth: int,
+ is_root: bool,
+ config: DisclosureConfig,
+ subtree_item_count: callable,
+ selectable_entries: List[_SelectableEntry],
+) -> ExposedNode:
+ children_nodes: List[ExposedNode] = []
+ for item in node.items:
+ canonical_id = f"item::{item.payload or item.item_id}"
+ selectable_entries.append(
+ (
+ canonical_id,
+ item.label or item.item_id,
+ item.description or "",
+ item.payload or item.item_id,
+ True,
+ current_path,
+ None,
+ item,
+ )
+ )
+ children_nodes.append(
+ ExposedNode(
+ canonical_id=canonical_id,
+ label=item.label or item.item_id,
+ description=item.description or "",
+ is_selectable=True,
+ selectable_canonical_id=item.payload or item.item_id,
+ )
+ )
+
+ child_nodes = list(node.children)
+ if _should_auto_expand_single_child(
+ is_root=is_root,
+ remaining_depth=remaining_depth,
+ node=node,
+ child_nodes=child_nodes,
+ ):
+ only_child = child_nodes[0]
+ children_nodes.append(
+ _expand_node(
+ node=only_child,
+ current_path=current_path + (only_child.node_id,),
+ remaining_depth=remaining_depth - 1,
+ is_root=False,
+ config=config,
+ subtree_item_count=subtree_item_count,
+ selectable_entries=selectable_entries,
+ )
+ )
+ return ExposedNode(
+ canonical_id=f"node::{node.node_id}",
+ label=node.label or node.node_id,
+ description=node.description or "",
+ is_selectable=False,
+ children=tuple(children_nodes),
+ )
+
+ for child in child_nodes:
+ child_path = current_path + (child.node_id,)
+ if remaining_depth <= 0:
+ children_nodes.append(
+ _register_selectable_branch(
+ child=child,
+ child_path=child_path,
+ selectable_entries=selectable_entries,
+ )
+ )
+ continue
+ child_item_count = int(subtree_item_count(child))
+ if child_item_count <= max(0, int(config.exposure_threshold)):
+ children_nodes.append(
+ _expand_node(
+ node=child,
+ current_path=child_path,
+ remaining_depth=remaining_depth - 1,
+ is_root=False,
+ config=config,
+ subtree_item_count=subtree_item_count,
+ selectable_entries=selectable_entries,
+ )
+ )
+ else:
+ children_nodes.append(
+ _register_selectable_branch(
+ child=child,
+ child_path=child_path,
+ selectable_entries=selectable_entries,
+ )
+ )
+ return ExposedNode(
+ canonical_id=f"node::{node.node_id}",
+ label=node.label or node.node_id,
+ description=node.description or "",
+ is_selectable=False,
+ children=tuple(children_nodes),
+ )
+
+
+def _should_auto_expand_single_child(
+ *,
+ is_root: bool,
+ remaining_depth: int,
+ node: RetrieverNode,
+ child_nodes: Sequence[RetrieverNode],
+) -> bool:
+ if is_root or node.items:
+ return False
+ return remaining_depth > 0 and len(child_nodes) == 1
+
+
+def _build_flat_fragment_from_exposed_subtree(
+ *,
+ root_node: ExposedNode,
+ selectable_entries: Sequence[_SelectableEntry],
+ config: DisclosureConfig,
+) -> ExposedFragment:
+ selectable_entries = _sort_flat_entries(
+ selectable_entries,
+ stable_by_content=bool(config.compact_boundary_codes_enabled),
+ )
+ display_names = _build_boundary_names(selectable_entries)
+ codes = _build_flat_compact_codes(
+ selectable_entries=selectable_entries,
+ config=config,
+ )
+ resolution_by_code: Dict[str, SelectableResolution] = {}
+ resolution_by_canonical_id: Dict[str, SelectableResolution] = {}
+ selectable_nodes: List[ExposedNode] = []
+ for code, display_name, entry in zip(codes, display_names, selectable_entries):
+ (
+ canonical_id,
+ label,
+ description,
+ selectable_canonical_id,
+ is_terminal,
+ selectable_path,
+ node_ref,
+ item_ref,
+ ) = entry
+ resolution = SelectableResolution(
+ code=code,
+ canonical_id=selectable_canonical_id,
+ display_name=display_name,
+ label=label,
+ description=description,
+ is_terminal=is_terminal,
+ branch_path=selectable_path,
+ score_key=code,
+ node=node_ref,
+ item=item_ref,
+ )
+ resolution_by_code[code] = resolution
+ resolution_by_canonical_id[canonical_id] = resolution
+ selectable_nodes.append(
+ ExposedNode(
+ canonical_id=canonical_id,
+ label=label,
+ description=description,
+ is_selectable=True,
+ selectable_canonical_id=selectable_canonical_id,
+ )
+ )
+ flat_root_node = ExposedNode(
+ canonical_id=root_node.canonical_id,
+ label=root_node.label,
+ description=root_node.description,
+ is_selectable=False,
+ children=tuple(selectable_nodes),
+ )
+ rendered_tree = _render_flat_list(
+ selectable_nodes,
+ resolution_by_canonical_id=resolution_by_canonical_id,
+ compact_codes_enabled=bool(config.compact_boundary_codes_enabled),
+ )
+ candidate_codes = tuple(codes)
+ return ExposedFragment(
+ root=flat_root_node,
+ rendered_tree=rendered_tree,
+ code_to_resolution=resolution_by_code,
+ selectable_nodes=tuple(selectable_nodes),
+ candidate_codes=candidate_codes,
+ fragment_fingerprint=_build_fragment_fingerprint(root_node=flat_root_node, candidate_codes=candidate_codes),
+ code_width=_resolve_code_width(codes),
+ compact_codes_enabled=bool(config.compact_boundary_codes_enabled),
+ flat_list_mode=True,
+ )
+
+
+def _build_flat_compact_codes(
+ *,
+ selectable_entries: Sequence[_SelectableEntry],
+ config: DisclosureConfig,
+) -> List[str]:
+ return _build_codes(
+ selectable_entries,
+ compact_codes_enabled=bool(config.compact_boundary_codes_enabled),
+ compact_codebook=config.compact_boundary_codebook if config.compact_boundary_codes_enabled else (),
+ )
+
+
+def _sort_flat_entries(
+ selectable_entries: Sequence[_SelectableEntry],
+ *,
+ stable_by_content: bool = False,
+) -> List[_SelectableEntry]:
+ del stable_by_content
+ return sorted(
+ selectable_entries,
+ key=lambda entry: (
+ str(entry[3] or entry[0] or entry[1] or "").casefold(),
+ str(entry[1] or "").casefold(),
+ ),
+ )
+
+
+def _register_selectable_branch(
+ *,
+ child: RetrieverNode,
+ child_path: tuple[str, ...],
+ selectable_entries: List[_SelectableEntry],
+) -> ExposedNode:
+ canonical_id = f"node::{child.node_id}"
+ selectable_entries.append(
+ (
+ canonical_id,
+ child.label or child.node_id,
+ child.description or "",
+ child.node_id,
+ False,
+ child_path,
+ child,
+ None,
+ )
+ )
+ return ExposedNode(
+ canonical_id=canonical_id,
+ label=child.label or child.node_id,
+ description=child.description or "",
+ is_selectable=True,
+ selectable_canonical_id=child.node_id,
+ )
+
+
+def _render_tree(
+ node: ExposedNode,
+ *,
+ resolution_by_canonical_id: Dict[str, SelectableResolution],
+ compact_codes_enabled: bool,
+ depth: int = 0,
+) -> str:
+ lines: List[str] = []
+ indent = " " * depth
+ if node.is_selectable:
+ resolution = resolution_by_canonical_id[node.canonical_id]
+ if compact_codes_enabled:
+ identifier = f"{resolution.display_name} [id: {resolution.code}]"
+ else:
+ identifier = f"Candidate {resolution.display_name}"
+ else:
+ identifier = f"Category {node.label}"
+ description = str(node.description or "")
+ if node.is_selectable:
+ description = _sanitize_candidate_description(description)
+ if description:
+ lines.append(f"{indent}- {identifier}: {description}")
+ else:
+ lines.append(f"{indent}- {identifier}")
+ for child in node.children:
+ lines.append(
+ _render_tree(
+ child,
+ resolution_by_canonical_id=resolution_by_canonical_id,
+ compact_codes_enabled=compact_codes_enabled,
+ depth=depth + 1,
+ )
+ )
+ return "\n".join(lines)
+
+
+def _render_flat_list(
+ selectable_nodes: Sequence[ExposedNode],
+ *,
+ resolution_by_canonical_id: Dict[str, SelectableResolution],
+ compact_codes_enabled: bool,
+) -> str:
+ if compact_codes_enabled:
+ candidates: List[Dict[str, str]] = []
+ for node in selectable_nodes:
+ resolution = resolution_by_canonical_id[node.canonical_id]
+ description = _sanitize_candidate_description(
+ str(node.description or ""),
+ collapse_newlines=True,
+ )
+ description = _maybe_shorten_flat_compact_description(description)
+ candidates.append(
+ _ordered_flat_compact_item(
+ {
+ "category": _format_branch_category(resolution.branch_path),
+ "name": _format_flat_compact_name(resolution),
+ "raw_name": _format_flat_compact_raw_name(resolution),
+ "description": description,
+ "id": str(resolution.code),
+ }
+ )
+ )
+ return json.dumps(candidates, ensure_ascii=False, indent=2)
+
+ lines: List[str] = []
+ for node in selectable_nodes:
+ resolution = resolution_by_canonical_id[node.canonical_id]
+ description = _sanitize_candidate_description(
+ str(node.description or ""),
+ collapse_newlines=False,
+ )
+ line = f"- {resolution.display_name}"
+ if description:
+ line = f"{line}: {description}"
+ lines.append(line)
+ return "\n".join(lines)
+
+
+def _ordered_flat_compact_item(fields: Dict[str, str]) -> Dict[str, str]:
+ order = _flat_compact_field_order()
+ return {field: fields[field] for field in order}
+
+
+def _flat_compact_field_order() -> tuple[str, ...]:
+ return _FLAT_COMPACT_FIELD_ORDER_DEFAULT
+
+
+def _format_flat_compact_name(resolution: SelectableResolution) -> str:
+ if not resolution.is_terminal:
+ return str(resolution.display_name or "").strip()
+ label = re.sub(r"\s+", " ", str(resolution.label or "").strip())
+ if label:
+ return label
+ return str(resolution.display_name or "").strip()
+
+
+def _format_flat_compact_raw_name(resolution: SelectableResolution) -> str:
+ if resolution.is_terminal and resolution.item is not None:
+ worker_id = str(getattr(resolution.item, "worker_id", "") or "").strip()
+ if worker_id:
+ return worker_id
+ return str(resolution.display_name or "").strip()
+
+
+def _sanitize_candidate_description(description: str, *, collapse_newlines: bool = False) -> str:
+ text = str(description or "").strip()
+ if not text:
+ return ""
+ text = _REPRESENTATIVE_DESCENDANTS_RE.sub("", text).strip()
+ if collapse_newlines:
+ text = re.sub(r"\s*\n+\s*", " ", text).strip()
+ return text
+
+
+def _maybe_shorten_flat_compact_description(text: str) -> str:
+ max_chars = _FLAT_COMPACT_DESCRIPTION_MAX_CHARS_DEFAULT
+ cleaned = re.sub(r"\s+", " ", str(text or "").strip())
+ if len(cleaned) <= max_chars:
+ return cleaned
+ boundary = max(
+ cleaned.rfind("。", 0, max_chars),
+ cleaned.rfind(".", 0, max_chars),
+ cleaned.rfind(";", 0, max_chars),
+ cleaned.rfind(";", 0, max_chars),
+ )
+ if boundary >= max(40, max_chars // 2):
+ return cleaned[:boundary + 1].strip()
+ return cleaned[:max_chars].rstrip(" ,,;;。.") + "..."
+
+
+def _format_branch_category(branch_path: Sequence[str]) -> str:
+ category_labels = _fixed_category_labels()
+ labels: List[str] = []
+ for raw_part in branch_path:
+ part = str(raw_part or "").strip()
+ if not part:
+ continue
+ label = part.rsplit(".", 1)[-1]
+ if label.upper() == "ROOT":
+ continue
+ label = category_labels.get(label, label)
+ if label and (not labels or labels[-1] != label):
+ labels.append(label)
+ if not labels:
+ return ""
+ return " > ".join(labels[-3:])
+
+
+@lru_cache(maxsize=1)
+def _fixed_category_labels() -> Dict[str, str]:
+ try:
+ from indexing.tree.schema import FIXED_ROOT_CATEGORIES
+ except Exception:
+ return {}
+
+ labels: Dict[str, str] = {}
+
+ def visit(category_id: str, spec: object) -> None:
+ if not isinstance(spec, dict):
+ return
+ name = str(spec.get("name") or "").strip()
+ if name:
+ labels[str(category_id)] = name
+ pascal = to_pascal_case(str(category_id))
+ if pascal:
+ labels[pascal] = name
+ children = spec.get("children")
+ if isinstance(children, dict):
+ for child_id, child_spec in children.items():
+ visit(str(child_id), child_spec)
+
+ for root_id, root_spec in FIXED_ROOT_CATEGORIES.items():
+ visit(str(root_id), root_spec)
+ return labels
+
+
+def _iter_selectable_nodes(node: ExposedNode) -> Iterable[ExposedNode]:
+ if node.is_selectable:
+ yield node
+ for child in node.children:
+ yield from _iter_selectable_nodes(child)
+
+
+def _build_codes(
+ selectable_entries: Sequence[_SelectableEntry],
+ *,
+ compact_codes_enabled: bool,
+ compact_codebook: Sequence[str] = (),
+) -> List[str]:
+ count = len(selectable_entries)
+ if count <= 0:
+ return []
+ if not compact_codes_enabled:
+ return _build_boundary_names(selectable_entries)
+ normalized_codebook = _normalize_codebook(compact_codebook)
+ if normalized_codebook:
+ if len(normalized_codebook) < count:
+ raise ValueError(
+ "compact codebook provides "
+ f"{len(normalized_codebook)} codes, but {count} selectable nodes were exposed"
+ )
+ return list(normalized_codebook[:count])
+ return [_encode_boundary_code(index, width=0) for index in range(count)]
+
+
+def _build_boundary_names(
+ selectable_entries: Sequence[_SelectableEntry],
+) -> List[str]:
+ base_names: List[str] = []
+ for entry in selectable_entries:
+ selectable_canonical_id = str(entry[3] or "").strip()
+ terminal = selectable_canonical_id.split(".")[-1] if selectable_canonical_id else ""
+ base_name = (
+ to_pascal_case(terminal)
+ or to_pascal_case(selectable_canonical_id.replace(".", "-"))
+ or selectable_canonical_id
+ or str(entry[1] or "").strip()
+ )
+ base_names.append(base_name)
+ grouped: Dict[str, List[int]] = {}
+ for index, name in enumerate(base_names):
+ grouped.setdefault(name, []).append(index)
+
+ identifiers = list(base_names)
+ for name, indices in grouped.items():
+ if len(indices) <= 1:
+ continue
+ for index in indices:
+ selectable_path = tuple(
+ str(part or "").strip()
+ for part in selectable_entries[index][5]
+ if str(part or "").strip()
+ )
+ path_parts = [to_pascal_case(part) or part for part in selectable_path[1:] if part]
+ if path_parts:
+ identifiers[index] = "/".join([*path_parts, name])
+ else:
+ identifiers[index] = f"{name}__{index + 1}"
+ return identifiers
+
+
+def _normalize_codebook(codebook: Sequence[str]) -> tuple[str, ...]:
+ normalized: List[str] = []
+ seen: set[str] = set()
+ for raw_code in codebook:
+ code = str(raw_code or "").strip()
+ if not code:
+ raise ValueError("compact codebook entries must be non-empty strings")
+ if code == "0":
+ raise ValueError("compact codebook cannot include reserved abstain code '0'")
+ if any(character.isspace() for character in code):
+ raise ValueError(f"compact codebook entry {code!r} cannot contain whitespace")
+ if code in seen:
+ raise ValueError(f"compact codebook entry {code!r} is duplicated")
+ seen.add(code)
+ normalized.append(code)
+ return tuple(normalized)
+
+
+def _resolve_code_width(codes: Sequence[str]) -> int:
+ if not codes:
+ return 1
+ widths = {len(str(code)) for code in codes}
+ if len(widths) == 1:
+ return next(iter(widths))
+ return 0
+
+
+def _build_fragment_fingerprint(*, root_node: ExposedNode, candidate_codes: Sequence[str]) -> str:
+ payload = f"{_serialize_exposed_node(root_node)}|{'/'.join(str(code) for code in candidate_codes)}"
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
+
+
+def _serialize_exposed_node(node: ExposedNode) -> str:
+ children = ",".join(_serialize_exposed_node(child) for child in node.children)
+ return f"{node.canonical_id}|{node.label}|{int(node.is_selectable)}|{children}"
+
+
+def _encode_boundary_code(index: int, *, width: int) -> str:
+ del width
+ return str(max(0, int(index)) + 1)
+
+
+__all__ = [
+ "DisclosureConfig",
+ "DisclosurePromptParts",
+ "ExposedFragment",
+ "ExposedNode",
+ "SelectableResolution",
+ "build_disclosure_messages",
+ "build_disclosure_prompt_parts",
+ "build_exposed_fragment",
+ "parse_selected_codes",
+]
diff --git a/jiuwenswarm/symphony/retrieval/tree/render/prompts.yaml b/jiuwenswarm/symphony/retrieval/tree/render/prompts.yaml
new file mode 100644
index 0000000000..5a9ed37b98
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/render/prompts.yaml
@@ -0,0 +1,229 @@
+progressive_system_prompt:
+ shared: |-
+
+ /no_think
+
+ # 背景与目标:
+ - 系统的最终目标是解决用户的问题。
+ - 系统通过调用 Candidate skill 来执行任务。
+ - 你的职责是:组建一个最优 skill 小组,以端到端闭环用户的任务。
+
+ 注意:
+ - 你只做“候选筛选”,不做规划、不做执行。
+
+
+ # 输出规则:
+
+ 1. 总共输出至多 {top_k} 个 Candidate skill 节点 id
+
+ 2. 该结果必须是:
+ - 最优 Candidate skill 组合
+ - 该组合能够完整闭环用户任务
+
+ 3. 至多输出 {top_k} 行
+
+
+ # 选择规则:
+
+ ## 1. 决策目标
+ - 组合应覆盖用户的核心目标、必要前置条件和关键辅助能力。
+ - 不要为了凑满 {top_k} 选择低相关或无关 skill。
+
+ ## 2. 约束优先级
+ - 用户的显式约束优先级最高,包括时间、范围、条件、格式、工具类型、排除项等。
+ - 如果用户明确排除某类能力,不能选择对应 skill。
+ - 例如:用户明确不要 PPT,就不能选择 PPT、幻灯片、演示文稿相关 skill。
+
+ ## 3. 意图理解
+ - 先识别用户的显式意图,再补全与任务闭环强相关的隐式意图。
+ - 当用户只表达状态、场景、计划或意向时,不要轻易返回空;应保守预测可帮助用户的潜在意图。
+ - 潜在意图必须与用户原话高度相关。
+
+ ## 4. 组合补全
+ - 围绕用户目标,补全完成任务所需的关键上下游能力。
+ - 优先选择能形成闭环的互补 skill,而不是只选择表面最相似的 skill。
+ - 只补全与用户目标强相关、能够实际提升任务完成度的 skill。
+ - 不要为了覆盖更多方面而加入弱相关 skill。
+
+ ## 5. Notes
+ - 务必识别真实隐含意图,避免被表面词误导。
+ - 例如:“生成一张地图”更可能需要图像生成,而不是地点查询。
+ - 用户要求根据时间线、历史路线、事件节点生成、绘制或标注地图/路线图时,应选择图像生成/视觉设计类 skill;不要选择地图查询、导航、定位或地图 JSAPI,除非用户明确要查询真实地点、规划路线或开发地图应用。
+ - 不要选择与用户任务无关的 skill。
+ - 必须严格遵守用户的显式约束(如时间、范围、条件等)
+ - 要选出**能够完整闭环用户意图的 skill 组合**,包括用户的显式意图和隐式意图。
+ - 例如,用户有出行意图时,不仅考虑出行规划,也要选择查询天气相关 skill
+ - 用户有饮食、购物等意图时,不仅直接选择对应的出行助手,也要选择美团红包优惠
+ - 用户要搭建网站时,不仅直接选择 html 生成与前端开发,也可以考虑艺术创作
+ - 务必确认用户的真实隐含意图,例如“生成一张地图”实质上对应于基于 AI 的图像生成,而非查询地图。
+ - 不要附带任何无关的 skill,例如,用户不需要 PPT 时不要选择 PPT 相关技能。用户需要生成地图而非查询地点时,不要选择地图相关技能。
+ - 用户明确不要某类 skill 时,不要选择对应的 skill。
+
+ {structure_block}
+
+ {candidate_block}
+
+
+
+
+
+ # 输出 id 说明:
+
+ {output_block}
+
+ shared_top2: |-
+
+ # 背景与目标:
+ - 系统的最终目标是解决用户的问题。
+ - 系统通过调用 Candidate skill 来执行任务。
+ - 你的职责是:从候选中选择 2 个 skill,组成能够闭环当前用户请求的执行小组。
+
+ 注意:
+ - 你只做“候选筛选”,不做规划、不做执行。
+ - 默认必须输出 2 个候选;不要因为只找到一个最相似 skill 就停止。
+ - 少召回一个真正有用的 skill,比召回一个弱相关但仍可解释的辅助 skill 更糟。
+ - 第二个 skill 不要求和用户请求字面最相似,但必须能放进同一个任务链路中。
+ - 不要因为用户请求复杂,就选择用于创建、管理或调度其他 skill/agent 的候选;只有当这类候选本身就是用户明示目标时才选择。
+ - 候选在列表或树中的出现顺序没有相关性含义;不要因为候选靠前就选择它。
+ - 第一个候选不是默认项;如果不能用用户请求中的目标对象或动作解释它,禁止输出第一个候选。
+
+
+ # 输出规则:
+
+ 1. 默认输出 2 个 Candidate skill 节点 id
+
+ 2. 这 2 个 skill 应组成最优执行小组:
+ - 第一个 skill 覆盖用户的主任务
+ - 第二个 skill 覆盖同一任务链路中的前置、后置、输入理解、信息查询、内容生成、格式化、保存、发送、上下文补充或执行辅助能力
+ - 两者共同提高完成用户请求的把握
+
+ 3. 必须尽量输出 2 行,每行 1 个 id;只有当所有候选中完全不存在可放入同一任务链路的第二个 skill 时,才输出 1 行
+
+
+ # 选择规则:
+
+ ## 1. 决策目标
+ - 目标不是找“最像 query 的单个 skill”,而是找“最可能完整完成任务的 2 个 skill 小组”。
+ - 先选择最能直接完成用户主任务的 skill。
+ - 再选择一个能补全任务链路的 skill。
+ - 如果用户请求包含多个动作、多个阶段、多个输入或多个输出格式,应优先用 2 个 skill 分别覆盖这些部分。
+
+ ## 2. 第二个 skill 的召回规则
+ - 第二个 skill 可以是以下任一类型:
+ - 获取或搜索完成任务所需的信息
+ - 读取、识别、理解输入材料
+ - 分析、计算、对比或总结内容
+ - 生成用户要求的目标格式
+ - 保存、上传、发送、同步或自动执行结果
+ - 提供天气、地图、出行、优惠、健康数据等关键上下文
+ - 第二个 skill 只要能被用户请求的目标、动作、输入、输出或场景解释,就应该输出。
+ - 不要因为第二个 skill 不是字面最匹配而省略它。
+ - 不要输出两个功能完全重复的 skill;但如果两个候选分别覆盖同一任务的不同阶段,可以同时选择。
+
+ ## 3. 无关项过滤
+ - 禁止选择与用户任务链路无关的 skill。
+ - 禁止用泛化 agent、skill 管理、内部治理、通用记忆、通用规划类候选填充第二个位置,除非用户明确要求这类能力。
+ - 如果某个候选只能通过非常牵强的联想解释,不能选择。
+ - 如果一个候选只是因为类别相近、名字常见或位置靠前而相关,不能选择。
+
+ ## 4. 约束优先级
+ - 用户的显式约束优先级最高,包括时间、范围、条件、格式、工具类型、排除项等。
+ - 如果用户明确排除某类能力,不能选择对应 skill。
+ - 例如:用户明确不要 PPT,就不能选择 PPT、幻灯片、演示文稿相关 skill。
+
+ ## 5. 意图理解
+ - 先识别用户的显式意图,再补全与任务闭环强相关的隐式意图。
+ - 当用户只表达状态、场景、计划或意向时,不要轻易只输出 1 个;应保守召回一个可帮助闭环的辅助 skill。
+ - 务必区分“查询已有信息”和“生成新内容”。
+ - 务必区分“读取/理解输入材料”和“创作/编辑输出材料”。
+ - 务必识别真实隐含意图,避免被表面词误导。
+
+ ## 6. Notes
+ - 用户有出行或户外计划时,除旅行/路线 skill 外,天气通常是合理的第二候选。
+ - 用户有饮食、餐厅、门店、优惠相关意图时,美团优惠/券通常是合理的第二候选。
+ - 用户要生成网站、页面、展览展示、视觉作品时,网页/前端和图片/视觉创作可以形成互补。
+ - 用户要处理图片、截图、照片中的信息时,应优先考虑图像理解/识别;只有用户要求画、生成、编辑、美化图片时,才选择图像生成/设计。
+ - 用户要搜索、查询、对比真实产品或外部事实时,应选择搜索/调研类 skill;如果还要求表格、文档、邮件等输出,再选择对应输出 skill。
+ - 用户询问真实股票行情、走势、拐点、建仓或投资分析时,选择行情/金融数据/预测类 skill;只有用户明确要模拟交易、虚拟持仓或投资练习时,才选择股票模拟器。
+ - 用户要求根据时间线、历史路线、事件节点生成、绘制或标注地图/路线图时,应选择图像创作类 skill;不要选择地图查询、导航、定位或地图 JSAPI,除非用户明确要查询真实地点、规划路线或开发地图应用。
+ - 用户询问家中空间或智能家居物理设备的状态或控制时,应选择智能家居/家庭设备状态控制类 skill;例如灯光、空调、电视、路由器、门锁、传感器。不要用通用 APP 操控替代;也不要把运动健康、手机 App 数据或个人健康数据归到智能家居。
+ - 用户提到录音、语音、会议音频、语音转文字或从音频中找信息时,优先选择音频转写/听写类 skill;不要用视频剪辑、播客生成或图片识别替代。
+ - 用户要查询真实产品参数、价格、座位图、已有图片或外部事实时,信息获取 skill 是必要能力;不要用图像生成、表格、PPT 或文档输出 skill 替代搜索/调研/图片搜索。
+ - 用户要查看已有运动健康数据、心率、血压、睡眠或心理数据时,优先选择健康数据类 skill;不要用习惯打卡替代已有数据查询。
+ - 用户明确提到天气、气象、户外条件或气象风险时,天气通常是必要候选之一。
+ - 用户表达家中空间、睡眠环境或物理设备状态/控制时,优先考虑智能家居;设置闹钟只在用户要求提醒、叫醒或定时时选择。
+ - 不要附带与用户任务无关的 skill。
+
+ {structure_block}
+
+ {candidate_block}
+
+ # 输出 id 说明:
+
+ {output_block}
+
+ structure_codes: |-
+ # 候选格式:
+ - <CANDIDATE_TREE> 中的 Category 表示分组,不可选择。
+ - <CANDIDATE_TREE> 中的 NAME [id: X] 表示候选 skill,可选择,其中 X 是候选 id。
+ - 缩进表示候选与分组之间的从属关系。
+
+ structure_names: |-
+ # 候选格式:
+ - <CANDIDATE_TREE> 中的 Category 表示分组,不可选择。
+ - <CANDIDATE_TREE> 中的 Candidate NAME 表示候选 skill,可选择,其中 NAME 是 Candidate skill 节点 id。
+ - 缩进表示候选与分组之间的从属关系。
+
+ structure_codes_flat: |-
+ # 候选格式:
+ - Available options 是 JSON 数组,每个对象都是一个可选择的候选 skill。
+ - 每个对象格式为 {"category": "CATEGORY", "name": "NAME", "raw_name": "RAW_NAME", "description": "DESCRIPTION", "id": "ID"}。
+ - id 是两个大写字母候选 ID;category、name、raw_name 和 description 只用于判断相关性。
+ - 最终只能输出候选 JSON 对象 id 字段中的两个大写字母 ID。
+
+ structure_names_flat: ""
+
+ output_codes: |-
+ - 仅输出候选行 [id: ...] 方括号中的 id,不要附带任何其他内容。
+ - 每个非空行必须只包含一个候选 id;整行只能是 id 本身。
+ - 禁止输出横线、候选名称、[id: ...]、冒号、描述或整行候选文本。
+ - 任何以 - 开头的行都是错误输出。
+ - 如果想复制候选行,必须改为只输出该候选行 [id: ...] 中的 id。
+ - id 是无语义序号句柄,不是英文缩写、类别名或能力名,不参与语义判断。
+ - 不要根据 id 的字母含义、字母顺序或常见缩写含义判断相关性。
+ - 选择时只根据 NAME 和 DESCRIPTION 判断相关性;[id: X] 是无语义序号句柄,不是英文缩写、类别名或能力名,不参与语义判断。
+ - NAME 只能用于选择判断,不能出现在最终输出中。
+ - 最终只能输出方括号中的 id;不要输出 NAME、DESCRIPTION、[id:] 前缀或整行候选文本。
+ - 如果选择多个候选,每一行都必须是对应候选的 id;不要用候选名称替代 id。
+ - 绝对不要先输出 id,再继续输出候选名称。
+ - 如果想输出某个候选名称,必须改为输出该候选行 [id: ...] 中的 id。
+ - 输出前自检:每个非空行都必须完全匹配一个候选 id;如果某行不是候选 id,删除该行。
+ - 不要输出候选名称、描述、整行候选文本、[id:] 前缀、列表、编号、后缀或解释。
+ - 例如,候选行为 Summary [id: CC]: Summarize long documents 时,只能输出 CC。
+ - 错误输出包括:以 - 开头、包含候选名称、包含 [id:]、包含冒号、包含描述或复制整行候选文本。
+ - 正确输出示例:CC
+
+ output_codes_flat: |-
+ - 仅输出候选对象中的 id,不要附带任何其他内容。
+ - 每个非空行必须只包含一个候选 ID;整行只能是 ID 本身。
+ - 候选 ID 来自 JSON 对象的 "id" 字段。
+ - 禁止输出 JSON、方括号、花括号、引号、字段名、候选名称、冒号、描述或整个候选对象。
+ - 如果想复制候选对象,必须改为只输出该对象的 id。
+ - ID 是无语义序号句柄,不是英文缩写、类别名或能力名,不参与语义判断。
+ - 不要根据 ID 的字符含义、字符顺序或常见缩写含义判断相关性。
+ - 选择时只根据 NAME 和 DESCRIPTION 判断相关性;ID 是无语义序号句柄,不参与语义判断。
+ - NAME 只能用于选择判断,不能出现在最终输出中。
+ - 最终只能输出 ID;不要输出 NAME、DESCRIPTION、JSON 片段或整个候选对象。
+ - 如果选择多个候选,每一行都必须是对应候选的 ID;不要用候选名称替代 ID。
+ - 绝对不要先输出 ID,再继续输出候选名称。
+ - 输出前自检:每个非空行都必须完全匹配一个候选 ID;如果某行不是候选 ID,删除该行。
+ - 例如,候选对象为 {{"id": "AB", "name": "Summary", "description": "Summarize long documents"}} 时,只能输出 AB。
+ - 错误输出包括:包含候选名称、包含字段名、包含引号、包含冒号、包含描述或复制整个候选对象。
+ - 正确输出示例:AB
+
+ output_names_tree: |-
+ - 仅输出驼峰格式的节点 id, 不要附带任何其他内容
+ - 只能输出 Candidate 行中的 NAME,不要输出 Category、描述、编号、解释或整行候选文本。
+
+ output_names_flat: |-
+ - 仅输出驼峰格式的节点 id, 不要附带任何其他内容
diff --git a/jiuwenswarm/symphony/retrieval/tree/select/__init__.py b/jiuwenswarm/symphony/retrieval/tree/select/__init__.py
new file mode 100644
index 0000000000..1197cd0588
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/select/__init__.py
@@ -0,0 +1,17 @@
+from .default import DefaultTopKSelector
+from .selection import (
+ FragmentSelector,
+ GenerateFragmentSelector,
+ LogitSelectionFragmentSelector,
+ ScoringFragmentSelector,
+ SoftmaxFragmentSelector,
+)
+
+__all__ = [
+ "DefaultTopKSelector",
+ "FragmentSelector",
+ "GenerateFragmentSelector",
+ "LogitSelectionFragmentSelector",
+ "ScoringFragmentSelector",
+ "SoftmaxFragmentSelector",
+]
diff --git a/jiuwenswarm/symphony/retrieval/tree/select/default.py b/jiuwenswarm/symphony/retrieval/tree/select/default.py
new file mode 100644
index 0000000000..50c1f6bf58
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/select/default.py
@@ -0,0 +1,74 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+from typing import Callable, Sequence
+
+from models.retrieval import RetrieverTrace
+from .selection import GenerateFragmentSelector, LogitSelectionFragmentSelector
+
+from ..contracts import TopKSelector
+from ..types import (
+ CurrentSubtree,
+ ProgressiveRetrieverConfig,
+ PromptBundle,
+ SearchCursor,
+ SelectableTarget,
+ SelectionProtocol,
+ SelectionResult,
+)
+
+_ABSTAIN_HINT_RE = re.compile(
+ r"(none|no suitable|no relevant|not relevant|unrelated|cannot determine|can't determine|"
+ r"无合适|没有合适|无相关|没有相关|不相关|无法判断|无法确定)",
+ re.IGNORECASE,
+)
+
+
+@dataclass
+class DefaultTopKSelector(TopKSelector):
+ config: ProgressiveRetrieverConfig
+ build_generate_selector: Callable[[], GenerateFragmentSelector | LogitSelectionFragmentSelector]
+
+ def build_protocol(self, *, subtree: CurrentSubtree) -> SelectionProtocol:
+ return SelectionProtocol(
+ compact_codes_enabled=bool(subtree.fragment.compact_codes_enabled),
+ candidate_codes=tuple(subtree.fragment.candidate_codes),
+ code_width=int(subtree.fragment.code_width),
+ abstain_token="0",
+ )
+
+ def select_topk(
+ self,
+ *,
+ model: str,
+ cursor: SearchCursor,
+ query_messages: Sequence[dict[str, str]],
+ subtree: CurrentSubtree,
+ prompt: PromptBundle,
+ trace: RetrieverTrace,
+ ) -> SelectionResult:
+ selector = self.build_generate_selector()
+ output, selected = selector.select(
+ model=model,
+ query_messages=list(query_messages),
+ node=cursor.node,
+ depth=cursor.depth,
+ top_k=cursor.top_k,
+ trace=trace,
+ fragment=subtree.fragment,
+ )
+ return SelectionResult(
+ raw_output=output,
+ selected_targets=tuple(SelectableTarget(resolution=item) for item in selected),
+ is_abstain=not selected and self._is_abstain_output(output),
+ )
+
+ @staticmethod
+ def _is_abstain_output(output: str) -> bool:
+ text = str(output or "").strip()
+ if not text:
+ return False
+ if text == "0":
+ return True
+ return _ABSTAIN_HINT_RE.search(text) is not None
diff --git a/jiuwenswarm/symphony/retrieval/tree/select/selection.py b/jiuwenswarm/symphony/retrieval/tree/select/selection.py
new file mode 100644
index 0000000000..d3223d8663
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/select/selection.py
@@ -0,0 +1,256 @@
+from __future__ import annotations
+
+from abc import abstractmethod
+from dataclasses import dataclass
+import logging
+from time import perf_counter
+from typing import Callable, Protocol
+
+from models.retrieval import RetrieverNode, RetrieverTrace
+from ...llm import ProgressiveLLMClient
+from ..render.disclosure import ExposedFragment, SelectableResolution
+from ..render.disclosure import build_disclosure_messages
+
+LOGGER = logging.getLogger("retrieval.logit_selection.selection")
+
+
+class FragmentSelector(Protocol):
+ @abstractmethod
+ def select(
+ self,
+ *,
+ model: str,
+ query_messages: list[dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ fragment: ExposedFragment,
+ ) -> tuple[str, list[SelectableResolution]]:
+ raise NotImplementedError
+
+
+@dataclass
+class GenerateFragmentSelector:
+ generate_fn: Callable[..., tuple[str, list[SelectableResolution]]]
+
+ def select(
+ self,
+ *,
+ model: str,
+ query_messages: list[dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ fragment: ExposedFragment,
+ ) -> tuple[str, list[SelectableResolution]]:
+ return self.generate_fn(
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ fragment=fragment,
+ )
+
+
+@dataclass
+class LogitSelectionFragmentSelector:
+ client: ProgressiveLLMClient
+ require_single_token_codes: bool
+ fallback_mode: str
+ generate_selector: GenerateFragmentSelector
+ max_candidates: int = 512
+ min_probability: float | None = None
+ trace_top_n: int = 10
+
+ def select(
+ self,
+ *,
+ model: str,
+ query_messages: list[dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ fragment: ExposedFragment,
+ ) -> tuple[str, list[SelectableResolution]]:
+ backend_name = getattr(self.client, "name", type(self.client).__name__)
+ LOGGER.info(
+ "fragment selection start mode=logit_selection backend=%s node=%s depth=%d "
+ "top_k=%d candidate_count=%d compact=%s",
+ backend_name,
+ node.node_id,
+ int(depth),
+ int(top_k),
+ len(fragment.candidate_codes),
+ bool(fragment.compact_codes_enabled),
+ )
+ if not self.client.capabilities.candidate_scoring or not fragment.compact_codes_enabled:
+ return self._fallback(
+ reason=(
+ "backend_unavailable"
+ if not self.client.capabilities.candidate_scoring
+ else "compact_codes_disabled"
+ ),
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ fragment=fragment,
+ )
+ if len(fragment.candidate_codes) > max(1, int(self.max_candidates)):
+ return self._fallback(
+ reason=f"candidate_count_exceeds_limit:{len(fragment.candidate_codes)}>{int(self.max_candidates)}",
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ fragment=fragment,
+ )
+ trace.record(
+ "fragment_logit_selection_requested",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "backend": backend_name,
+ "candidate_count": len(fragment.candidate_codes),
+ "candidate_codes": list(fragment.candidate_codes),
+ "candidate_canonical_ids": [
+ fragment.code_to_resolution[code].canonical_id
+ for code in fragment.candidate_codes
+ if code in fragment.code_to_resolution
+ ],
+ "fragment_fingerprint": fragment.fragment_fingerprint,
+ "selection_mode": "logit_selection",
+ },
+ )
+ try:
+ scoring_started = perf_counter()
+ messages = build_disclosure_messages(fragment=fragment, query_messages=query_messages)
+ scoring_result = self.client.score_candidate_codes(
+ model=model,
+ messages=messages,
+ candidate_codes=fragment.candidate_codes or tuple(fragment.code_to_resolution.keys()),
+ code_to_canonical_id={
+ code: resolution.canonical_id for code, resolution in fragment.code_to_resolution.items()
+ },
+ top_k=max(1, len(fragment.candidate_codes or tuple(fragment.code_to_resolution.keys()))),
+ require_single_token_codes=self.require_single_token_codes,
+ )
+ scores = list(scoring_result.scores)
+ scoring_total_ms = round((perf_counter() - scoring_started) * 1000.0, 3)
+ except Exception as exc:
+ LOGGER.warning(
+ "fragment selection scoring_failed backend=%s node=%s depth=%d reason=%s",
+ backend_name,
+ node.node_id,
+ int(depth),
+ exc,
+ )
+ return self._fallback(
+ reason=str(exc),
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ fragment=fragment,
+ )
+ top_scores = list(scores[:max(1, int(self.trace_top_n))])
+ trace.record(
+ "fragment_logit_selection_completed",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "backend": backend_name,
+ "candidate_count": len(fragment.candidate_codes),
+ "fragment_fingerprint": fragment.fragment_fingerprint,
+ "top_codes": [item.code for item in top_scores],
+ "top_canonical_ids": [item.canonical_id for item in top_scores],
+ "top_logits": [item.logit for item in top_scores],
+ "top_probabilities": [item.probability for item in top_scores],
+ "latency_breakdown": dict(scoring_result.latency_breakdown, selector_total_ms=scoring_total_ms),
+ },
+ )
+ threshold = None if self.min_probability is None else float(self.min_probability)
+ filtered_scores = [item for item in scores if threshold is None or float(item.probability) >= threshold]
+ selected = [
+ fragment.code_to_resolution[item.code]
+ for item in filtered_scores[:max(1, int(top_k))]
+ if item.code in fragment.code_to_resolution
+ ]
+ raw_output = "\n".join(item.code for item in filtered_scores[:max(1, int(top_k))]) if selected else "0"
+ LOGGER.info(
+ "fragment selection complete backend=%s node=%s depth=%d selected_count=%d raw_output=%s",
+ backend_name,
+ node.node_id,
+ int(depth),
+ len(selected),
+ raw_output,
+ )
+ return raw_output, selected
+
+ def _fallback(
+ self,
+ *,
+ reason: str,
+ model: str,
+ query_messages: list[dict[str, str]],
+ node: RetrieverNode,
+ depth: int,
+ top_k: int,
+ trace: RetrieverTrace,
+ fragment: ExposedFragment,
+ ) -> tuple[str, list[SelectableResolution]]:
+ trace.record(
+ "fragment_logit_selection_fallback",
+ node_id=node.node_id,
+ depth=depth,
+ detail={
+ "backend": getattr(self.client, "name", type(self.client).__name__),
+ "fallback_mode": self.fallback_mode,
+ "reason": reason,
+ "fragment_fingerprint": fragment.fragment_fingerprint,
+ },
+ )
+ mode = str(self.fallback_mode or "generate").strip().lower()
+ LOGGER.warning(
+ "fragment selection fallback backend=%s node=%s depth=%d mode=%s reason=%s",
+ getattr(self.client, "name", type(self.client).__name__),
+ node.node_id,
+ int(depth),
+ mode,
+ reason,
+ )
+ if mode == "abstain":
+ return "0", []
+ if mode == "error":
+ raise RuntimeError(reason)
+ return self.generate_selector.select(
+ model=model,
+ query_messages=query_messages,
+ node=node,
+ depth=depth,
+ top_k=top_k,
+ trace=trace,
+ fragment=fragment,
+ )
+
+
+__all__ = [
+ "FragmentSelector",
+ "GenerateFragmentSelector",
+ "LogitSelectionFragmentSelector",
+]
+
+
+ScoringFragmentSelector = LogitSelectionFragmentSelector
+SoftmaxFragmentSelector = LogitSelectionFragmentSelector
diff --git a/jiuwenswarm/symphony/retrieval/tree/subtree/__init__.py b/jiuwenswarm/symphony/retrieval/tree/subtree/__init__.py
new file mode 100644
index 0000000000..f8ef3a94b6
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/subtree/__init__.py
@@ -0,0 +1,17 @@
+from .default import DefaultCurrentSubtreeProvider
+from .roots import (
+ build_progressive_branch_description,
+ build_progressive_item_label,
+ build_progressive_root,
+ choices_cache_key,
+ freeze_progressive_root,
+)
+
+__all__ = [
+ "DefaultCurrentSubtreeProvider",
+ "build_progressive_branch_description",
+ "build_progressive_item_label",
+ "build_progressive_root",
+ "choices_cache_key",
+ "freeze_progressive_root",
+]
diff --git a/jiuwenswarm/symphony/retrieval/tree/subtree/default.py b/jiuwenswarm/symphony/retrieval/tree/subtree/default.py
new file mode 100644
index 0000000000..81cf3088aa
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/subtree/default.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from ..render.disclosure import DisclosureConfig, build_exposed_fragment
+
+from ..contracts import CurrentSubtreeProvider
+from ..types import CurrentSubtree, ProgressiveRetrieverConfig, SearchCursor, SelectableTarget
+
+
+@dataclass(frozen=True)
+class DefaultCurrentSubtreeProvider(CurrentSubtreeProvider):
+ config: ProgressiveRetrieverConfig
+ subtree_item_count: object
+ cache: dict[tuple[int, tuple[str, ...]], CurrentSubtree] | None = None
+ cache_lock: Any | None = None
+
+ def get_current_subtree(self, *, cursor: SearchCursor) -> CurrentSubtree:
+ cache_key = (id(cursor.node), tuple(cursor.branch_path))
+ if self.cache is not None:
+ if self.cache_lock is None:
+ cached = self.cache.get(cache_key)
+ else:
+ with self.cache_lock:
+ cached = self.cache.get(cache_key)
+ if cached is not None:
+ return CurrentSubtree(
+ cursor=cursor,
+ fragment=cached.fragment,
+ selectable_targets=cached.selectable_targets,
+ )
+ fragment = build_exposed_fragment(
+ root=cursor.node,
+ branch_path=cursor.branch_path,
+ config=DisclosureConfig(
+ max_exposure_depth_per_call=max(0, int(self.config.max_exposure_depth_per_call)),
+ exposure_threshold=max(0, int(self.config.exposure_threshold)),
+ compact_boundary_codes_enabled=bool(self.config.compact_boundary_codes_enabled),
+ compact_boundary_codebook=tuple(str(code) for code in self.config.compact_boundary_codebook),
+ flatten_full_tree_in_prompt=bool(self.config.flatten_full_tree_in_prompt),
+ ),
+ subtree_item_count=self.subtree_item_count,
+ )
+ subtree = CurrentSubtree(
+ cursor=cursor,
+ fragment=fragment,
+ selectable_targets=tuple(
+ SelectableTarget(resolution=item) for item in fragment.code_to_resolution.values()
+ ),
+ )
+ if self.cache is not None:
+ if self.cache_lock is None:
+ self.cache[cache_key] = subtree
+ else:
+ with self.cache_lock:
+ self.cache.setdefault(cache_key, subtree)
+ subtree = self.cache[cache_key]
+ return subtree
diff --git a/jiuwenswarm/symphony/retrieval/tree/subtree/roots.py b/jiuwenswarm/symphony/retrieval/tree/subtree/roots.py
new file mode 100644
index 0000000000..6542be3da1
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/subtree/roots.py
@@ -0,0 +1,111 @@
+from __future__ import annotations
+
+import hashlib
+import json
+from typing import Any, Dict, MutableMapping, Sequence
+
+from models.retrieval import RetrieverItem, RetrieverNode
+
+
+def choices_cache_key(choices: Sequence[object]) -> str:
+ payload = [
+ {
+ "choice_id": str(getattr(choice, "choice_id", "") or ""),
+ "payload": str(getattr(choice, "payload", "") or ""),
+ "description": str(getattr(choice, "description", "") or ""),
+ }
+ for choice in choices
+ ]
+ return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")).hexdigest()
+
+
+def build_progressive_root(
+ choices: Sequence[object], *, cache: MutableMapping[str, RetrieverNode]
+) -> RetrieverNode | None:
+ cache_key = choices_cache_key(choices)
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached
+
+ class _NodeBuilder:
+ __slots__ = ("node_id", "label", "children", "items")
+
+ def __init__(self, *, node_id: str, label: str) -> None:
+ self.node_id = node_id
+ self.label = label
+ self.children: Dict[str, "_NodeBuilder"] = {}
+ self.items: list[RetrieverItem] = []
+
+ root = _NodeBuilder(node_id="ROOT", label="ROOT")
+ hierarchical = False
+ for choice in choices:
+ choice_id = str(getattr(choice, "choice_id", "") or "").strip()
+ payload = str(getattr(choice, "payload", "") or "").strip()
+ description = str(getattr(choice, "description", "") or "").strip()
+ if not choice_id or not payload:
+ continue
+ parts = [part.strip() for part in payload.split(".") if part.strip()]
+ item = RetrieverItem(
+ item_id=choice_id,
+ payload=payload,
+ label=build_progressive_item_label(choice_id=choice_id, payload=payload),
+ description=description,
+ )
+ if len(parts) <= 1:
+ root.items.append(item)
+ continue
+ hierarchical = True
+ current = root
+ for depth, part in enumerate(parts[:-1], start=1):
+ branch_id = ".".join(parts[:depth])
+ child = current.children.get(branch_id)
+ if child is None:
+ child = _NodeBuilder(node_id=branch_id, label=part)
+ current.children[branch_id] = child
+ current = child
+ current.items.append(item)
+
+ if not hierarchical and not root.items:
+ return None
+ frozen = freeze_progressive_root(root)
+ cache[cache_key] = frozen
+ return frozen
+
+
+def freeze_progressive_root(builder: Any) -> RetrieverNode:
+ children = [
+ freeze_progressive_root(child) for _node_id, child in sorted(builder.children.items(), key=lambda item: item[0])
+ ]
+ items = sorted(builder.items, key=lambda item: (str(item.label or item.item_id).lower(), str(item.item_id).lower()))
+ return RetrieverNode(
+ node_id=str(builder.node_id),
+ label=str(builder.label),
+ description=build_progressive_branch_description(
+ label=str(builder.label or builder.node_id), children=children, items=items
+ ),
+ children=tuple(children),
+ items=tuple(items),
+ )
+
+
+def build_progressive_item_label(*, choice_id: str, payload: str) -> str:
+ display_name = str(choice_id or "").strip()
+ if display_name:
+ return display_name
+ leaf_term = payload.split(".")[-1].strip() if payload else ""
+ return leaf_term or payload
+
+
+def build_progressive_branch_description(
+ *, label: str, children: Sequence[RetrieverNode], items: Sequence[RetrieverItem]
+) -> str:
+ return ""
+
+
+__all__ = [
+ "build_progressive_branch_description",
+ "build_progressive_item_label",
+ "build_progressive_root",
+ "choices_cache_key",
+ "freeze_progressive_root",
+]
diff --git a/jiuwenswarm/symphony/retrieval/tree/types.py b/jiuwenswarm/symphony/retrieval/tree/types.py
new file mode 100644
index 0000000000..553061e6e4
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/tree/types.py
@@ -0,0 +1,116 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Dict, List
+
+from models.retrieval import RetrieverCandidate, RetrieverItem, RetrieverNode, RetrieverTrace
+from ..llm.config import LLMClientConfig, OpenAIClientConfig
+from .codebooks import DEFAULT_COMPACT_BOUNDARY_CODEBOOK
+from .render.disclosure import ExposedFragment, SelectableResolution
+
+
+@dataclass(frozen=True)
+class ProgressiveRetrieverConfig:
+ top_k: int = 5
+ max_tokens: int = 96
+ trie_constrained_decoding_enabled: bool = False
+ max_branch_choices: int = 6
+ max_parallel_branches: int = 3
+ enable_parallel_branches: bool = True
+ branch_choice_slack: int = 2
+ branch_candidate_slack: int = 1
+ round_robin_branch_reduce: bool = True
+ request_timeout: float | None = 120.0
+ compact_boundary_codes_enabled: bool = True
+ compact_boundary_codebook: tuple[str, ...] = DEFAULT_COMPACT_BOUNDARY_CODEBOOK
+ flatten_full_tree_in_prompt: bool = True
+ max_exposure_depth_per_call: int = 99
+ exposure_threshold: int = 1_000_000_000
+ selection_mode: str = "generate"
+ scoring_require_single_token_codes: bool = True
+ scoring_return_probabilities: bool = True
+ scoring_fallback_mode: str = "error"
+ scoring_max_candidates: int = 512
+ scoring_min_probability: float | None = None
+ scoring_trace_top_n: int = 10
+ llm_client_config: LLMClientConfig = field(default_factory=OpenAIClientConfig)
+
+
+@dataclass
+class ProgressiveRetrieverResult:
+ candidates: List[RetrieverCandidate]
+ trace: RetrieverTrace
+ candidate_records: List[Dict[str, object]] = field(default_factory=list)
+ summary_lines: List[str] = field(default_factory=list)
+ selected_payload: str | None = None
+ selected_rank: int = -1
+ raw_outputs: List[str] = field(default_factory=list)
+ request_messages: List[Dict[str, str]] = field(default_factory=list)
+ elapsed_ms: float = 0.0
+
+
+@dataclass(frozen=True)
+class SearchCursor:
+ node: RetrieverNode
+ depth: int
+ branch_path: tuple[str, ...]
+ top_k: int
+
+
+@dataclass(frozen=True)
+class SelectableTarget:
+ resolution: SelectableResolution
+
+ @property
+ def is_terminal(self) -> bool:
+ return bool(self.resolution.is_terminal)
+
+ @property
+ def branch_path(self) -> tuple[str, ...]:
+ return tuple(self.resolution.branch_path)
+
+
+@dataclass(frozen=True)
+class CurrentSubtree:
+ cursor: SearchCursor
+ fragment: ExposedFragment
+ selectable_targets: tuple[SelectableTarget, ...]
+
+
+@dataclass(frozen=True)
+class SelectionProtocol:
+ compact_codes_enabled: bool
+ candidate_codes: tuple[str, ...]
+ code_width: int
+ abstain_token: str = "0"
+
+
+@dataclass(frozen=True)
+class PromptBundle:
+ fragment: ExposedFragment
+ protocol: SelectionProtocol
+ messages: tuple[Dict[str, str], ...]
+
+
+@dataclass(frozen=True)
+class SelectionResult:
+ raw_output: str
+ selected_targets: tuple[SelectableTarget, ...]
+ is_abstain: bool = False
+
+
+@dataclass(frozen=True)
+class ChildSearchCursor:
+ cursor: SearchCursor
+ target: SelectableTarget
+
+
+@dataclass(frozen=True)
+class ExpansionPlan:
+ leaf_results: tuple[RetrieverCandidate, ...]
+ child_cursors: tuple[ChildSearchCursor, ...]
+
+
+@dataclass(frozen=True)
+class NodeSearchResult:
+ candidates: tuple[RetrieverCandidate, ...]
diff --git a/jiuwenswarm/symphony/retrieval/truncation.py b/jiuwenswarm/symphony/retrieval/truncation.py
new file mode 100644
index 0000000000..9e3996b512
--- /dev/null
+++ b/jiuwenswarm/symphony/retrieval/truncation.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass
+from typing import Callable, Sequence, TypeVar
+
+
+T = TypeVar("T")
+
+
+@dataclass(frozen=True)
+class ScoreTruncationConfig:
+ min_score: float | None = None
+ relative_min_score: float | None = None
+ autocut_jumps: int = 0
+ autocut_min_relative_drop: float = 0.0
+
+
+@dataclass(frozen=True)
+class ScoreTruncationDecision:
+ initial_count: int
+ kept_count: int
+ cutoff_index: int | None = None
+ reason: str = ""
+ best_score: float | None = None
+ min_score: float | None = None
+ relative_min_score: float | None = None
+ autocut_jumps: int = 0
+ autocut_min_relative_drop: float = 0.0
+
+ def to_dict(self) -> dict[str, object]:
+ return asdict(self)
+
+
+def truncate_sorted_by_score(
+ items: Sequence[T],
+ *,
+ score_getter: Callable[[T], float],
+ config: ScoreTruncationConfig,
+) -> tuple[list[T], ScoreTruncationDecision]:
+ values = list(items)
+ if not values:
+ return [], ScoreTruncationDecision(initial_count=0, kept_count=0)
+
+ best_score = float(score_getter(values[0]))
+ cutoff = len(values)
+ reason = ""
+
+ if config.min_score is not None:
+ candidate_cutoff = _first_score_below(values, score_getter=score_getter, threshold=float(config.min_score))
+ if candidate_cutoff < cutoff:
+ cutoff = candidate_cutoff
+ reason = "min_score"
+
+ if config.relative_min_score is not None and best_score > 0.0:
+ relative_threshold = best_score * max(0.0, float(config.relative_min_score))
+ candidate_cutoff = _first_score_below(values, score_getter=score_getter, threshold=relative_threshold)
+ if candidate_cutoff < cutoff:
+ cutoff = candidate_cutoff
+ reason = "relative_min_score"
+
+ if config.autocut_jumps > 0:
+ candidate_cutoff = _autocut_cutoff(
+ values,
+ score_getter=score_getter,
+ jumps=max(1, int(config.autocut_jumps)),
+ min_relative_drop=max(0.0, float(config.autocut_min_relative_drop)),
+ )
+ if candidate_cutoff < cutoff:
+ cutoff = candidate_cutoff
+ reason = "autocut"
+
+ kept = values[:cutoff]
+ return kept, ScoreTruncationDecision(
+ initial_count=len(values),
+ kept_count=len(kept),
+ cutoff_index=cutoff if cutoff < len(values) else None,
+ reason=reason,
+ best_score=best_score,
+ min_score=config.min_score,
+ relative_min_score=config.relative_min_score,
+ autocut_jumps=max(0, int(config.autocut_jumps)),
+ autocut_min_relative_drop=max(0.0, float(config.autocut_min_relative_drop)),
+ )
+
+
+def _first_score_below(
+ items: Sequence[T],
+ *,
+ score_getter: Callable[[T], float],
+ threshold: float,
+) -> int:
+ for index, item in enumerate(items):
+ if float(score_getter(item)) < threshold:
+ return index
+ return len(items)
+
+
+def _autocut_cutoff(
+ items: Sequence[T],
+ *,
+ score_getter: Callable[[T], float],
+ jumps: int,
+ min_relative_drop: float,
+) -> int:
+ if len(items) <= 1:
+ return len(items)
+ observed_jumps = 0
+ for index in range(1, len(items)):
+ previous = float(score_getter(items[index - 1]))
+ current = float(score_getter(items[index]))
+ absolute_drop = previous - current
+ if absolute_drop <= 0.0:
+ continue
+ relative_drop = absolute_drop / max(abs(previous), 1e-9)
+ if relative_drop < min_relative_drop:
+ continue
+ observed_jumps += 1
+ if observed_jumps >= jumps:
+ return index
+ return len(items)
+
+
+__all__ = [
+ "ScoreTruncationConfig",
+ "ScoreTruncationDecision",
+ "truncate_sorted_by_score",
+]
diff --git a/jiuwenswarm/symphony/shared/__init__.py b/jiuwenswarm/symphony/shared/__init__.py
new file mode 100644
index 0000000000..b80db191ee
--- /dev/null
+++ b/jiuwenswarm/symphony/shared/__init__.py
@@ -0,0 +1,29 @@
+from .storage import (
+ S3Location,
+ create_s3_client,
+ download_s3_object_to_path,
+ download_s3_relative_object_if_exists,
+ is_s3_uri,
+ join_s3_uri,
+ materialize_s3_dir,
+ parse_s3_uri,
+ read_s3_bytes,
+ read_s3_text,
+ upload_local_dir_to_s3,
+ upload_s3_bytes,
+)
+
+__all__ = [
+ "S3Location",
+ "create_s3_client",
+ "download_s3_object_to_path",
+ "download_s3_relative_object_if_exists",
+ "is_s3_uri",
+ "join_s3_uri",
+ "materialize_s3_dir",
+ "parse_s3_uri",
+ "read_s3_bytes",
+ "read_s3_text",
+ "upload_local_dir_to_s3",
+ "upload_s3_bytes",
+]
diff --git a/jiuwenswarm/symphony/shared/profiling.py b/jiuwenswarm/symphony/shared/profiling.py
new file mode 100644
index 0000000000..6b7794872b
--- /dev/null
+++ b/jiuwenswarm/symphony/shared/profiling.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+import logging
+from contextlib import contextmanager
+from time import perf_counter
+
+
+class StageTimer:
+ def __init__(self, scope: str, *, logger: logging.Logger | None = None) -> None:
+ self._scope = str(scope or "").strip() or "unknown"
+ self._logger = logger or logging.getLogger("index_builder")
+ self._start = perf_counter()
+ self._phases: list[tuple[str, float]] = []
+
+ @contextmanager
+ def phase(self, name: str):
+ phase_name = str(name or "").strip() or "phase"
+ phase_start = perf_counter()
+ try:
+ yield
+ finally:
+ elapsed_ms = (perf_counter() - phase_start) * 1000.0
+ self._phases.append((phase_name, elapsed_ms))
+ self._logger.info(
+ "timing | scope=%s | phase=%s | elapsed_ms=%.2f",
+ self._scope,
+ phase_name,
+ elapsed_ms,
+ )
+
+ def finish(self) -> None:
+ total_ms = (perf_counter() - self._start) * 1000.0
+ phases_summary = "; ".join(f"{name}:{elapsed:.2f}ms" for name, elapsed in self._phases) or "-"
+ self._logger.info(
+ "timing | scope=%s | total_ms=%.2f | phases=%s",
+ self._scope,
+ total_ms,
+ phases_summary,
+ )
+
diff --git a/jiuwenswarm/symphony/shared/rich_compat.py b/jiuwenswarm/symphony/shared/rich_compat.py
new file mode 100644
index 0000000000..c0f53244f3
--- /dev/null
+++ b/jiuwenswarm/symphony/shared/rich_compat.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+try:
+ from rich.console import Console
+ from rich.panel import Panel
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
+ from rich.tree import Tree as RichTree
+except ModuleNotFoundError:
+
+ class Console:
+ @staticmethod
+ def print(*args, **kwargs) -> None:
+ return None
+
+ class Panel:
+ def __init__(self, renderable=None, *args, **kwargs) -> None:
+ self.renderable = renderable
+
+ @classmethod
+ def fit(cls, renderable=None, *args, **kwargs):
+ return cls(renderable, *args, **kwargs)
+
+ class Progress:
+ def __init__(self, *args, **kwargs) -> None:
+ self._next_task_id = 0
+
+ def __enter__(self):
+ return self
+
+ @staticmethod
+ def __exit__(exc_type, exc, tb) -> None:
+ return None
+
+ def add_task(self, *args, **kwargs) -> int:
+ task_id = self._next_task_id
+ self._next_task_id += 1
+ return task_id
+
+ @staticmethod
+ def update(*args, **kwargs) -> None:
+ return None
+
+ class SpinnerColumn:
+ def __init__(self, *args, **kwargs) -> None:
+ return None
+
+ class TextColumn:
+ def __init__(self, *args, **kwargs) -> None:
+ return None
+
+ class BarColumn:
+ def __init__(self, *args, **kwargs) -> None:
+ return None
+
+ class TaskProgressColumn:
+ def __init__(self, *args, **kwargs) -> None:
+ return None
+
+ class RichTree:
+ def __init__(self, label, *args, **kwargs) -> None:
+ self.label = label
+ self.children = []
+
+ def add(self, label, *args, **kwargs):
+ child = RichTree(label, *args, **kwargs)
+ self.children.append(child)
+ return child
+
+
+__all__ = [
+ "BarColumn",
+ "Console",
+ "Panel",
+ "Progress",
+ "RichTree",
+ "SpinnerColumn",
+ "TaskProgressColumn",
+ "TextColumn",
+]
diff --git a/jiuwenswarm/symphony/shared/storage.py b/jiuwenswarm/symphony/shared/storage.py
new file mode 100644
index 0000000000..5c489a5319
--- /dev/null
+++ b/jiuwenswarm/symphony/shared/storage.py
@@ -0,0 +1,298 @@
+from __future__ import annotations
+
+from contextlib import suppress
+from dataclasses import dataclass
+from hashlib import sha1
+import os
+from pathlib import Path
+import tempfile
+from typing import Dict, Sequence
+from urllib.parse import urlparse
+
+_SUPPORTED_SCHEMES = {"s3", "obs"}
+_DEFAULT_DOWNLOAD_NAMES = (
+ "manifest.json",
+ "tree_index.yaml",
+ "catalog.jsonl",
+ "tree_index.html",
+)
+
+
+@dataclass(frozen=True)
+class S3Location:
+ scheme: str
+ bucket: str
+ key: str
+
+ @property
+ def uri(self) -> str:
+ if self.key:
+ return f"{self.scheme}://{self.bucket}/{self.key}"
+ return f"{self.scheme}://{self.bucket}"
+
+
+def is_s3_uri(value: str | Path) -> bool:
+ parsed = urlparse(str(value).strip())
+ return parsed.scheme.lower() in _SUPPORTED_SCHEMES
+
+
+def parse_s3_uri(uri: str, *, require_key: bool = False) -> S3Location:
+ parsed = urlparse(str(uri).strip())
+ scheme = str(parsed.scheme or "").strip().lower()
+ bucket = str(parsed.netloc or "").strip()
+ key = str(parsed.path or "").lstrip("/").strip()
+ invalid_location = scheme not in _SUPPORTED_SCHEMES or not bucket
+ missing_required_key = require_key and not key
+ if invalid_location or missing_required_key:
+ raise ValueError(f"Invalid S3 URI: {uri}")
+ return S3Location(scheme=scheme, bucket=bucket, key=key)
+
+
+def join_s3_uri(base_uri: str, *parts: str) -> str:
+ location = parse_s3_uri(base_uri)
+ suffix = "/".join(str(part or "").strip("/").strip() for part in parts if str(part or "").strip("/").strip())
+ key = str(location.key or "").strip("/")
+ if key and suffix:
+ final_key = f"{key}/{suffix}"
+ elif suffix:
+ final_key = suffix
+ else:
+ final_key = key
+ return S3Location(scheme=location.scheme, bucket=location.bucket, key=final_key).uri
+
+
+def read_s3_bytes(uri: str) -> bytes:
+ location = parse_s3_uri(uri, require_key=True)
+ client = create_s3_client()
+ response = client.get_object(Bucket=location.bucket, Key=location.key)
+ body = response.get("Body")
+ if body is None:
+ raise RuntimeError(f"S3 object body is empty: {uri}")
+ try:
+ return body.read()
+ finally:
+ with suppress(Exception):
+ body.close()
+
+
+def read_s3_text(uri: str, *, encoding: str = "utf-8") -> str:
+ return read_s3_bytes(uri).decode(encoding)
+
+
+def download_s3_object_to_path(uri: str, destination_path: str | Path) -> Path:
+ target = Path(destination_path)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(read_s3_bytes(uri))
+ return target
+
+
+def download_s3_relative_object_if_exists(*, base_uri: str, relative_path: str, destination_path: str | Path) -> bool:
+ try:
+ download_s3_object_to_path(join_s3_uri(base_uri, relative_path), destination_path)
+ return True
+ except Exception as exc:
+ if _is_missing_object_error(exc):
+ return False
+ raise
+
+
+def upload_s3_bytes(uri: str, payload: bytes) -> None:
+ location = parse_s3_uri(uri, require_key=True)
+ client = create_s3_client()
+ client.put_object(Bucket=location.bucket, Key=location.key, Body=payload)
+
+
+def upload_local_dir_to_s3(local_dir: str | Path, base_uri: str) -> None:
+ directory = Path(local_dir)
+ if not directory.exists():
+ raise FileNotFoundError(directory)
+ if not directory.is_dir():
+ raise NotADirectoryError(directory)
+
+ primary_signing = _resolve_payload_signing_enabled_from_env()
+ primary_addressing = _resolve_addressing_style_from_env()
+ alternative_addressing = "path" if primary_addressing == "virtual" else "virtual"
+ clients: Dict[tuple[bool, str], object] = {}
+
+ def get_client(signing: bool, style: str):
+ key = (signing, style)
+ if key not in clients:
+ clients[key] = create_s3_client(payload_signing_enabled=signing, addressing_style=style)
+ return clients[key]
+
+ for path in sorted(directory.rglob("*")):
+ if not path.is_file():
+ continue
+ relative = str(path.relative_to(directory)).replace("\\", "/")
+ payload = path.read_bytes()
+ destination_uri = join_s3_uri(base_uri, relative)
+ location = parse_s3_uri(destination_uri, require_key=True)
+ attempts = (
+ (primary_signing, primary_addressing),
+ (not primary_signing, primary_addressing),
+ (primary_signing, alternative_addressing),
+ (not primary_signing, alternative_addressing),
+ )
+ last_error: Exception | None = None
+ for signing, style in attempts:
+ client = get_client(signing, style)
+ try:
+ client.put_object(Bucket=location.bucket, Key=location.key, Body=payload)
+ last_error = None
+ break
+ except Exception as exc:
+ if not _is_retryable_put_error(exc):
+ raise
+ last_error = exc
+ if last_error is not None:
+ raise last_error
+
+
+def materialize_s3_dir(
+ base_uri: str,
+ *,
+ relative_paths: Sequence[str] | None = None,
+ cache_namespace: str = "s3-dir-cache",
+) -> Path:
+ normalized_base = str(base_uri).rstrip("/")
+ cache_root = Path(tempfile.gettempdir()) / cache_namespace
+ cache_root.mkdir(parents=True, exist_ok=True)
+ cache_key = sha1(normalized_base.encode("utf-8")).hexdigest()[:16]
+ local_dir = cache_root / cache_key
+ local_dir.mkdir(parents=True, exist_ok=True)
+
+ names = list(relative_paths or _DEFAULT_DOWNLOAD_NAMES)
+ if "manifest.json" not in names:
+ names = ["manifest.json", *names]
+ for relative in names:
+ download_s3_relative_object_if_exists(
+ base_uri=normalized_base,
+ relative_path=relative,
+ destination_path=local_dir / relative,
+ )
+ manifest_path = local_dir / "manifest.json"
+ if not manifest_path.exists():
+ raise FileNotFoundError(f"Index manifest not found under {normalized_base}")
+ return local_dir
+
+
+def create_s3_client(
+ *,
+ payload_signing_enabled: bool | None = None,
+ addressing_style: str | None = None,
+):
+ try:
+ import boto3
+ from botocore.config import Config
+ except Exception as exc:
+ raise RuntimeError("boto3/botocore is required for S3 storage access") from exc
+
+ endpoint = _first_env("MARKET_S3_ENDPOINT", "OBS_ENDPOINT", "S3_ENDPOINT", "AWS_ENDPOINT_URL")
+ access_key = _first_env("MARKET_S3_ACCESS_KEY", "OBS_ACCESS_KEY", "AWS_ACCESS_KEY_ID")
+ secret_key = _first_env("MARKET_S3_SECRET_KEY", "OBS_SECRET_KEY", "AWS_SECRET_ACCESS_KEY")
+ region = _first_env("MARKET_S3_REGION", "OBS_REGION", "AWS_REGION", "AWS_DEFAULT_REGION") or "us-east-1"
+
+ use_ssl_raw = _first_env("MARKET_S3_USE_SSL")
+ if use_ssl_raw.lower() in {"1", "true", "yes", "on"}:
+ use_ssl = True
+ elif use_ssl_raw.lower() in {"0", "false", "no", "off"}:
+ use_ssl = False
+ else:
+ use_ssl = endpoint.startswith("https://") if endpoint else True
+
+ resolved_payload_signing = payload_signing_enabled
+ if resolved_payload_signing is None:
+ resolved_payload_signing = _resolve_payload_signing_enabled_from_env()
+ resolved_addressing_style = addressing_style or _resolve_addressing_style_from_env()
+ config = _new_botocore_config(
+ Config,
+ s3_subconfig={
+ "addressing_style": resolved_addressing_style,
+ "payload_signing_enabled": resolved_payload_signing,
+ },
+ )
+
+ kwargs = {
+ "service_name": "s3",
+ "region_name": region,
+ "use_ssl": use_ssl,
+ "config": config,
+ }
+ if endpoint:
+ kwargs["endpoint_url"] = endpoint
+ if access_key:
+ kwargs["aws_access_key_id"] = access_key
+ if secret_key:
+ kwargs["aws_secret_access_key"] = secret_key
+ return boto3.client(**kwargs)
+
+
+def _new_botocore_config(config_cls, *, s3_subconfig: Dict[str, object]):
+ try:
+ return config_cls(
+ signature_version="s3v4",
+ s3=s3_subconfig,
+ request_checksum_calculation="when_required",
+ response_checksum_validation="when_required",
+ )
+ except TypeError:
+ return config_cls(signature_version="s3v4", s3=s3_subconfig)
+
+
+def _first_env(*names: str) -> str:
+ for name in names:
+ value = str(os.getenv(name) or "").strip()
+ if value:
+ return value
+ return ""
+
+
+def _resolve_payload_signing_enabled_from_env() -> bool:
+ raw = _first_env("MARKET_S3_PAYLOAD_SIGNING_ENABLED", "OBS_S3_PAYLOAD_SIGNING_ENABLED")
+ return raw.lower() in {"1", "true", "yes", "on"}
+
+
+def _resolve_addressing_style_from_env() -> str:
+ raw = _first_env("MARKET_S3_ADDRESSING_STYLE", "OBS_S3_ADDRESSING_STYLE") or "virtual"
+ value = raw.strip().lower()
+ return value if value in {"virtual", "path"} else "virtual"
+
+
+def _is_retryable_put_error(exc: Exception) -> bool:
+ response = getattr(exc, "response", None)
+ if isinstance(response, dict):
+ error = response.get("Error")
+ if isinstance(error, dict):
+ code = str(error.get("Code") or "").strip()
+ if code in {"XAmzContentSHA256Mismatch", "VirtualHostDomainRequired"}:
+ return True
+ text = str(exc)
+ return "XAmzContentSHA256Mismatch" in text or "VirtualHostDomainRequired" in text
+
+
+def _is_missing_object_error(exc: Exception) -> bool:
+ response = getattr(exc, "response", None)
+ if isinstance(response, dict):
+ error = response.get("Error")
+ if isinstance(error, dict):
+ code = str(error.get("Code") or "").strip()
+ if code in {"NoSuchKey", "404", "NotFound"}:
+ return True
+ text = str(exc)
+ return "NoSuchKey" in text or "Not Found" in text or "404" in text
+
+
+__all__ = [
+ "S3Location",
+ "create_s3_client",
+ "download_s3_object_to_path",
+ "download_s3_relative_object_if_exists",
+ "is_s3_uri",
+ "join_s3_uri",
+ "materialize_s3_dir",
+ "parse_s3_uri",
+ "read_s3_bytes",
+ "read_s3_text",
+ "upload_local_dir_to_s3",
+ "upload_s3_bytes",
+]
diff --git a/jiuwenswarm/symphony/skill_retrieval/__init__.py b/jiuwenswarm/symphony/skill_retrieval/__init__.py
new file mode 100644
index 0000000000..3e0ea12109
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/__init__.py
@@ -0,0 +1,10 @@
+"""JiuwenSwarm adapters for dispatch-based installed-skill retrieval."""
+
+from .api import build_skill_index, get_skill_retrieval_status, get_skill_retrieval_tree, retrieve_skills
+
+__all__ = [
+ "build_skill_index",
+ "get_skill_retrieval_status",
+ "get_skill_retrieval_tree",
+ "retrieve_skills",
+]
diff --git a/jiuwenswarm/symphony/skill_retrieval/api.py b/jiuwenswarm/symphony/skill_retrieval/api.py
new file mode 100644
index 0000000000..60d23c8001
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/api.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from typing import Any
+
+
+def build_skill_index(manager: Any | None = None) -> dict[str, Any]:
+ from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+
+ from .index_service import SkillIndexService
+
+ resolved_manager = manager or SkillManager()
+ payload = SkillIndexService(resolved_manager).build_index()
+ return _tool_payload(payload)
+
+
+def retrieve_skills(query: str, manager: Any | None = None) -> dict[str, Any]:
+ from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+
+ from .retrieve_service import SkillRetrieveService
+
+ resolved_manager = manager or SkillManager()
+ payload = SkillRetrieveService(resolved_manager).retrieve(query)
+ return _tool_payload(payload)
+
+
+def get_skill_retrieval_status(manager: Any | None = None) -> dict[str, Any]:
+ from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+
+ from .index_service import SkillIndexService
+
+ resolved_manager = manager or SkillManager()
+ return SkillIndexService(resolved_manager).status()
+
+
+def get_skill_retrieval_tree(manager: Any | None = None) -> dict[str, Any]:
+ from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+
+ from .index_service import SkillIndexService
+
+ resolved_manager = manager or SkillManager()
+ return SkillIndexService(resolved_manager).tree()
+
+
+def _tool_payload(payload: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "success": bool(payload.get("success")),
+ "result": str(payload.get("result") or ""),
+ }
diff --git a/jiuwenswarm/symphony/skill_retrieval/config.py b/jiuwenswarm/symphony/skill_retrieval/config.py
new file mode 100644
index 0000000000..e1d9d701b9
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/config.py
@@ -0,0 +1,197 @@
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from jiuwenswarm.common.config import get_config
+from jiuwenswarm.common.utils import get_agent_workspace_dir
+
+
+@dataclass(frozen=True)
+class LLMSettings:
+ model: str
+ api_key: str
+ base_url: str
+ seed: int | None = None
+
+
+@dataclass(frozen=True)
+class BuildSettings:
+ branching_factor: int = 128
+ max_depth: int = 6
+ root_categories: Any = None
+ max_workers: int = 2
+ max_retries: int = 2
+ request_timeout_seconds: float = 420.0
+ classification_batch_limit: int = 32
+ discovery_seed: int = 42
+ postprocess_enabled: bool = True
+ postprocess_max_passes: int = 1
+ postprocess_min_skills: int = 6
+ equivalence_enabled: bool = True
+
+
+@dataclass(frozen=True)
+class RetrieveSettings:
+ top_k: int = 10
+ compact_codes_enabled: bool = False
+ flatten_tree: bool = False
+ max_exposure_depth: int = 99
+ max_branch_choices: int = 2
+ max_parallel_branches: int = 2
+ max_tokens: int = 96
+ request_timeout_seconds: float = 120.0
+
+
+@dataclass(frozen=True)
+class SkillRetrievalSettings:
+ enabled: bool
+ artifact_root: Path
+ llm: LLMSettings
+ build: BuildSettings
+ retrieve: RetrieveSettings
+
+
+def load_settings() -> SkillRetrievalSettings:
+ config = get_config() or {}
+ section = _dict_get(config, "symphony", "skill_retrieval")
+ artifact_root = _artifact_root(section)
+ return SkillRetrievalSettings(
+ enabled=_as_bool(section.get("enabled"), False),
+ artifact_root=artifact_root,
+ llm=_load_llm(section, config),
+ build=_load_build(section.get("build") if isinstance(section.get("build"), dict) else {}),
+ retrieve=_load_retrieve(section.get("retrieve") if isinstance(section.get("retrieve"), dict) else {}),
+ )
+
+
+def _dict_get(payload: dict[str, Any], *keys: str) -> dict[str, Any]:
+ current: Any = payload
+ for key in keys:
+ if not isinstance(current, dict):
+ return {}
+ current = current.get(key)
+ return current if isinstance(current, dict) else {}
+
+
+def _artifact_root(section: dict[str, Any]) -> Path:
+ raw = str(section.get("artifact_root") or os.getenv("SYMPHONY_SKILL_RETRIEVAL_ROOT") or "").strip()
+ if raw:
+ return Path(raw).expanduser().resolve()
+ return get_agent_workspace_dir() / "symphony" / "skill_retrieval"
+
+
+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)
+ model = str(
+ override.get("model")
+ or override.get("model_name")
+ or model_cfg.get("model")
+ or model_cfg.get("model_name")
+ or os.getenv("MODEL_NAME")
+ or ""
+ ).strip()
+ api_key = str(override.get("api_key") or model_cfg.get("api_key") or os.getenv("API_KEY") or "").strip()
+ base_url = str(
+ override.get("base_url")
+ or override.get("api_base")
+ or model_cfg.get("base_url")
+ or model_cfg.get("api_base")
+ or os.getenv("API_BASE")
+ or ""
+ ).strip()
+ seed = _as_optional_int(override.get("seed"))
+ return LLMSettings(model=model, api_key=api_key, base_url=base_url, seed=seed)
+
+
+def _default_model_client_config(config: dict[str, Any]) -> dict[str, Any]:
+ models = config.get("models") if isinstance(config.get("models"), dict) else {}
+ defaults = models.get("defaults")
+ if isinstance(defaults, list) and defaults:
+ first = defaults[0]
+ if isinstance(first, dict):
+ mcc = first.get("model_client_config")
+ if isinstance(mcc, dict):
+ return mcc
+ default = models.get("default")
+ if isinstance(default, dict):
+ mcc = default.get("model_client_config")
+ if isinstance(mcc, dict):
+ return mcc
+ return {}
+
+
+def _load_build(raw: dict[str, Any]) -> BuildSettings:
+ return BuildSettings(
+ branching_factor=_as_int(raw.get("branching_factor"), 128),
+ 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),
+ 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),
+ postprocess_enabled=_as_bool(raw.get("postprocess_enabled"), True),
+ postprocess_max_passes=_as_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),
+ )
+
+
+def _load_retrieve(raw: dict[str, Any]) -> RetrieveSettings:
+ return RetrieveSettings(
+ top_k=_as_int(raw.get("top_k"), 10),
+ 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),
+ )
+
+
+def _as_bool(value: Any, default: bool) -> bool:
+ if value is None:
+ return default
+ if isinstance(value, bool):
+ return value
+ text = str(value).strip().lower()
+ if not text:
+ return default
+ return text in {"1", "true", "yes", "on", "enabled"}
+
+
+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
+
+
+def _as_int(value: Any, default: int) -> int:
+ try:
+ return max(1, int(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
+
+
+def _as_float(value: Any, default: float) -> float:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return default
diff --git a/jiuwenswarm/symphony/skill_retrieval/dispatch_imports.py b/jiuwenswarm/symphony/skill_retrieval/dispatch_imports.py
new file mode 100644
index 0000000000..6d8bc1b262
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/dispatch_imports.py
@@ -0,0 +1,27 @@
+from __future__ import annotations
+
+import sys
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Iterator
+
+SYMPHONY_ROOT = Path(__file__).resolve().parents[1]
+
+
+@contextmanager
+def dispatch_import_path() -> Iterator[None]:
+ """Expose the vendored dispatch source as top-level packages."""
+
+ root = str(SYMPHONY_ROOT)
+ inserted = False
+ if root not in sys.path:
+ sys.path.append(root)
+ inserted = True
+ try:
+ yield
+ finally:
+ if inserted:
+ try:
+ sys.path.remove(root)
+ except ValueError:
+ pass
diff --git a/jiuwenswarm/symphony/skill_retrieval/index_service.py b/jiuwenswarm/symphony/skill_retrieval/index_service.py
new file mode 100644
index 0000000000..dadbcd8359
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/index_service.py
@@ -0,0 +1,473 @@
+from __future__ import annotations
+
+import json
+import logging
+import shutil
+import time
+from dataclasses import asdict
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+from .config import SkillRetrievalSettings, load_settings
+from .dispatch_imports import dispatch_import_path
+from .inventory import SkillInventory, scan_skill_inventory
+from .markdown import render_build_failure, render_build_success, render_disabled
+
+TREE_INDEX_FILENAME = "tree_index.yaml"
+CATALOG_FILENAME = "catalog.jsonl"
+MANIFEST_FILENAME = "manifest.json"
+STATE_FILENAME = "state.json"
+LOGGER = logging.getLogger(__name__)
+
+
+class SkillIndexService:
+ def __init__(self, manager: Any) -> None:
+ self._manager = manager
+
+ def status(self) -> dict[str, Any]:
+ settings = load_settings()
+ inventory = scan_skill_inventory(self._manager)
+ index_dir = _index_dir(settings)
+ state = _read_state(settings)
+ expected = _expected_fingerprint(inventory, settings)
+ complete = _is_complete_index(index_dir)
+ fresh = complete and state.get("fingerprint") == expected
+ return {
+ "enabled": settings.enabled,
+ "artifact_root": str(settings.artifact_root),
+ "index_dir": str(index_dir),
+ "index_exists": complete,
+ "fresh": fresh,
+ "installed_enabled_count": inventory.count,
+ "indexed_count": int(state.get("indexed_count") or 0) if complete else 0,
+ "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,
+ }
+
+ def build_index(self) -> dict[str, Any]:
+ started = time.monotonic()
+ settings = load_settings()
+ if not settings.enabled:
+ return {"success": False, "result": render_disabled()}
+
+ inventory = scan_skill_inventory(self._manager)
+ if inventory.count == 0:
+ return {
+ "success": False,
+ "result": render_build_failure(
+ "No enabled installed skills were found under the agent skills directory."
+ ),
+ }
+
+ settings.artifact_root.mkdir(parents=True, exist_ok=True)
+ _tmp_dir(settings).mkdir(parents=True, exist_ok=True)
+ expected = _expected_fingerprint(inventory, settings)
+
+ recovered = self._recover_index(settings=settings, inventory=inventory, expected_fingerprint=expected)
+ state = _read_state(settings)
+ if _is_complete_index(_index_dir(settings)) and state.get("fingerprint") == expected:
+ return {
+ "success": True,
+ "result": render_build_success(
+ reused=True,
+ inventory=inventory,
+ index_dir=str(_index_dir(settings)),
+ elapsed_seconds=time.monotonic() - started,
+ ),
+ "recovered": recovered,
+ }
+
+ if not settings.llm.model or not settings.llm.api_key:
+ return {
+ "success": False,
+ "result": render_build_failure(
+ "Offline dispatch tree build requires a model and API key. "
+ "Configure `models.defaults[0].model_client_config` or `symphony.skill_retrieval.llm`."
+ ),
+ }
+
+ build_root = (
+ _tmp_dir(settings) / f"build-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}-{time.time_ns()}"
+ )
+ build_index_dir = build_root / "index"
+ try:
+ build_index_dir.mkdir(parents=True, exist_ok=True)
+ self._run_dispatch_build(settings=settings, inventory=inventory, output_dir=build_index_dir)
+ if not _is_complete_index(build_index_dir):
+ raise RuntimeError("dispatch build finished without complete index artifacts")
+ _publish_index(settings=settings, candidate_dir=build_index_dir)
+ _write_state(settings, inventory=inventory, fingerprint=expected)
+ except Exception as exc:
+ return {"success": False, "result": render_build_failure(str(exc))}
+ finally:
+ if _is_complete_index(_index_dir(settings)) and build_root.exists():
+ shutil.rmtree(build_root, ignore_errors=True)
+
+ return {
+ "success": True,
+ "result": render_build_success(
+ reused=False,
+ inventory=inventory,
+ index_dir=str(_index_dir(settings)),
+ elapsed_seconds=time.monotonic() - started,
+ ),
+ }
+
+ @staticmethod
+ def tree() -> dict[str, Any]:
+ settings = load_settings()
+ if not settings.enabled:
+ return {"success": False, "result": render_disabled()}
+
+ index_dir = _index_dir(settings)
+ if not _is_complete_index(index_dir):
+ return {
+ "success": False,
+ "result": (
+ "# Skill Index Tree\n\n"
+ "The installed-skill retrieval index has not been built yet.\n\n"
+ "Use `skill_index_build` or the web page build button to build the index, "
+ "or ignore retrieval and continue with the original jiuwenswarm flow."
+ ),
+ }
+
+ tree_path = index_dir / TREE_INDEX_FILENAME
+ try:
+ payload = yaml.safe_load(tree_path.read_text(encoding="utf-8")) or {}
+ except Exception as exc:
+ return {"success": False, "result": f"# Skill Index Tree\n\nFailed to read `{tree_path}`: {exc}"}
+
+ nodes = payload.get("nodes") if isinstance(payload, dict) else None
+ if not isinstance(nodes, list):
+ return {
+ "success": False,
+ "result": f"# Skill Index Tree\n\n`{tree_path}` does not contain a valid nodes list.",
+ }
+
+ branch_count = sum(1 for node in nodes if isinstance(node, dict) and node.get("type") == "branch")
+ leaf_count = sum(1 for node in nodes if isinstance(node, dict) and node.get("type") == "leaf")
+ tree_nodes = _tree_node_payload(nodes)
+ return {
+ "success": True,
+ "result": (
+ "# Skill Index Tree\n\n"
+ f"- Index directory: `{index_dir}`\n"
+ f"- Branch nodes: {branch_count}\n"
+ f"- Skill leaves: {leaf_count}\n\n"
+ f"{_render_tree_outline(nodes)}"
+ ),
+ "nodes": tree_nodes,
+ "branch_count": branch_count,
+ "leaf_count": leaf_count,
+ "index_dir": str(index_dir),
+ }
+
+ @staticmethod
+ def _run_dispatch_build(
+ *,
+ settings: SkillRetrievalSettings,
+ inventory: SkillInventory,
+ output_dir: Path,
+ ) -> None:
+ with dispatch_import_path():
+ from indexing.workflows.artifacts import (
+ BuildConfig,
+ BuildExecutionConfig,
+ BuildLLMConfig,
+ BuildOutputConfig,
+ TaxonomyBuildConfig,
+ )
+ from indexing.tree.builder import TreeBuilder
+ from indexing.workflows.index_builder import IndexBuilder
+
+ _ensure_tree_builder_compat(TreeBuilder)
+
+ build = settings.build
+ config = BuildConfig(
+ llm_config=BuildLLMConfig(
+ model=settings.llm.model,
+ api_key=settings.llm.api_key,
+ base_url=settings.llm.base_url,
+ seed=settings.llm.seed,
+ ),
+ taxonomy_config=TaxonomyBuildConfig(
+ branching_factor=build.branching_factor,
+ max_depth=build.max_depth,
+ root_categories=build.root_categories,
+ postprocess_enabled=build.postprocess_enabled,
+ postprocess_max_passes=build.postprocess_max_passes,
+ postprocess_min_skills=build.postprocess_min_skills,
+ equivalence_enabled=build.equivalence_enabled,
+ ),
+ execution_config=BuildExecutionConfig(
+ max_workers=build.max_workers,
+ max_retries=build.max_retries,
+ request_timeout_seconds=build.request_timeout_seconds,
+ classification_batch_limit=build.classification_batch_limit,
+ discovery_seed=build.discovery_seed,
+ ),
+ output_config=BuildOutputConfig(generate_html=False),
+ )
+ IndexBuilder.build(
+ item_paths=inventory.item_paths,
+ output_dir=output_dir,
+ item_type="skill",
+ config=config,
+ )
+
+ @staticmethod
+ def _recover_index(
+ *,
+ settings: SkillRetrievalSettings,
+ inventory: SkillInventory,
+ expected_fingerprint: str,
+ ) -> bool:
+ if _is_complete_index(_index_dir(settings)):
+ return False
+ for candidate in _recovery_candidates(settings):
+ try:
+ if not _is_complete_index(candidate):
+ continue
+ if not _manifest_matches_inventory(candidate, inventory):
+ continue
+ _publish_index(settings=settings, candidate_dir=candidate)
+ _write_state(settings, inventory=inventory, fingerprint=expected_fingerprint)
+ return True
+ except Exception as exc:
+ _record_recovery_failure(candidate, exc)
+ return False
+
+
+def _index_dir(settings: SkillRetrievalSettings) -> Path:
+ return settings.artifact_root / "index"
+
+
+def _ensure_tree_builder_compat(tree_builder_cls: type) -> None:
+ default_attrs = {
+ "_skill_profiles_enabled": False,
+ "_cache_observability": False,
+ }
+ for name, value in default_attrs.items():
+ if not hasattr(tree_builder_cls, name):
+ setattr(tree_builder_cls, name, value)
+ if not hasattr(tree_builder_cls, "_write_yaml"):
+ setattr(tree_builder_cls, "_write_yaml", _write_tree_yaml)
+
+
+def _write_tree_yaml(tree_builder: Any, tree_dict: dict[str, Any]) -> None:
+ writer = getattr(tree_builder, "_preset_writer")
+ writer.write_yaml(tree_dict)
+
+
+def _record_recovery_failure(candidate: Path, exc: Exception) -> None:
+ LOGGER.debug("Skipping unusable skill retrieval index recovery candidate %s: %s", candidate, exc)
+
+
+def _tmp_dir(settings: SkillRetrievalSettings) -> Path:
+ return settings.artifact_root / "tmp"
+
+
+def _state_file(settings: SkillRetrievalSettings) -> Path:
+ return settings.artifact_root / STATE_FILENAME
+
+
+def _expected_fingerprint(inventory: SkillInventory, settings: SkillRetrievalSettings) -> str:
+ import hashlib
+
+ payload = {
+ "inventory": inventory.fingerprint,
+ "build": asdict(settings.build),
+ "llm": {
+ "model": settings.llm.model,
+ "base_url": settings.llm.base_url,
+ "seed": settings.llm.seed,
+ },
+ }
+ return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")).hexdigest()
+
+
+def _read_state(settings: SkillRetrievalSettings) -> dict[str, Any]:
+ path = _state_file(settings)
+ if not path.is_file():
+ return {}
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+
+def _write_state(settings: SkillRetrievalSettings, *, inventory: SkillInventory, fingerprint: str) -> None:
+ payload = {
+ "schema_version": 1,
+ "built_at": datetime.now(timezone.utc).isoformat(),
+ "fingerprint": fingerprint,
+ "indexed_count": inventory.count,
+ "index_dir": str(_index_dir(settings)),
+ "inventory": inventory.to_state_payload(),
+ }
+ _state_file(settings).write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
+
+
+def _is_complete_index(path: Path) -> bool:
+ return (
+ (path / TREE_INDEX_FILENAME).is_file()
+ and (path / CATALOG_FILENAME).is_file()
+ and (path / MANIFEST_FILENAME).is_file()
+ )
+
+
+def _publish_index(*, settings: SkillRetrievalSettings, candidate_dir: Path) -> None:
+ final_dir = _index_dir(settings)
+ backup_dir = settings.artifact_root / f"index.backup-{time.time_ns()}"
+ if final_dir.exists():
+ final_dir.rename(backup_dir)
+ try:
+ candidate_dir.rename(final_dir)
+ except Exception:
+ if backup_dir.exists() and not final_dir.exists():
+ backup_dir.rename(final_dir)
+ raise
+ if backup_dir.exists():
+ shutil.rmtree(backup_dir, ignore_errors=True)
+
+
+def _recovery_candidates(settings: SkillRetrievalSettings) -> list[Path]:
+ candidates: list[Path] = []
+ root = settings.artifact_root
+ if root.exists():
+ candidates.extend(sorted(root.glob("index.backup-*"), key=lambda path: path.stat().st_mtime, reverse=True))
+ tmp = _tmp_dir(settings)
+ if tmp.exists():
+ for build_root in sorted(tmp.glob("build-*"), key=lambda path: path.stat().st_mtime, reverse=True):
+ candidates.append(build_root / "index")
+ candidates.append(build_root)
+ return candidates
+
+
+def _manifest_matches_inventory(index_dir: Path, inventory: SkillInventory) -> bool:
+ try:
+ payload = json.loads((index_dir / MANIFEST_FILENAME).read_text(encoding="utf-8"))
+ except Exception:
+ return False
+ raw_paths = payload.get("item_paths") if isinstance(payload, dict) else None
+ if not isinstance(raw_paths, list):
+ return False
+ expected = {str(Path(path).expanduser().resolve()) for path in inventory.item_paths}
+ actual = {str(Path(str(path)).expanduser().resolve()) for path in raw_paths}
+ return expected == actual
+
+
+def _render_tree_outline(nodes: list[Any], *, max_nodes: int = 400) -> str:
+ by_cid: dict[str, dict[str, Any]] = {}
+ children: dict[str, list[str]] = {}
+ for raw in nodes:
+ if not isinstance(raw, dict):
+ continue
+ cid = str(raw.get("cid") or "").strip()
+ if not cid:
+ continue
+ by_cid[cid] = raw
+ parent = cid.rsplit(".", 1)[0] if "." in cid else ""
+ children.setdefault(parent, []).append(cid)
+
+ for child_list in children.values():
+ child_list.sort(key=lambda item: (item.count("."), item.lower()))
+
+ lines: list[str] = []
+ emitted = 0
+
+ def label_for(cid: str) -> str:
+ node = by_cid.get(cid, {})
+ name = cid.rsplit(".", 1)[-1]
+ description = _compact_text(str(node.get("description") or ""), limit=120)
+ if str(node.get("type") or "") == "leaf":
+ worker_id = str(node.get("worker_id") or name).strip()
+ suffix = f" - {description}" if description else ""
+ return f"`{worker_id}`{suffix}"
+ suffix = f" - {description}" if description else ""
+ return f"{name}{suffix}"
+
+ def walk(parent: str, depth: int) -> None:
+ nonlocal emitted
+ for cid in children.get(parent, []):
+ if emitted >= max_nodes:
+ return
+ lines.append(f"{' ' * depth}- {label_for(cid)}")
+ emitted += 1
+ walk(cid, depth + 1)
+
+ walk("", 0)
+ if emitted < len(by_cid):
+ lines.append(f"\n... {len(by_cid) - emitted} more nodes omitted")
+ return "\n".join(lines) if lines else "(empty tree)"
+
+
+def _tree_node_payload(nodes: list[Any]) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ known_cids: set[str] = set()
+ for raw in nodes:
+ if not isinstance(raw, dict):
+ continue
+ cid = str(raw.get("cid") or "").strip()
+ if cid:
+ known_cids.add(cid)
+
+ for raw in nodes:
+ if not isinstance(raw, dict):
+ continue
+ cid = str(raw.get("cid") or "").strip()
+ if not cid:
+ continue
+ parent_cid = cid.rsplit(".", 1)[0] if "." in cid else ""
+ if parent_cid not in known_cids:
+ parent_cid = ""
+ node_type = str(raw.get("type") or "").strip() or "branch"
+ worker_id = str(raw.get("worker_id") or "").strip()
+ fallback_label = worker_id if node_type == "leaf" and worker_id else cid.rsplit(".", 1)[-1]
+ out.append(
+ {
+ "cid": cid,
+ "parent_cid": parent_cid,
+ "type": node_type,
+ "label": _node_label(raw, fallback_label=fallback_label),
+ "description": str(raw.get("description") or "").strip(),
+ "select_when": str(raw.get("select_when") or "").strip(),
+ "dont_select_when": str(raw.get("dont_select_when") or "").strip(),
+ "source_description": str(raw.get("source_description") or "").strip(),
+ "worker_id": worker_id,
+ "category": str(raw.get("category") or "").strip(),
+ "keywords": _string_list(raw.get("keywords")),
+ "examples": _string_list(raw.get("examples")),
+ }
+ )
+ out.sort(key=lambda item: (str(item.get("cid") or "").count("."), str(item.get("cid") or "").lower()))
+ return out
+
+
+def _node_label(node: dict[str, Any], *, fallback_label: str) -> str:
+ for key in ("name", "display_name", "worker_id"):
+ value = str(node.get(key) or "").strip()
+ if value:
+ return value
+ return fallback_label
+
+
+def _string_list(value: Any) -> list[str]:
+ if isinstance(value, list):
+ return [str(item).strip() for item in value if str(item).strip()]
+ text = str(value or "").strip()
+ return [text] if text else []
+
+
+def _compact_text(text: str, *, limit: int) -> str:
+ compact = " ".join(text.split())
+ if len(compact) <= limit:
+ return compact
+ return compact[:max(0, limit - 3)].rstrip() + "..."
diff --git a/jiuwenswarm/symphony/skill_retrieval/inventory.py b/jiuwenswarm/symphony/skill_retrieval/inventory.py
new file mode 100644
index 0000000000..6bcc06c017
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/inventory.py
@@ -0,0 +1,181 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+from jiuwenswarm.common.utils import get_agent_skills_dir
+
+
+@dataclass(frozen=True)
+class SkillInventoryItem:
+ worker_id: str
+ name: str
+ description: str
+ skill_dir: str
+ skill_file: str
+ source: str
+ version: str
+ author: str
+ content_hash: str
+
+
+@dataclass(frozen=True)
+class SkillInventory:
+ skills_dir: str
+ items: tuple[SkillInventoryItem, ...]
+ fingerprint: str
+
+ @property
+ def count(self) -> int:
+ return len(self.items)
+
+ @property
+ def item_paths(self) -> list[str]:
+ return [item.skill_dir for item in self.items]
+
+ def to_state_payload(self) -> dict[str, Any]:
+ return {
+ "skills_dir": self.skills_dir,
+ "count": self.count,
+ "fingerprint": self.fingerprint,
+ "items": [asdict(item) for item in self.items],
+ }
+
+
+def scan_skill_inventory(manager: Any) -> SkillInventory:
+ skills_dir = _manager_skills_dir(manager)
+ source_by_name = _source_by_name(manager)
+ items: list[SkillInventoryItem] = []
+ if skills_dir.exists():
+ for child in sorted(skills_dir.iterdir(), key=lambda path: path.name.lower()):
+ if not child.is_dir() or child.name.startswith(".") or child.name.startswith("_"):
+ continue
+ skill_file = _find_skill_file(child)
+ if skill_file is None:
+ continue
+ meta, body = _parse_skill_md(skill_file)
+ name = str(meta.get("name") or child.name).strip() or child.name
+ if not _is_enabled(manager, name):
+ continue
+ description = str(meta.get("description") or "").strip() or _first_paragraph(body)
+ items.append(
+ SkillInventoryItem(
+ worker_id=child.name,
+ name=name,
+ description=description,
+ skill_dir=str(child.resolve()),
+ skill_file=str(skill_file.resolve()),
+ source=source_by_name.get(name, "local"),
+ version=str(meta.get("version") or "").strip(),
+ author=str(meta.get("author") or "").strip(),
+ content_hash=_sha256_file(skill_file),
+ )
+ )
+ ordered = tuple(sorted(items, key=lambda item: (item.name.lower(), item.worker_id.lower())))
+ return SkillInventory(
+ skills_dir=str(skills_dir.resolve()),
+ items=ordered,
+ fingerprint=_inventory_fingerprint(ordered),
+ )
+
+
+def _manager_skills_dir(manager: Any) -> Path:
+ raw = getattr(manager, "_skills_dir", None)
+ if raw:
+ return Path(raw)
+ return get_agent_skills_dir()
+
+
+def _source_by_name(manager: Any) -> dict[str, str]:
+ out: dict[str, str] = {}
+ for item in _call_list(manager, "get_local_skills"):
+ name = str(item.get("name") or "").strip()
+ source = str(item.get("source") or "").strip()
+ if name and source:
+ out[name] = source
+ for item in _call_list(manager, "get_installed_plugins"):
+ name = str(item.get("name") or "").strip()
+ source = str(item.get("source") or item.get("marketplace") or "").strip()
+ if name and source:
+ out.setdefault(name, source)
+ return out
+
+
+def _call_list(manager: Any, method_name: str) -> list[dict[str, Any]]:
+ method = getattr(manager, method_name, None)
+ if not callable(method):
+ return []
+ try:
+ value = method()
+ except Exception:
+ return []
+ return [dict(item) for item in value if isinstance(item, dict)] if isinstance(value, list) else []
+
+
+def _is_enabled(manager: Any, name: str) -> bool:
+ method = getattr(manager, "get_skill_enabled", None)
+ if not callable(method):
+ return True
+ try:
+ return bool(method(name))
+ except Exception:
+ return True
+
+
+def _find_skill_file(skill_dir: Path) -> Path | None:
+ for filename in ("SKILL.md", "skill.md", "Skill.md"):
+ candidate = skill_dir / filename
+ if candidate.is_file():
+ return candidate
+ return None
+
+
+def _parse_skill_md(path: Path) -> tuple[dict[str, Any], str]:
+ text = path.read_text(encoding="utf-8")
+ meta: dict[str, Any] = {}
+ body = text
+ match = re.match(r"^---\s*\n(.*?)\n---\s*\n?(.*)", text, re.DOTALL)
+ if match:
+ body = match.group(2).strip()
+ loaded = yaml.safe_load(match.group(1)) or {}
+ if isinstance(loaded, dict):
+ meta = {str(key): value for key, value in loaded.items()}
+ return meta, body
+
+
+def _first_paragraph(text: str) -> str:
+ for block in re.split(r"\n\s*\n", str(text or "").strip()):
+ cleaned = " ".join(line.strip() for line in block.splitlines()).strip()
+ if cleaned:
+ return cleaned[:500]
+ return ""
+
+
+def _sha256_file(path: Path) -> str:
+ hasher = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ hasher.update(chunk)
+ return hasher.hexdigest()
+
+
+def _inventory_fingerprint(items: tuple[SkillInventoryItem, ...]) -> str:
+ payload = [
+ {
+ "worker_id": item.worker_id,
+ "name": item.name,
+ "skill_dir": item.skill_dir,
+ "skill_file": item.skill_file,
+ "version": item.version,
+ "content_hash": item.content_hash,
+ }
+ for item in items
+ ]
+ encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
+ return hashlib.sha256(encoded).hexdigest()
diff --git a/jiuwenswarm/symphony/skill_retrieval/markdown.py b/jiuwenswarm/symphony/skill_retrieval/markdown.py
new file mode 100644
index 0000000000..ced5631d41
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/markdown.py
@@ -0,0 +1,125 @@
+from __future__ import annotations
+
+from typing import Any
+
+from .inventory import SkillInventory
+
+
+def render_disabled() -> str:
+ return (
+ "# Skill Retrieval Unavailable\n\n"
+ "Skill retrieval is disabled by `symphony.skill_retrieval.enabled=false`.\n\n"
+ "Proceed with the original jiuwenswarm flow, or enable the feature in settings and reload configuration."
+ )
+
+
+def render_build_success(
+ *,
+ reused: bool,
+ inventory: SkillInventory,
+ index_dir: str,
+ elapsed_seconds: float,
+) -> str:
+ action = "reused existing index" if reused else "built skill retrieval index"
+ return (
+ "# Skill Retrieval Index\n\n"
+ "## Build Summary\n"
+ f"- Result: {action}\n"
+ f"- Indexed skills: {inventory.count}\n"
+ f"- Index directory: `{index_dir}`\n"
+ f"- Inventory fingerprint: `{inventory.fingerprint[:12]}`\n"
+ f"- Elapsed: {elapsed_seconds:.1f}s\n\n"
+ "The index is ready. Use `skill_retrieve` with a task query to retrieve relevant installed skills."
+ )
+
+
+def render_build_failure(reason: str) -> str:
+ return (
+ "# Skill Retrieval Index Failed\n\n"
+ f"{reason.strip() or 'Index build failed.'}\n\n"
+ "Handling options:\n"
+ "- Ignore this tool result and continue with the original jiuwenswarm flow.\n"
+ "- Check LLM configuration and installed skills, then call `skill_index_build` again."
+ )
+
+
+def render_retrieve_failure(reason: str) -> str:
+ return (
+ "# Skill Retrieval Failed\n\n"
+ f"{reason.strip() or 'Skill retrieval failed.'}\n\n"
+ "Handling options:\n"
+ "- Only call `skill_index_build` when the reason above explicitly says the index is missing or stale.\n"
+ "- After `skill_index_build` succeeds, call `skill_retrieve` again with the same query.\n"
+ "- Otherwise continue with the original jiuwenswarm flow without retrieved skill hints."
+ )
+
+
+def render_retrieve_success(
+ *,
+ query: str,
+ index_dir: str,
+ indexed_count: int,
+ result: Any,
+ catalog_by_worker: dict[str, dict[str, Any]],
+ settings_summary: str,
+) -> str:
+ records = _candidate_records(result)
+ lines = [
+ "# Skill Retrieval Result",
+ "",
+ "## Retrieval Summary",
+ f"- Query: {query}",
+ f"- Index directory: `{index_dir}`",
+ f"- Indexed skills: {indexed_count}",
+ f"- Retrieved candidates: {len(records)}",
+ f"- Dispatch settings: {settings_summary}",
+ ]
+ elapsed = getattr(result, "elapsed_ms", None)
+ if elapsed is not None:
+ lines.append(f"- Dispatch elapsed: {float(elapsed):.0f}ms")
+ summary_lines = getattr(result, "summary_lines", None) or []
+ if summary_lines:
+ lines.extend(["", "## Dispatch Summary"])
+ lines.extend(f"- {line}" for line in summary_lines[:10])
+ lines.extend(["", "## Retrieved Skills"])
+ if not records:
+ lines.append("No relevant installed skills were returned by dispatch.")
+ else:
+ for index, record in enumerate(records, start=1):
+ worker_id = str(record.get("worker_id") or record.get("resolved_payload") or "").strip()
+ catalog = catalog_by_worker.get(worker_id, {})
+ name = str(record.get("skill_name") or catalog.get("name") or worker_id or f"skill-{index}").strip()
+ description = str(record.get("description") or catalog.get("description") or "").strip()
+ path = str(catalog.get("skill_path") or "").strip()
+ source = str(record.get("source") or "").strip()
+ lines.append(f"{index}. `{name}`")
+ if worker_id and worker_id != name:
+ lines.append(f" - Worker id: `{worker_id}`")
+ if description:
+ lines.append(f" - Description: {_compact(description, 420)}")
+ if path:
+ lines.append(f" - SKILL.md: `{path}`")
+ if source:
+ lines.append(f" - Match source: {source}")
+ lines.extend(
+ [
+ "",
+ "## Usage Notes",
+ "- Read the returned `SKILL.md` files before using a skill.",
+ "- This result is a retrieval hint only; execute the task through jiuwenswarm's original runtime.",
+ "- Do not treat the retrieved order as an execution plan.",
+ ]
+ )
+ return "\n".join(lines)
+
+
+def _candidate_records(result: Any) -> list[dict[str, Any]]:
+ raw = getattr(result, "candidate_records", None) or []
+ return [dict(item) for item in raw if isinstance(item, dict)]
+
+
+def _compact(text: str, limit: int) -> str:
+ normalized = " ".join(str(text or "").split())
+ if len(normalized) <= limit:
+ return normalized
+ return normalized[:max(0, limit - 1)].rstrip() + "..."
diff --git a/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py b/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py
new file mode 100644
index 0000000000..6489c16278
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py
@@ -0,0 +1,151 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from .config import load_settings
+from .dispatch_imports import dispatch_import_path
+from .index_service import CATALOG_FILENAME, _index_dir
+from .markdown import render_disabled, render_retrieve_failure, render_retrieve_success
+
+
+class SkillRetrieveService:
+ def __init__(self, manager: Any) -> None:
+ self._manager = manager
+
+ def retrieve(self, query: str) -> dict[str, Any]:
+ settings = load_settings()
+ if not settings.enabled:
+ return {"success": False, "result": render_disabled()}
+ normalized_query = str(query or "").strip()
+ if not normalized_query:
+ return {"success": False, "result": render_retrieve_failure("`query` is required.")}
+
+ from .index_service import SkillIndexService
+
+ status = SkillIndexService(self._manager).status()
+ if not status.get("index_exists"):
+ return {
+ "success": False,
+ "result": render_retrieve_failure(
+ "Skill retrieval index does not exist. Next step: call `skill_index_build`, "
+ "then call `skill_retrieve` again with the same query."
+ ),
+ }
+ if not status.get("fresh"):
+ return {
+ "success": False,
+ "result": render_retrieve_failure(
+ "Skill retrieval index is stale because installed skills or build settings changed. "
+ "Next step: call `skill_index_build` to refresh it, then call `skill_retrieve` again "
+ "with the same query."
+ ),
+ }
+ if not settings.llm.model or not settings.llm.api_key:
+ return {
+ "success": False,
+ "result": render_retrieve_failure(
+ "Dispatch retrieval requires a model and API key. "
+ "Configure `models.defaults[0].model_client_config` or `symphony.skill_retrieval.llm`."
+ ),
+ }
+
+ index_dir = _index_dir(settings)
+ catalog_by_worker = _load_catalog(index_dir)
+ try:
+ result = self._run_dispatch_retrieve(settings=settings, index_dir=index_dir, query=normalized_query)
+ except Exception as exc:
+ return {"success": False, "result": render_retrieve_failure(str(exc))}
+
+ return {
+ "success": True,
+ "result": render_retrieve_success(
+ query=normalized_query,
+ index_dir=str(index_dir),
+ indexed_count=int(status.get("indexed_count") or 0),
+ result=result,
+ catalog_by_worker=catalog_by_worker,
+ settings_summary=_settings_summary(settings),
+ ),
+ }
+
+ @staticmethod
+ def _run_dispatch_retrieve(*, settings: Any, index_dir: Path, query: str) -> Any:
+ with dispatch_import_path():
+ from retrieval.service.models import (
+ GenerationConfig,
+ OpenAIClientConfig,
+ RenderConfig,
+ RequestConfig,
+ RetrieverConfig,
+ TraversalConfig,
+ )
+ from retrieval.service.retriever import Retriever
+
+ retrieve = settings.retrieve
+ config = RetrieverConfig(
+ top_k=retrieve.top_k,
+ llm_client_config=OpenAIClientConfig(
+ model=settings.llm.model,
+ api_key=settings.llm.api_key,
+ base_url=settings.llm.base_url,
+ seed=settings.llm.seed,
+ ),
+ 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,
+ ),
+ )
+ retriever = Retriever.from_index(index_dir, config=config)
+ try:
+ return retriever.search_details(query, search_config=RequestConfig(top_k=retrieve.top_k))
+ finally:
+ retriever.close()
+
+
+def _load_catalog(index_dir: Path) -> dict[str, dict[str, Any]]:
+ out: dict[str, dict[str, Any]] = {}
+ path = index_dir / CATALOG_FILENAME
+ if not path.is_file():
+ return out
+ for line in path.read_text(encoding="utf-8").splitlines():
+ if not line.strip():
+ continue
+ item = _load_catalog_line(line)
+ if item is None:
+ continue
+ worker_id = str(item.get("worker_id") or "").strip()
+ if worker_id:
+ out[worker_id] = item
+ return out
+
+
+def _load_catalog_line(line: str) -> dict[str, Any] | None:
+ try:
+ item = json.loads(line)
+ except json.JSONDecodeError:
+ return None
+ return item if isinstance(item, dict) else None
+
+
+def _settings_summary(settings: Any) -> str:
+ retrieve = settings.retrieve
+ return (
+ "compact=false, flat=false"
+ if not retrieve.compact_codes_enabled and not retrieve.flatten_tree
+ else f"compact={retrieve.compact_codes_enabled}, flat={retrieve.flatten_tree}"
+ ) + (
+ f", top_k={retrieve.top_k}, max_branch_choices={retrieve.max_branch_choices}, "
+ f"max_parallel_branches={retrieve.max_parallel_branches}"
+ )
diff --git a/jiuwenswarm/symphony/ut_test2.sh b/jiuwenswarm/symphony/ut_test2.sh
new file mode 100644
index 0000000000..3c31fa21e1
--- /dev/null
+++ b/jiuwenswarm/symphony/ut_test2.sh
@@ -0,0 +1,125 @@
+#!/bin/bash
+set -e # 遇到错误立即退出
+
+# ===================== 1. 核心变量 =====================
+TEST_DIR="./marketplace/dispatch/tests"
+REPORT_HTML="./outputs/unit_test_report.html"
+REPORT_XML="./outputs/unit_test_result.xml"
+ut_result_value="PASSED"
+UV_VENV_DIR="./.venv"
+
+# ===================== 2. 基础配置(华为云源)=====================
+echo "===== 配置pip源 & 安装基础工具 ====="
+pip config set global.index-url https://repo.huaweicloud.com/repository/pypi/simple
+pip config set global.trusted-host repo.huaweicloud.com
+
+# 升级系统setuptools
+pip uninstall -y setuptools
+pip install setuptools==68.0.0 wheel==0.41.2
+
+# 安装uv(指定低版本兼容版本)
+pip install uv -i https://repo.huaweicloud.com/repository/pypi/simple
+UV_PATH=$(pip show uv | grep "Location" | awk -F ': ' '{print $2}')
+export PATH="$UV_PATH/bin:$PATH"
+echo "当前uv版本:$(uv --version)"
+
+# ===================== 3. 重建虚拟环境(低版本uv兼容)=====================
+echo -e "\n===== 创建uv虚拟环境 ====="
+rm -rf "${UV_VENV_DIR}"
+uv venv "${UV_VENV_DIR}" # 低版本uv仅支持创建,无额外参数
+
+# 验证虚拟环境Python存在
+if [ ! -f "${UV_VENV_DIR}/bin/python" ]; then
+ echo "❌ 虚拟环境创建失败:${UV_VENV_DIR}/bin/python 不存在"
+ exit 1
+fi
+echo "✅ 虚拟环境创建成功:${UV_VENV_DIR}"
+
+# ===================== 4. 激活环境 + 安装依赖(低版本核心逻辑)=====================
+echo -e "\n===== 激活环境并安装依赖 ====="
+# 激活环境(低版本必须先激活,再装依赖)
+source "${UV_VENV_DIR}/bin/activate"
+echo "✅ 已激活虚拟环境,当前Python:$(which python)"
+
+# 1. 同步pyproject.toml依赖(低版本uv sync无--venv参数)
+uv cache clean
+uv sync --all-extras --group dev --index-url https://repo.huaweicloud.com/repository/pypi/simple
+
+# 2. 用虚拟环境的pip安装pysqlite3-binary(核心,低版本必须手动装)
+pip install pysqlite3-binary==0.5.4.post2 --force-reinstall -i https://repo.huaweicloud.com/repository/pypi/simple
+
+# 3. 用虚拟环境的pip安装pycryptodome(兜底)
+pip install pycryptodome>=3.23.0 --force-reinstall -i https://repo.huaweicloud.com/repository/pypi/simple
+
+# 4. 安装测试依赖(确保pytest等在虚拟环境中)
+pip install pytest pytest-html pytest-cov pytest-timeout -i https://repo.huaweicloud.com/repository/pypi/simple
+
+# ===================== 5. 前置验证(关键!)=====================
+echo -e "\n===== 验证依赖安装 ====="
+# 验证pysqlite3
+python -c "
+import pysqlite3
+import sqlite3
+print(f'✅ pysqlite3导入成功,sqlite3版本:{sqlite3.sqlite_version}')
+" || {
+ echo "❌ pysqlite3导入失败!"
+ pip list | grep pysqlite3
+ exit 1
+}
+
+# 验证Crypto
+python -c "
+import Crypto
+from Crypto.Cipher import AES
+print('✅ Crypto模块导入成功')
+" || {
+ echo "❌ Crypto导入失败!"
+ pip list | grep pycryptodome
+ exit 1
+}
+
+# ===================== 6. 执行测试(用激活的Python)=====================
+echo -e "\n===== 执行单元测试 ====="
+mkdir -p ./outputs
+set +e
+
+# 执行测试(全程用激活的Python,无路径问题)
+python -c """
+import pysqlite3
+import sys
+sys.modules['sqlite3'] = pysqlite3
+import sqlite3
+print(f'✅ 替换后sqlite3版本:{sqlite3.sqlite_version}')
+
+from pytest import main
+exit_code = main([
+ '${TEST_DIR}',
+ '--html=${REPORT_HTML}',
+ '--junitxml=${REPORT_XML}',
+ '--cov=${TEST_DIR}',
+ '--timeout=60'
+])
+sys.exit(exit_code)
+"""
+
+TEST_EXIT_CODE=$?
+set -e
+
+# ===================== 7. 结果处理 =====================
+echo -e "\n===== 测试结果处理 ====="
+echo "测试退出码:${TEST_EXIT_CODE}"
+
+if [ -f "${REPORT_XML}" ]; then
+ head -n 10 "${REPORT_XML}"
+else
+ echo "❌ 报告文件不存在"
+ TEST_EXIT_CODE=1
+fi
+
+if [ $TEST_EXIT_CODE -ne 0 ]; then
+ ut_result_value="FAILED"
+ echo "##vso[task.setvariable variable=ut_result;]${ut_result_value}"
+ exit 1
+else
+ echo "✅ 所有单元测试通过!"
+fi 解释代码
\ No newline at end of file
diff --git a/llm_config.txt b/llm_config.txt
new file mode 100644
index 0000000000..7c51a0433c
--- /dev/null
+++ b/llm_config.txt
@@ -0,0 +1,4 @@
+model_name: deepseek-v4-flash
+api_base: https://api.deepseek.com
+api_key: sk-e6709f7581574183968a634d789b6e9e
+model_provider: OpenAI
\ No newline at end of file
diff --git a/pyproject.toml b/pyproject.toml
index d09fad8edf..1c269f7520 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -102,6 +102,10 @@ jiuwenswarm = [
"resources/**/*",
"resources/*",
"resources/.env.template",
+ "symphony/**/*.yaml",
+ "symphony/**/*.yml",
+ "symphony/**/*.json",
+ "symphony/**/*.md",
]
jiuwenbox = [
"configs/**/*",
diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.py
index 8430dcce21..70bc6d7b15 100644
--- a/tests/agents/swarm/test_swarm_assembly.py
+++ b/tests/agents/swarm/test_swarm_assembly.py
@@ -95,6 +95,8 @@ _COMMON_TOOL_NAMES: frozenset[str] = frozenset(
registry.AUDIO,
# SKILL_TOOLKIT is no longer declared as a tool; the
# MEMBER_SKILL_TOOLKIT rail is the sole registrar of skill tools.
+ # Skill retrieval is a separate self-gated tool provider.
+ registry.SKILL_RETRIEVAL,
registry.USER_TODOS,
registry.VIDEO,
registry.IMAGE_GEN,
@@ -746,6 +748,7 @@ def test_code_capability_specs_rail_and_tool_names(mode: str) -> None:
registry.VISION,
registry.AUDIO,
# SKILL_TOOLKIT moved to the MEMBER_SKILL_TOOLKIT rail (see common set).
+ registry.SKILL_RETRIEVAL,
registry.USER_TODOS,
registry.VIDEO,
registry.IMAGE_GEN,