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): 优化 Symphony 编排,清理死代码,精简prompt

lin-xiaoyubf3a7220d6f2
diff --git a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
index f489818103..20f5920a3a 100644
--- a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
+++ b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
@@ -39,7 +39,6 @@ symphony:
orchestration:
mode: fast
- top_k: 3
max_depth: 4
min_edge_confidence: 0.3
diff --git a/docs/en/Configuration.md b/docs/en/Configuration.md
index 2a08648a2b..8d760e30f1 100644
--- a/docs/en/Configuration.md
+++ b/docs/en/Configuration.md
@@ -383,7 +383,6 @@ Common settings:
| `symphony.build.require_consensus` | `false` | Whether multiple judgments must agree before accepting a relationship |
| `symphony.build.min_edge_confidence` | `0.1` | Minimum edge confidence written into the skill score |
| `symphony.orchestration.mode` | `fast` | Orchestration mode. The current runtime uses the fast orchestration path |
-| `symphony.orchestration.top_k` | `3` | Maximum number of candidate routes retained during orchestration |
| `symphony.orchestration.max_depth` | `4` | Maximum skill-chain search depth |
| `symphony.orchestration.min_edge_confidence` | `0.3` | Minimum skill-score edge confidence preferred by orchestration |
| `symphony.skill_retrieval.artifact_root` | Empty string | Skill index artifact directory; empty means the default workspace is used; can be supplied by `SYMPHONY_SKILL_RETRIEVAL_ROOT` |
diff --git a/docs/en/Symphony.md b/docs/en/Symphony.md
index e271cdc21e..e5b102981c 100644
--- a/docs/en/Symphony.md
+++ b/docs/en/Symphony.md
@@ -295,11 +295,10 @@ Runtime parameters for Skill Orchestration. The current template is:
| Setting | Default | Description |
|---------|---------|-------------|
| `mode` | `fast` | Orchestration mode. The current runtime tools use the fast orchestration path and prioritize an executable skill chain |
-| `top_k` | `3` | Maximum number of candidate routes retained per orchestration round. Larger values cover more alternatives but can make output less focused |
| `max_depth` | `4` | Maximum skill-chain search depth, limiting how many skills can be chained in one task |
| `min_edge_confidence` | `0.3` | Minimum confidence threshold for skill-score edges. Edges below this value are not preferred for orchestration |
-These settings tune how candidate skills are connected into a route. If routes are too short or often miss intermediate steps, consider increasing `max_depth`. If routes are too broad or unstable, consider lowering `top_k` or increasing `min_edge_confidence`.
+These settings tune how candidate skills are connected into a route. If routes are too short or often miss intermediate steps, consider increasing `max_depth`. If routes often use low-confidence connections, consider increasing `min_edge_confidence`.
#### `symphony.skill_retrieval.enabled`
@@ -409,7 +408,6 @@ symphony:
orchestration:
mode: fast
- top_k: 3
max_depth: 4
min_edge_confidence: 0.3
diff --git "a/docs/zh/Symphony-\346\212\200\350\203\275\347\274\226\346\216\222\344\270\216\345\210\206\345\217\221.md" "b/docs/zh/Symphony-\346\212\200\350\203\275\347\274\226\346\216\222\344\270\216\345\210\206\345\217\221.md"
index 16f5495263..6d9f7588e5 100644
--- "a/docs/zh/Symphony-\346\212\200\350\203\275\347\274\226\346\216\222\344\270\216\345\210\206\345\217\221.md"
+++ "b/docs/zh/Symphony-\346\212\200\350\203\275\347\274\226\346\216\222\344\270\216\345\210\206\345\217\221.md"
@@ -295,11 +295,10 @@ Symphony 只会使用已安装技能。请先在左侧导航栏 **技能** 页
| 配置项 | 默认值 | 说明 |
|--------|--------|------|
| `mode` | `fast` | 编排模式。当前运行时工具使用快速编排路径,优先给出可执行的技能链 |
-| `top_k` | `3` | 每轮编排保留的候选路线数量上限,值越大越容易覆盖备选路线,但输出也会更分散 |
| `max_depth` | `4` | 技能链最大搜索深度,用于限制一次任务中串联技能的长度 |
| `min_edge_confidence` | `0.3` | 技能总谱边的最低置信度阈值,低于该值的连接关系不会优先用于编排 |
-这些参数适用于调节“如何把候选技能连成路线”。如果结果过短、经常漏掉中间处理步骤,可以适当增加 `max_depth`;如果路线过多或不稳定,可以降低 `top_k` 或提高 `min_edge_confidence`。
+这些参数适用于调节“如何把候选技能连成路线”。如果结果过短、经常漏掉中间处理步骤,可以适当增加 `max_depth`;如果路线经常使用低置信度连接,可以提高 `min_edge_confidence`。
#### `symphony.skill_retrieval.enabled`
@@ -410,7 +409,6 @@ symphony:
orchestration:
mode: fast
- top_k: 3
max_depth: 4
min_edge_confidence: 0.3
diff --git "a/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md" "b/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
index ed4ea06feb..b6bd7bd0ea 100644
--- "a/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
+++ "b/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
@@ -386,7 +386,6 @@ permissions:
| `symphony.build.require_consensus` | `false` | 是否要求多个判断达成一致后再接受关系 |
| `symphony.build.min_edge_confidence` | `0.1` | 写入技能总谱的最低边置信度 |
| `symphony.orchestration.mode` | `fast` | 编排模式,当前运行时使用快速编排路径 |
-| `symphony.orchestration.top_k` | `3` | 编排时保留的候选路线数量上限 |
| `symphony.orchestration.max_depth` | `4` | 技能链最大搜索深度 |
| `symphony.orchestration.min_edge_confidence` | `0.3` | 编排优先使用的技能总谱边最低置信度 |
| `symphony.skill_retrieval.artifact_root` | 空字符串 | 技能索引产物目录;为空时使用默认工作区,可由 `SYMPHONY_SKILL_RETRIEVAL_ROOT` 提供 |
diff --git a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
index 84b70a16a8..09308f5bd2 100644
--- a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
@@ -438,9 +438,14 @@ class SymphonyToolkit:
compact["source_id"] = source
if target not in (None, ""):
compact["target_id"] = target
- confidence = edge.get("confidence")
- if confidence not in (None, ""):
- compact["confidence"] = confidence
+ if "confidence" in edge:
+ compact["confidence"] = edge.get("confidence")
+ method = edge.get("method")
+ if method not in (None, ""):
+ compact["method"] = method
+ reason = edge.get("reason")
+ if reason not in (None, ""):
+ compact["reason"] = reason
return compact
@staticmethod
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index ee764cb00a..b001e22571 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -39,7 +39,6 @@ symphony:
orchestration:
mode: fast
- top_k: 3
max_depth: 4
min_edge_confidence: 0.3
diff --git a/jiuwenswarm/symphony/config.py b/jiuwenswarm/symphony/config.py
index db790f458b..dfe609384a 100644
--- a/jiuwenswarm/symphony/config.py
+++ b/jiuwenswarm/symphony/config.py
@@ -27,7 +27,6 @@ DEFAULT_BUILD_MIN_EDGE_CONFIDENCE = 0.7
DEFAULT_SYMPHONY_ENABLED = False
DEFAULT_ORCHESTRATION_MODE = "fast"
-DEFAULT_ORCHESTRATION_TOP_K = 3
DEFAULT_ORCHESTRATION_MAX_DEPTH = 4
DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE = 0.7
@@ -78,7 +77,6 @@ class SymphonyBuildConfig:
@dataclass(frozen=True)
class SymphonyOrchestrationConfig:
mode: str = DEFAULT_ORCHESTRATION_MODE
- top_k: int = DEFAULT_ORCHESTRATION_TOP_K
max_depth: int = DEFAULT_ORCHESTRATION_MAX_DEPTH
min_edge_confidence: float = DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE
@@ -201,10 +199,6 @@ def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:
orchestration.get("mode"),
DEFAULT_ORCHESTRATION_MODE,
),
- top_k=_positive_int(
- orchestration.get("top_k"),
- DEFAULT_ORCHESTRATION_TOP_K,
- ),
max_depth=_positive_int(
orchestration.get("max_depth"),
DEFAULT_ORCHESTRATION_MAX_DEPTH,
diff --git a/jiuwenswarm/symphony/graph/candidates/generator.py b/jiuwenswarm/symphony/graph/candidates/generator.py
index c130ad21f8..85c6aad212 100644
--- a/jiuwenswarm/symphony/graph/candidates/generator.py
+++ b/jiuwenswarm/symphony/graph/candidates/generator.py
@@ -61,7 +61,7 @@ class CandidateGenerator:
def __init__(
self,
*,
- max_candidates_per_skill_relation: int = 12,
+ max_candidates_per_skill_relation: int = 32,
max_port_mappings_per_candidate: int = 12,
generic_io_names: Iterable[str] = IO_NAMES_EXCLUDED_FROM_EDGE_BUILDING,
max_exact_io_pair_fanout: int = 64,
@@ -330,6 +330,7 @@ class CandidateGenerator:
buckets[key],
key=lambda item: (
-PRIORITY_RANK.get(item.priority, 0),
+ _candidate_quality_rank(item),
item.target_id,
",".join(item.relation_hints),
),
@@ -512,6 +513,35 @@ def _limit_port_mappings_for_candidate(
)
+def _candidate_quality_rank(candidate: RelationCandidate) -> tuple[int, int, int, int]:
+ port_mapping_count = 0
+ content_input_count = 0
+ for evidence in dict(candidate.evidence.get("directions", {})).values():
+ if not isinstance(evidence, dict):
+ continue
+ mappings = [
+ mapping
+ for mapping in evidence.get("port_mappings", [])
+ if isinstance(mapping, dict)
+ ]
+ port_mapping_count += len(mappings)
+ for mapping in mappings:
+ target_input = str(mapping.get("target_input") or "")
+ if target_input in GENERIC_CONTENT_INPUT_NAMES:
+ content_input_count += 1
+ for item in evidence.get("target_inputs", []):
+ if not isinstance(item, dict):
+ continue
+ if str(item.get("name") or "") in GENERIC_CONTENT_INPUT_NAMES:
+ content_input_count += 1
+ return (
+ -len(set(candidate.candidate_methods)),
+ -int(port_mapping_count > 0),
+ -port_mapping_count,
+ -content_input_count,
+ )
+
+
def _dedupe_port_mappings(values: List[dict]) -> List[dict]:
seen = set()
result = []
diff --git a/jiuwenswarm/symphony/orchestration/execution_graph.py b/jiuwenswarm/symphony/orchestration/execution_graph.py
index 1d35eb8cc6..21e88d06cc 100644
--- a/jiuwenswarm/symphony/orchestration/execution_graph.py
+++ b/jiuwenswarm/symphony/orchestration/execution_graph.py
@@ -81,6 +81,7 @@ def _project_edge(edge: dict[str, Any]) -> dict[str, Any]:
"target": target,
"type": edge.get("type") or edge.get("relation_type") or "can_feed",
"confidence": edge.get("confidence"),
+ "method": edge.get("method"),
"evidence": edge.get("evidence") or edge.get("supporting_fields") or {},
}
diff --git a/jiuwenswarm/symphony/orchestration/planning/fast.py b/jiuwenswarm/symphony/orchestration/planning/fast.py
index 1aa2355f3b..d662953625 100644
--- a/jiuwenswarm/symphony/orchestration/planning/fast.py
+++ b/jiuwenswarm/symphony/orchestration/planning/fast.py
@@ -2,7 +2,9 @@
from __future__ import annotations
+import heapq
import json
+from collections import defaultdict
from typing import Any, Sequence
from jiuwenswarm.symphony.llm import LLMConfig, create_llm_client, llm_usage_context
@@ -10,9 +12,6 @@ from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
from jiuwenswarm.symphony.orchestration.planning.plan_builder import edge_plan_item
from jiuwenswarm.symphony.orchestration.planning.utils import skill_id
-FAST_PLANNER_MAX_SKILLS = 40
-FAST_PLANNER_MAX_EDGES = 80
-
FAST_PLANNER_SYSTEM_PROMPT = """You are Symphony's fast Skill planner.
Return strict JSON only.
@@ -22,10 +21,19 @@ You receive:
- Candidate can_feed relationships between those Skills.
Task:
-- Select the best existing Skill execution path for the query.
+- Select the best Skill execution plan for the query.
+- Return the single best plan using the schema below.
- Use only provided skill IDs.
-- Use only provided can_feed edges.
-- Do not invent Skills, inputs, outputs, or edge relationships.
+- Prefer provided can_feed edges. Infer a missing relationship only when needed to form
+ the plan.
+- Give a short reason when explicitly including an inferred edge in can_feed_edges.
+- When can_feed_edges is omitted, Symphony infers adjacent step edges during validation.
+- Do not judge compatibility from Skill I/O because it is not provided; Symphony handles
+ Skill I/O after validating the plan.
+- missing_inputs does not describe a Skill I/O schema. Use it only for information the
+ user must provide when that need can be determined from the query and Skill
+ descriptions.
+- Do not invent Skills, inputs, or outputs.
- Prefer the shortest path that satisfies the user's intent.
- If required information is missing, set status to "needs_input" and list it.
- If no useful plan exists from the candidates, set status to "no_plan".
@@ -39,7 +47,7 @@ Schema:
{"skill_id": "skill-a", "reason": "why this step is used"}
],
"can_feed_edges": [
- {"source_id": "skill-a", "target_id": "skill-b"}
+ {"source_id": "skill-a", "target_id": "skill-b", "reason": "why the relationship is needed"}
],
"missing_inputs": [
{"skill_id": "skill-a", "name": "input name", "type": "unknown", "reason": "why it is needed"}
@@ -49,7 +57,7 @@ Schema:
class FastOneShotPlanner:
- """Ask the LLM for one validated plan from a bounded score subgraph."""
+ """Ask the LLM for one validated plan from a compact score subgraph."""
def __init__(
self,
@@ -58,14 +66,14 @@ class FastOneShotPlanner:
llm_config: LLMConfig | None,
llm_client: Any | None,
min_edge_confidence: float,
- top_k: int,
+ max_depth: int = 4,
candidate_skill_ids: Sequence[str] | None = None,
) -> None:
self.artifacts = artifacts
self.llm_config = llm_config
self.llm_client = llm_client
self.min_edge_confidence = min_edge_confidence
- self.top_k = max(1, int(top_k))
+ self.max_depth = max(1, int(max_depth))
self.candidate_skill_ids = self._normalize_candidate_skill_ids(
candidate_skill_ids,
known_skill_ids=set(artifacts.skill_by_id),
@@ -76,22 +84,17 @@ class FastOneShotPlanner:
subgraph = self._candidate_subgraph()
prompt_payload = {
"query": query,
- "top_k": self.top_k,
- "min_edge_confidence": self.min_edge_confidence,
"skills": subgraph["skills"],
"can_feed_edges": subgraph["edges"],
- "planning_instructions": [
- "Return the single best plan as strict JSON.",
- "Use only skill IDs from skills.",
- "Use only can_feed_edges from can_feed_edges.",
- "Do not rely on skill inputs or outputs; they are filled by Symphony after validation.",
- ],
}
with llm_usage_context("orchestration", "one_shot_fast_planning"):
raw = await client.complete_json_async(
system_prompt=FAST_PLANNER_SYSTEM_PROMPT,
user_content=json.dumps(prompt_payload, ensure_ascii=False),
error_context="Symphony one-shot fast planning",
+ request_overrides={
+ "extra_body": {"thinking": {"type": "disabled"}},
+ },
)
base = {
@@ -147,101 +150,168 @@ class FastOneShotPlanner:
return self._default_candidate_subgraph()
def _default_candidate_subgraph(self) -> dict[str, Any]:
- skill_by_id = self.artifacts.skill_by_id
- sorted_edges = self._sorted_eligible_edges()
- selected: set[str] = set()
- for edge in sorted_edges:
- for key in ("source", "target"):
- edge_skill_id = skill_id(edge.get(key))
- if (
- edge_skill_id in skill_by_id
- and len(selected) < FAST_PLANNER_MAX_SKILLS
- ):
- selected.add(edge_skill_id)
- if len(selected) >= FAST_PLANNER_MAX_SKILLS:
- break
-
- candidate_edges = []
- for edge in sorted_edges:
- if (
- skill_id(edge.get("source")) in selected
- and skill_id(edge.get("target")) in selected
- ):
- candidate_edges.append(edge)
- candidate_edges.sort(
- key=lambda item: (
- -float(item.get("confidence") or 0.0),
- skill_id(item.get("source")),
- skill_id(item.get("target")),
- )
- )
- candidate_edges = candidate_edges[:FAST_PLANNER_MAX_EDGES]
-
+ candidate_edges = self._known_edges(self._sorted_eligible_edges())
+ selected = []
+ selected_set = set()
for edge in candidate_edges:
- for key in ("source", "target"):
- edge_skill_id = skill_id(edge.get(key))
- if (
- edge_skill_id in skill_by_id
- and len(selected) < FAST_PLANNER_MAX_SKILLS
- ):
- selected.add(edge_skill_id)
-
+ self._append_skill(selected, selected_set, skill_id(edge.get("source")))
+ self._append_skill(selected, selected_set, skill_id(edge.get("target")))
if not selected:
- for skill in self.artifacts.skills[:FAST_PLANNER_MAX_SKILLS]:
+ for skill in self.artifacts.skills:
current_skill_id = str(skill.get("id") or "")
- if current_skill_id.strip():
- selected.add(current_skill_id)
-
- filtered_candidate_edges = []
- for edge in candidate_edges:
- if (
- skill_id(edge.get("source")) in selected
- and skill_id(edge.get("target")) in selected
- ):
- filtered_candidate_edges.append(edge)
- candidate_edges = filtered_candidate_edges
+ self._append_skill(selected, selected_set, current_skill_id)
return self._subgraph_payload(selected, candidate_edges)
def _retrieval_candidate_subgraph(self) -> dict[str, Any]:
- skill_by_id = self.artifacts.skill_by_id
- sorted_edges = self._sorted_eligible_edges()
- selected: set[str] = set()
-
- def add_skill(current_skill_id: str) -> None:
- if (
- current_skill_id in skill_by_id
- and current_skill_id not in selected
- and len(selected) < FAST_PLANNER_MAX_SKILLS
- ):
- selected.add(current_skill_id)
-
- for current_skill_id in self.candidate_skill_ids:
- add_skill(current_skill_id)
- if not selected:
- return self._default_candidate_subgraph()
-
- seed_ids = set(selected)
- for edge in sorted_edges:
- source_id = skill_id(edge.get("source"))
- target_id = skill_id(edge.get("target"))
- if source_id not in seed_ids and target_id not in seed_ids:
- continue
- add_skill(source_id)
- add_skill(target_id)
- if len(selected) >= FAST_PLANNER_MAX_SKILLS:
- break
-
+ sorted_edges = self._known_edges(self._sorted_eligible_edges())
+ edge_by_key = {
+ (skill_id(edge.get("source")), skill_id(edge.get("target"))): edge
+ for edge in sorted_edges
+ }
+ seeds = list(self.candidate_skill_ids)
+ adjacency: dict[str, list[str]] = defaultdict(list)
+ for source_id, target_id in edge_by_key:
+ adjacency[source_id].append(target_id)
+ for source_id in adjacency:
+ adjacency[source_id].sort()
+
+ selected = list(seeds)
+ selected_set = set(seeds)
candidate_edges = []
- for edge in sorted_edges:
- if (
- skill_id(edge.get("source")) in selected
- and skill_id(edge.get("target")) in selected
- ):
- candidate_edges.append(edge)
- if len(candidate_edges) >= FAST_PLANNER_MAX_EDGES:
- break
+ candidate_edge_keys = set()
+ parent = {seed_id: seed_id for seed_id in seeds}
+
+ def find(current_skill_id: str) -> str:
+ while parent[current_skill_id] != current_skill_id:
+ parent[current_skill_id] = parent[parent[current_skill_id]]
+ current_skill_id = parent[current_skill_id]
+ return current_skill_id
+
+ def union(left: str, right: str) -> None:
+ left_root = find(left)
+ right_root = find(right)
+ if left_root != right_root:
+ parent[right_root] = left_root
+
+ connections = []
+ for left_index, left_seed in enumerate(seeds):
+ for right_index in range(left_index + 1, len(seeds)):
+ right_seed = seeds[right_index]
+ paths = [
+ self._best_directed_path(
+ left_seed,
+ right_seed,
+ adjacency=adjacency,
+ edge_by_key=edge_by_key,
+ ),
+ self._best_directed_path(
+ right_seed,
+ left_seed,
+ adjacency=adjacency,
+ edge_by_key=edge_by_key,
+ ),
+ ]
+ ranked_paths = [
+ (self._path_rank(path), path) for path in paths if path
+ ]
+ if ranked_paths:
+ path_rank, path = min(ranked_paths, key=lambda item: item[0])
+ connections.append((path_rank, left_index, right_index, path))
+
+ seed_set = set(seeds)
+ for _, left_index, right_index, path in sorted(connections):
+ left_seed = seeds[left_index]
+ right_seed = seeds[right_index]
+ if find(left_seed) == find(right_seed):
+ continue
+ for edge in path:
+ self._append_candidate_edge(
+ candidate_edges,
+ candidate_edge_keys,
+ edge,
+ )
+ self._append_skill(
+ selected,
+ selected_set,
+ skill_id(edge.get("source")),
+ )
+ self._append_skill(
+ selected,
+ selected_set,
+ skill_id(edge.get("target")),
+ )
+ path_seeds = [skill for skill in self._path_skill_ids(path) if skill in seed_set]
+ for path_seed in path_seeds[1:]:
+ union(path_seeds[0], path_seed)
+
+ components: dict[str, list[str]] = defaultdict(list)
+ for seed_id in seeds:
+ components[find(seed_id)].append(seed_id)
+ neighbor_owners: dict[str, str] = {}
+ for component_seeds in components.values():
+ if len(component_seeds) != 1:
+ continue
+ seed_id = component_seeds[0]
+ incoming = next(
+ (edge for edge in sorted_edges if skill_id(edge.get("target")) == seed_id),
+ None,
+ )
+ outgoing = next(
+ (edge for edge in sorted_edges if skill_id(edge.get("source")) == seed_id),
+ None,
+ )
+ for edge in (incoming, outgoing):
+ if edge is None:
+ continue
+ source_id = skill_id(edge.get("source"))
+ target_id = skill_id(edge.get("target"))
+ neighbor_id = source_id if target_id == seed_id else target_id
+ owner = neighbor_owners.get(neighbor_id)
+ if neighbor_id in seed_set or (owner is not None and owner != seed_id):
+ continue
+ neighbor_owners[neighbor_id] = seed_id
+ self._append_candidate_edge(candidate_edges, candidate_edge_keys, edge)
+ self._append_skill(selected, selected_set, source_id)
+ self._append_skill(selected, selected_set, target_id)
return self._subgraph_payload(selected, candidate_edges)
+ def _best_directed_path(
+ self,
+ source_id: str,
+ target_id: str,
+ *,
+ adjacency: dict[str, list[str]],
+ edge_by_key: dict[tuple[str, str], dict[str, Any]],
+ ) -> list[dict[str, Any]]:
+ queue = [(0, -1.0, 0.0, (source_id,))]
+ while queue:
+ hops, negative_minimum, negative_total, nodes = heapq.heappop(queue)
+ current_id = nodes[-1]
+ if current_id == target_id and hops:
+ return [
+ edge_by_key[(nodes[index], nodes[index + 1])]
+ for index in range(len(nodes) - 1)
+ ]
+ if hops >= self.max_depth:
+ continue
+ minimum_confidence = -negative_minimum
+ total_confidence = -negative_total
+ for next_id in adjacency.get(current_id, []):
+ if next_id in nodes:
+ continue
+ edge = edge_by_key[(current_id, next_id)]
+ confidence = float(edge.get("confidence") or 0.0)
+ heapq.heappush(
+ queue,
+ (
+ hops + 1,
+ -min(minimum_confidence, confidence),
+ -(total_confidence + confidence),
+ (*nodes, next_id),
+ ),
+ )
+ return []
+
def _sorted_eligible_edges(self) -> list[dict[str, Any]]:
filtered_edges = []
for edge in self.artifacts.graph.get("edges", []):
@@ -259,13 +329,13 @@ class FastOneShotPlanner:
def _subgraph_payload(
self,
- selected: set[str],
+ selected: Sequence[str],
candidate_edges: list[dict[str, Any]],
) -> dict[str, Any]:
skill_by_id = self.artifacts.skill_by_id
skill_payloads = [
self._skill_payload(skill_by_id[current_skill_id])
- for current_skill_id in sorted(selected)
+ for current_skill_id in selected
if current_skill_id in skill_by_id
]
edge_payloads = [self._edge_payload(edge) for edge in candidate_edges]
@@ -279,6 +349,59 @@ class FastOneShotPlanner:
},
}
+ def _known_edges(self, edges: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
+ known_skill_ids = set(self.artifacts.skill_by_id)
+ output = []
+ seen = set()
+ for edge in edges:
+ key = (skill_id(edge.get("source")), skill_id(edge.get("target")))
+ if key in seen or key[0] not in known_skill_ids or key[1] not in known_skill_ids:
+ continue
+ seen.add(key)
+ output.append(edge)
+ return output
+
+ @staticmethod
+ def _append_skill(output: list[str], seen: set[str], current_skill_id: str) -> None:
+ current_skill_id = str(current_skill_id or "").strip()
+ if current_skill_id and current_skill_id not in seen:
+ seen.add(current_skill_id)
+ output.append(current_skill_id)
+
+ @staticmethod
+ def _append_candidate_edge(
+ output: list[dict[str, Any]],
+ seen: set[tuple[str, str]],
+ edge: dict[str, Any],
+ ) -> None:
+ key = (skill_id(edge.get("source")), skill_id(edge.get("target")))
+ if key not in seen:
+ seen.add(key)
+ output.append(edge)
+
+ @staticmethod
+ def _path_skill_ids(path: Sequence[dict[str, Any]]) -> list[str]:
+ if not path:
+ return []
+ return [
+ skill_id(path[0].get("source")),
+ *(skill_id(edge.get("target")) for edge in path),
+ ]
+
+ @classmethod
+ def _path_rank(cls, path: Sequence[dict[str, Any]]) -> tuple[Any, ...]:
+ confidences = [float(edge.get("confidence") or 0.0) for edge in path]
+ edge_ids = tuple(
+ (skill_id(edge.get("source")), skill_id(edge.get("target")))
+ for edge in path
+ )
+ return (
+ len(path),
+ -min(confidences),
+ -sum(confidences),
+ edge_ids,
+ )
+
def _materialize_selection(
self,
selection: dict[str, Any],
@@ -322,19 +445,6 @@ class FastOneShotPlanner:
"detail": f"Fast planner selected unknown skill IDs: {unknown_ids}",
}
skill_by_id = self.artifacts.skill_by_id
- missing_artifact_ids = [
- current_skill_id
- for current_skill_id in step_ids
- if current_skill_id not in skill_by_id
- ]
- if missing_artifact_ids:
- return {
- "valid": False,
- "detail": (
- "Fast planner selected missing artifact skill IDs: "
- f"{missing_artifact_ids}"
- ),
- }
selected_edges_result = self._normalize_selected_edges(
selection.get("can_feed_edges") or []
@@ -348,17 +458,33 @@ class FastOneShotPlanner:
f"{selected_edges_result['invalid']}"
),
}
+ if selected_edges_result["duplicates"]:
+ return {
+ "valid": False,
+ "detail": (
+ "Fast planner returned duplicate can_feed edges: "
+ f"{selected_edges_result['duplicates']}"
+ ),
+ }
if len(step_ids) > 1 and not selected_edges:
selected_edges = [
(step_ids[index], step_ids[index + 1])
for index in range(len(step_ids) - 1)
]
- invalid_edges = [edge for edge in selected_edges if edge not in candidate_edges]
- if invalid_edges:
+ step_id_set = set(step_ids)
+ unknown_edge_endpoints = [
+ edge
+ for edge in selected_edges
+ if edge[0] not in step_id_set or edge[1] not in step_id_set
+ ]
+ if unknown_edge_endpoints:
return {
"valid": False,
- "detail": f"Fast planner selected illegal can_feed edges: {invalid_edges}",
+ "detail": (
+ "Fast planner selected edges outside plan steps: "
+ f"{unknown_edge_endpoints}"
+ ),
}
order = {current_skill_id: index for index, current_skill_id in enumerate(step_ids)}
backward_edges = [
@@ -413,7 +539,19 @@ class FastOneShotPlanner:
}
)
- edge_items = [edge_plan_item(candidate_edges[edge]) for edge in selected_edges]
+ edge_items = []
+ has_inferred_edges = False
+ for edge in selected_edges:
+ if edge in candidate_edges:
+ edge_items.append(edge_plan_item(candidate_edges[edge]))
+ continue
+ has_inferred_edges = True
+ edge_items.append(
+ self._inferred_edge_plan_item(
+ edge,
+ selected_edges_result["reasons"].get(edge, ""),
+ )
+ )
if missing_inputs:
status = "needs_input"
return {
@@ -436,7 +574,11 @@ class FastOneShotPlanner:
if status == "ready"
else "structurally_valid_but_incomplete"
),
- "connectivity_trace": ["can_feed"] if edge_items else [],
+ "connectivity_trace": (
+ ["can_feed", "fast_llm_inferred"]
+ if has_inferred_edges
+ else (["can_feed"] if edge_items else [])
+ ),
"source": "one_shot_fast",
},
}
@@ -478,6 +620,23 @@ class FastOneShotPlanner:
"target_id": skill_id(edge.get("target")),
}
+ @staticmethod
+ def _inferred_edge_plan_item(
+ edge: tuple[str, str],
+ reason: str,
+ ) -> dict[str, Any]:
+ return {
+ "source_id": edge[0],
+ "target_id": edge[1],
+ "confidence": None,
+ "method": "fast_llm_inferred",
+ "port_mappings": [],
+ "source_outputs": [],
+ "target_inputs": [],
+ "reasons": [reason] if reason else [],
+ "reason": reason,
+ }
+
@staticmethod
def _normalize_step_ids(raw_steps: Any) -> list[str]:
if not isinstance(raw_steps, list):
@@ -494,9 +653,16 @@ class FastOneShotPlanner:
@staticmethod
def _normalize_selected_edges(raw_edges: Any) -> dict[str, Any]:
if not isinstance(raw_edges, list):
- return {"edges": [], "invalid": [raw_edges]}
+ return {
+ "edges": [],
+ "invalid": [raw_edges],
+ "duplicates": [],
+ "reasons": {},
+ }
edges = []
invalid = []
+ duplicates = []
+ reasons = {}
for item in raw_edges:
if not isinstance(item, dict):
invalid.append(item)
@@ -506,10 +672,20 @@ class FastOneShotPlanner:
if not source or not target:
invalid.append(item)
continue
+ if source == target:
+ continue
edge = (source, target)
- if edge not in edges:
- edges.append(edge)
- return {"edges": edges, "invalid": invalid}
+ if edge in edges:
+ duplicates.append(edge)
+ continue
+ edges.append(edge)
+ reasons[edge] = str(item.get("reason") or "").strip()
+ return {
+ "edges": edges,
+ "invalid": invalid,
+ "duplicates": duplicates,
+ "reasons": reasons,
+ }
@staticmethod
def _normalize_missing_inputs(
diff --git a/jiuwenswarm/symphony/orchestration/service.py b/jiuwenswarm/symphony/orchestration/service.py
index a6af2ee8c9..31ac18f43d 100644
--- a/jiuwenswarm/symphony/orchestration/service.py
+++ b/jiuwenswarm/symphony/orchestration/service.py
@@ -21,11 +21,9 @@ async def plan_from_score(
query: str,
llm_config: LLMConfig | None = None,
*,
- top_k: int = 3,
max_depth: int = 4,
min_edge_confidence: float = 0.7,
llm_client: Any | None = None,
- ranker: Any | None = None,
orchestration_config: SymphonyOrchestrationConfig | None = None,
candidate_skill_ids: Sequence[str] | None = None,
disabled_skill_names: Sequence[str] | None = None,
@@ -33,7 +31,6 @@ async def plan_from_score(
"""Run online planning from an existing Symphony score."""
if orchestration_config is not None:
- top_k = orchestration_config.top_k
min_edge_confidence = orchestration_config.min_edge_confidence
mode = orchestration_config.mode if orchestration_config is not None else "fast"
@@ -53,7 +50,10 @@ async def plan_from_score(
llm_config=llm_config,
llm_client=llm_client,
min_edge_confidence=clamp(min_edge_confidence),
- top_k=max(1, int(top_k)),
+ max_depth=max(
+ 1,
+ int(orchestration_config.max_depth if orchestration_config else max_depth),
+ ),
candidate_skill_ids=selected_candidate_skill_ids,
).plan(query)
result["skill_retrieval"] = skill_retrieval
diff --git a/jiuwenswarm/symphony/orchestration/skill_retrieval.py b/jiuwenswarm/symphony/orchestration/skill_retrieval.py
deleted file mode 100644
index 807f0439c7..0000000000
--- a/jiuwenswarm/symphony/orchestration/skill_retrieval.py
+++ /dev/null
@@ -1,201 +0,0 @@
-"""Skill retrieval candidate narrowing for Symphony orchestration."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any, Iterable
-
-from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
-from jiuwenswarm.symphony.skill_retrieval.config import load_settings
-from jiuwenswarm.symphony.skill_retrieval.retrieve_service import (
- run_structured_skill_retrieve,
-)
-
-
-@dataclass(frozen=True)
-class OrchestrationSkillRetrievalSelection:
- enabled: bool
- used: bool = False
- candidate_skill_ids: tuple[str, ...] = ()
- fallback_reason: str = ""
- candidate_records: tuple[dict[str, Any], ...] = field(default_factory=tuple)
-
- @property
- def candidate_count(self) -> int:
- return len(self.candidate_skill_ids)
-
- def to_dict(self) -> dict[str, Any]:
- return {
- "enabled": self.enabled,
- "used": self.used,
- "candidate_skill_ids": list(self.candidate_skill_ids),
- "candidate_count": self.candidate_count,
- "fallback_reason": self.fallback_reason,
- "candidate_records": [dict(record) for record in self.candidate_records],
- }
-
-
-def select_orchestration_skill_candidates(
- *,
- query: str,
- artifacts: ScoreArtifacts,
-) -> OrchestrationSkillRetrievalSelection:
- settings = load_settings()
- if not settings.enabled:
- return OrchestrationSkillRetrievalSelection(enabled=False)
-
- try:
- status = _skill_retrieval_status()
- except Exception as exc: # noqa: BLE001
- return _fallback(f"skill retrieval status failed: {exc}")
- if not bool(status.get("index_exists")):
- return _fallback("skill retrieval index does not exist")
- if not bool(status.get("fresh")):
- return _fallback("skill retrieval index is stale")
- if (
- not str(settings.llm.model or "").strip()
- or not str(settings.llm.api_key or "").strip()
- ):
- return _fallback("skill retrieval LLM config is missing")
-
- raw_index_dir = str(status.get("index_dir") or "").strip()
- if not raw_index_dir:
- return _fallback("skill retrieval index path is empty")
- index_dir = Path(raw_index_dir).expanduser()
-
- try:
- result = run_structured_skill_retrieve(
- settings=settings,
- index_dir=index_dir,
- query=str(query or "").strip(),
- )
- except Exception as exc: # noqa: BLE001
- return _fallback(f"skill retrieval failed: {exc}")
-
- known_skill_ids = set(artifacts.skill_by_id)
- candidate_records = _simplify_candidate_records(
- getattr(result, "candidate_records", ()),
- known_skill_ids=known_skill_ids,
- )
- candidate_skill_ids = _candidate_skill_ids_from_result(
- result,
- known_skill_ids=known_skill_ids,
- )
- if not candidate_skill_ids:
- return OrchestrationSkillRetrievalSelection(
- enabled=True,
- fallback_reason="skill retrieval returned no candidates present in current score",
- candidate_records=tuple(candidate_records),
- )
-
- return OrchestrationSkillRetrievalSelection(
- enabled=True,
- used=True,
- candidate_skill_ids=tuple(candidate_skill_ids),
- candidate_records=tuple(candidate_records),
- )
-
-
-def _fallback(reason: str) -> OrchestrationSkillRetrievalSelection:
- return OrchestrationSkillRetrievalSelection(
- enabled=True,
- fallback_reason=str(reason or "").strip(),
- )
-
-
-def _skill_retrieval_status() -> dict[str, Any]:
- from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
- from jiuwenswarm.symphony.skill_retrieval.index_service import SkillIndexService
-
- return SkillIndexService(SkillManager()).status()
-
-
-def _candidate_skill_ids_from_result(
- result: Any,
- *,
- known_skill_ids: set[str],
-) -> list[str]:
- output: list[str] = []
- seen: set[str] = set()
- records = getattr(result, "candidate_records", ()) or ()
- for record in records:
- if not isinstance(record, dict):
- continue
- _append_known_candidate_ids(
- _candidate_id_values(record),
- known_skill_ids=known_skill_ids,
- output=output,
- seen=seen,
- )
-
- payloads = getattr(result, "payloads", ()) or ()
- _append_known_candidate_ids(
- (str(payload or "").strip() for payload in payloads),
- known_skill_ids=known_skill_ids,
- output=output,
- seen=seen,
- )
- return output
-
-
-def _append_known_candidate_ids(
- values: Iterable[str],
- *,
- known_skill_ids: set[str],
- output: list[str],
- seen: set[str],
-) -> None:
- for value in values:
- candidate_id = str(value or "").strip()
- if (
- not candidate_id
- or candidate_id in seen
- or candidate_id not in known_skill_ids
- ):
- continue
- seen.add(candidate_id)
- output.append(candidate_id)
-
-
-def _candidate_id_values(record: dict[str, Any]) -> Iterable[str]:
- for key in ("worker_id", "resolved_payload"):
- value = str(record.get(key) or "").strip()
- if value:
- yield value
-
-
-def _simplify_candidate_records(
- records: Iterable[Any],
- *,
- known_skill_ids: set[str],
-) -> list[dict[str, Any]]:
- output: list[dict[str, Any]] = []
- for record in records:
- if not isinstance(record, dict):
- continue
- skill_id = next(
- (
- value
- for value in _candidate_id_values(record)
- if value in known_skill_ids
- ),
- "",
- )
- simplified = {
- "rank": record.get("rank"),
- "skill_id": skill_id,
- "worker_id": record.get("worker_id"),
- "resolved_payload": record.get("resolved_payload"),
- "skill_name": record.get("skill_name"),
- "score": record.get("score"),
- "source": record.get("source"),
- }
- output.append(
- {
- key: value
- for key, value in simplified.items()
- if value not in (None, "")
- }
- )
- return output
diff --git a/tests/unit_tests/symphony/test_config.py b/tests/unit_tests/symphony/test_config.py
index 30691f7392..cf972698a8 100644
--- a/tests/unit_tests/symphony/test_config.py
+++ b/tests/unit_tests/symphony/test_config.py
@@ -61,7 +61,6 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
},
"orchestration": {
"mode": "fast",
- "top_k": 0,
"max_depth": "7",
"min_edge_confidence": -1,
},
@@ -84,7 +83,6 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
assert cfg.build.require_consensus is False
assert cfg.build.min_edge_confidence == 1.0
assert cfg.orchestration.mode == "fast"
- assert cfg.orchestration.top_k == 1
assert cfg.orchestration.max_depth == 7
assert cfg.orchestration.min_edge_confidence == 0.0
assert cfg.enabled is True
diff --git a/tests/unit_tests/symphony/test_graph_exact_io.py b/tests/unit_tests/symphony/test_graph_exact_io.py
index cdb0b537cc..6376a85b88 100644
--- a/tests/unit_tests/symphony/test_graph_exact_io.py
+++ b/tests/unit_tests/symphony/test_graph_exact_io.py
@@ -42,6 +42,154 @@ def test_candidate_generator_emits_exact_io_match():
]
+def test_candidate_generator_default_candidate_limit_is_thirty_two():
+ assert CandidateGenerator().max_candidates_per_skill_relation == 32
+
+
+def test_candidate_generator_keeps_stronger_candidates_before_target_name():
+ candidates = CandidateGenerator(max_candidates_per_skill_relation=1).generate(
+ SkillRegistry(
+ skills={
+ "source": _skill(
+ "source",
+ outputs=[
+ ArtifactSpec(
+ name="outline",
+ type="markdown",
+ description="shared research slides evidence",
+ )
+ ],
+ ),
+ "aaa-weak": _skill(
+ "aaa-weak",
+ inputs=[
+ ParameterSpec(
+ name="report",
+ type="text",
+ description="shared research slides evidence",
+ )
+ ],
+ ),
+ "zzz-content": _skill(
+ "zzz-content",
+ inputs=[
+ ParameterSpec(
+ name="content",
+ type="markdown",
+ description="shared research slides evidence",
+ )
+ ],
+ ),
+ }
+ )
+ )
+
+ assert [candidate.key for candidate in candidates] == ["source->zzz-content"]
+ assert candidates[0].candidate_methods == [
+ "semantic_overlap_match",
+ "textual_coercion_match",
+ ]
+
+
+def test_candidate_generator_keeps_more_port_mapping_evidence_before_target_name():
+ candidates = CandidateGenerator(max_candidates_per_skill_relation=1).generate(
+ SkillRegistry(
+ skills={
+ "source": _skill(
+ "source",
+ outputs=[
+ ArtifactSpec(
+ name="brief",
+ type="text",
+ description="shared planning evidence",
+ ),
+ ArtifactSpec(
+ name="outline",
+ type="text",
+ description="shared planning evidence",
+ ),
+ ],
+ ),
+ "aaa-weak": _skill(
+ "aaa-weak",
+ inputs=[
+ ParameterSpec(
+ name="request",
+ type="text",
+ description="shared planning evidence",
+ )
+ ],
+ ),
+ "zzz-rich": _skill(
+ "zzz-rich",
+ inputs=[
+ ParameterSpec(
+ name="content",
+ type="text",
+ description="shared planning evidence",
+ ),
+ ParameterSpec(
+ name="text",
+ type="text",
+ description="shared planning evidence",
+ ),
+ ],
+ ),
+ }
+ )
+ )
+
+ assert [candidate.key for candidate in candidates] == ["source->zzz-rich"]
+ evidence = candidates[0].evidence["directions"]["source->zzz-rich"]
+ assert len(evidence["port_mappings"]) > 1
+
+
+def test_candidate_generator_candidate_limit_sorting_is_stable():
+ skills = [
+ _skill(
+ "source",
+ outputs=[
+ ArtifactSpec(
+ name="outline",
+ type="markdown",
+ description="shared research slides evidence",
+ )
+ ],
+ ),
+ _skill(
+ "aaa-weak",
+ inputs=[
+ ParameterSpec(
+ name="report",
+ type="text",
+ description="shared research slides evidence",
+ )
+ ],
+ ),
+ _skill(
+ "zzz-content",
+ inputs=[
+ ParameterSpec(
+ name="content",
+ type="markdown",
+ description="shared research slides evidence",
+ )
+ ],
+ ),
+ ]
+
+ first = CandidateGenerator(max_candidates_per_skill_relation=1).generate(
+ SkillRegistry(skills={skill.id: skill for skill in skills})
+ )
+ second = CandidateGenerator(max_candidates_per_skill_relation=1).generate(
+ SkillRegistry(skills={skill.id: skill for skill in reversed(skills)})
+ )
+
+ assert [candidate.key for candidate in first] == [
+ candidate.key for candidate in second
+ ]
+
+
def test_candidate_generator_keeps_reverse_direction_candidates_distinct():
candidates = _candidates(
_skill(
diff --git a/tests/unit_tests/symphony/test_llm_required.py b/tests/unit_tests/symphony/test_llm_required.py
index 57d4b9ff14..6de0ab5781 100644
--- a/tests/unit_tests/symphony/test_llm_required.py
+++ b/tests/unit_tests/symphony/test_llm_required.py
@@ -23,7 +23,6 @@ async def test_fast_planner_requires_llm_config_or_client(tmp_path):
llm_config=None,
llm_client=None,
min_edge_confidence=0.7,
- top_k=1,
)
with pytest.raises(ValueError, match="requires llm_config or llm_client"):
diff --git a/tests/unit_tests/symphony/test_service.py b/tests/unit_tests/symphony/test_service.py
index 8bdb3f4ae9..de33034c8e 100644
--- a/tests/unit_tests/symphony/test_service.py
+++ b/tests/unit_tests/symphony/test_service.py
@@ -1,5 +1,4 @@
import json
-from types import SimpleNamespace
import pytest
@@ -117,7 +116,6 @@ async def test_plan_from_score_fast_uses_one_shot_planner(monkeypatch, tmp_path)
llm_client=llm,
orchestration_config=SymphonyOrchestrationConfig(
mode="fast",
- top_k=2,
min_edge_confidence=0.7,
),
)
@@ -135,6 +133,7 @@ async def test_plan_from_score_fast_uses_one_shot_planner(monkeypatch, tmp_path)
assert result["execution_graph"]["edges"][0]["source"] == "skill-a"
prompt_payload = json.loads(llm.calls[0]["user_content"])
+ assert set(prompt_payload) == {"query", "skills", "can_feed_edges"}
assert prompt_payload["can_feed_edges"] == [
{
"source_id": "skill-a",
@@ -147,6 +146,14 @@ async def test_plan_from_score_fast_uses_one_shot_planner(monkeypatch, tmp_path)
]
assert all("inputs" not in skill for skill in prompt_payload["skills"])
assert all("outputs" not in skill for skill in prompt_payload["skills"])
+ system_prompt = llm.calls[0]["system_prompt"]
+ assert "Infer a missing relationship only when needed" in system_prompt
+ assert "explicitly including an inferred edge" in system_prompt
+ assert "Symphony infers adjacent step edges during validation" in system_prompt
+ assert "missing_inputs does not describe a Skill I/O schema" in system_prompt
+ assert llm.calls[0]["request_overrides"] == {
+ "extra_body": {"thinking": {"type": "disabled"}},
+ }
async def test_plan_from_score_fast_accepts_prefixed_graph_skill_ids(
@@ -239,7 +246,7 @@ async def test_plan_from_score_fast_no_plan_calls_llm_once(monkeypatch, tmp_path
assert result["execution_graph"]["nodes"] == []
-async def test_plan_from_score_fast_rejects_low_confidence_edge_once(
+async def test_plan_from_score_fast_accepts_low_confidence_edge_as_inferred(
monkeypatch,
tmp_path,
):
@@ -253,7 +260,11 @@ async def test_plan_from_score_fast_rejects_low_confidence_edge_once(
{"skill_id": "skill-c"},
],
"can_feed_edges": [
- {"source_id": "skill-a", "target_id": "skill-c"},
+ {
+ "source_id": "skill-a",
+ "target_id": "skill-c",
+ "reason": "The selected capabilities should run in sequence.",
+ },
],
}
)
@@ -281,8 +292,11 @@ async def test_plan_from_score_fast_rejects_low_confidence_edge_once(
"target_id": "skill-c",
},
]
- assert result["success"] is False
- assert "illegal can_feed edges" in result["detail"]
+ inferred_edge = result["recommended_plans"][0]["can_feed_edges"][0]
+ assert inferred_edge["method"] == "fast_llm_inferred"
+ assert inferred_edge["confidence"] is None
+ assert inferred_edge["reason"] == "The selected capabilities should run in sequence."
+ assert result["execution_graph"]["edges"][0]["method"] == "fast_llm_inferred"
async def test_plan_from_score_fast_uses_input_candidates_and_neighbors(
@@ -513,192 +527,365 @@ async def test_plan_from_score_rejects_non_fast_mode(monkeypatch, tmp_path):
tmp_path,
"beam plan",
llm_client=object(),
- ranker=object(),
orchestration_config=SymphonyOrchestrationConfig(mode="beam"),
)
-def test_orchestration_skill_retrieval_filters_unknown_ids(
- monkeypatch,
- tmp_path,
-):
- from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
+def _custom_artifacts(tmp_path, skill_ids, edges):
+ return ScoreArtifacts(
+ score_dir=tmp_path,
+ manifest={},
+ skills=[
+ {
+ "id": current_skill_id,
+ "name": current_skill_id,
+ "description": f"Capability {current_skill_id}",
+ "inputs": [],
+ "outputs": [],
+ }
+ for current_skill_id in skill_ids
+ ],
+ graph={"edges": edges},
+ lookup={},
+ )
- artifacts = _artifacts(tmp_path)
- settings = SimpleNamespace(
- enabled=True,
- llm=SimpleNamespace(model="model", api_key="key"),
- retrieve=SimpleNamespace(top_k=2),
- )
- result = SimpleNamespace(
- candidate_records=[
- {"rank": 1, "worker_id": "missing-skill", "score": 0.9},
- {"rank": 2, "worker_id": "skill-b", "score": 0.8},
+
+def _score_edge(source, target, confidence=0.9):
+ return {
+ "type": "can_feed",
+ "source": source,
+ "target": target,
+ "confidence": confidence,
+ "method": "test",
+ "evidence": {"reasons": [f"{source} feeds {target}"]},
+ }
+
+
+async def test_retrieval_forest_prefers_shortest_path(monkeypatch, tmp_path):
+ artifacts = _custom_artifacts(
+ tmp_path,
+ ["seed-a", "seed-b", "bridge", "incoming", "outgoing"],
+ [
+ _score_edge("seed-a", "seed-b", 0.71),
+ _score_edge("seed-a", "bridge", 0.99),
+ _score_edge("bridge", "seed-b", 0.99),
+ _score_edge("incoming", "seed-a", 0.98),
+ _score_edge("seed-b", "outgoing", 0.97),
],
- payloads=["missing-skill", "skill-b"],
- )
- monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
- monkeypatch.setattr(
- retrieval_module,
- "_skill_retrieval_status",
- lambda: {
- "index_exists": True,
- "fresh": True,
- "index_dir": str(tmp_path),
- },
)
- monkeypatch.setattr(
- retrieval_module,
- "run_structured_skill_retrieve",
- lambda **kwargs: result,
+ llm = _FakeLLMClient(
+ {
+ "status": "ready",
+ "steps": [{"skill_id": "seed-a"}, {"skill_id": "seed-b"}],
+ "can_feed_edges": [
+ {"source_id": "seed-a", "target_id": "seed-b"},
+ ],
+ }
)
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
- selection = retrieval_module.select_orchestration_skill_candidates(
- query="use beta",
- artifacts=artifacts,
+ await service.plan_from_score(
+ tmp_path,
+ "connect seeds",
+ llm_client=llm,
+ orchestration_config=SymphonyOrchestrationConfig(mode="fast", max_depth=3),
+ candidate_skill_ids=["seed-a", "seed-b"],
)
- assert selection.used is True
- assert selection.candidate_skill_ids == ("skill-b",)
- assert selection.candidate_count == 1
+ prompt = json.loads(llm.calls[0]["user_content"])
+ assert [skill["id"] for skill in prompt["skills"]] == ["seed-a", "seed-b"]
+ assert prompt["can_feed_edges"] == [
+ {"source_id": "seed-a", "target_id": "seed-b"}
+ ]
-def test_orchestration_skill_retrieval_falls_back_when_all_ids_are_stale(
+async def test_retrieval_forest_prefers_higher_confidence_for_equal_hops(
monkeypatch,
tmp_path,
):
- from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
-
- artifacts = _artifacts(tmp_path)
- settings = SimpleNamespace(
- enabled=True,
- llm=SimpleNamespace(model="model", api_key="key"),
- retrieve=SimpleNamespace(top_k=1),
- )
- result = SimpleNamespace(
- candidate_records=[{"rank": 1, "worker_id": "missing-skill"}],
- payloads=["missing-skill"],
- )
- monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
- monkeypatch.setattr(
- retrieval_module,
- "_skill_retrieval_status",
- lambda: {
- "index_exists": True,
- "fresh": True,
- "index_dir": str(tmp_path),
- },
- )
- monkeypatch.setattr(
- retrieval_module,
- "run_structured_skill_retrieve",
- lambda **kwargs: result,
+ artifacts = _custom_artifacts(
+ tmp_path,
+ ["seed-a", "seed-b", "weak", "strong"],
+ [
+ _score_edge("seed-a", "weak", 0.8),
+ _score_edge("weak", "seed-b", 0.8),
+ _score_edge("seed-a", "strong", 0.9),
+ _score_edge("strong", "seed-b", 0.9),
+ ],
)
+ llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": "strong"}]})
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
- selection = retrieval_module.select_orchestration_skill_candidates(
- query="use beta",
- artifacts=artifacts,
+ await service.plan_from_score(
+ tmp_path,
+ "connect seeds",
+ llm_client=llm,
+ orchestration_config=SymphonyOrchestrationConfig(mode="fast", max_depth=2),
+ candidate_skill_ids=["seed-a", "seed-b"],
)
- assert selection.used is False
- assert selection.candidate_skill_ids == ()
- assert "no candidates present" in selection.fallback_reason
+ prompt = json.loads(llm.calls[0]["user_content"])
+ assert [skill["id"] for skill in prompt["skills"]] == [
+ "seed-a",
+ "seed-b",
+ "strong",
+ ]
+ assert prompt["can_feed_edges"] == [
+ {"source_id": "seed-a", "target_id": "strong"},
+ {"source_id": "strong", "target_id": "seed-b"},
+ ]
-def test_orchestration_skill_retrieval_falls_back_when_index_missing(
+async def test_retrieval_forest_keeps_components_beyond_max_depth(
monkeypatch,
tmp_path,
):
- from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
-
- artifacts = _artifacts(tmp_path)
- settings = SimpleNamespace(
- enabled=True,
- llm=SimpleNamespace(model="model", api_key="key"),
+ artifacts = _custom_artifacts(
+ tmp_path,
+ ["seed-a", "seed-b", "bridge"],
+ [
+ _score_edge("seed-a", "bridge"),
+ _score_edge("bridge", "seed-b"),
+ ],
)
- monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
- monkeypatch.setattr(
- retrieval_module,
- "_skill_retrieval_status",
- lambda: {"index_exists": False, "fresh": False},
+ llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": "seed-a"}]})
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+
+ await service.plan_from_score(
+ tmp_path,
+ "keep separate",
+ llm_client=llm,
+ orchestration_config=SymphonyOrchestrationConfig(mode="fast", max_depth=1),
+ candidate_skill_ids=["seed-a", "seed-b"],
)
- selection = retrieval_module.select_orchestration_skill_candidates(
- query="use beta",
- artifacts=artifacts,
+ prompt = json.loads(llm.calls[0]["user_content"])
+ assert {skill["id"] for skill in prompt["skills"]} == {
+ "seed-a",
+ "seed-b",
+ "bridge",
+ }
+ assert prompt["can_feed_edges"] == [
+ {"source_id": "seed-a", "target_id": "bridge"}
+ ]
+
+
+async def test_fast_default_subgraph_has_no_skill_or_edge_limit(monkeypatch, tmp_path):
+ skill_ids = [f"skill-{index:02d}" for index in range(42)]
+ edges = []
+ for source_index in range(len(skill_ids)):
+ for target_index in range(source_index + 1, len(skill_ids)):
+ edges.append(_score_edge(skill_ids[source_index], skill_ids[target_index]))
+ if len(edges) == 82:
+ break
+ if len(edges) == 82:
+ break
+ artifacts = _custom_artifacts(tmp_path, skill_ids, edges)
+ llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": skill_ids[0]}]})
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+
+ result = await service.plan_from_score(tmp_path, "all candidates", llm_client=llm)
+
+ prompt = json.loads(llm.calls[0]["user_content"])
+ assert len(prompt["skills"]) == 42
+ assert len(prompt["can_feed_edges"]) == 82
+ assert result["candidate_skill_count"] == 42
+ assert result["candidate_edge_count"] == 82
+
+
+async def test_fast_retrieval_forest_has_no_skill_limit(monkeypatch, tmp_path):
+ skill_ids = [f"skill-{index:02d}" for index in range(42)]
+ edges = [
+ _score_edge(skill_ids[index], skill_ids[index + 1])
+ for index in range(len(skill_ids) - 1)
+ ]
+ edge_keys = {(edge["source"], edge["target"]) for edge in edges}
+ for source_index in range(len(skill_ids)):
+ for target_index in range(source_index + 1, len(skill_ids)):
+ key = (skill_ids[source_index], skill_ids[target_index])
+ if key not in edge_keys:
+ edges.append(_score_edge(*key))
+ edge_keys.add(key)
+ if len(edges) == 82:
+ break
+ if len(edges) == 82:
+ break
+ artifacts = _custom_artifacts(tmp_path, skill_ids, edges)
+ llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": skill_ids[0]}]})
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+
+ result = await service.plan_from_score(
+ tmp_path,
+ "all retrieved candidates",
+ llm_client=llm,
+ candidate_skill_ids=skill_ids,
)
- assert selection.used is False
- assert selection.fallback_reason == "skill retrieval index does not exist"
+ prompt = json.loads(llm.calls[0]["user_content"])
+ assert len(edges) == 82
+ assert len(prompt["skills"]) == 42
+ assert result["candidate_skill_count"] == 42
-def test_orchestration_skill_retrieval_falls_back_when_llm_config_missing(
- monkeypatch,
- tmp_path,
-):
- from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
+async def test_fast_default_subgraph_uses_all_skills_without_edges(monkeypatch, tmp_path):
+ skill_ids = [f"skill-{index:02d}" for index in range(45)]
+ artifacts = _custom_artifacts(tmp_path, skill_ids, [])
+ llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": skill_ids[0]}]})
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+
+ await service.plan_from_score(tmp_path, "all skills", llm_client=llm)
+ prompt = json.loads(llm.calls[0]["user_content"])
+ assert len(prompt["skills"]) == 45
+ assert prompt["can_feed_edges"] == []
+
+
+async def test_fast_plan_materializes_existing_and_inferred_edges(monkeypatch, tmp_path):
artifacts = _artifacts(tmp_path)
- settings = SimpleNamespace(
- enabled=True,
- llm=SimpleNamespace(model="", api_key=""),
- )
- monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
- monkeypatch.setattr(
- retrieval_module,
- "_skill_retrieval_status",
- lambda: {
- "index_exists": True,
- "fresh": True,
- "index_dir": str(tmp_path),
- },
+ artifacts.graph["edges"] = artifacts.graph["edges"][:1]
+ llm = _FakeLLMClient(
+ {
+ "status": "ready",
+ "steps": [
+ {"skill_id": "skill-a"},
+ {"skill_id": "skill-b"},
+ {"skill_id": "skill-c"},
+ ],
+ "can_feed_edges": [
+ {"source_id": "skill-a", "target_id": "skill-b"},
+ {
+ "source_id": "skill-b",
+ "target_id": "skill-c",
+ "reason": "Continue with the selected publisher.",
+ },
+ ],
+ }
)
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
- selection = retrieval_module.select_orchestration_skill_candidates(
- query="use beta",
- artifacts=artifacts,
+ result = await service.plan_from_score(
+ tmp_path,
+ "mixed edges",
+ llm_client=llm,
+ candidate_skill_ids=["skill-a", "skill-b", "skill-c"],
)
- assert selection.used is False
- assert selection.fallback_reason == "skill retrieval LLM config is missing"
+ edges = result["recommended_plans"][0]["can_feed_edges"]
+ assert [edge["method"] for edge in edges] == ["llm", "fast_llm_inferred"]
+ assert result["execution_graph"]["edges"][1]["method"] == "fast_llm_inferred"
-def test_orchestration_skill_retrieval_falls_back_when_retrieve_raises(
+async def test_fast_plan_infers_adjacent_edges_when_omitted(monkeypatch, tmp_path):
+ artifacts = _artifacts(tmp_path)
+ llm = _FakeLLMClient(
+ {
+ "status": "ready",
+ "steps": [{"skill_id": "skill-a"}, {"skill_id": "skill-c"}],
+ }
+ )
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+
+ result = await service.plan_from_score(tmp_path, "infer adjacency", llm_client=llm)
+
+ edge = result["recommended_plans"][0]["can_feed_edges"][0]
+ assert edge["source_id"] == "skill-a"
+ assert edge["target_id"] == "skill-c"
+ assert edge["method"] == "fast_llm_inferred"
+
+
+ ("steps", "edges", "detail"),
+ [
+ (
+ ["skill-a", "skill-b"],
+ [{"source_id": "skill-a", "target_id": "skill-c"}],
+ "outside plan steps",
+ ),
+ (
+ ["skill-a", "skill-b"],
+ [{"source_id": "skill-b", "target_id": "skill-a"}],
+ "violate step order",
+ ),
+ (
+ ["skill-a", "skill-b"],
+ [
+ {"source_id": "skill-a", "target_id": "skill-b"},
+ {"source_id": "skill-a", "target_id": "skill-b"},
+ ],
+ "duplicate can_feed edges",
+ ),
+ ],
+)
+async def test_fast_plan_rejects_invalid_inferred_edges(
monkeypatch,
tmp_path,
+ steps,
+ edges,
+ detail,
):
- from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
-
artifacts = _artifacts(tmp_path)
- settings = SimpleNamespace(
- enabled=True,
- llm=SimpleNamespace(model="model", api_key="key"),
- )
-
- def raise_retrieve(**kwargs):
- del kwargs
- raise RuntimeError("boom")
-
- monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
- monkeypatch.setattr(
- retrieval_module,
- "_skill_retrieval_status",
- lambda: {
- "index_exists": True,
- "fresh": True,
- "index_dir": str(tmp_path),
- },
+ llm = _FakeLLMClient(
+ {
+ "status": "ready",
+ "steps": [{"skill_id": skill} for skill in steps],
+ "can_feed_edges": edges,
+ }
)
- monkeypatch.setattr(
- retrieval_module,
- "run_structured_skill_retrieve",
- raise_retrieve,
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+
+ result = await service.plan_from_score(tmp_path, "invalid edge", llm_client=llm)
+
+ assert result["success"] is False
+ assert detail in result["detail"]
+
+
+async def test_fast_plan_drops_single_step_self_loop_edge(monkeypatch, tmp_path):
+ artifacts = _artifacts(tmp_path)
+ llm = _FakeLLMClient(
+ {
+ "status": "ready",
+ "steps": [{"skill_id": "skill-a"}],
+ "can_feed_edges": [
+ {
+ "source_id": "skill-a",
+ "target_id": "skill-a",
+ "reason": "Self reuse should not become a can_feed edge.",
+ }
+ ],
+ }
)
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+
+ result = await service.plan_from_score(tmp_path, "self loop", llm_client=llm)
+
+ assert result["validation"]["valid"] is True
+ plan = result["recommended_plans"][0]
+ assert [step["skill_id"] for step in plan["steps"]] == ["skill-a"]
+ assert plan["can_feed_edges"] == []
- selection = retrieval_module.select_orchestration_skill_candidates(
- query="use beta",
- artifacts=artifacts,
+
+async def test_fast_plan_drops_self_loop_and_keeps_valid_edge(monkeypatch, tmp_path):
+ artifacts = _artifacts(tmp_path)
+ llm = _FakeLLMClient(
+ {
+ "status": "ready",
+ "steps": [{"skill_id": "skill-a"}, {"skill_id": "skill-b"}],
+ "can_feed_edges": [
+ {
+ "source_id": "skill-a",
+ "target_id": "skill-a",
+ "reason": "Self reuse should not become a can_feed edge.",
+ },
+ {"source_id": "skill-a", "target_id": "skill-b"},
+ ],
+ }
)
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
- assert selection.used is False
- assert selection.fallback_reason == "skill retrieval failed: boom"
+ result = await service.plan_from_score(tmp_path, "mixed edges", llm_client=llm)
+
+ assert result["validation"]["valid"] is True
+ edges = result["recommended_plans"][0]["can_feed_edges"]
+ assert [(edge["source_id"], edge["target_id"]) for edge in edges] == [
+ ("skill-a", "skill-b")
+ ]
diff --git a/tests/unit_tests/symphony/test_toolkit.py b/tests/unit_tests/symphony/test_toolkit.py
index d59db93121..86facfc6e2 100644
--- a/tests/unit_tests/symphony/test_toolkit.py
+++ b/tests/unit_tests/symphony/test_toolkit.py
@@ -620,6 +620,27 @@ def test_toolkit_plan_returns_compact_plan_and_skill_retrieval():
assert "resolved_payload" not in skill_retrieval["candidate_records"][0]
+def test_toolkit_compacts_inferred_edge_provenance():
+ edge = SymphonyToolkit._compact_can_feed_edge(
+ {
+ "source_id": "skill-a",
+ "target_id": "skill-b",
+ "confidence": None,
+ "method": "fast_llm_inferred",
+ "reason": "LLM connected retrieved candidates.",
+ "port_mappings": [],
+ }
+ )
+
+ assert edge == {
+ "source_id": "skill-a",
+ "target_id": "skill-b",
+ "confidence": None,
+ "method": "fast_llm_inferred",
+ "reason": "LLM connected retrieved candidates.",
+ }
+
+
def test_toolkit_no_plan_continues_for_skill_discovery():
registry = ExtensionRegistry.create_instance(
callback_framework=_CallbackFramework(),