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): learn dynamic graph from session history

layShang264f17a6645ec9c
diff --git a/docs/en/Symphony.md b/docs/en/Symphony.md
index e5b102981c..d09e6bab81 100644
--- a/docs/en/Symphony.md
+++ b/docs/en/Symphony.md
@@ -37,7 +37,13 @@ The skill score is the graph used by orchestration. Each node represents a skill
![Skill score](../assets/images/symphony_score.png)
-The skill score shows connectable candidate relationships. It is not execution history, and it does not guarantee every visible connection can be chained directly for every task. Always check the skill details, required inputs, and current task goal.
+The skill score shows statically built connectable candidate relationships, and it does not guarantee every visible connection can be chained directly for every task. Always check the skill details, required inputs, and current task goal.
+
+#### Improve orchestration from Session execution traces
+
+When **Dynamic Graph** is enabled, Symphony asynchronously reads JiuwenSwarm's existing Session JSON history after each conversation completes. It correlates the orchestration result with observed Skill calls and results. Repeated successful edges receive bounded reinforcement for later relevant tasks, while explicitly failed edges are downranked. A displayed orchestration graph without an observed Skill call is not counted as success evidence.
+
+Dynamic data is a replayable overlay on top of the static graph; it never overwrites the permanent static graph. Turning the switch off immediately returns planning to static-only behavior while retaining existing dynamic data.
#### What problem does it solve?
@@ -70,6 +76,10 @@ Skill Orchestration builds a skill chain from the task goal, candidate skills, a
User confirms
v
JiuwenSwarm continues with concrete skill execution
+ v
+Asynchronously consume Session JSON after the conversation (dynamic graph only)
+ v
+Update runtime events and the dynamic overlay for later orchestration
```
Skill Retrieval mainly finds skills. Skill Orchestration organizes candidate skills into a task-oriented execution route. The skill score records and displays whether skills can connect, giving orchestration the graph relationships it needs. Skill Retrieval and Skill Orchestration are Symphony's two core capabilities.
@@ -213,10 +223,10 @@ When a skill looks relevant, the agent may read its `SKILL.md` before executing
#### Before you use it
1. Open left sidebar -> **Configuration** -> **Other configuration**.
-2. Expand **Skill Symphony**, turn on **Enable Skill Symphony**, then click **Save** in the top-right corner.
+2. Expand **Skill Symphony** and turn on **Enable skill orchestration**. To learn from real execution traces, also turn on **Enable dynamic graph**, then click **Save** in the top-right corner.
3. Confirm the required skills are installed. If you recently added, removed, or changed skills, open **Skills** -> **Skill Graph** and run **Incremental build**. If you only need to confirm the current score state, use **Read score**.
-The **Skill Symphony** switch enables Symphony orchestration. Skill Retrieval is still controlled by the separate **Skill Retrieval** switch.
+**Enable skill orchestration** is the Symphony master switch. **Enable dynamic graph** takes effect only while orchestration is enabled. Skill Retrieval is still controlled by the separate **Skill Retrieval** switch.
![Skill Symphony configuration](../assets/images/symphony_config.png)
@@ -264,7 +274,7 @@ After seeing the route, you can respond in one of these ways:
## Configuration
-The Web configuration page exposes two related switches: **Enable Skill Retrieval** controls skill-tree retrieval tools, and **Enable Skill Symphony** controls skill score and orchestration tools. The Skill Index page provides index build, rebuild, cancel, status, and tree viewing operations. The Skill Graph page provides score reading, incremental build, pause build, and full rebuild operations.
+The Web configuration page exposes three related switches: **Enable Skill Retrieval** controls skill-tree retrieval tools, **Enable skill orchestration** controls skill score and orchestration tools, and **Enable dynamic graph** controls whether Session execution traces are learned from and used by later orchestration. The Skill Index page provides index build, rebuild, cancel, status, and tree viewing operations. The Skill Graph page provides score reading, incremental build, pause build, and full rebuild operations.
Advanced build, retrieval, and orchestration settings are configured in the user runtime config file:
@@ -288,6 +298,10 @@ The skill source directory and skill score artifact directory. Both default temp
`symphony_refresh_score` reads skills from `skills_root` and refreshes the skill score. `symphony_read_score` and `symphony_compose_score` read score artifacts from `score_dir`. Configure these paths explicitly when the score needs to be cached in a fixed location or reused across runtime environments.
+#### `symphony.build`
+
+Graph construction keeps up to `32` candidates per Skill/relation and uses `0.5` as the edge acceptance threshold by default. Tune the cap with `max_candidates_per_skill_relation`; the effective value is recorded in the build manifest for reproducibility and diagnosis.
+
#### `symphony.orchestration`
Runtime parameters for Skill Orchestration. The current template is:
@@ -296,7 +310,7 @@ Runtime parameters for Skill Orchestration. The current template is:
|---------|---------|-------------|
| `mode` | `fast` | Orchestration mode. The current runtime tools use the fast orchestration path and prioritize an executable skill chain |
| `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 |
+| `min_edge_confidence` | `0.5` | 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 often use low-confidence connections, consider increasing `min_edge_confidence`.
@@ -406,10 +420,17 @@ symphony:
skills_root: ""
score_dir: ""
+ build:
+ max_candidates_per_skill_relation: 32
+ min_edge_confidence: 0.5
+
+ evolution:
+ enabled: true
+
orchestration:
mode: fast
max_depth: 4
- min_edge_confidence: 0.3
+ min_edge_confidence: 0.5
skill_retrieval:
enabled: true
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 6d9f7588e5..c8843f1049 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"
@@ -37,7 +37,13 @@ Symphony(技能交响乐)是 JiuwenSwarm 面向海量已安装技能提供
![技能总谱](../assets/images/symphony_score.png)
-技能总谱展示的是“可衔接候选关系”,不是已经执行过的任务记录,也不保证所有场景都一定能直接串联。实际使用时仍需结合技能详情、输入参数和任务目标确认。
+技能总谱展示的是静态构建的“可衔接候选关系”,不保证所有场景都一定能直接串联。实际使用时仍需结合技能详情、输入参数和任务目标确认。
+
+#### 用 Session 执行轨迹持续优化编排
+
+开启 **动态图谱** 后,Symphony 会在每轮对话完成后异步读取 JiuwenSwarm 已有的 Session JSON 历史,将编排结果与实际观测到的 Skill 调用及结果关联起来。稳定成功的边会在后续相关任务中获得有界强化,明确失败的边会降权;仅展示过编排图、但没有真实 Skill 调用的记录不作为成功证据。
+
+动态数据作为可回放的 overlay 叠加在静态图谱之上,不改写永久静态图谱。关闭开关后编排立即回到仅使用静态图谱,已累积的动态数据会保留。
#### 它解决什么问题
@@ -70,6 +76,10 @@ skill_branch_explore 展开相关分支
用户确认
↓
继续执行具体技能
+ ↓
+对话完成后异步消费 Session JSON(仅动态图谱开启时)
+ ↓
+更新运行事件与动态 overlay,供后续编排使用
```
技能检索主要负责“找技能”;技能编排负责把候选技能组织成一条面向任务的执行路线;技能总谱负责展示和沉淀“技能之间能否衔接”,为编排提供关系图依据。技能检索和技能编排构成 Symphony(技能交响乐)的两类核心能力。
@@ -213,10 +223,10 @@ Symphony 只会使用已安装技能。请先在左侧导航栏 **技能** 页
#### 使用前准备
1. 打开左侧导航栏 → **配置信息** → **其他配置**。
-2. 展开 **技能交响乐** 配置项,开启 **启用技能交响乐**,然后点击右上角 **保存**。
+2. 展开 **技能交响乐** 配置项,开启 **启用技能编排**。需要从真实执行轨迹持续学习时,同时开启 **启用动态图谱**,然后点击右上角 **保存**。
3. 确认任务需要的技能已经安装;如果刚新增、删除或修改过技能,建议先到 **技能** → **技能总谱** 中执行一次 **增量构建**。如果只是确认当前总谱状态,可以先 **读谱**。
-这里的 **技能交响乐** 开关用于开启 Symphony 的编排能力;技能检索仍由前面的 **技能检索** 开关单独控制。
+这里的 **启用技能编排** 是 Symphony 编排总开关;**启用动态图谱** 只在总开关开启时生效;技能检索仍由前面的 **技能检索** 开关单独控制。
![技能交响乐配置](../assets/images/symphony_config.png)
@@ -264,7 +274,7 @@ Symphony 只会使用已安装技能。请先在左侧导航栏 **技能** 页
## 配置说明
-当前 Web 配置页主要提供两个相关开关:**启用技能检索** 控制技能树检索工具,**启用技能交响乐** 控制技能总谱与编排工具。技能索引页提供索引构建、重新构建、取消构建、查看构建状态和查看索引树等操作;技能总谱页提供读谱、增量构建、暂停构建和全量重新构建等操作。
+当前 Web 配置页提供三个相关开关:**启用技能检索** 控制技能树检索工具,**启用技能编排** 控制技能总谱与编排工具,**启用动态图谱** 控制 Session 执行轨迹是否参与学习和后续编排。技能索引页提供索引构建、重新构建、取消构建、查看构建状态和查看索引树等操作;技能总谱页提供读谱、增量构建、暂停构建和全量重新构建等操作。
构建、检索和编排的高级参数需要在用户运行时配置文件进行配置:
@@ -288,6 +298,10 @@ Symphony 只会使用已安装技能。请先在左侧导航栏 **技能** 页
`symphony_refresh_score` 会从 `skills_root` 读取技能并刷新技能总谱;`symphony_read_score` 和 `symphony_compose_score` 会读取 `score_dir` 下的总谱产物。需要把总谱缓存到固定位置、或者在不同运行环境之间复用总谱时,可以显式配置这些目录。
+#### `symphony.build`
+
+构图阶段默认最多为每个 Skill/关系保留 `32` 个候选,并以 `0.5` 作为边验收阈值。候选上限可通过 `max_candidates_per_skill_relation` 调整;实际使用的值会写入构建 manifest,便于复现和排查。
+
#### `symphony.orchestration`
技能编排的运行参数。当前模板配置如下:
@@ -296,7 +310,7 @@ Symphony 只会使用已安装技能。请先在左侧导航栏 **技能** 页
|--------|--------|------|
| `mode` | `fast` | 编排模式。当前运行时工具使用快速编排路径,优先给出可执行的技能链 |
| `max_depth` | `4` | 技能链最大搜索深度,用于限制一次任务中串联技能的长度 |
-| `min_edge_confidence` | `0.3` | 技能总谱边的最低置信度阈值,低于该值的连接关系不会优先用于编排 |
+| `min_edge_confidence` | `0.5` | 技能总谱边的最低置信度阈值,低于该值的连接关系不会优先用于编排 |
这些参数适用于调节“如何把候选技能连成路线”。如果结果过短、经常漏掉中间处理步骤,可以适当增加 `max_depth`;如果路线经常使用低置信度连接,可以提高 `min_edge_confidence`。
@@ -407,10 +421,17 @@ symphony:
skills_root: ""
score_dir: ""
+ build:
+ max_candidates_per_skill_relation: 32
+ min_edge_confidence: 0.5
+
+ evolution:
+ enabled: true
+
orchestration:
mode: fast
max_depth: 4
- min_edge_confidence: 0.3
+ min_edge_confidence: 0.5
skill_retrieval:
enabled: true
diff --git a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
index d715cc94da..7bb9d3028b 100644
--- a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
@@ -129,6 +129,13 @@ class SymphonyToolkit:
if isinstance(beam_search, dict):
compact["beam_search"] = cls._compact_beam_search(beam_search)
+ for key in ("plan_id", "dynamic_graph_enabled"):
+ value = planning_payload.get(key)
+ if value in (None, ""):
+ value = payload.get(key)
+ if value not in (None, ""):
+ compact[key] = value
+
plan = cls._compact_plan(cls._primary_plan(planning_payload))
if plan:
compact["plan"] = plan
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
index ca15493e15..24a5c4c3cf 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
@@ -359,7 +359,10 @@ const HIDDEN_CONFIG_KEYS = new Set([
const MEMORY_KEYS = new Set(["memory_forbidden_enabled", "memory_forbidden_description"]);
const A2UI_KEYS = new Set(["a2ui_enabled"]);
const SWARMFLOW_KEYS = new Set(["swarmflow_enabled"]);
-const SYMPHONY_BOOLEAN_KEYS = new Set(["symphony_enabled"]);
+const SYMPHONY_BOOLEAN_KEYS = new Set([
+ "symphony_enabled",
+ "symphony_dynamic_graph_enabled",
+]);
const SKILL_RETRIEVAL_BOOLEAN_KEYS = new Set([
"skill_retrieval_enabled",
]);
@@ -641,6 +644,7 @@ function getBooleanKeyLabel(key: string, t: (key: string) => string): string {
a2ui_enabled: t('config.booleanLabels.enabled'),
swarmflow_enabled: t('config.booleanLabels.enabled'),
symphony_enabled: t('config.booleanLabels.enabled'),
+ symphony_dynamic_graph_enabled: t('config.booleanLabels.dynamicGraph'),
skill_retrieval_enabled: t('config.booleanLabels.enabled'),
proactive_recommendation_enabled: t('config.booleanLabels.enabled'),
};
@@ -717,6 +721,7 @@ const KEY_DISPLAY_I18N: Record<string, string> = {
model: "config.keys.agentModel",
skills: "config.keys.agentSkills",
symphony_enabled: "config.keys.symphonyEnabled",
+ symphony_dynamic_graph_enabled: "config.keys.symphonyDynamicGraphEnabled",
skill_retrieval_enabled: "config.keys.skillRetrievalEnabled",
skill_retrieval_build_branching_factor: "config.keys.skillRetrievalBuildBranchingFactor",
skill_retrieval_build_max_depth: "config.keys.skillRetrievalBuildMaxDepth",
@@ -744,6 +749,7 @@ const KEY_PLACEHOLDER_I18N: Record<string, string> = {
};
const KEY_LABEL_HINT_I18N: Record<string, string> = {
skill_create: "config.keyHelp.skillCreate",
+ symphony_dynamic_graph_enabled: "config.keyHelp.symphonyDynamicGraphEnabled",
skill_retrieval_build_root_categories: "config.keyHelp.skillRetrievalBuildRootCategories",
};
@@ -754,7 +760,8 @@ const KEY_SORT_PRIORITY: Record<string, number> = {
free_search_ddg_enabled: 0,
free_search_bing_enabled: 1,
symphony_enabled: 0,
- skill_retrieval_enabled: 1,
+ symphony_dynamic_graph_enabled: 1,
+ skill_retrieval_enabled: 2,
proactive_recommendation_enabled: 0,
proactive_recommendation_max_recommend_per_day: 2,
proactive_recommendation_max_rounds_per_tick: 3,
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx
index 836293313d..92163f6e2f 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx
@@ -120,6 +120,7 @@ type GraphEdge = {
target: string;
type: string;
confidence: number;
+ runtimeWeight?: number;
method: string;
evidence: RawRecord;
};
@@ -306,11 +307,13 @@ function normalizeEdge(raw: RawRecord): GraphEdge | null {
const rawSource = asString(raw.source ?? raw.source_id);
const rawTarget = asString(raw.target ?? raw.target_id);
if (!rawSource || !rawTarget) return null;
+ const runtimeWeight = Number(raw.runtime_weight);
return {
source: rawSource.includes(':') ? rawSource : `skill:${rawSource}`,
target: rawTarget.includes(':') ? rawTarget : `skill:${rawTarget}`,
type: asString(raw.type ?? raw.relation_type, 'relates_to'),
confidence: Number(raw.confidence ?? 1),
+ runtimeWeight: Number.isFinite(runtimeWeight) ? runtimeWeight : undefined,
method: asString(raw.method, 'deterministic'),
evidence: asRecord(raw.evidence ?? raw.metadata),
};
@@ -1649,7 +1652,13 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
}}
>
<span>{edge.source === selectedNode.id ? '→' : '←'} {other?.label || labelFromId(otherId)}</span>
- <small>{edge.type} · {Math.round(edge.confidence * 100)}%</small>
+ <small>
+ {edge.type}
+ {edge.runtimeWeight === undefined
+ ? ''
+ : ` · runtime_weight ${edge.runtimeWeight.toFixed(2)}`}
+ {' · '}{Math.round(edge.confidence * 100)}%
+ </small>
</button>
);
})
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index bc8609dd96..df81bdb3aa 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -774,6 +774,7 @@
"teamMemberPromptHint": "Prompt Hint",
"teamMemberAgentKey": "Agent Key",
"symphonyEnabled": "Enable skill orchestration",
+ "symphonyDynamicGraphEnabled": "Enable dynamic graph",
"skillRetrievalEnabled": "Enable skill retrieval",
"skillRetrievalBuildBranchingFactor": "Split threshold base",
"skillRetrievalBuildMaxDepth": "Max tree depth",
@@ -802,6 +803,7 @@
},
"keyHelp": {
"skillCreate": "Install `skill-creator` and `teamskill-creator` before enabling",
+ "symphonyDynamicGraphEnabled": "When disabled, planning uses only the static graph. Existing runtime data is retained.",
"skillRetrievalBuildRootCategories": "Edit YAML/JSON containing tree_root_categories or root_categories directly. The page shows the default taxonomy as a reference; saving writes the config content itself, not an external file path."
},
"hideValue": "Hide value",
@@ -948,6 +950,7 @@
"freeSearchDdg": "Enable DuckDuckGo (including DDG via Jina)",
"freeSearchBing": "Enable Bing",
"enabled": "Enable",
+ "dynamicGraph": "Enable dynamic graph",
"kvCacheAffinity": "Compute affinity (KV cache release)"
},
"permissionsTools": {
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 68c1bf9e63..1d3e8cc1e6 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -774,6 +774,7 @@
"teamMemberPromptHint": "提示词",
"teamMemberAgentKey": "Agent Key",
"symphonyEnabled": "启用技能编排",
+ "symphonyDynamicGraphEnabled": "启用动态图谱",
"skillRetrievalEnabled": "启用技能检索",
"skillRetrievalBuildBranchingFactor": "拆分阈值基数",
"skillRetrievalBuildMaxDepth": "最大树深",
@@ -802,6 +803,7 @@
},
"keyHelp": {
"skillCreate": "建议先安装 `skill-creator` 和 `teamskill-creator`,再开启",
+ "symphonyDynamicGraphEnabled": "关闭后仅使用静态图谱,已有运行时数据会保留。",
"skillRetrievalBuildRootCategories": "直接编辑包含 tree_root_categories 或 root_categories 的 YAML/JSON;页面会展示默认分层供参考。保存后会写入配置内容本身,而不是外部文件路径。"
},
"hideValue": "隐藏明文",
@@ -948,6 +950,7 @@
"freeSearchDdg": "启用 DuckDuckGo(含 DDG via Jina)",
"freeSearchBing": "启用 Bing",
"enabled": "启用",
+ "dynamicGraph": "启用动态图谱",
"kvCacheAffinity": "算力亲和(KV 释放)"
},
"permissionsTools": {
diff --git a/jiuwenswarm/extensions/symphony/extension.py b/jiuwenswarm/extensions/symphony/extension.py
index e6f278232b..f8a2d22279 100644
--- a/jiuwenswarm/extensions/symphony/extension.py
+++ b/jiuwenswarm/extensions/symphony/extension.py
@@ -17,6 +17,8 @@ from jiuwenswarm.symphony.llm import LLMConfig
from jiuwenswarm.symphony.config import load_symphony_config, symphony_config_from_dict
from jiuwenswarm.symphony.build import build_score as service_build_score
from jiuwenswarm.symphony.build import score_status
+from jiuwenswarm.symphony.evolution.models import edge_key, skill_id
+from jiuwenswarm.symphony.evolution.service import load_dynamic_overlay
from jiuwenswarm.symphony.orchestration import load_score_artifacts
from jiuwenswarm.symphony.orchestration.artifacts import filter_disabled_score_artifacts
from jiuwenswarm.symphony.orchestration.execution_graph import select_primary_plan
@@ -166,7 +168,12 @@ class SymphonyExtension(BaseExtension):
orchestration_min_edge_confidence
),
"skills": artifacts.skills,
- "graph": artifacts.graph,
+ "graph": _graph_with_runtime_weights(
+ artifacts.graph,
+ load_dynamic_overlay(artifacts.score_dir)
+ if config.evolution.enabled
+ else None,
+ ),
"score_lookup": artifacts.lookup,
}
payload.update(_build_log_payload(score_dir))
@@ -238,6 +245,7 @@ class SymphonyExtension(BaseExtension):
query,
LLMConfig.from_default_model(),
orchestration_config=orchestration_config,
+ dynamic_graph_enabled=config.evolution.enabled,
candidate_skill_ids=candidate_skill_ids,
disabled_skill_names=load_execution_disabled_skills(),
progress_callback=progress_callback,
@@ -378,6 +386,28 @@ def _missing_artifacts_payload(
}
+def _graph_with_runtime_weights(
+ graph: dict[str, Any],
+ overlay: dict[str, Any] | None,
+) -> dict[str, Any]:
+ runtime_edges = overlay.get("edges") if isinstance(overlay, dict) else None
+ if not isinstance(runtime_edges, dict) or not runtime_edges:
+ return graph
+ output_edges = []
+ for edge in graph.get("edges", []):
+ item = dict(edge)
+ current_key = edge_key(
+ skill_id(item.get("source")),
+ skill_id(item.get("target")),
+ str(item.get("type") or "can_feed"),
+ )
+ stats = runtime_edges.get(current_key)
+ if isinstance(stats, dict):
+ item["runtime_weight"] = float(stats.get("runtime_weight") or 1.0)
+ output_edges.append(item)
+ return {**graph, "edges": output_edges}
+
+
def _param_bool(value: Any, default: bool = False) -> bool:
if value is None:
return default
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index b213a0ce7f..e907e3947d 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -833,6 +833,7 @@ def _validate_wechat_numeric_params(params: dict) -> str | None:
_SYMPHONY_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {
"symphony_enabled": (("enabled",), "bool", False),
+ "symphony_dynamic_graph_enabled": (("evolution", "enabled"), "bool", False),
}
_SYMPHONY_CONFIG_KEYS = tuple(_SYMPHONY_CONFIG_SPECS.keys())
_SKILL_RETRIEVAL_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 5898754900..c2b2b66eb5 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -34,8 +34,12 @@ symphony:
build:
workers: 4
batch_size: 16
+ max_candidates_per_skill_relation: 32
require_consensus: false
- min_edge_confidence: 0.1
+ min_edge_confidence: 0.5
+
+ evolution:
+ enabled: false # true = 消费 Session 轨迹并使用动态 overlay
orchestration:
# fast is the default one-shot path; beam enables bidirectional search.
@@ -43,7 +47,7 @@ symphony:
# Beam-only candidate count retained after each search round.
top_k: 3
max_depth: 4
- min_edge_confidence: 0.3
+ min_edge_confidence: 0.5
skill_retrieval:
enabled: false
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 7cd87ea636..b42836f5d6 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -63,6 +63,22 @@ class _TeamPlanApprovalPayloadError(ValueError):
"""Raised when a structured team.plan approval payload is malformed."""
+def _schedule_symphony_session_feedback(session_id: str, request_id: str) -> None:
+ """Submit session-based Symphony learning without delaying the response."""
+
+ try:
+ from jiuwenswarm.symphony.evolution.session_consumer import (
+ schedule_session_evolution_consume,
+ )
+
+ schedule_session_evolution_consume(session_id, request_id)
+ except Exception as exc: # noqa: BLE001
+ logging.getLogger(__name__).debug(
+ "Failed to schedule Symphony session feedback: %s",
+ exc,
+ )
+
+
def _history_user_content(params: Any, query: Any) -> Any:
"""返回写入历史记录的用户消息内容.
@@ -1946,6 +1962,7 @@ class JiuWenSwarm:
if is_auto_memory_enabled(mode, config) and is_memory_enabled(mode, config):
_trigger_auto_memory_extraction(adapter, request, session_id, is_stream=False)
+ _schedule_symphony_session_feedback(session_id, request.request_id)
return result
async def process_message_stream(
@@ -2630,6 +2647,7 @@ class JiuWenSwarm:
if is_auto_memory_enabled(mode, config) and is_memory_enabled(mode, config):
_trigger_auto_memory_extraction(adapter, request, session_id, is_stream=True)
+ _schedule_symphony_session_feedback(session_id, rid)
yield AgentResponseChunk(
request_id=rid,
channel_id=cid,
diff --git a/jiuwenswarm/symphony/build.py b/jiuwenswarm/symphony/build.py
index e2ff900981..c708c178a4 100644
--- a/jiuwenswarm/symphony/build.py
+++ b/jiuwenswarm/symphony/build.py
@@ -28,6 +28,7 @@ from jiuwenswarm.symphony.fingerprint import (
SkillSchemaExtractor,
write_extraction_result,
)
+from jiuwenswarm.symphony.graph.candidates import CandidateGenerator
from jiuwenswarm.symphony.graph.matcher import (
CachedOntologyMatcher,
OntologyMatcher,
@@ -344,7 +345,14 @@ class SymphonyScoreBuilder:
output_dir / "cache" / "relation_matches.json",
fingerprints=extraction_result.fingerprints,
)
- graph_builder = GraphBuilder(matcher=matcher)
+ graph_builder = GraphBuilder(
+ matcher=matcher,
+ candidate_generator=CandidateGenerator(
+ max_candidates_per_skill_relation=(
+ runtime_config.build.max_candidates_per_skill_relation
+ )
+ ),
+ )
checkpoint.record("graph.start", status="running")
graph_result = await graph_builder.build(
extraction_result.fingerprints,
diff --git a/jiuwenswarm/symphony/config.py b/jiuwenswarm/symphony/config.py
index 09c859f76a..ba4188d1f5 100644
--- a/jiuwenswarm/symphony/config.py
+++ b/jiuwenswarm/symphony/config.py
@@ -21,15 +21,17 @@ DEFAULT_FINGERPRINT_NORMALIZATION_MAX_VOCAB_SIZE = None
DEFAULT_BUILD_WORKERS = 1
DEFAULT_BUILD_MATCHER_BATCH_SIZE = 12
+DEFAULT_BUILD_MAX_CANDIDATES_PER_SKILL_RELATION = 32
DEFAULT_BUILD_REQUIRE_CONSENSUS = False
-DEFAULT_BUILD_MIN_EDGE_CONFIDENCE = 0.7
+DEFAULT_BUILD_MIN_EDGE_CONFIDENCE = 0.5
DEFAULT_SYMPHONY_ENABLED = False
+DEFAULT_EVOLUTION_ENABLED = False
DEFAULT_ORCHESTRATION_MODE = "fast"
DEFAULT_ORCHESTRATION_TOP_K = 3
DEFAULT_ORCHESTRATION_MAX_DEPTH = 4
-DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE = 0.7
+DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE = 0.5
@dataclass(frozen=True)
@@ -71,10 +73,18 @@ class SymphonyFingerprintConfig:
class SymphonyBuildConfig:
workers: int = DEFAULT_BUILD_WORKERS
batch_size: int = DEFAULT_BUILD_MATCHER_BATCH_SIZE
+ max_candidates_per_skill_relation: int = (
+ DEFAULT_BUILD_MAX_CANDIDATES_PER_SKILL_RELATION
+ )
require_consensus: bool = DEFAULT_BUILD_REQUIRE_CONSENSUS
min_edge_confidence: float = DEFAULT_BUILD_MIN_EDGE_CONFIDENCE
+@dataclass(frozen=True)
+class SymphonyEvolutionConfig:
+ enabled: bool = DEFAULT_EVOLUTION_ENABLED
+
+
@dataclass(frozen=True)
class SymphonyOrchestrationConfig:
mode: str = DEFAULT_ORCHESTRATION_MODE
@@ -89,6 +99,7 @@ class SymphonyConfig:
paths: SymphonyPathsConfig
fingerprint: SymphonyFingerprintConfig
build: SymphonyBuildConfig
+ evolution: SymphonyEvolutionConfig
orchestration: SymphonyOrchestrationConfig
@@ -125,6 +136,9 @@ def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:
else {}
)
build = data.get("build") if isinstance(data.get("build"), dict) else {}
+ evolution = (
+ data.get("evolution") if isinstance(data.get("evolution"), dict) else {}
+ )
orchestration = (
data.get("orchestration") if isinstance(data.get("orchestration"), dict) else {}
)
@@ -187,6 +201,10 @@ def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:
build.get("batch_size"),
DEFAULT_BUILD_MATCHER_BATCH_SIZE,
),
+ max_candidates_per_skill_relation=_positive_int(
+ build.get("max_candidates_per_skill_relation"),
+ DEFAULT_BUILD_MAX_CANDIDATES_PER_SKILL_RELATION,
+ ),
require_consensus=_bool(
build.get("require_consensus"),
DEFAULT_BUILD_REQUIRE_CONSENSUS,
@@ -196,6 +214,12 @@ def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:
DEFAULT_BUILD_MIN_EDGE_CONFIDENCE,
),
),
+ evolution=SymphonyEvolutionConfig(
+ enabled=_bool(
+ evolution.get("enabled"),
+ DEFAULT_EVOLUTION_ENABLED,
+ ),
+ ),
orchestration=SymphonyOrchestrationConfig(
mode=_orchestration_mode(
orchestration.get("mode"),
diff --git a/jiuwenswarm/symphony/evolution/__init__.py b/jiuwenswarm/symphony/evolution/__init__.py
new file mode 100644
index 0000000000..9232438b64
--- /dev/null
+++ b/jiuwenswarm/symphony/evolution/__init__.py
@@ -0,0 +1,13 @@
+"""Runtime evolution layer for Symphony skill graphs."""
+
+from jiuwenswarm.symphony.evolution.aggregate import build_overlay_from_events
+from jiuwenswarm.symphony.evolution.service import (
+ evolution_status,
+ load_dynamic_overlay,
+)
+
+__all__ = [
+ "build_overlay_from_events",
+ "evolution_status",
+ "load_dynamic_overlay",
+]
diff --git a/jiuwenswarm/symphony/evolution/aggregate.py b/jiuwenswarm/symphony/evolution/aggregate.py
new file mode 100644
index 0000000000..291ad7d96d
--- /dev/null
+++ b/jiuwenswarm/symphony/evolution/aggregate.py
@@ -0,0 +1,458 @@
+"""Aggregate Symphony runtime events into a dynamic graph overlay."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from datetime import datetime, timezone
+from typing import Any
+
+from jiuwenswarm.symphony.evolution.models import (
+ ATTRIBUTION_ALL_EDGES,
+ ATTRIBUTION_EXPLICIT,
+ ATTRIBUTION_SUCCESS_ONLY,
+ ATTRIBUTION_TERMINAL_EDGE,
+ CAN_FEED,
+ OUTCOME_FAILURE,
+ OUTCOME_NEEDS_INPUT,
+ OUTCOME_NO_PLAN,
+ OUTCOME_SUCCESS,
+ OVERLAY_SCHEMA_VERSION,
+ PLAN_CREATED,
+ PLAN_OUTCOME,
+ edge_key,
+ normalize_edges,
+ normalize_failure_attribution,
+ normalize_outcome,
+ skill_id,
+)
+
+RUNTIME_WEIGHT_POLICY = "skillgraph_linear_v1"
+RUNTIME_WEIGHT_STEP = 0.05
+RUNTIME_WEIGHT_MIN = 0.2
+RUNTIME_WEIGHT_MAX = 2.0
+
+
+def build_overlay_from_events(
+ events: list[dict[str, Any]],
+ *,
+ base_score_version: str | None = None,
+) -> dict[str, Any]:
+ """Build a runtime overlay from append-only evolution events."""
+
+ generated_at = datetime.now(timezone.utc).isoformat()
+ edge_stats: dict[str, dict[str, Any]] = {}
+ node_stats: dict[str, dict[str, Any]] = {}
+ path_stats: dict[str, dict[str, Any]] = {}
+ no_plan_count = 0
+ last_event_at = ""
+ created_plans = _created_plan_contexts(events)
+
+ for event in events:
+ event_type = str(event.get("event_type") or event.get("type") or "")
+ ts = str(event.get("ts") or "")
+ if ts:
+ last_event_at = max(last_event_at, ts)
+ if event_type != PLAN_OUTCOME:
+ continue
+
+ outcome = normalize_outcome(event.get("outcome") or event.get("status"))
+ selected_edges = normalize_edges(
+ event.get("selected_edges") or event.get("can_feed_edges") or []
+ )
+ plan_context = created_plans.get(str(event.get("plan_id") or ""), {})
+ selected_skill_ids = _selected_skill_ids(
+ event,
+ selected_edges,
+ fallback=plan_context.get("selected_skill_ids") or [],
+ )
+ query = str(event.get("query") or plan_context.get("query") or "").strip()
+ if selected_skill_ids and outcome != OUTCOME_NO_PLAN:
+ _record_path_outcome(
+ path_stats,
+ event=event,
+ outcome=outcome,
+ query=query,
+ selected_skill_ids=selected_skill_ids,
+ selected_edges=selected_edges,
+ )
+ if outcome == OUTCOME_NO_PLAN:
+ no_plan_count += 1
+
+ for index, edge in enumerate(selected_edges):
+ edge_outcome = _edge_outcome(
+ event_outcome=outcome,
+ edge=edge,
+ index=index,
+ edge_count=len(selected_edges),
+ event=event,
+ )
+ if edge_outcome is None:
+ continue
+ current_key = edge_key(
+ edge["source_id"],
+ edge["target_id"],
+ edge.get("relation_type") or CAN_FEED,
+ )
+ stats = edge_stats.setdefault(
+ current_key,
+ {
+ "source_id": edge["source_id"],
+ "target_id": edge["target_id"],
+ "relation_type": edge.get("relation_type") or CAN_FEED,
+ "success_count": 0,
+ "failure_count": 0,
+ "needs_input_count": 0,
+ "attempt_count": 0,
+ "representative_queries": [],
+ "last_attribution": "",
+ "last_outcome": "",
+ "last_failure_type": "",
+ "last_updated_at": "",
+ },
+ )
+ _apply_edge_outcome(stats, edge_outcome, event, edge)
+ _apply_node_outcome(node_stats, edge["source_id"], edge_outcome, ts)
+ _apply_node_outcome(node_stats, edge["target_id"], edge_outcome, ts)
+
+ edges = {
+ current_key: _finalize_edge_stats(stats)
+ for current_key, stats in sorted(edge_stats.items())
+ }
+ nodes = {
+ current_key: _finalize_node_stats(stats)
+ for current_key, stats in sorted(node_stats.items())
+ }
+ paths = {
+ current_key: _finalize_path_stats(stats)
+ for current_key, stats in sorted(path_stats.items())
+ }
+ return {
+ "schema_version": OVERLAY_SCHEMA_VERSION,
+ "base_score_version": base_score_version or "",
+ "generated_at": generated_at,
+ "events": {
+ "count": len(events),
+ "last_event_at": last_event_at,
+ },
+ "weight_policy": {
+ "name": RUNTIME_WEIGHT_POLICY,
+ "step": RUNTIME_WEIGHT_STEP,
+ "minimum": RUNTIME_WEIGHT_MIN,
+ "neutral": 1.0,
+ "maximum": RUNTIME_WEIGHT_MAX,
+ "needs_input_effect": "neutral",
+ },
+ "stats": {
+ "edge_count": len(edges),
+ "node_count": len(nodes),
+ "path_count": len(paths),
+ "no_plan_count": no_plan_count,
+ },
+ "edges": edges,
+ "nodes": nodes,
+ "paths": paths,
+ }
+
+
+def _created_plan_contexts(events: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ contexts = {}
+ for event in events:
+ event_type = str(event.get("event_type") or event.get("type") or "")
+ plan_id = str(event.get("plan_id") or "").strip()
+ if event_type != PLAN_CREATED or not plan_id:
+ continue
+ selected_edges = normalize_edges(
+ event.get("selected_edges") or event.get("can_feed_edges") or []
+ )
+ contexts[plan_id] = {
+ "query": str(event.get("query") or "").strip(),
+ "selected_skill_ids": _selected_skill_ids(event, selected_edges),
+ }
+ return contexts
+
+
+def _selected_skill_ids(
+ event: dict[str, Any],
+ selected_edges: list[dict[str, Any]],
+ *,
+ fallback: list[str] | tuple[str, ...] = (),
+) -> list[str]:
+ values = _string_list(
+ event.get("selected_skill_ids")
+ or event.get("selected_skills")
+ or event.get("skill_ids")
+ or []
+ )
+ if not values:
+ values = _string_list(fallback)
+ if not values:
+ for edge in selected_edges:
+ values.extend((edge["source_id"], edge["target_id"]))
+ output = []
+ seen = set()
+ for value in values:
+ current_skill_id = skill_id(value).strip()
+ if current_skill_id and current_skill_id not in seen:
+ seen.add(current_skill_id)
+ output.append(current_skill_id)
+ return output
+
+
+def _record_path_outcome(
+ paths: dict[str, dict[str, Any]],
+ *,
+ event: dict[str, Any],
+ outcome: str,
+ query: str,
+ selected_skill_ids: list[str],
+ selected_edges: list[dict[str, Any]],
+) -> None:
+ canonical_edges = sorted(
+ (
+ {
+ "source_id": edge["source_id"],
+ "target_id": edge["target_id"],
+ "relation_type": edge.get("relation_type") or CAN_FEED,
+ }
+ for edge in selected_edges
+ ),
+ key=lambda edge: (
+ edge["source_id"],
+ edge["target_id"],
+ edge["relation_type"],
+ ),
+ )
+ canonical_skills = sorted(set(selected_skill_ids))
+ signature_payload = {
+ "selected_skill_ids": canonical_skills,
+ "can_feed_edges": canonical_edges,
+ }
+ digest = hashlib.sha256(
+ json.dumps(signature_payload, sort_keys=True, separators=(",", ":")).encode()
+ ).hexdigest()[:24]
+ path_id = f"path:{digest}"
+ stats = paths.setdefault(
+ path_id,
+ {
+ "path_id": path_id,
+ "selected_skill_ids": canonical_skills,
+ "can_feed_edges": canonical_edges,
+ "success_count": 0,
+ "failure_count": 0,
+ "needs_input_count": 0,
+ "attempt_count": 0,
+ "representative_queries": [],
+ "example_plan_ids": [],
+ "last_outcome": "",
+ "last_updated_at": "",
+ },
+ )
+ stats["attempt_count"] += 1
+ if outcome == OUTCOME_SUCCESS:
+ stats["success_count"] += 1
+ elif outcome == OUTCOME_NEEDS_INPUT:
+ stats["needs_input_count"] += 1
+ else:
+ stats["failure_count"] += 1
+ if query and query not in stats["representative_queries"]:
+ if len(stats["representative_queries"]) < 8:
+ stats["representative_queries"].append(query)
+ plan_id = str(event.get("plan_id") or "").strip()
+ if plan_id and plan_id not in stats["example_plan_ids"]:
+ if len(stats["example_plan_ids"]) < 8:
+ stats["example_plan_ids"].append(plan_id)
+ stats["last_outcome"] = outcome
+ ts = str(event.get("ts") or "")
+ if ts:
+ stats["last_updated_at"] = ts
+
+
+def _apply_edge_outcome(
+ stats: dict[str, Any],
+ outcome: str,
+ event: dict[str, Any],
+ edge: dict[str, Any],
+) -> None:
+ stats["attempt_count"] = int(stats.get("attempt_count") or 0) + 1
+ if outcome == OUTCOME_SUCCESS:
+ stats["success_count"] = int(stats.get("success_count") or 0) + 1
+ elif outcome == OUTCOME_NEEDS_INPUT:
+ stats["needs_input_count"] = int(stats.get("needs_input_count") or 0) + 1
+ else:
+ stats["failure_count"] = int(stats.get("failure_count") or 0) + 1
+ stats["last_outcome"] = outcome
+ query = str(event.get("query") or "").strip()
+ representative_queries = stats.setdefault("representative_queries", [])
+ if query and query not in representative_queries and len(representative_queries) < 8:
+ representative_queries.append(query)
+ attribution = str(event.get("failure_attribution") or "").strip()
+ if attribution:
+ stats["last_attribution"] = attribution
+ failure_type = str(
+ edge.get("failure_type")
+ or event.get("failure_type")
+ or event.get("error_type")
+ or ""
+ ).strip()
+ if failure_type:
+ stats["last_failure_type"] = failure_type
+ ts = str(event.get("ts") or "")
+ if ts:
+ stats["last_updated_at"] = ts
+
+
+def _apply_node_outcome(
+ node_stats: dict[str, dict[str, Any]],
+ node_id: str,
+ outcome: str,
+ ts: str,
+) -> None:
+ stats = node_stats.setdefault(
+ node_id,
+ {
+ "skill_id": node_id,
+ "success_count": 0,
+ "failure_count": 0,
+ "needs_input_count": 0,
+ "attempt_count": 0,
+ "last_outcome": "",
+ "last_updated_at": "",
+ },
+ )
+ stats["attempt_count"] = int(stats.get("attempt_count") or 0) + 1
+ if outcome == OUTCOME_SUCCESS:
+ stats["success_count"] = int(stats.get("success_count") or 0) + 1
+ elif outcome == OUTCOME_NEEDS_INPUT:
+ stats["needs_input_count"] = int(stats.get("needs_input_count") or 0) + 1
+ else:
+ stats["failure_count"] = int(stats.get("failure_count") or 0) + 1
+ stats["last_outcome"] = outcome
+ if ts:
+ stats["last_updated_at"] = ts
+
+
+def _finalize_edge_stats(stats: dict[str, Any]) -> dict[str, Any]:
+ success_count = int(stats.get("success_count") or 0)
+ failure_count = int(stats.get("failure_count") or 0)
+ needs_input_count = int(stats.get("needs_input_count") or 0)
+ attempt_count = max(
+ int(stats.get("attempt_count") or 0),
+ success_count + failure_count + needs_input_count,
+ )
+ success_rate = (success_count + 1) / (attempt_count + 2)
+ reliability = (success_count + 1) / (success_count + failure_count + 2)
+ runtime_weight = _runtime_weight(success_count, failure_count, needs_input_count)
+ return {
+ **stats,
+ "attempt_count": attempt_count,
+ "success_rate": round(success_rate, 4),
+ "reliability": round(reliability, 4),
+ "runtime_weight": round(runtime_weight, 4),
+ "confidence_delta": round(runtime_weight - 1.0, 4),
+ }
+
+
+def _finalize_node_stats(stats: dict[str, Any]) -> dict[str, Any]:
+ success_count = int(stats.get("success_count") or 0)
+ failure_count = int(stats.get("failure_count") or 0)
+ needs_input_count = int(stats.get("needs_input_count") or 0)
+ attempt_count = max(
+ int(stats.get("attempt_count") or 0),
+ success_count + failure_count + needs_input_count,
+ )
+ success_rate = (success_count + 1) / (attempt_count + 2)
+ return {
+ **stats,
+ "attempt_count": attempt_count,
+ "success_rate": round(success_rate, 4),
+ }
+
+
+def _finalize_path_stats(stats: dict[str, Any]) -> dict[str, Any]:
+ success_count = int(stats.get("success_count") or 0)
+ failure_count = int(stats.get("failure_count") or 0)
+ needs_input_count = int(stats.get("needs_input_count") or 0)
+ attempt_count = max(
+ int(stats.get("attempt_count") or 0),
+ success_count + failure_count + needs_input_count,
+ )
+ return {
+ **stats,
+ "attempt_count": attempt_count,
+ "success_rate": round((success_count + 1) / (attempt_count + 2), 4),
+ "reliability": round(
+ (success_count + 1) / (success_count + failure_count + 2),
+ 4,
+ ),
+ }
+
+
+def _runtime_weight(
+ success_count: int,
+ failure_count: int,
+ needs_input_count: int,
+) -> float:
+ """Return a bounded additive weight aligned with SkillGraph reinforcement.
+
+ SkillGraph reinforces a successful path with a fixed additive step. Symphony
+ applies the same public step size symmetrically to explicitly attributed
+ failures. Missing user input is recorded, but is not evidence that an edge is
+ invalid and therefore does not change its runtime weight.
+ """
+
+ del needs_input_count
+ evidence = max(0, success_count) - max(0, failure_count)
+ weight = 1.0 + RUNTIME_WEIGHT_STEP * evidence
+ return max(RUNTIME_WEIGHT_MIN, min(RUNTIME_WEIGHT_MAX, weight))
+
+
+def _edge_outcome(
+ *,
+ event_outcome: str,
+ edge: dict[str, Any],
+ index: int,
+ edge_count: int,
+ event: dict[str, Any],
+) -> str | None:
+ explicit_outcome = edge.get("outcome") or edge.get("status")
+ if explicit_outcome:
+ return normalize_outcome(explicit_outcome)
+ if event_outcome == OUTCOME_SUCCESS:
+ return OUTCOME_SUCCESS
+ if event_outcome == OUTCOME_NO_PLAN:
+ return None
+ if event_outcome == OUTCOME_NEEDS_INPUT:
+ attribution = normalize_failure_attribution(
+ event.get("needs_input_attribution") or event.get("failure_attribution")
+ )
+ if attribution == ATTRIBUTION_ALL_EDGES:
+ return OUTCOME_NEEDS_INPUT
+ if attribution == ATTRIBUTION_SUCCESS_ONLY:
+ return OUTCOME_SUCCESS
+ if attribution == ATTRIBUTION_EXPLICIT:
+ return OUTCOME_NEEDS_INPUT if _edge_marked_failed(edge) else OUTCOME_SUCCESS
+ return OUTCOME_NEEDS_INPUT if index == edge_count - 1 else OUTCOME_SUCCESS
+ attribution = normalize_failure_attribution(event.get("failure_attribution"))
+ if attribution == ATTRIBUTION_ALL_EDGES:
+ return OUTCOME_FAILURE
+ if attribution == ATTRIBUTION_SUCCESS_ONLY:
+ return OUTCOME_SUCCESS
+ if attribution == ATTRIBUTION_EXPLICIT:
+ return OUTCOME_FAILURE if _edge_marked_failed(edge) else OUTCOME_SUCCESS
+ if attribution == ATTRIBUTION_TERMINAL_EDGE:
+ return OUTCOME_FAILURE if index == edge_count - 1 else OUTCOME_SUCCESS
+ return OUTCOME_FAILURE
+
+
+def _edge_marked_failed(edge: dict[str, Any]) -> bool:
+ value = edge.get("failed")
+ if isinstance(value, bool):
+ return value
+ return str(value or "").strip().lower() in {"1", "true", "yes", "failed", "failure"}
+
+
+def _string_list(value: Any) -> list[str]:
+ if not isinstance(value, (list, tuple, set)):
+ return []
+ return [str(item).strip() for item in value if str(item).strip()]
diff --git a/jiuwenswarm/symphony/evolution/models.py b/jiuwenswarm/symphony/evolution/models.py
new file mode 100644
index 0000000000..ea19529e9b
--- /dev/null
+++ b/jiuwenswarm/symphony/evolution/models.py
@@ -0,0 +1,116 @@
+"""Shared helpers for Symphony evolution events and overlay keys."""
+
+from __future__ import annotations
+
+from typing import Any
+
+OVERLAY_SCHEMA_VERSION = "symphony.dynamic_overlay.v3"
+EVENT_SCHEMA_VERSION = "symphony.evolution_event.v2"
+
+PLAN_CREATED = "plan.created"
+PLAN_OUTCOME = "plan.outcome"
+
+OUTCOME_SUCCESS = "success"
+OUTCOME_FAILURE = "failure"
+OUTCOME_NO_PLAN = "no_plan"
+OUTCOME_NEEDS_INPUT = "needs_input"
+
+CAN_FEED = "can_feed"
+
+ATTRIBUTION_ALL_EDGES = "all_edges"
+ATTRIBUTION_TERMINAL_EDGE = "terminal_edge"
+ATTRIBUTION_EXPLICIT = "explicit"
+ATTRIBUTION_SUCCESS_ONLY = "success_only"
+
+ALLOWED_FAILURE_ATTRIBUTIONS = {
+ ATTRIBUTION_ALL_EDGES,
+ ATTRIBUTION_TERMINAL_EDGE,
+ ATTRIBUTION_EXPLICIT,
+ ATTRIBUTION_SUCCESS_ONLY,
+}
+
+
+def edge_key(source: Any, target: Any, relation_type: str = CAN_FEED) -> str:
+ """Return a stable key for a runtime edge overlay entry."""
+
+ return f"{skill_id(source)}->{skill_id(target)}:{relation_type or CAN_FEED}"
+
+
+def skill_id(node_id: Any) -> str:
+ text = str(node_id or "")
+ return text.removeprefix("skill:")
+
+
+def normalize_edge(item: Any) -> dict[str, Any] | None:
+ """Normalize any edge-like payload to source_id/target_id/relation_type."""
+
+ if not isinstance(item, dict):
+ return None
+ source = skill_id(item.get("source_id") or item.get("source")).strip()
+ target = skill_id(item.get("target_id") or item.get("target")).strip()
+ if not source or not target:
+ return None
+ relation_type = str(
+ item.get("relation_type") or item.get("type") or CAN_FEED
+ ).strip() or CAN_FEED
+ return {
+ "source_id": source,
+ "target_id": target,
+ "relation_type": relation_type,
+ "confidence": item.get("confidence"),
+ "outcome": item.get("outcome") or item.get("status"),
+ "failure_type": item.get("failure_type") or item.get("error_type"),
+ "failed": item.get("failed"),
+ "weight": item.get("weight"),
+ }
+
+
+def normalize_edges(values: Any) -> list[dict[str, Any]]:
+ """Normalize and deduplicate a list of edge-like payloads."""
+
+ if not isinstance(values, list):
+ return []
+ output: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for item in values:
+ normalized = normalize_edge(item)
+ if normalized is None:
+ continue
+ key = edge_key(
+ normalized["source_id"],
+ normalized["target_id"],
+ normalized["relation_type"],
+ )
+ if key in seen:
+ continue
+ seen.add(key)
+ output.append(normalized)
+ return output
+
+
+def normalize_outcome(value: Any) -> str:
+ """Normalize runtime outcome labels to the overlay vocabulary."""
+
+ outcome = str(value or "").strip().lower()
+ if outcome in {OUTCOME_SUCCESS, OUTCOME_FAILURE, OUTCOME_NO_PLAN, OUTCOME_NEEDS_INPUT}:
+ return outcome
+ if outcome in {"failed", "error", "exception", "invalid"}:
+ return OUTCOME_FAILURE
+ if outcome in {"ready", "ok", "done", "passed"}:
+ return OUTCOME_SUCCESS
+ return OUTCOME_FAILURE
+
+
+def normalize_failure_attribution(value: Any) -> str:
+ """Normalize failure-attribution strategy labels."""
+
+ text = str(value or "").strip().lower()
+ if text in ALLOWED_FAILURE_ATTRIBUTIONS:
+ return text
+ if text in {"terminal", "last_edge", "last"}:
+ return ATTRIBUTION_TERMINAL_EDGE
+ if text in {"all", "plan", "plan_level"}:
+ return ATTRIBUTION_ALL_EDGES
+ if text in {"edge", "per_edge"}:
+ return ATTRIBUTION_EXPLICIT
+ return ATTRIBUTION_TERMINAL_EDGE
diff --git a/jiuwenswarm/symphony/evolution/service.py b/jiuwenswarm/symphony/evolution/service.py
new file mode 100644
index 0000000000..6b69b306df
--- /dev/null
+++ b/jiuwenswarm/symphony/evolution/service.py
@@ -0,0 +1,259 @@
+"""Service helpers for Symphony dynamic graph evolution."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+from uuid import uuid4
+
+from jiuwenswarm.symphony.evolution.aggregate import build_overlay_from_events
+from jiuwenswarm.symphony.evolution.models import (
+ EVENT_SCHEMA_VERSION,
+ OUTCOME_NEEDS_INPUT,
+ OUTCOME_FAILURE,
+ PLAN_OUTCOME,
+ edge_key,
+ normalize_edges,
+ normalize_failure_attribution,
+ normalize_outcome,
+ skill_id,
+)
+from jiuwenswarm.symphony.evolution.store import (
+ append_event,
+ evolution_store_transaction,
+ events_path,
+ overlay_file_mtime,
+ overlay_path,
+ read_events,
+ read_overlay,
+ write_overlay,
+)
+
+
+def load_dynamic_overlay(score_dir: str | Path) -> dict[str, Any] | None:
+ """Load the current dynamic overlay if it exists."""
+
+ return read_overlay(score_dir)
+
+
+def rebuild_dynamic_overlay(
+ score_dir: str | Path,
+ *,
+ base_score_version: str | None = None,
+) -> dict[str, Any]:
+ """Rebuild and persist the dynamic overlay from event logs."""
+
+ with evolution_store_transaction():
+ events = read_events(score_dir)
+ overlay = build_overlay_from_events(
+ events,
+ base_score_version=base_score_version,
+ )
+ write_overlay(score_dir, overlay)
+ return overlay
+
+
+def evolution_status(score_dir: str | Path) -> dict[str, Any]:
+ """Return a compact runtime-evolution status payload."""
+
+ events = read_events(score_dir)
+ overlay = read_overlay(score_dir)
+ overlay_mtime = overlay_file_mtime(score_dir)
+ stats = overlay.get("stats") if isinstance(overlay, dict) else {}
+ payload = {
+ "success": True,
+ "score_dir": str(score_dir),
+ "event_log": str(events_path(score_dir)),
+ "overlay_path": str(overlay_path(score_dir)),
+ "event_count": len(events),
+ "last_event_at": _last_event_ts(events),
+ "overlay_exists": overlay is not None,
+ "overlay_mtime": overlay_mtime,
+ "overlay_generated_at": overlay.get("generated_at") if isinstance(overlay, dict) else "",
+ "overlay_stats": stats if isinstance(stats, dict) else {},
+ "weight_policy": (
+ dict(overlay.get("weight_policy") or {}) if isinstance(overlay, dict) else {}
+ ),
+ "top_edges": _top_overlay_edges(overlay),
+ }
+ try:
+ from jiuwenswarm.symphony.evolution.session_consumer import (
+ session_feedback_status,
+ )
+
+ payload["session_feedback"] = session_feedback_status(score_dir)
+ except Exception: # noqa: BLE001
+ payload["session_feedback"] = {
+ "source": "session_history",
+ "available": False,
+ }
+ return payload
+
+
+def record_plan_outcome(
+ score_dir: str | Path,
+ *,
+ plan_id: str,
+ outcome: str,
+ query: str = "",
+ selected_skill_ids: list[str] | None = None,
+ selected_edges: list[dict[str, Any]] | None = None,
+ failed_edges: list[dict[str, Any]] | None = None,
+ missing_inputs: list[dict[str, Any]] | None = None,
+ failure_attribution: str = "",
+ failure_type: str = "",
+ detail: str = "",
+ source: str = "",
+ evidence_id: str = "",
+ session_id: str = "",
+ request_id: str = "",
+ evidence: dict[str, Any] | None = None,
+ rebuild_overlay: bool = True,
+) -> dict[str, Any]:
+ """Append a plan outcome event and optionally refresh the overlay."""
+
+ normalized_outcome = normalize_outcome(outcome)
+ normalized_edges = _annotate_failed_edges(
+ normalize_edges(selected_edges or []),
+ failed_edges=failed_edges or [],
+ )
+ attribution = _default_failure_attribution(
+ normalized_outcome,
+ normalized_edges,
+ failure_attribution,
+ )
+ event = _base_event(PLAN_OUTCOME, plan_id=plan_id, query=query)
+ event.update(
+ {
+ "outcome": normalized_outcome,
+ "failure_type": str(failure_type or "").strip(),
+ "failure_attribution": attribution,
+ "detail": str(detail or "").strip()[:1000],
+ "selected_skill_ids": _clean_skill_ids(selected_skill_ids or []),
+ "selected_edges": normalized_edges,
+ "missing_inputs": [
+ item for item in (missing_inputs or []) if isinstance(item, dict)
+ ],
+ }
+ )
+ clean_source = str(source or "").strip()
+ clean_evidence_id = str(evidence_id or "").strip()
+ if clean_source:
+ event["source"] = clean_source
+ if clean_evidence_id:
+ event["evidence_id"] = clean_evidence_id
+ if session_id:
+ event["session_id"] = str(session_id).strip()
+ if request_id:
+ event["request_id"] = str(request_id).strip()
+ if isinstance(evidence, dict) and evidence:
+ event["evidence"] = dict(evidence)
+
+ with evolution_store_transaction():
+ if clean_evidence_id:
+ existing = next(
+ (
+ item
+ for item in read_events(score_dir)
+ if str(item.get("evidence_id") or "") == clean_evidence_id
+ ),
+ None,
+ )
+ if existing is not None:
+ return {**existing, "deduplicated": True}
+ append_event(score_dir, event)
+ if rebuild_overlay:
+ rebuild_dynamic_overlay(score_dir)
+ return event
+
+
+def _base_event(event_type: str, *, plan_id: str, query: str) -> dict[str, Any]:
+ return {
+ "schema_version": EVENT_SCHEMA_VERSION,
+ "event_id": str(uuid4()),
+ "event_type": event_type,
+ "ts": datetime.now(timezone.utc).isoformat(),
+ "plan_id": plan_id,
+ "query": str(query or "").strip(),
+ }
+
+
+def _last_event_ts(events: list[dict[str, Any]]) -> str:
+ return max((str(event.get("ts") or "") for event in events), default="")
+
+
+def _default_failure_attribution(
+ outcome: str,
+ selected_edges: list[dict[str, Any]],
+ requested: str,
+) -> str:
+ if requested:
+ return normalize_failure_attribution(requested)
+ if outcome in {OUTCOME_FAILURE, OUTCOME_NEEDS_INPUT} and len(selected_edges) > 1:
+ return "terminal_edge"
+ if outcome in {OUTCOME_FAILURE, OUTCOME_NEEDS_INPUT}:
+ return "all_edges"
+ return ""
+
+
+def _annotate_failed_edges(
+ selected_edges: list[dict[str, Any]],
+ *,
+ failed_edges: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ failed_keys = set()
+ for edge in normalize_edges(failed_edges):
+ failed_keys.add(
+ edge_key(
+ edge.get("source_id") or edge.get("source"),
+ edge.get("target_id") or edge.get("target"),
+ edge.get("relation_type") or edge.get("type") or "can_feed",
+ )
+ )
+ if not failed_keys:
+ return selected_edges
+ output = []
+ for edge in selected_edges:
+ item = dict(edge)
+ current_key = edge_key(
+ item.get("source_id"),
+ item.get("target_id"),
+ item.get("relation_type") or "can_feed",
+ )
+ if current_key in failed_keys:
+ item["failed"] = True
+ output.append(item)
+ return output
+
+
+def _clean_skill_ids(values: list[Any]) -> list[str]:
+ output = []
+ seen = set()
+ for value in values:
+ current_skill_id = skill_id(value).strip()
+ if current_skill_id and current_skill_id not in seen:
+ seen.add(current_skill_id)
+ output.append(current_skill_id)
+ return output
+
+
+def _top_overlay_edges(overlay: dict[str, Any] | None) -> list[dict[str, Any]]:
+ if not isinstance(overlay, dict):
+ return []
+ edges = overlay.get("edges")
+ if not isinstance(edges, dict):
+ return []
+ items = [
+ {"edge_key": key, **value}
+ for key, value in edges.items()
+ if isinstance(value, dict)
+ ]
+ return sorted(
+ items,
+ key=lambda item: (
+ -float(item.get("runtime_weight") or 1.0),
+ -int(item.get("attempt_count") or 0),
+ str(item.get("edge_key") or ""),
+ ),
+ )[:10]
diff --git a/jiuwenswarm/symphony/evolution/session_consumer.py b/jiuwenswarm/symphony/evolution/session_consumer.py
new file mode 100644
index 0000000000..c6647fa51b
--- /dev/null
+++ b/jiuwenswarm/symphony/evolution/session_consumer.py
@@ -0,0 +1,910 @@
+"""Learn Symphony runtime outcomes from durable session history."""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+import threading
+import time
+from concurrent.futures import Future, ThreadPoolExecutor
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from jiuwenswarm.server.runtime.session.session_history import (
+ get_read_history_path,
+ load_history_records,
+)
+from jiuwenswarm.symphony.config import load_symphony_config
+from jiuwenswarm.symphony.evolution.models import normalize_edges, skill_id
+from jiuwenswarm.symphony.evolution.service import record_plan_outcome
+from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dir
+
+LOGGER = logging.getLogger(__name__)
+
+SESSION_FEEDBACK_SCHEMA_VERSION = "symphony.session_feedback.v1"
+SESSION_FEEDBACK_STATE_FILE = "session_feedback_state.json"
+SESSION_FEEDBACK_SOURCE = "session_history"
+SESSION_INFERENCE_VERSION = "session_history_v1"
+_MAX_TRACKED_SESSIONS = 500
+_MAX_SKIPPED_TURNS = 3
+_HISTORY_READY_RETRIES = 20
+_HISTORY_READY_INTERVAL_SECONDS = 0.05
+_SYMPHONY_TOOL_NAMES = {
+ "symphony_compose_score",
+ "symphony_read_score",
+ "symphony_refresh_score",
+}
+_CONTINUATION_RE = re.compile(
+ r"(?:"
+ r"确认.{0,12}(?:执行|继续|开始)|"
+ r"按(?:照)?(?:上面|上述|这个|该)?(?:的)?"
+ r"(?:路径|计划|方案|技能)?.{0,12}(?:执行|继续|做)|"
+ r"继续(?:执行|完成)|开始执行|直接执行|就按.{0,16}(?:执行|做)|"
+ r"用(?:上面|上述|这个|该)?.{0,16}技能.{0,8}执行|"
+ r"\b(?:confirm|proceed|continue|execute|run|go ahead|follow the plan)\b"
+ r")",
+ re.IGNORECASE,
+)
+_SKILL_FRONTMATTER_NAME_RE = re.compile(
+ r"---[ \t]*(?:\r?\n|\\n)[ \t]*name[ \t]*:[ \t]*[\"']?"
+ r"([A-Za-z0-9_.-]+)",
+ re.IGNORECASE,
+)
+
+_STATE_LOCK = threading.RLock()
+_SCHEDULE_LOCK = threading.Lock()
+_SCHEDULED: set[tuple[str, str, str]] = set()
+_EXECUTOR = ThreadPoolExecutor(
+ max_workers=1,
+ thread_name_prefix="symphony-session-feedback",
+)
+
+
+def session_feedback_state_path(score_dir: str | Path) -> Path:
+ return Path(score_dir) / "evolution" / SESSION_FEEDBACK_STATE_FILE
+
+
+def schedule_session_evolution_consume(
+ session_id: str,
+ request_id: str,
+) -> bool:
+ """Schedule non-blocking feedback consumption after history is durable."""
+
+ clean_session_id = str(session_id or "").strip()
+ clean_request_id = str(request_id or "").strip()
+ if not clean_session_id or not clean_request_id:
+ return False
+ try:
+ config = load_symphony_config()
+ if not config.enabled or not config.evolution.enabled:
+ return False
+ score_dir = resolve_score_artifact_dir(config.paths.score_dir)
+ except Exception as exc: # noqa: BLE001
+ LOGGER.debug("Symphony session feedback is unavailable: %s", exc)
+ return False
+
+ schedule_key = (str(score_dir), clean_session_id, clean_request_id)
+ with _SCHEDULE_LOCK:
+ if schedule_key in _SCHEDULED:
+ return False
+ _SCHEDULED.add(schedule_key)
+
+ future = _EXECUTOR.submit(
+ _consume_after_history_ready,
+ clean_session_id,
+ clean_request_id,
+ score_dir,
+ )
+ future.add_done_callback(lambda current: _on_consume_done(schedule_key, current))
+ return True
+
+
+def _consume_after_history_ready(
+ session_id: str,
+ request_id: str,
+ score_dir: Path,
+) -> dict[str, Any]:
+ history_path = get_read_history_path(session_id)
+ history_limit = _wait_for_request_history(session_id, request_id, history_path)
+ return consume_session_history(
+ session_id,
+ completed_request_id=request_id,
+ score_dir=score_dir,
+ history_limit_bytes=history_limit,
+ )
+
+
+def _wait_for_request_history(
+ session_id: str,
+ request_id: str,
+ history_path: Path,
+) -> int | None:
+ """Wait off the request thread until this request's terminal record is durable."""
+
+ for _attempt in range(_HISTORY_READY_RETRIES):
+ records = load_history_records(session_id)
+ if any(
+ str(record.get("request_id") or "") == request_id
+ and record.get("event_type") == "chat.final"
+ for record in reversed(records)
+ ):
+ return _file_size(history_path)
+ time.sleep(_HISTORY_READY_INTERVAL_SECONDS)
+ return _file_size(history_path)
+
+
+def consume_session_history(
+ session_id: str,
+ *,
+ completed_request_id: str = "",
+ score_dir: str | Path | None = None,
+ history_limit_bytes: int | None = None,
+) -> dict[str, Any]:
+ """Incrementally consume one session and emit at most one outcome per plan."""
+
+ clean_session_id = str(session_id or "").strip()
+ if not clean_session_id:
+ return {"success": False, "detail": "session_id is required"}
+ if score_dir is None:
+ config = load_symphony_config()
+ if not config.enabled or not config.evolution.enabled:
+ return {
+ "success": True,
+ "enabled": False,
+ "recorded": False,
+ "source": SESSION_FEEDBACK_SOURCE,
+ }
+ score_dir = resolve_score_artifact_dir(config.paths.score_dir)
+ resolved_score_dir = Path(score_dir).resolve()
+ history_path = get_read_history_path(clean_session_id)
+
+ with _STATE_LOCK:
+ state = _read_state(resolved_score_dir)
+ sessions = state.setdefault("sessions", {})
+ session_state = dict(sessions.get(clean_session_id) or {})
+ try:
+ records, cursor = _read_new_records(
+ history_path,
+ session_state,
+ completed_request_id=completed_request_id,
+ history_limit_bytes=history_limit_bytes,
+ )
+ results = _consume_records(
+ records,
+ session_id=clean_session_id,
+ session_state=session_state,
+ score_dir=resolved_score_dir,
+ )
+ session_state.update(cursor)
+ session_state["updated_at"] = _utc_now()
+ sessions[clean_session_id] = session_state
+ _update_state_stats(state, records, results)
+ state["last_error"] = ""
+ state["updated_at"] = _utc_now()
+ _prune_sessions(sessions)
+ _write_state(resolved_score_dir, state)
+ except Exception as exc: # noqa: BLE001
+ state["last_error"] = str(exc)[:1000]
+ state["updated_at"] = _utc_now()
+ _write_state(resolved_score_dir, state)
+ LOGGER.exception(
+ "Failed to consume Symphony session feedback: session_id=%s request_id=%s",
+ clean_session_id,
+ completed_request_id,
+ )
+ return {
+ "success": False,
+ "source": SESSION_FEEDBACK_SOURCE,
+ "session_id": clean_session_id,
+ "request_id": completed_request_id,
+ "detail": str(exc),
+ }
+
+ return {
+ "success": True,
+ "source": SESSION_FEEDBACK_SOURCE,
+ "session_id": clean_session_id,
+ "request_id": completed_request_id,
+ "records_consumed": len(records),
+ "outcomes": results,
+ }
+
+
+def session_feedback_status(score_dir: str | Path) -> dict[str, Any]:
+ """Return frontend-safe observability for the session feedback worker."""
+
+ resolved_score_dir = Path(score_dir).resolve()
+ with _STATE_LOCK:
+ state = _read_state(resolved_score_dir)
+ sessions = state.get("sessions") if isinstance(state.get("sessions"), dict) else {}
+ stats = state.get("stats") if isinstance(state.get("stats"), dict) else {}
+ with _SCHEDULE_LOCK:
+ pending_jobs = sum(
+ 1 for item in _SCHEDULED if item[0] == str(resolved_score_dir)
+ )
+ return {
+ "available": True,
+ "source": SESSION_FEEDBACK_SOURCE,
+ "mode": "incremental_async",
+ "state_path": str(session_feedback_state_path(resolved_score_dir)),
+ "tracked_session_count": len(sessions),
+ "pending_plan_count": sum(
+ 1
+ for item in sessions.values()
+ if isinstance(item, dict) and isinstance(item.get("pending_plan"), dict)
+ ),
+ "pending_job_count": pending_jobs,
+ "records_consumed": int(stats.get("records_consumed") or 0),
+ "plans_observed": int(stats.get("plans_observed") or 0),
+ "outcomes_recorded": int(stats.get("outcomes_recorded") or 0),
+ "duplicates_ignored": int(stats.get("duplicates_ignored") or 0),
+ "last_result": dict(state.get("last_result") or {}),
+ "last_error": str(state.get("last_error") or ""),
+ "updated_at": str(state.get("updated_at") or ""),
+ }
+
+
+def _consume_records(
+ records: list[dict[str, Any]],
+ *,
+ session_id: str,
+ session_state: dict[str, Any],
+ score_dir: Path,
+) -> list[dict[str, Any]]:
+ pending = (
+ dict(session_state.get("pending_plan") or {})
+ if isinstance(session_state.get("pending_plan"), dict)
+ else {}
+ )
+ results: list[dict[str, Any]] = []
+ for request_id, request_records in _group_by_request(records):
+ markers = _plan_markers(request_records, score_dir=score_dir)
+
+ if markers:
+ # A new plan supersedes an older plan that the user never executed.
+ pending = {}
+ elif pending:
+ result = _consume_execution_turn(
+ pending,
+ request_records,
+ session_id=session_id,
+ request_id=request_id,
+ score_dir=score_dir,
+ same_turn=False,
+ )
+ if result is not None:
+ results.append(result)
+ pending = {}
+ elif _has_user_record(request_records):
+ skipped = int(pending.get("skipped_turns") or 0) + 1
+ if skipped >= _MAX_SKIPPED_TURNS:
+ pending = {}
+ else:
+ pending["skipped_turns"] = skipped
+
+ for marker_index, marker in markers:
+ pending = marker
+ trailing_records = request_records[marker_index + 1:]
+ result = _consume_execution_turn(
+ pending,
+ trailing_records,
+ session_id=session_id,
+ request_id=request_id,
+ score_dir=score_dir,
+ same_turn=True,
+ )
+ if result is not None:
+ results.append(result)
+ pending = {}
+
+ if pending:
+ session_state["pending_plan"] = pending
+ else:
+ session_state.pop("pending_plan", None)
+ return results
+
+
+def _consume_execution_turn(
+ pending: dict[str, Any],
+ records: list[dict[str, Any]],
+ *,
+ session_id: str,
+ request_id: str,
+ score_dir: Path,
+ same_turn: bool,
+) -> dict[str, Any] | None:
+ correlation = _execution_correlation(pending, records, same_turn=same_turn)
+ if not correlation:
+ return None
+ classification = _classify_outcome(records)
+ if classification is None:
+ return None
+ outcome, failure_type, detail = classification
+ observed_skills = _observed_skill_ids(
+ records,
+ pending.get("selected_skill_ids") or [],
+ include_attempted=outcome != "success",
+ )
+ observed_tools = _observed_tool_names(records)
+ planned_skill_ids = list(pending.get("selected_skill_ids") or [])
+ if outcome == "success" and not _all_planned_skills_observed(
+ planned_skill_ids,
+ observed_skills,
+ ):
+ return None
+ planned_edges = normalize_edges(pending.get("selected_edges") or [])
+ selected_edges = _observed_edges(planned_edges, observed_skills)
+ failed_edges = selected_edges[-1:] if outcome == "failure" else []
+ evidence_id = f"session:{session_id}:{pending['plan_id']}:{request_id}"
+ event = record_plan_outcome(
+ score_dir,
+ plan_id=str(pending["plan_id"]),
+ query=str(pending.get("query") or ""),
+ outcome=outcome,
+ selected_skill_ids=observed_skills,
+ selected_edges=selected_edges,
+ failed_edges=failed_edges,
+ failure_attribution="terminal_edge" if outcome == "failure" else "",
+ failure_type=failure_type,
+ detail=detail,
+ source=SESSION_FEEDBACK_SOURCE,
+ evidence_id=evidence_id,
+ session_id=session_id,
+ request_id=request_id,
+ evidence={
+ "inference_version": SESSION_INFERENCE_VERSION,
+ "correlation": correlation,
+ "planned_skill_ids": planned_skill_ids,
+ "planned_edges": planned_edges,
+ "observed_skill_ids": observed_skills,
+ "observed_tool_names": observed_tools,
+ "same_turn": same_turn,
+ },
+ )
+ return {
+ "plan_id": str(pending["plan_id"]),
+ "session_id": session_id,
+ "request_id": request_id,
+ "outcome": outcome,
+ "correlation": correlation,
+ "event_id": str(event.get("event_id") or ""),
+ "evidence_id": evidence_id,
+ "deduplicated": bool(event.get("deduplicated")),
+ "processed_at": _utc_now(),
+ }
+
+
+def _plan_markers(
+ records: list[dict[str, Any]],
+ *,
+ score_dir: Path,
+) -> list[tuple[int, dict[str, Any]]]:
+ output: list[tuple[int, dict[str, Any]]] = []
+ for index, record in enumerate(records):
+ if record.get("event_type") != "chat.tool_result":
+ continue
+ if str(record.get("tool_name") or "") != "symphony_compose_score":
+ continue
+ raw_output = record.get("raw_output")
+ if not isinstance(raw_output, dict):
+ continue
+ if raw_output.get("dynamic_graph_enabled") is False:
+ continue
+ plan = raw_output.get("plan")
+ if not isinstance(plan, dict) or str(plan.get("status") or "").lower() != "ready":
+ continue
+ plan_id = str(raw_output.get("plan_id") or "").strip()
+ if not plan_id or not _score_dir_matches(raw_output.get("score_dir"), score_dir):
+ continue
+ selected_skill_ids = []
+ for step in plan.get("steps") or []:
+ if not isinstance(step, dict):
+ continue
+ current = skill_id(step.get("skill_id") or step.get("id")).strip()
+ if current and current not in selected_skill_ids:
+ selected_skill_ids.append(current)
+ output.append(
+ (
+ index,
+ {
+ "plan_id": plan_id,
+ "query": str(raw_output.get("query") or _user_text(records)).strip(),
+ "planning_request_id": str(record.get("request_id") or ""),
+ "selected_skill_ids": selected_skill_ids,
+ "selected_edges": normalize_edges(plan.get("can_feed_edges") or []),
+ "planned_at": record.get("timestamp"),
+ "skipped_turns": 0,
+ },
+ )
+ )
+ return output
+
+
+def _execution_correlation(
+ pending: dict[str, Any],
+ records: list[dict[str, Any]],
+ *,
+ same_turn: bool,
+) -> str:
+ if not records:
+ return ""
+ if _observed_skill_ids(records, pending.get("selected_skill_ids") or []):
+ return "planned_skill_observed"
+ observed_tools = _observed_tool_names(records)
+ has_execution_tool = any(
+ name and name not in _SYMPHONY_TOOL_NAMES
+ for name in observed_tools
+ )
+ if same_turn:
+ return "same_turn_tool_execution" if has_execution_tool else ""
+ if not _CONTINUATION_RE.search(_user_text(records)):
+ return ""
+ if has_execution_tool:
+ return "explicit_continuation_with_tool_execution"
+ if any(record.get("event_type") == "chat.error" for record in records):
+ return "explicit_continuation_with_error"
+ if any(
+ record.get("event_type") == "chat.ask_user_question"
+ for record in records
+ ):
+ return "explicit_continuation_with_needs_input"
+ return ""
+
+
+def _classify_outcome(
+ records: list[dict[str, Any]],
+) -> tuple[str, str, str] | None:
+ for record in records:
+ if record.get("event_type") == "chat.error":
+ error = str(record.get("error") or record.get("content") or "execution failed")
+ return "failure", str(record.get("error_type") or "agent_error"), error[:1000]
+ for record in records:
+ if record.get("event_type") != "chat.tool_result":
+ continue
+ if _tool_result_failed(record):
+ tool_name = str(record.get("tool_name") or "tool")
+ detail = str(record.get("error") or record.get("result") or "tool execution failed")
+ return "failure", f"{tool_name}_failed", detail[:1000]
+ if any(record.get("event_type") == "chat.ask_user_question" for record in records):
+ return "needs_input", "missing_input", "execution paused for user input"
+ final_text = "\n".join(
+ str(record.get("content") or "").strip()
+ for record in records
+ if record.get("event_type") == "chat.final" and str(record.get("content") or "").strip()
+ )
+ if final_text:
+ return "success", "", final_text[-1000:]
+ return None
+
+
+def _tool_result_failed(record: dict[str, Any]) -> bool:
+ if record.get("success") is False or record.get("is_error") is True:
+ return True
+ status = str(record.get("status") or "").strip().lower()
+ if status in {"error", "failed", "failure"}:
+ return True
+ result = record.get("raw_output")
+ if result is None:
+ result = record.get("result")
+ return _value_reports_failure(result)
+
+
+def _value_reports_failure(value: Any) -> bool:
+ if isinstance(value, dict):
+ if value.get("success") is False or value.get("is_error") is True:
+ return True
+ if str(value.get("status") or "").lower() in {"error", "failed", "failure"}:
+ return True
+ return any(
+ _value_reports_failure(value.get(key))
+ for key in ("data", "raw_output", "rawOutput", "result")
+ if key in value
+ )
+ if isinstance(value, list):
+ return any(_value_reports_failure(item) for item in value)
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return False
+ try:
+ parsed = json.loads(text)
+ except (TypeError, ValueError):
+ parsed = None
+ if isinstance(parsed, (dict, list)) and _value_reports_failure(parsed):
+ return True
+ return bool(
+ re.search(r"\bsuccess\s*[:=]\s*False\b", text, re.IGNORECASE)
+ or text.startswith("[ERROR]")
+ )
+ return False
+
+
+def _observed_skill_ids(
+ records: list[dict[str, Any]],
+ selected_skill_ids: list[str],
+ *,
+ include_attempted: bool = True,
+) -> list[str]:
+ selected = {
+ skill_id(item).strip().lower(): skill_id(item).strip()
+ for item in selected_skill_ids
+ }
+ observed: list[str] = []
+ attempted: list[str] = []
+ pending_calls: list[tuple[str, str]] = []
+ for record in records:
+ event_type = record.get("event_type")
+ if event_type == "chat.tool_call":
+ tool_call = record.get("tool_call")
+ if not isinstance(tool_call, dict):
+ continue
+ name = str(tool_call.get("name") or "").strip()
+ if name != "skill_tool":
+ continue
+ arguments = _tool_arguments(tool_call.get("arguments"))
+ candidate = str(arguments.get("skill_name") or "").strip()
+ if not candidate:
+ continue
+ call_id = str(tool_call.get("tool_call_id") or "").strip()
+ pending_calls.append((call_id, candidate))
+ attempted.append(candidate)
+ continue
+ if event_type != "chat.tool_result":
+ continue
+ if str(record.get("tool_name") or "").strip() != "skill_tool":
+ continue
+ call_id = str(record.get("tool_call_id") or "").strip()
+ invoked_name = _take_pending_skill_call(pending_calls, call_id)
+ canonical_name = _skill_name_from_result(record)
+ matched = _match_selected_skill(canonical_name, selected)
+ if not matched:
+ matched = _match_selected_skill(invoked_name, selected)
+ if matched and matched not in observed:
+ observed.append(matched)
+ if include_attempted:
+ for candidate in attempted:
+ matched = _match_selected_skill(candidate, selected)
+ if matched and matched not in observed:
+ observed.append(matched)
+ return observed
+
+
+def _take_pending_skill_call(
+ pending_calls: list[tuple[str, str]],
+ call_id: str,
+) -> str:
+ if call_id:
+ for index, (pending_id, candidate) in enumerate(pending_calls):
+ if pending_id == call_id:
+ pending_calls.pop(index)
+ return candidate
+ if pending_calls:
+ return pending_calls.pop(0)[1]
+ return ""
+
+
+def _skill_name_from_result(record: dict[str, Any]) -> str:
+ for value in (record.get("raw_output"), record.get("result")):
+ skill_content = _find_skill_content(value)
+ if skill_content:
+ match = _SKILL_FRONTMATTER_NAME_RE.search(skill_content)
+ if match:
+ return match.group(1).strip()
+ if isinstance(value, str):
+ match = _SKILL_FRONTMATTER_NAME_RE.search(value)
+ if match:
+ return match.group(1).strip()
+ return ""
+
+
+def _find_skill_content(value: Any) -> str:
+ if isinstance(value, dict):
+ direct = value.get("skill_content")
+ if isinstance(direct, str):
+ return direct
+ for key in ("data", "raw_output", "rawOutput", "result"):
+ nested = _find_skill_content(value.get(key))
+ if nested:
+ return nested
+ elif isinstance(value, list):
+ for item in value:
+ nested = _find_skill_content(item)
+ if nested:
+ return nested
+ return ""
+
+
+def _match_selected_skill(
+ candidate: str,
+ selected: dict[str, str],
+) -> str:
+ normalized = skill_id(candidate).strip().lower()
+ if not normalized:
+ return ""
+ exact = selected.get(normalized)
+ if exact:
+ return exact
+ for selected_key, selected_value in selected.items():
+ package_pattern = rf"{re.escape(selected_key)}-v?\d+(?:\.\d+)*"
+ if re.fullmatch(package_pattern, normalized):
+ return selected_value
+ return ""
+
+
+def _observed_tool_names(records: list[dict[str, Any]]) -> list[str]:
+ output: list[str] = []
+ for record in records:
+ name = ""
+ if record.get("event_type") == "chat.tool_call":
+ tool_call = record.get("tool_call")
+ if isinstance(tool_call, dict):
+ name = str(tool_call.get("name") or "").strip()
+ elif record.get("event_type") == "chat.tool_result":
+ name = str(record.get("tool_name") or "").strip()
+ if name and name not in output:
+ output.append(name)
+ return output
+
+
+def _observed_edges(
+ planned_edges: list[dict[str, Any]],
+ observed_skill_ids: list[str],
+) -> list[dict[str, Any]]:
+ observed = {skill_id(item).strip() for item in observed_skill_ids}
+ if len(observed) < 2:
+ return []
+ output = []
+ for edge in planned_edges:
+ source_id = skill_id(edge.get("source_id")).strip()
+ target_id = skill_id(edge.get("target_id")).strip()
+ if source_id in observed and target_id in observed:
+ output.append(edge)
+ return output
+
+
+def _all_planned_skills_observed(
+ planned_skill_ids: list[str],
+ observed_skill_ids: list[str],
+) -> bool:
+ planned = {skill_id(item).strip() for item in planned_skill_ids if skill_id(item).strip()}
+ observed = {skill_id(item).strip() for item in observed_skill_ids}
+ return bool(planned) and planned.issubset(observed)
+
+
+def _tool_arguments(value: Any) -> dict[str, Any]:
+ if isinstance(value, dict):
+ return value
+ if isinstance(value, str):
+ try:
+ parsed = json.loads(value)
+ except (TypeError, ValueError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+ return {}
+
+
+def _group_by_request(
+ records: list[dict[str, Any]],
+) -> list[tuple[str, list[dict[str, Any]]]]:
+ groups: list[tuple[str, list[dict[str, Any]]]] = []
+ for index, record in enumerate(records):
+ request_id = str(record.get("request_id") or f"__record_{index}")
+ if groups and groups[-1][0] == request_id:
+ groups[-1][1].append(record)
+ else:
+ groups.append((request_id, [record]))
+ return groups
+
+
+def _has_user_record(records: list[dict[str, Any]]) -> bool:
+ return any(record.get("role") == "user" for record in records)
+
+
+def _user_text(records: list[dict[str, Any]]) -> str:
+ return "\n".join(
+ str(record.get("content") or "")
+ for record in records
+ if record.get("role") == "user"
+ ).strip()
+
+
+def _read_new_records(
+ history_path: Path,
+ session_state: dict[str, Any],
+ *,
+ completed_request_id: str,
+ history_limit_bytes: int | None,
+) -> tuple[list[dict[str, Any]], dict[str, Any]]:
+ if history_path.suffix.lower() == ".jsonl":
+ return _read_new_jsonl_records(
+ history_path,
+ session_state,
+ history_limit_bytes=history_limit_bytes,
+ )
+
+ records = load_history_records(history_path.parent.name)
+ processed_count = max(0, int(session_state.get("processed_record_count") or 0))
+ if processed_count > len(records):
+ processed_count = 0
+ limit = len(records)
+ if completed_request_id:
+ matching = [
+ index
+ for index, record in enumerate(records)
+ if str(record.get("request_id") or "") == completed_request_id
+ ]
+ if matching:
+ limit = matching[-1] + 1
+ return records[processed_count:limit], {
+ "history_path": str(history_path),
+ "processed_record_count": limit,
+ "history_offset": 0,
+ "history_identity": "legacy_json",
+ }
+
+
+def _read_new_jsonl_records(
+ history_path: Path,
+ session_state: dict[str, Any],
+ *,
+ history_limit_bytes: int | None,
+) -> tuple[list[dict[str, Any]], dict[str, Any]]:
+ try:
+ stat = history_path.stat()
+ except OSError:
+ return [], {
+ "history_path": str(history_path),
+ "processed_record_count": 0,
+ "history_offset": 0,
+ "history_identity": "",
+ }
+ identity = f"{stat.st_dev}:{stat.st_ino}"
+ previous_identity = str(session_state.get("history_identity") or "")
+ offset = max(0, int(session_state.get("history_offset") or 0))
+ limit = stat.st_size
+ if history_limit_bytes is not None:
+ limit = min(limit, max(0, int(history_limit_bytes)))
+ if previous_identity != identity or offset > limit:
+ offset = 0
+ payload = b""
+ with history_path.open("rb") as handle:
+ handle.seek(offset)
+ payload = handle.read(limit - offset)
+ records: list[dict[str, Any]] = []
+ for raw_line in payload.decode("utf-8", errors="replace").splitlines():
+ if not raw_line.strip():
+ continue
+ try:
+ item = json.loads(raw_line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(item, dict):
+ records.append(item)
+ return records, {
+ "history_path": str(history_path),
+ "processed_record_count": int(session_state.get("processed_record_count") or 0)
+ + len(records),
+ "history_offset": limit,
+ "history_identity": identity,
+ }
+
+
+def _read_state(score_dir: Path) -> dict[str, Any]:
+ path = session_feedback_state_path(score_dir)
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ payload = {}
+ if not isinstance(payload, dict):
+ payload = {}
+ payload.setdefault("schema_version", SESSION_FEEDBACK_SCHEMA_VERSION)
+ payload.setdefault("source", SESSION_FEEDBACK_SOURCE)
+ payload.setdefault("sessions", {})
+ payload.setdefault("stats", {})
+ return payload
+
+
+def _write_state(score_dir: Path, state: dict[str, Any]) -> None:
+ path = session_feedback_state_path(score_dir)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp_path = path.with_suffix(".json.tmp")
+ tmp_path.write_text(
+ json.dumps(state, ensure_ascii=False, indent=2, default=str) + "\n",
+ encoding="utf-8",
+ )
+ tmp_path.replace(path)
+
+
+def _update_state_stats(
+ state: dict[str, Any],
+ records: list[dict[str, Any]],
+ results: list[dict[str, Any]],
+) -> None:
+ stats = state.setdefault("stats", {})
+ stats["records_consumed"] = int(stats.get("records_consumed") or 0) + len(records)
+ plans_observed = 0
+ for record in records:
+ if _is_symphony_plan_result(record):
+ plans_observed += 1
+ stats["plans_observed"] = (
+ int(stats.get("plans_observed") or 0) + plans_observed
+ )
+ new_results = [item for item in results if not item.get("deduplicated")]
+ stats["outcomes_recorded"] = int(stats.get("outcomes_recorded") or 0) + len(new_results)
+ stats["duplicates_ignored"] = int(stats.get("duplicates_ignored") or 0) + sum(
+ 1 for item in results if item.get("deduplicated")
+ )
+ if results:
+ state["last_result"] = results[-1]
+
+
+def _is_symphony_plan_result(record: dict[str, Any]) -> bool:
+ if record.get("event_type") != "chat.tool_result":
+ return False
+ if record.get("tool_name") != "symphony_compose_score":
+ return False
+ raw_output = record.get("raw_output")
+ if not isinstance(raw_output, dict):
+ return False
+ return bool(raw_output.get("plan_id"))
+
+
+def _prune_sessions(sessions: dict[str, Any]) -> None:
+ if len(sessions) <= _MAX_TRACKED_SESSIONS:
+ return
+ ordered = sorted(
+ sessions.items(),
+ key=lambda item: str(
+ item[1].get("updated_at") if isinstance(item[1], dict) else ""
+ ),
+ reverse=True,
+ )
+ sessions.clear()
+ sessions.update(ordered[:_MAX_TRACKED_SESSIONS])
+
+
+def _score_dir_matches(value: Any, score_dir: Path) -> bool:
+ text = str(value or "").strip()
+ if not text:
+ return True
+ try:
+ return Path(text).resolve() == score_dir.resolve()
+ except OSError:
+ return False
+
+
+def _file_size(path: Path) -> int | None:
+ try:
+ return path.stat().st_size
+ except OSError:
+ return None
+
+
+def _on_consume_done(
+ schedule_key: tuple[str, str, str],
+ future: Future[dict[str, Any]],
+) -> None:
+ with _SCHEDULE_LOCK:
+ _SCHEDULED.discard(schedule_key)
+ try:
+ result = future.result()
+ except Exception: # noqa: BLE001
+ LOGGER.exception(
+ "Symphony session feedback worker crashed: session_id=%s request_id=%s",
+ schedule_key[1],
+ schedule_key[2],
+ )
+ return
+ if result.get("outcomes"):
+ LOGGER.info(
+ "Symphony session feedback recorded: session_id=%s request_id=%s outcomes=%s",
+ schedule_key[1],
+ schedule_key[2],
+ len(result["outcomes"]),
+ )
+
+
+def _utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
diff --git a/jiuwenswarm/symphony/evolution/store.py b/jiuwenswarm/symphony/evolution/store.py
new file mode 100644
index 0000000000..5319a5d391
--- /dev/null
+++ b/jiuwenswarm/symphony/evolution/store.py
@@ -0,0 +1,101 @@
+"""Append-only storage for Symphony evolution events and overlays."""
+
+from __future__ import annotations
+
+import json
+import threading
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Any, Iterator
+
+EVENT_DIR = "evolution"
+EVENTS_FILE = "events.jsonl"
+OVERLAY_FILE = "dynamic_graph_overlay.json"
+_STORE_LOCK = threading.RLock()
+
+
+@contextmanager
+def evolution_store_transaction() -> Iterator[None]:
+ """Serialize event append, deduplication, and overlay rebuild in-process."""
+
+ with _STORE_LOCK:
+ yield
+
+
+def evolution_dir(score_dir: str | Path) -> Path:
+ return Path(score_dir) / EVENT_DIR
+
+
+def events_path(score_dir: str | Path) -> Path:
+ return evolution_dir(score_dir) / EVENTS_FILE
+
+
+def overlay_path(score_dir: str | Path) -> Path:
+ return evolution_dir(score_dir) / OVERLAY_FILE
+
+
+def append_event(score_dir: str | Path, event: dict[str, Any]) -> None:
+ with _STORE_LOCK:
+ path = events_path(score_dir)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("a", encoding="utf-8") as handle:
+ handle.write(json.dumps(event, ensure_ascii=False, default=str) + "\n")
+
+
+def read_events(
+ score_dir: str | Path,
+ *,
+ limit: int | None = None,
+) -> list[dict[str, Any]]:
+ with _STORE_LOCK:
+ path = events_path(score_dir)
+ if not path.is_file():
+ return []
+ try:
+ lines = path.read_text(encoding="utf-8").splitlines()
+ except OSError:
+ return []
+ if limit is not None and limit > 0:
+ lines = lines[-limit:]
+ events: list[dict[str, Any]] = []
+ for line in lines:
+ try:
+ payload = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(payload, dict):
+ events.append(payload)
+ return events
+
+
+def write_overlay(score_dir: str | Path, overlay: dict[str, Any]) -> None:
+ with _STORE_LOCK:
+ path = overlay_path(score_dir)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp_path = path.with_suffix(".json.tmp")
+ tmp_path.write_text(
+ json.dumps(overlay, ensure_ascii=False, indent=2, default=str) + "\n",
+ encoding="utf-8",
+ )
+ tmp_path.replace(path)
+
+
+def read_overlay(score_dir: str | Path) -> dict[str, Any] | None:
+ with _STORE_LOCK:
+ path = overlay_path(score_dir)
+ if not path.is_file():
+ return None
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+def overlay_file_mtime(score_dir: str | Path) -> float | None:
+ with _STORE_LOCK:
+ path = overlay_path(score_dir)
+ try:
+ return path.stat().st_mtime
+ except OSError:
+ return None
diff --git a/jiuwenswarm/symphony/graph/matcher/cache.py b/jiuwenswarm/symphony/graph/matcher/cache.py
index fdfc07eee0..125b303893 100644
--- a/jiuwenswarm/symphony/graph/matcher/cache.py
+++ b/jiuwenswarm/symphony/graph/matcher/cache.py
@@ -60,8 +60,10 @@ class CachedOntologyMatcher:
resolved_by_index: dict[int, list[LLMMatch]] = {}
diagnostics: list[Any] = []
if misses:
- for chunk in _chunked(misses, _matcher_batch_size(self.matcher)):
- miss_candidates = [candidate for _, candidate in chunk]
+ # Preserve the wrapped matcher's worker-level concurrency while
+ # retaining cache flush boundaries for resumable graph builds.
+ for window in _chunked(misses, _matcher_window_size(self.matcher)):
+ miss_candidates = [candidate for _, candidate in window]
resolved_matches = list(
await self.matcher.match(registry, miss_candidates)
)
@@ -69,7 +71,7 @@ class CachedOntologyMatcher:
miss_candidates,
resolved_matches,
)
- for index, candidate in chunk:
+ for index, candidate in window:
matches = resolved_by_candidate.get(candidate.key, [])
resolved_by_index[index] = matches
self.cache.store(candidate, matches)
@@ -233,6 +235,17 @@ def _matcher_batch_size(matcher: Any) -> int:
return 1
+def _matcher_max_workers(matcher: Any) -> int:
+ try:
+ return max(1, int(getattr(matcher, "max_workers", 0) or 0))
+ except (TypeError, ValueError):
+ return 1
+
+
+def _matcher_window_size(matcher: Any) -> int:
+ return _matcher_batch_size(matcher) * _matcher_max_workers(matcher)
+
+
def _chunked(values: list[Any], size: int) -> list[list[Any]]:
return [
values[index: index + size]
diff --git a/jiuwenswarm/symphony/graph/models.py b/jiuwenswarm/symphony/graph/models.py
index 09a0e7b415..154acdf93b 100644
--- a/jiuwenswarm/symphony/graph/models.py
+++ b/jiuwenswarm/symphony/graph/models.py
@@ -224,6 +224,7 @@ class BuildManifest:
"enable_backward_search": True,
}
)
+ candidate_generation: Dict[str, Any] = field(default_factory=dict)
llm: Dict[str, Any] = field(default_factory=dict)
created_at: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat()
@@ -235,6 +236,7 @@ class BuildManifest:
"artifacts": self.artifacts,
"thresholds": self.thresholds,
"planning_defaults": self.planning_defaults,
+ "candidate_generation": self.candidate_generation,
"llm": self.llm,
"created_at": self.created_at,
}
diff --git a/jiuwenswarm/symphony/graph/pipeline.py b/jiuwenswarm/symphony/graph/pipeline.py
index 6fade026a9..685a7a32ec 100644
--- a/jiuwenswarm/symphony/graph/pipeline.py
+++ b/jiuwenswarm/symphony/graph/pipeline.py
@@ -101,6 +101,9 @@ class GraphBuilder:
llm_metadata["token_usage"] = get_llm_token_usage_summary()
manifest = BuildManifest(
thresholds=_matcher_thresholds(self.matcher),
+ candidate_generation=_candidate_generator_metadata(
+ self.candidate_generator
+ ),
llm=llm_metadata,
)
@@ -153,3 +156,17 @@ def _matcher_thresholds(matcher: OntologyMatcher) -> dict:
if hasattr(matcher, "thresholds"):
return dict(matcher.thresholds)
return dict(DEFAULT_THRESHOLDS)
+
+
+def _candidate_generator_metadata(candidate_generator: CandidateGenerator) -> dict:
+ return {
+ "max_candidates_per_skill_relation": int(
+ candidate_generator.max_candidates_per_skill_relation
+ ),
+ "max_port_mappings_per_candidate": int(
+ candidate_generator.max_port_mappings_per_candidate
+ ),
+ "max_exact_io_pair_fanout": int(
+ candidate_generator.max_exact_io_pair_fanout
+ ),
+ }
diff --git a/jiuwenswarm/symphony/orchestration/execution_graph.py b/jiuwenswarm/symphony/orchestration/execution_graph.py
index 21e88d06cc..4f40759cf4 100644
--- a/jiuwenswarm/symphony/orchestration/execution_graph.py
+++ b/jiuwenswarm/symphony/orchestration/execution_graph.py
@@ -39,8 +39,13 @@ def build_execution_graph(
decision = planning_result.get("decision")
if isinstance(decision, dict):
diagnostics.append({"source": "decision", **decision})
+ runtime_scoring = planning_result.get("runtime_scoring_summary")
+ if isinstance(runtime_scoring, dict):
+ diagnostics.append({"source": "runtime_scoring", **runtime_scoring})
return {
+ "plan_id": planning_result.get("plan_id"),
+ "dynamic_overlay_used": bool(planning_result.get("dynamic_overlay_used")),
"nodes": [
_project_skill(artifacts.skill_by_id[skill_id])
for skill_id in skill_ids
diff --git a/jiuwenswarm/symphony/orchestration/planning/fast.py b/jiuwenswarm/symphony/orchestration/planning/fast.py
index ccfdcbb55d..2f2fd73595 100644
--- a/jiuwenswarm/symphony/orchestration/planning/fast.py
+++ b/jiuwenswarm/symphony/orchestration/planning/fast.py
@@ -4,9 +4,14 @@ from __future__ import annotations
import heapq
import json
+import re
from collections import defaultdict
from typing import Any, Sequence
+from jiuwenswarm.symphony.evolution.models import (
+ CAN_FEED,
+ edge_key as evolution_edge_key,
+)
from jiuwenswarm.symphony.llm import LLMConfig, create_llm_client, llm_usage_context
from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
from jiuwenswarm.symphony.orchestration.language import (
@@ -44,6 +49,9 @@ Task:
descriptions.
- Do not invent Skills, inputs, or outputs.
- Prefer the shortest path that satisfies the user's intent.
+- When runtime_weight and planner_score are present, use them only as tie-breakers
+ between otherwise relevant relationships. planner_score already combines static and
+ scoped runtime evidence.
- 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".
@@ -78,6 +86,7 @@ class FastOneShotPlanner:
max_depth: int = 4,
candidate_skill_ids: Sequence[str] | None = None,
language: str = "cn",
+ dynamic_overlay: dict[str, Any] | None = None,
) -> None:
self.artifacts = artifacts
self.llm_config = llm_config
@@ -85,6 +94,9 @@ class FastOneShotPlanner:
self.min_edge_confidence = min_edge_confidence
self.max_depth = max(1, int(max_depth))
self.language = language
+ self.dynamic_overlay = (
+ dynamic_overlay if isinstance(dynamic_overlay, dict) else {}
+ )
self.candidate_skill_ids = normalize_known_skill_ids(
candidate_skill_ids,
known_skill_ids=set(artifacts.skill_by_id),
@@ -92,7 +104,7 @@ class FastOneShotPlanner:
async def plan(self, query: str) -> dict[str, Any]:
client = self._client()
- subgraph = self._candidate_subgraph()
+ subgraph = self._candidate_subgraph(query)
prompt_payload = {
"query": query,
"skills": subgraph["skills"],
@@ -119,6 +131,8 @@ class FastOneShotPlanner:
"llm_call_count": 1,
"candidate_skill_count": len(subgraph["skills"]),
"candidate_edge_count": len(subgraph["edges"]),
+ "dynamic_overlay_used": bool(subgraph["runtime_summary"]["applied_edges"]),
+ "runtime_scoring_summary": subgraph["runtime_summary"],
}
try:
selection = json.loads(raw)
@@ -159,13 +173,13 @@ class FastOneShotPlanner:
raise ValueError("fast Symphony planning requires llm_config or llm_client.")
return create_llm_client(self.llm_config)
- def _candidate_subgraph(self) -> dict[str, Any]:
+ def _candidate_subgraph(self, query: str) -> dict[str, Any]:
if self.candidate_skill_ids:
- return self._retrieval_candidate_subgraph()
- return self._default_candidate_subgraph()
+ return self._retrieval_candidate_subgraph(query)
+ return self._default_candidate_subgraph(query)
- def _default_candidate_subgraph(self) -> dict[str, Any]:
- candidate_edges = self._known_edges(self._sorted_eligible_edges())
+ def _default_candidate_subgraph(self, query: str) -> dict[str, Any]:
+ candidate_edges = self._known_edges(self._sorted_eligible_edges(query))
selected = []
selected_set = set()
for edge in candidate_edges:
@@ -177,8 +191,8 @@ class FastOneShotPlanner:
self._append_skill(selected, selected_set, current_skill_id)
return self._subgraph_payload(selected, candidate_edges)
- def _retrieval_candidate_subgraph(self) -> dict[str, Any]:
- sorted_edges = self._known_edges(self._sorted_eligible_edges())
+ def _retrieval_candidate_subgraph(self, query: str) -> dict[str, Any]:
+ sorted_edges = self._known_edges(self._sorted_eligible_edges(query))
edge_by_key = {
(skill_id(edge.get("source")), skill_id(edge.get("target"))): edge
for edge in sorted_edges
@@ -315,7 +329,7 @@ class FastOneShotPlanner:
if next_id in nodes:
continue
edge = edge_by_key[(current_id, next_id)]
- confidence = float(edge.get("confidence") or 0.0)
+ confidence = self._edge_rank_score(edge)
heapq.heappush(
queue,
(
@@ -327,12 +341,181 @@ class FastOneShotPlanner:
)
return []
- def _sorted_eligible_edges(self) -> list[dict[str, Any]]:
- return eligible_can_feed_edges(
- self.artifacts.graph.get("edges", []),
+ def _sorted_eligible_edges(self, query: str) -> list[dict[str, Any]]:
+ graph_edges = self.artifacts.graph.get("edges", [])
+ static_keys = {
+ evolution_edge_key(
+ skill_id(edge.get("source")),
+ skill_id(edge.get("target")),
+ CAN_FEED,
+ )
+ for edge in graph_edges
+ if edge.get("type") == CAN_FEED
+ }
+ eligible_edges = eligible_can_feed_edges(
+ graph_edges,
known_skill_ids=set(self.artifacts.skill_by_id),
min_confidence=self.min_edge_confidence,
)
+ filtered_edges = [
+ self._with_runtime_score(
+ edge,
+ self._overlay_edges().get(
+ evolution_edge_key(
+ skill_id(edge.get("source")),
+ skill_id(edge.get("target")),
+ CAN_FEED,
+ )
+ ),
+ query=query,
+ )
+ for edge in eligible_edges
+ ]
+ filtered_edges.extend(self._runtime_only_edges(query, static_keys=static_keys))
+ return sorted(
+ filtered_edges,
+ key=lambda item: (
+ -self._edge_rank_score(item),
+ str(item.get("source") or ""),
+ str(item.get("target") or ""),
+ ),
+ )
+
+ def _runtime_only_edges(
+ self,
+ query: str,
+ *,
+ static_keys: set[str],
+ ) -> list[dict[str, Any]]:
+ known_skill_ids = set(self.artifacts.skill_by_id)
+ output = []
+ for current_key, stats in self._overlay_edges().items():
+ if current_key in static_keys or not isinstance(stats, dict):
+ continue
+ source_id = str(stats.get("source_id") or "").strip()
+ target_id = str(stats.get("target_id") or "").strip()
+ relation_type = str(stats.get("relation_type") or CAN_FEED)
+ success_count = int(stats.get("success_count") or 0)
+ failure_count = int(stats.get("failure_count") or 0)
+ attempt_count = max(int(stats.get("attempt_count") or 0), success_count)
+ if relation_type != CAN_FEED:
+ continue
+ if source_id not in known_skill_ids or target_id not in known_skill_ids:
+ continue
+ if success_count < 2 or failure_count > 0:
+ continue
+ if not self._runtime_is_query_relevant(stats, query, require_seed=True):
+ continue
+ runtime_confidence = (success_count + 1) / (attempt_count + 2)
+ runtime_weight = self._runtime_weight(stats)
+ output.append(
+ {
+ "type": CAN_FEED,
+ "source": source_id,
+ "target": target_id,
+ "confidence": runtime_confidence,
+ "method": "runtime_observed",
+ "evidence": {
+ "reasons": ["Repeated successful Session executions"],
+ },
+ "runtime_only": True,
+ "runtime_weight": runtime_weight,
+ "effective_score": runtime_confidence * runtime_weight,
+ "runtime_evidence": self._runtime_evidence(stats),
+ }
+ )
+ return output
+
+ def _with_runtime_score(
+ self,
+ edge: dict[str, Any],
+ stats: dict[str, Any] | None,
+ *,
+ query: str,
+ ) -> dict[str, Any]:
+ if not isinstance(stats, dict) or not self._runtime_is_query_relevant(stats, query):
+ return edge
+ runtime_weight = self._runtime_weight(stats)
+ confidence = float(edge.get("confidence") or 0.0)
+ return {
+ **edge,
+ "runtime_weight": runtime_weight,
+ "effective_score": confidence * runtime_weight,
+ "runtime_evidence": self._runtime_evidence(stats),
+ }
+
+ def _runtime_is_query_relevant(
+ self,
+ stats: dict[str, Any],
+ query: str,
+ *,
+ require_seed: bool = False,
+ ) -> bool:
+ endpoints = {
+ str(stats.get("source_id") or "").strip(),
+ str(stats.get("target_id") or "").strip(),
+ }
+ seeds = set(self.candidate_skill_ids or ())
+ touches_seed = bool(seeds & endpoints)
+ representative_queries = [
+ str(value).strip()
+ for value in stats.get("representative_queries") or []
+ if str(value).strip()
+ ]
+ query_matches = any(
+ self._text_overlap(query, example) >= 0.2
+ for example in representative_queries
+ )
+ if require_seed:
+ return (
+ touches_seed and (query_matches or not representative_queries)
+ ) or (not seeds and query_matches)
+ return touches_seed or query_matches
+
+ def _overlay_edges(self) -> dict[str, dict[str, Any]]:
+ edges = self.dynamic_overlay.get("edges")
+ return edges if isinstance(edges, dict) else {}
+
+ @staticmethod
+ def _runtime_weight(stats: dict[str, Any]) -> float:
+ try:
+ value = float(stats.get("runtime_weight") or 1.0)
+ except (TypeError, ValueError):
+ value = 1.0
+ return max(0.2, min(2.0, value))
+
+ @staticmethod
+ def _runtime_evidence(stats: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "success_count": int(stats.get("success_count") or 0),
+ "failure_count": int(stats.get("failure_count") or 0),
+ "needs_input_count": int(stats.get("needs_input_count") or 0),
+ "attempt_count": int(stats.get("attempt_count") or 0),
+ }
+
+ @staticmethod
+ def _edge_rank_score(edge: dict[str, Any]) -> float:
+ return float(edge.get("effective_score") or edge.get("confidence") or 0.0)
+
+ @classmethod
+ def _text_overlap(cls, left: str, right: str) -> float:
+ left_tokens = cls._text_tokens(left)
+ right_tokens = cls._text_tokens(right)
+ if not left_tokens or not right_tokens:
+ return 0.0
+ return len(left_tokens & right_tokens) / min(len(left_tokens), len(right_tokens))
+
+ @staticmethod
+ def _text_tokens(value: str) -> set[str]:
+ normalized = str(value or "").lower()
+ tokens = set(re.findall(r"[a-z0-9][a-z0-9_-]+", normalized))
+ cjk_runs = re.findall(r"[\u3400-\u9fff]+", normalized)
+ for run in cjk_runs:
+ if len(run) == 1:
+ tokens.add(run)
+ else:
+ tokens.update(run[index:index + 2] for index in range(len(run) - 1))
+ return tokens
def _subgraph_payload(
self,
@@ -346,6 +529,7 @@ class FastOneShotPlanner:
if current_skill_id in skill_by_id
]
edge_payloads = [self._edge_payload(edge) for edge in candidate_edges]
+ runtime_edges = [edge for edge in candidate_edges if edge.get("runtime_evidence")]
return {
"skills": skill_payloads,
"edges": edge_payloads,
@@ -354,6 +538,13 @@ class FastOneShotPlanner:
(skill_id(edge.get("source")), skill_id(edge.get("target"))): edge
for edge in candidate_edges
},
+ "runtime_summary": {
+ "available": bool(self._overlay_edges()),
+ "applied_edges": len(runtime_edges),
+ "runtime_only_edges": sum(
+ 1 for edge in runtime_edges if edge.get("runtime_only")
+ ),
+ },
}
def _known_edges(self, edges: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
@@ -397,7 +588,7 @@ class FastOneShotPlanner:
@classmethod
def _path_rank(cls, path: Sequence[dict[str, Any]]) -> tuple[Any, ...]:
- confidences = [float(edge.get("confidence") or 0.0) for edge in path]
+ confidences = [cls._edge_rank_score(edge) for edge in path]
edge_ids = tuple(
(skill_id(edge.get("source")), skill_id(edge.get("target")))
for edge in path
@@ -614,10 +805,19 @@ class FastOneShotPlanner:
@staticmethod
def _edge_payload(edge: dict[str, Any]) -> dict[str, Any]:
- return {
+ payload = {
"source_id": skill_id(edge.get("source")),
"target_id": skill_id(edge.get("target")),
}
+ if isinstance(edge.get("runtime_evidence"), dict):
+ payload.update(
+ {
+ "runtime_weight": edge.get("runtime_weight"),
+ "planner_score": edge.get("effective_score"),
+ "runtime_only": bool(edge.get("runtime_only")),
+ }
+ )
+ return payload
@staticmethod
def _inferred_edge_plan_item(
diff --git a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py b/jiuwenswarm/symphony/orchestration/planning/plan_builder.py
index 38b0946975..8ca57d3f1d 100644
--- a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py
+++ b/jiuwenswarm/symphony/orchestration/planning/plan_builder.py
@@ -131,7 +131,7 @@ def plan_stages(
def edge_plan_item(edge: dict[str, Any]) -> dict[str, Any]:
evidence = edge.get("evidence") or {}
supporting_fields = evidence.get("supporting_fields") or {}
- return {
+ item = {
"source_id": skill_id(edge.get("source")),
"target_id": skill_id(edge.get("target")),
"confidence": edge.get("confidence"),
@@ -141,3 +141,13 @@ def edge_plan_item(edge: dict[str, Any]) -> dict[str, Any]:
"target_inputs": supporting_fields.get("target_inputs", [])[:3],
"reasons": evidence.get("reasons", [])[:3],
}
+ runtime_evidence = edge.get("runtime_evidence")
+ if isinstance(runtime_evidence, dict):
+ item.update(
+ {
+ "effective_score": edge.get("effective_score"),
+ "runtime_weight": edge.get("runtime_weight"),
+ "runtime_evidence": runtime_evidence,
+ }
+ )
+ return item
diff --git a/jiuwenswarm/symphony/orchestration/service.py b/jiuwenswarm/symphony/orchestration/service.py
index bb31fe280f..0e2fcbc2e9 100644
--- a/jiuwenswarm/symphony/orchestration/service.py
+++ b/jiuwenswarm/symphony/orchestration/service.py
@@ -4,8 +4,13 @@ from __future__ import annotations
from pathlib import Path
from typing import Any, Sequence
+from uuid import uuid4
-from jiuwenswarm.symphony.config import SymphonyOrchestrationConfig
+from jiuwenswarm.symphony.config import (
+ DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE,
+ SymphonyOrchestrationConfig,
+)
+from jiuwenswarm.symphony.evolution.service import load_dynamic_overlay
from jiuwenswarm.symphony.llm import LLMConfig
from jiuwenswarm.symphony.orchestration.artifacts import (
filter_disabled_score_artifacts,
@@ -24,9 +29,10 @@ async def plan_from_score(
*,
top_k: int = 3,
max_depth: int = 4,
- min_edge_confidence: float = 0.7,
+ min_edge_confidence: float = DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE,
llm_client: Any | None = None,
orchestration_config: SymphonyOrchestrationConfig | None = None,
+ dynamic_graph_enabled: bool = False,
candidate_skill_ids: Sequence[str] | None = None,
disabled_skill_names: Sequence[str] | None = None,
progress_callback: Any | None = None,
@@ -47,6 +53,10 @@ async def plan_from_score(
if mode not in {"fast", "beam"}:
raise ValueError(f"Unsupported orchestration mode: {mode}")
+ plan_id = str(uuid4())
+ dynamic_overlay = (
+ load_dynamic_overlay(artifacts.score_dir) if dynamic_graph_enabled else {}
+ )
selected_candidate_skill_ids, skill_retrieval = _input_candidate_summary(
candidate_skill_ids,
skills=artifacts.skills,
@@ -72,8 +82,12 @@ async def plan_from_score(
max_depth=max(1, int(max_depth)),
candidate_skill_ids=selected_candidate_skill_ids,
language=language,
+ dynamic_overlay=dynamic_overlay,
).plan(query)
result["language"] = language
+ result["plan_id"] = plan_id
+ result["score_dir"] = str(artifacts.score_dir)
+ result["dynamic_graph_enabled"] = bool(dynamic_graph_enabled)
result["skill_retrieval"] = skill_retrieval
result["execution_graph"] = build_execution_graph(result, artifacts)
return result
diff --git a/tests/unit_tests/symphony/test_config.py b/tests/unit_tests/symphony/test_config.py
index 9842c5d018..488ce1e3e8 100644
--- a/tests/unit_tests/symphony/test_config.py
+++ b/tests/unit_tests/symphony/test_config.py
@@ -19,8 +19,11 @@ def test_symphony_config_defaults_paths(monkeypatch, tmp_path):
assert cfg.fingerprint.scan.max_depth is None
assert cfg.fingerprint.extraction.body_limit is None
assert cfg.build.batch_size == 12
- assert cfg.build.min_edge_confidence == 0.7
+ assert cfg.build.max_candidates_per_skill_relation == 32
+ assert cfg.build.min_edge_confidence == 0.5
assert cfg.orchestration.mode == "fast"
+ assert cfg.orchestration.min_edge_confidence == 0.5
+ assert cfg.evolution.enabled is False
assert cfg.enabled is False
@@ -56,6 +59,7 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
"build": {
"workers": "3",
"batch_size": "0",
+ "max_candidates_per_skill_relation": "19",
"require_consensus": "false",
"min_edge_confidence": 2,
},
@@ -64,6 +68,7 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
"max_depth": "7",
"min_edge_confidence": -1,
},
+ "evolution": {"enabled": "false"},
"enabled": "true",
}
)
@@ -80,11 +85,13 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
assert cfg.fingerprint.normalization.max_vocab_size == 9
assert cfg.build.workers == 3
assert cfg.build.batch_size == 1
+ assert cfg.build.max_candidates_per_skill_relation == 19
assert cfg.build.require_consensus is False
assert cfg.build.min_edge_confidence == 1.0
assert cfg.orchestration.mode == "fast"
assert cfg.orchestration.max_depth == 7
assert cfg.orchestration.min_edge_confidence == 0.0
+ assert cfg.evolution.enabled is False
assert cfg.enabled is True
diff --git a/tests/unit_tests/symphony/test_evolution.py b/tests/unit_tests/symphony/test_evolution.py
new file mode 100644
index 0000000000..3a7953b465
--- /dev/null
+++ b/tests/unit_tests/symphony/test_evolution.py
@@ -0,0 +1,196 @@
+from jiuwenswarm.symphony.evolution.aggregate import (
+ RUNTIME_WEIGHT_POLICY,
+ _runtime_weight,
+ build_overlay_from_events,
+)
+from jiuwenswarm.symphony.evolution.models import PLAN_CREATED, PLAN_OUTCOME
+from jiuwenswarm.symphony.evolution.service import (
+ evolution_status,
+ record_plan_outcome,
+)
+
+
+def test_evolution_overlay_reinforces_success_and_downranks_failures():
+ events = [
+ {
+ "event_type": PLAN_OUTCOME,
+ "ts": "2026-06-20T01:00:00+00:00",
+ "plan_id": "p1",
+ "query": "compose",
+ "outcome": "success",
+ "selected_edges": [{"source_id": "skill-a", "target_id": "skill-b"}],
+ },
+ {
+ "event_type": PLAN_OUTCOME,
+ "ts": "2026-06-20T01:01:00+00:00",
+ "plan_id": "p2",
+ "query": "compose",
+ "outcome": "success",
+ "selected_edges": [{"source_id": "skill-a", "target_id": "skill-b"}],
+ },
+ {
+ "event_type": PLAN_OUTCOME,
+ "ts": "2026-06-20T01:02:00+00:00",
+ "plan_id": "p3",
+ "query": "compose",
+ "outcome": "failure",
+ "failure_type": "schema_mismatch",
+ "selected_edges": [{"source_id": "skill-b", "target_id": "skill-c"}],
+ },
+ {
+ "event_type": PLAN_OUTCOME,
+ "ts": "2026-06-20T01:03:00+00:00",
+ "plan_id": "p4",
+ "query": "compose",
+ "outcome": "failure",
+ "failure_type": "schema_mismatch",
+ "selected_edges": [{"source_id": "skill-b", "target_id": "skill-c"}],
+ },
+ {
+ "event_type": PLAN_OUTCOME,
+ "ts": "2026-06-20T01:04:00+00:00",
+ "plan_id": "p5",
+ "query": "compose",
+ "outcome": "failure",
+ "failure_type": "schema_mismatch",
+ "selected_edges": [{"source_id": "skill-b", "target_id": "skill-c"}],
+ },
+ ]
+
+ overlay = build_overlay_from_events(events)
+
+ reinforced = overlay["edges"]["skill-a->skill-b:can_feed"]
+ downranked = overlay["edges"]["skill-b->skill-c:can_feed"]
+ assert reinforced["runtime_weight"] > 1
+ assert reinforced["representative_queries"] == ["compose"]
+ assert downranked["runtime_weight"] < 1
+ assert overlay["weight_policy"]["name"] == RUNTIME_WEIGHT_POLICY
+
+
+def test_runtime_weight_uses_symmetric_linear_evidence_and_neutral_missing_input():
+ assert _runtime_weight(1, 0, 0) == 1.05
+ assert _runtime_weight(0, 1, 0) == 0.95
+ assert _runtime_weight(3, 1, 0) == 1.1
+ assert _runtime_weight(0, 0, 20) == 1.0
+ assert _runtime_weight(100, 0, 0) == 2.0
+ assert _runtime_weight(0, 100, 0) == 0.2
+
+
+def test_evolution_overlay_aggregates_query_conditioned_complete_paths():
+ events = [
+ {
+ "event_type": PLAN_OUTCOME,
+ "plan_id": "path-1",
+ "query": "extract the invoice and verify it",
+ "outcome": "success",
+ "selected_skill_ids": ["ocr", "invoice-verifier"],
+ "selected_edges": [
+ {"source_id": "ocr", "target_id": "invoice-verifier"}
+ ],
+ },
+ {
+ "event_type": PLAN_OUTCOME,
+ "plan_id": "path-2",
+ "query": "read this receipt then validate it",
+ "outcome": "success",
+ "selected_skill_ids": ["ocr", "invoice-verifier"],
+ "selected_edges": [
+ {"source_id": "ocr", "target_id": "invoice-verifier"}
+ ],
+ },
+ ]
+
+ overlay = build_overlay_from_events(events)
+
+ assert overlay["schema_version"] == "symphony.dynamic_overlay.v3"
+ assert overlay["stats"]["path_count"] == 1
+ path = next(iter(overlay["paths"].values()))
+ assert path["selected_skill_ids"] == ["invoice-verifier", "ocr"]
+ assert path["success_count"] == 2
+ assert path["failure_count"] == 0
+ assert path["representative_queries"] == [
+ "extract the invoice and verify it",
+ "read this receipt then validate it",
+ ]
+
+
+def test_evolution_path_uses_plan_created_context_for_single_skill_success():
+ events = [
+ {
+ "event_type": PLAN_CREATED,
+ "plan_id": "single-1",
+ "query": "summarize this article",
+ "selected_skill_ids": ["summarizer"],
+ "selected_edges": [],
+ },
+ {
+ "event_type": PLAN_OUTCOME,
+ "plan_id": "single-1",
+ "query": "",
+ "outcome": "success",
+ "selected_edges": [],
+ },
+ ]
+
+ overlay = build_overlay_from_events(events)
+
+ path = next(iter(overlay["paths"].values()))
+ assert path["selected_skill_ids"] == ["summarizer"]
+ assert path["representative_queries"] == ["summarize this article"]
+ assert path["can_feed_edges"] == []
+
+
+def test_evolution_status_reads_recorded_outcomes_and_overlay(tmp_path):
+ record_plan_outcome(
+ tmp_path,
+ plan_id="p1",
+ query="invoice verification",
+ outcome="no_plan",
+ selected_edges=[],
+ )
+ record_plan_outcome(
+ tmp_path,
+ plan_id="p2",
+ query="invoice verification",
+ outcome="no_plan",
+ selected_edges=[],
+ )
+
+ status = evolution_status(tmp_path)
+
+ assert status["success"] is True
+ assert status["event_count"] == 2
+ assert status["overlay_exists"] is True
+ assert status["overlay_stats"]["no_plan_count"] == 2
+ assert status["weight_policy"]["name"] == RUNTIME_WEIGHT_POLICY
+
+
+def test_evolution_failure_attribution_defaults_to_terminal_edge():
+ events = []
+ for index in range(3):
+ events.append(
+ {
+ "event_type": PLAN_OUTCOME,
+ "ts": f"2026-06-20T02:0{index}:00+00:00",
+ "plan_id": f"p{index}",
+ "query": "forward email",
+ "outcome": "failure",
+ "failure_type": "workbench_outcome_miss",
+ "failure_attribution": "terminal_edge",
+ "selected_edges": [
+ {"source_id": "email.search", "target_id": "directory.lookup"},
+ {"source_id": "directory.lookup", "target_id": "email.send"},
+ ],
+ }
+ )
+
+ overlay = build_overlay_from_events(events)
+
+ upstream = overlay["edges"]["email.search->directory.lookup:can_feed"]
+ terminal = overlay["edges"]["directory.lookup->email.send:can_feed"]
+ assert upstream["success_count"] == 3
+ assert upstream["failure_count"] == 0
+ assert upstream["runtime_weight"] > 1
+ assert terminal["success_count"] == 0
+ assert terminal["failure_count"] == 3
+ assert terminal["runtime_weight"] < 1
diff --git a/tests/unit_tests/symphony/test_extension.py b/tests/unit_tests/symphony/test_extension.py
index f5946b8a0d..f4bf88e94f 100644
--- a/tests/unit_tests/symphony/test_extension.py
+++ b/tests/unit_tests/symphony/test_extension.py
@@ -51,11 +51,13 @@ def test_extension_registers_rpc_handlers():
SymphonyExtension().register(registry)
- assert SYMPHONY_SCORE_STATUS in registry.handlers
- assert SYMPHONY_BUILD_SCORE in registry.handlers
- assert SYMPHONY_PAUSE_BUILD in registry.handlers
- assert SYMPHONY_GRAPH in registry.handlers
- assert SYMPHONY_PLAN in registry.handlers
+ assert set(registry.handlers) == {
+ SYMPHONY_SCORE_STATUS,
+ SYMPHONY_BUILD_SCORE,
+ SYMPHONY_PAUSE_BUILD,
+ SYMPHONY_GRAPH,
+ SYMPHONY_PLAN,
+ }
def test_symphony_skill_metadata():
@@ -182,6 +184,7 @@ def test_plan_uses_llm_plan_from_score(monkeypatch, tmp_path):
assert seen["llm_config"] is llm_config
assert "orchestration_config" in seen["kwargs"]
assert seen["kwargs"]["language"] == "cn"
+ assert seen["kwargs"]["dynamic_graph_enabled"] is False
def test_plan_ignores_internal_language_parameter(monkeypatch, tmp_path):
@@ -267,6 +270,47 @@ def test_plan_resolves_language_from_runtime_config(monkeypatch, tmp_path):
assert seen["language"] == "en"
+def test_plan_passes_enabled_dynamic_graph_switch(monkeypatch, tmp_path):
+ configured_score_dir = tmp_path / "configured"
+ seen = {}
+ monkeypatch.setattr(
+ "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
+ lambda: symphony_config_from_dict(
+ {
+ "paths": {"score_dir": str(configured_score_dir)},
+ "evolution": {"enabled": True},
+ }
+ ),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.extensions.symphony.extension.load_score_artifacts",
+ lambda score_dir: {"score_dir": str(score_dir)},
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",
+ lambda: object(),
+ )
+
+ async def fake_plan_from_score(score_dir, query, received_llm_config, **kwargs):
+ del score_dir, query, received_llm_config
+ seen.update(kwargs)
+ return {
+ "status": "ready",
+ "recommended_plans": [],
+ "execution_graph": {"edges": []},
+ }
+
+ monkeypatch.setattr(
+ "jiuwenswarm.extensions.symphony.extension.plan_from_score",
+ fake_plan_from_score,
+ )
+
+ result = asyncio.run(SymphonyExtension().plan({"query": "do work"}))
+
+ assert result["success"] is True
+ assert seen["dynamic_graph_enabled"] is True
+
+
def test_plan_uses_requested_fast_mode(monkeypatch, tmp_path):
configured_score_dir = tmp_path / "configured"
seen = {}
@@ -397,7 +441,10 @@ def test_graph_filters_disabled_skills_from_visual_payload(monkeypatch, tmp_path
monkeypatch.setattr(
"jiuwenswarm.extensions.symphony.extension.load_symphony_config",
lambda: symphony_config_from_dict(
- {"paths": {"score_dir": str(configured_score_dir)}}
+ {
+ "paths": {"score_dir": str(configured_score_dir)},
+ "evolution": {"enabled": True},
+ }
),
)
monkeypatch.setattr(
@@ -408,6 +455,14 @@ def test_graph_filters_disabled_skills_from_visual_payload(monkeypatch, tmp_path
"jiuwenswarm.extensions.symphony.extension.load_execution_disabled_skills",
lambda: ["Beta Skill"],
)
+ monkeypatch.setattr(
+ "jiuwenswarm.extensions.symphony.extension.load_dynamic_overlay",
+ lambda score_dir: {
+ "edges": {
+ "skill-a->skill-c:can_feed": {"runtime_weight": 1.15},
+ }
+ },
+ )
result = asyncio.run(SymphonyExtension().graph({}))
@@ -418,7 +473,11 @@ def test_graph_filters_disabled_skills_from_visual_payload(monkeypatch, tmp_path
"skill:skill-c",
]
assert result["graph"]["edges"] == [
- {"source": "skill:skill-a", "target": "skill:skill-c"}
+ {
+ "source": "skill:skill-a",
+ "target": "skill:skill-c",
+ "runtime_weight": 1.15,
+ }
]
assert result["score_lookup"] == {
"by_output": {"draft": ["skill-a"]},
diff --git a/tests/unit_tests/symphony/test_graph_service.py b/tests/unit_tests/symphony/test_graph_service.py
index c7b75e88bd..ce7ad1a0f6 100644
--- a/tests/unit_tests/symphony/test_graph_service.py
+++ b/tests/unit_tests/symphony/test_graph_service.py
@@ -622,6 +622,7 @@ async def test_build_score_passes_separate_symphony_stage_configs(tmp_path):
"build": {
"workers": 8,
"batch_size": 9,
+ "max_candidates_per_skill_relation": 17,
"require_consensus": False,
"min_edge_confidence": 0.33,
},
@@ -669,6 +670,7 @@ async def test_build_score_passes_separate_symphony_stage_configs(tmp_path):
assert seen["normalization"].max_vocab_size == 7
assert seen["build"].workers == 8
assert seen["build"].batch_size == 9
+ assert seen["build"].max_candidates_per_skill_relation == 17
assert seen["build"].require_consensus is False
assert seen["build"].min_edge_confidence == 0.33
@@ -905,6 +907,55 @@ async def test_build_score_reuses_unchanged_relation_matches(tmp_path):
assert second_matcher.calls == []
+async def test_relation_cache_preserves_matcher_worker_windows(tmp_path):
+ matcher = _CountingAcceptedMatcher()
+ matcher.batch_size = 2
+ matcher.max_workers = 3
+ cached_matcher = CachedOntologyMatcher(
+ matcher,
+ tmp_path / "relation_matches.json",
+ fingerprints=[],
+ )
+ candidates = [
+ RelationCandidate(
+ source_id=f"source-{index}",
+ target_id=f"target-{index}",
+ relation_hints=["can_feed"],
+ candidate_methods=["test"],
+ priority="medium",
+ )
+ for index in range(8)
+ ]
+
+ first = await cached_matcher.match(SkillRegistry(skills={}), candidates)
+ second = await cached_matcher.match(SkillRegistry(skills={}), candidates)
+
+ assert [len(call) for call in matcher.calls] == [6, 2]
+ assert len(first) == 8
+ assert len(second) == 8
+ assert cached_matcher.stats.reused_count == 8
+ assert cached_matcher.stats.resolved_count == 0
+
+
+async def test_graph_manifest_records_candidate_generation_limit():
+ result = await GraphBuilder(
+ matcher=_NoopMatcher(),
+ candidate_generator=CandidateGenerator(
+ max_candidates_per_skill_relation=17,
+ max_port_mappings_per_candidate=9,
+ max_exact_io_pair_fanout=33,
+ ),
+ ).build([])
+
+ assert result.manifest.candidate_generation == {
+ "max_candidates_per_skill_relation": 17,
+ "max_port_mappings_per_candidate": 9,
+ "max_exact_io_pair_fanout": 33,
+ }
+
+
@pytest.mark.asyncio
async def test_build_score_reports_removed_skills(tmp_path):
skills_root = tmp_path / "skills"
diff --git a/tests/unit_tests/symphony/test_service.py b/tests/unit_tests/symphony/test_service.py
index 56279f8398..0c447e6129 100644
--- a/tests/unit_tests/symphony/test_service.py
+++ b/tests/unit_tests/symphony/test_service.py
@@ -5,6 +5,7 @@ import pytest
from jiuwenswarm.symphony.config import SymphonyOrchestrationConfig
from jiuwenswarm.symphony.orchestration import service
from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
+from jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlanner
class _FakeLLMClient:
@@ -1011,3 +1012,140 @@ async def test_fast_plan_drops_self_loop_and_keeps_valid_edge(monkeypatch, tmp_p
assert [(edge["source_id"], edge["target_id"]) for edge in edges] == [
("skill-a", "skill-b")
]
+
+
+def _dynamic_planner(artifacts, overlay, *, candidate_skill_ids=None):
+ return FastOneShotPlanner(
+ artifacts,
+ llm_config=None,
+ llm_client=object(),
+ min_edge_confidence=0.7,
+ candidate_skill_ids=candidate_skill_ids,
+ dynamic_overlay=overlay,
+ )
+
+
+def test_dynamic_overlay_reorders_query_relevant_static_edges(tmp_path):
+ planner = _dynamic_planner(
+ _artifacts(tmp_path),
+ {
+ "edges": {
+ "skill-b->skill-c:can_feed": {
+ "source_id": "skill-b",
+ "target_id": "skill-c",
+ "relation_type": "can_feed",
+ "runtime_weight": 1.5,
+ "success_count": 10,
+ "failure_count": 0,
+ "attempt_count": 10,
+ "representative_queries": ["publish the gamma report"],
+ }
+ }
+ },
+ )
+
+ edges = planner._sorted_eligible_edges("publish the gamma report")
+
+ assert (edges[0]["source"], edges[0]["target"]) == ("skill-b", "skill-c")
+ assert edges[0]["runtime_weight"] == 1.5
+ assert edges[0]["effective_score"] == pytest.approx(0.88 * 1.5)
+
+
+def test_dynamic_overlay_downranks_explicitly_failed_static_edge(tmp_path):
+ planner = _dynamic_planner(
+ _artifacts(tmp_path),
+ {
+ "edges": {
+ "skill-a->skill-b:can_feed": {
+ "source_id": "skill-a",
+ "target_id": "skill-b",
+ "relation_type": "can_feed",
+ "runtime_weight": 0.4,
+ "success_count": 0,
+ "failure_count": 12,
+ "attempt_count": 12,
+ "representative_queries": ["review the alpha draft"],
+ }
+ }
+ },
+ )
+
+ edges = planner._sorted_eligible_edges("review the alpha draft")
+
+ assert [(edge["source"], edge["target"]) for edge in edges[:2]] == [
+ ("skill-b", "skill-c"),
+ ("skill-a", "skill-b"),
+ ]
+ assert edges[1]["runtime_evidence"]["failure_count"] == 12
+
+
[email protected]("success_count", [1, 2])
+def test_runtime_only_edge_requires_repeated_clean_success(tmp_path, success_count):
+ planner = _dynamic_planner(
+ _artifacts(tmp_path),
+ {
+ "edges": {
+ "skill-c->skill-a:can_feed": {
+ "source_id": "skill-c",
+ "target_id": "skill-a",
+ "relation_type": "can_feed",
+ "runtime_weight": 1.1,
+ "success_count": success_count,
+ "failure_count": 0,
+ "attempt_count": success_count,
+ }
+ }
+ },
+ candidate_skill_ids=["skill-c"],
+ )
+
+ edges = planner._sorted_eligible_edges("create an alpha draft from gamma")
+ runtime_edges = [edge for edge in edges if edge.get("runtime_only")]
+
+ assert bool(runtime_edges) is (success_count >= 2)
+
+
+def test_dynamic_overlay_is_neutral_for_unrelated_query(tmp_path):
+ planner = _dynamic_planner(
+ _artifacts(tmp_path),
+ {
+ "edges": {
+ "skill-a->skill-b:can_feed": {
+ "source_id": "skill-a",
+ "target_id": "skill-b",
+ "relation_type": "can_feed",
+ "runtime_weight": 2.0,
+ "success_count": 20,
+ "failure_count": 0,
+ "attempt_count": 20,
+ "representative_queries": ["verify an invoice"],
+ }
+ }
+ },
+ )
+
+ edges = planner._sorted_eligible_edges("show tomorrow's weather")
+
+ assert edges[0].get("runtime_evidence") is None
+ assert edges[0]["confidence"] == 0.91
+
+
+async def test_disabled_dynamic_graph_does_not_load_overlay(monkeypatch, tmp_path):
+ artifacts = _artifacts(tmp_path)
+ llm = _FakeLLMClient({"status": "no_plan", "steps": []})
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+
+ def fail_if_loaded(score_dir):
+ raise AssertionError(f"overlay should not be loaded from {score_dir}")
+
+ monkeypatch.setattr(service, "load_dynamic_overlay", fail_if_loaded)
+
+ result = await service.plan_from_score(
+ tmp_path,
+ "static only",
+ llm_client=llm,
+ dynamic_graph_enabled=False,
+ )
+
+ assert result["dynamic_graph_enabled"] is False
+ assert result["dynamic_overlay_used"] is False
diff --git a/tests/unit_tests/symphony/test_session_consumer.py b/tests/unit_tests/symphony/test_session_consumer.py
new file mode 100644
index 0000000000..6ff1358e3b
--- /dev/null
+++ b/tests/unit_tests/symphony/test_session_consumer.py
@@ -0,0 +1,406 @@
+import json
+
+from jiuwenswarm.symphony.evolution import session_consumer
+from jiuwenswarm.symphony.evolution.service import evolution_status
+from jiuwenswarm.symphony.evolution.session_consumer import (
+ consume_session_history,
+ session_feedback_status,
+)
+from jiuwenswarm.symphony.evolution.store import read_events, read_overlay
+
+
+def _write_history(session_root, session_id, records):
+ session_dir = session_root / session_id
+ session_dir.mkdir(parents=True)
+ (session_dir / "history.jsonl").write_text(
+ "".join(json.dumps(record, ensure_ascii=False) + "\n" for record in records),
+ encoding="utf-8",
+ )
+
+
+def _plan_records(plan_id="plan-1"):
+ return [
+ {
+ "role": "user",
+ "request_id": "req-plan",
+ "content": "提取发票并校验真伪",
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-plan",
+ "event_type": "chat.tool_result",
+ "tool_name": "symphony_compose_score",
+ "success": True,
+ "raw_output": {
+ "success": True,
+ "plan_id": plan_id,
+ "dynamic_graph_enabled": True,
+ "plan": {
+ "status": "ready",
+ "steps": [
+ {"skill_id": "ocr-invoice"},
+ {"skill_id": "verify-invoice"},
+ ],
+ "can_feed_edges": [
+ {
+ "source_id": "ocr-invoice",
+ "target_id": "verify-invoice",
+ }
+ ],
+ },
+ },
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-plan",
+ "event_type": "chat.final",
+ "content": "已生成执行路径",
+ },
+ ]
+
+
+def _success_records():
+ return [
+ {
+ "role": "user",
+ "request_id": "req-run",
+ "content": "确认,按上面的路径继续执行",
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.tool_call",
+ "tool_call": {
+ "name": "skill_tool",
+ "arguments": json.dumps({"skill_name": "ocr-invoice"}),
+ },
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.tool_result",
+ "tool_name": "skill_tool",
+ "success": True,
+ "result": "success=True",
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.tool_call",
+ "tool_call": {
+ "name": "skill_tool",
+ "arguments": json.dumps({"skill_name": "verify-invoice"}),
+ },
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.tool_result",
+ "tool_name": "skill_tool",
+ "success": True,
+ "result": "success=True",
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.final",
+ "content": "发票识别和真伪校验完成",
+ },
+ ]
+
+
+def test_wait_for_request_history_observes_late_terminal_record(
+ monkeypatch,
+ tmp_path,
+):
+ session_root = tmp_path / "sessions"
+ session_id = "session-late-final"
+ request_id = "req-late-final"
+ _write_history(
+ session_root,
+ session_id,
+ [{"role": "user", "request_id": request_id, "content": "continue"}],
+ )
+ history_path = session_root / session_id / "history.jsonl"
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: session_root,
+ )
+ sleep_calls = []
+
+ def persist_terminal_record(_interval):
+ sleep_calls.append(True)
+ with history_path.open("a", encoding="utf-8") as handle:
+ handle.write(
+ json.dumps(
+ {
+ "role": "assistant",
+ "request_id": request_id,
+ "event_type": "chat.final",
+ "content": "done",
+ }
+ )
+ + "\n"
+ )
+
+ monkeypatch.setattr(session_consumer.time, "sleep", persist_terminal_record)
+
+ history_limit = session_consumer._wait_for_request_history(
+ session_id,
+ request_id,
+ history_path,
+ )
+
+ assert sleep_calls == [True]
+ assert history_limit == history_path.stat().st_size
+
+
+def test_session_consumer_records_cross_turn_success(monkeypatch, tmp_path):
+ session_root = tmp_path / "sessions"
+ score_dir = tmp_path / "score"
+ records = _plan_records() + _success_records()
+ _write_history(session_root, "session-1", records)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: session_root,
+ )
+
+ result = consume_session_history(
+ "session-1",
+ completed_request_id="req-run",
+ score_dir=score_dir,
+ )
+
+ assert result["success"] is True
+ assert result["outcomes"][0]["outcome"] == "success"
+ assert result["outcomes"][0]["correlation"] == "planned_skill_observed"
+ events = read_events(score_dir)
+ assert len(events) == 1
+ assert events[0]["source"] == "session_history"
+ assert events[0]["session_id"] == "session-1"
+ assert events[0]["request_id"] == "req-run"
+ overlay = read_overlay(score_dir)
+ edge = overlay["edges"]["ocr-invoice->verify-invoice:can_feed"]
+ assert edge["success_count"] == 1
+ assert edge["runtime_weight"] == 1.05
+ feedback = session_feedback_status(score_dir)
+ assert feedback["plans_observed"] == 1
+ assert feedback["outcomes_recorded"] == 1
+ assert feedback["last_result"]["plan_id"] == "plan-1"
+
+
+def test_session_consumer_maps_package_ids_from_skill_frontmatter(monkeypatch, tmp_path):
+ session_root = tmp_path / "sessions"
+ score_dir = tmp_path / "score"
+ run_records = _success_records()
+ run_records[1]["tool_call"]["arguments"] = json.dumps(
+ {"skill_name": "ocr-invoice-1.1.0"}
+ )
+ run_records[2]["result"] = (
+ "success=True data={'skill_directory': '/skills/ocr-invoice-1.1.0', "
+ "'skill_content': '---\nname: ocr-invoice\ndescription: OCR\n---\n'} "
+ "error=None"
+ )
+ run_records[3]["tool_call"]["arguments"] = json.dumps(
+ {"skill_name": "vendor-verifier-package-2.4.1"}
+ )
+ run_records[4]["result"] = (
+ "success=True data={'skill_directory': '/skills/vendor-verifier-package-2.4.1', "
+ "'skill_content': '---\nname: verify-invoice\ndescription: Verify\n---\n'} "
+ "error=None"
+ )
+ _write_history(
+ session_root,
+ "session-package-ids",
+ _plan_records() + run_records,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: session_root,
+ )
+
+ result = consume_session_history(
+ "session-package-ids",
+ completed_request_id="req-run",
+ score_dir=score_dir,
+ )
+
+ assert result["outcomes"][0]["outcome"] == "success"
+ event = read_events(score_dir)[0]
+ assert event["selected_skill_ids"] == ["ocr-invoice", "verify-invoice"]
+ assert event["selected_edges"][0]["source_id"] == "ocr-invoice"
+ assert event["selected_edges"][0]["target_id"] == "verify-invoice"
+ overlay = read_overlay(score_dir)
+ assert overlay["edges"]["ocr-invoice->verify-invoice:can_feed"][
+ "success_count"
+ ] == 1
+
+
+def test_session_consumer_does_not_treat_plan_display_as_success(monkeypatch, tmp_path):
+ session_root = tmp_path / "sessions"
+ score_dir = tmp_path / "score"
+ _write_history(session_root, "session-plan-only", _plan_records())
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: session_root,
+ )
+
+ result = consume_session_history(
+ "session-plan-only",
+ completed_request_id="req-plan",
+ score_dir=score_dir,
+ )
+
+ assert result["outcomes"] == []
+ assert read_events(score_dir) == []
+ feedback = session_feedback_status(score_dir)
+ assert feedback["pending_plan_count"] == 1
+
+
+def test_session_consumer_does_not_trust_confirmation_without_execution(
+ monkeypatch,
+ tmp_path,
+):
+ session_root = tmp_path / "sessions"
+ score_dir = tmp_path / "score"
+ records = _plan_records() + [
+ {
+ "role": "user",
+ "request_id": "req-run",
+ "content": "确认,按上面的路径继续执行",
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.final",
+ "content": "已经执行完成",
+ },
+ ]
+ _write_history(session_root, "session-no-execution", records)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: session_root,
+ )
+
+ result = consume_session_history(
+ "session-no-execution",
+ completed_request_id="req-run",
+ score_dir=score_dir,
+ )
+
+ assert result["outcomes"] == []
+ assert read_events(score_dir) == []
+ assert session_feedback_status(score_dir)["pending_plan_count"] == 1
+
+
+def test_session_consumer_records_tool_failure_and_is_idempotent(monkeypatch, tmp_path):
+ session_root = tmp_path / "sessions"
+ score_dir = tmp_path / "score"
+ failure_records = [
+ {
+ "role": "user",
+ "request_id": "req-run",
+ "content": "确认,继续执行",
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.tool_call",
+ "tool_call": {
+ "name": "skill_tool",
+ "arguments": json.dumps({"skill_name": "ocr-invoice"}),
+ },
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.tool_call",
+ "tool_call": {
+ "name": "skill_tool",
+ "arguments": json.dumps({"skill_name": "verify-invoice"}),
+ },
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.tool_result",
+ "tool_name": "verify_invoice",
+ "success": False,
+ "status": "error",
+ "error": "schema mismatch",
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.final",
+ "content": "校验失败",
+ },
+ ]
+ _write_history(session_root, "session-failure", _plan_records() + failure_records)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: session_root,
+ )
+
+ first = consume_session_history(
+ "session-failure",
+ completed_request_id="req-run",
+ score_dir=score_dir,
+ )
+ second = consume_session_history(
+ "session-failure",
+ completed_request_id="req-run",
+ score_dir=score_dir,
+ )
+
+ assert first["outcomes"][0]["outcome"] == "failure"
+ assert second["outcomes"] == []
+ assert len(read_events(score_dir)) == 1
+ overlay = read_overlay(score_dir)
+ edge = overlay["edges"]["ocr-invoice->verify-invoice:can_feed"]
+ assert edge["failure_count"] == 1
+ assert edge["runtime_weight"] == 0.95
+ status = evolution_status(score_dir)
+ assert status["session_feedback"]["outcomes_recorded"] == 1
+
+
+def test_session_consumer_does_not_learn_unobserved_plan_edges(monkeypatch, tmp_path):
+ session_root = tmp_path / "sessions"
+ score_dir = tmp_path / "score"
+ records = _plan_records() + [
+ {
+ "role": "user",
+ "request_id": "req-run",
+ "content": "确认,按上面的路径继续执行",
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.tool_call",
+ "tool_call": {
+ "name": "skill_tool",
+ "arguments": json.dumps({"skill_name": "ocr-invoice"}),
+ },
+ },
+ {
+ "role": "assistant",
+ "request_id": "req-run",
+ "event_type": "chat.final",
+ "content": "只完成了识别",
+ },
+ ]
+ _write_history(session_root, "session-partial", records)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
+ lambda: session_root,
+ )
+
+ result = consume_session_history(
+ "session-partial",
+ completed_request_id="req-run",
+ score_dir=score_dir,
+ )
+
+ assert result["outcomes"] == []
+ assert read_events(score_dir) == []
+ assert session_feedback_status(score_dir)["pending_plan_count"] == 1
diff --git a/tests/unit_tests/symphony/test_toolkit.py b/tests/unit_tests/symphony/test_toolkit.py
index 7ff843cf88..bdc79881be 100644
--- a/tests/unit_tests/symphony/test_toolkit.py
+++ b/tests/unit_tests/symphony/test_toolkit.py
@@ -182,6 +182,46 @@ def test_plan_returns_compact_plan_and_beam_graph():
assert "result" not in result
+def test_plan_preserves_dynamic_graph_metadata():
+ registry = _registry()
+
+ async def handler(params, request=None):
+ del params, request
+ return {
+ "success": True,
+ "plan_id": "plan-session-1",
+ "dynamic_graph_enabled": True,
+ "result": {"recommended_plans": []},
+ }
+
+ registry.register_rpc_handler("symphony.plan", handler)
+
+ result = asyncio.run(SymphonyToolkit().plan("compose"))
+
+ assert result["plan_id"] == "plan-session-1"
+ assert result["dynamic_graph_enabled"] is True
+
+
+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",
+ "method": "fast_llm_inferred",
+ "reason": "LLM connected retrieved candidates.",
+ }
+
+
def test_plan_reports_missing_rpc_handler():
_registry()
diff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.py
index 9f08ae78ff..a072fcc7b1 100644
--- a/tests/unit_tests/test_app_web_handlers.py
+++ b/tests/unit_tests/test_app_web_handlers.py
@@ -640,6 +640,7 @@ def test_config_panel_flatten_reads_symphony_enabled_and_skill_retrieval():
raw = {
"symphony": {
"enabled": True,
+ "evolution": {"enabled": False},
"orchestration": {"mode": "fast"},
"skill_retrieval": {
"enabled": True,
@@ -652,6 +653,7 @@ def test_config_panel_flatten_reads_symphony_enabled_and_skill_retrieval():
flat = _flatten_symphony_for_config_panel(raw)
assert flat["symphony_enabled"] == "true"
+ assert flat["symphony_dynamic_graph_enabled"] == "false"
assert "symphony_orchestration_mode" not in flat
assert flat["skill_retrieval_enabled"] == "true"
assert flat["skill_retrieval_build_branching_factor"] == "64"
@@ -689,13 +691,14 @@ async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):
"req-3",
{
"symphony_enabled": "true",
+ "symphony_dynamic_graph_enabled": "false",
"skill_retrieval_enabled": "false",
"skill_retrieval_retrieve_flatten_tree": "true",
},
"sess-3",
)
- assert recorded_symphony == [{"enabled": True}]
+ assert recorded_symphony == [{"enabled": True, "evolution": {"enabled": False}}]
assert recorded_skill_retrieval == [{"enabled": False, "retrieve": {"flatten_tree": True}}]
assert channel.responses[-1] == {
"id": "req-3",
@@ -703,6 +706,7 @@ async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):
"payload": {
"updated": [
"symphony_enabled",
+ "symphony_dynamic_graph_enabled",
"skill_retrieval_enabled",
"skill_retrieval_retrieve_flatten_tree",
],
@@ -713,6 +717,12 @@ async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):
}
+def test_web_does_not_expose_symphony_evolution_rpc_methods():
+ assert "symphony.evolution_status" not in app_web_handlers._FORWARD_REQ_METHODS
+ assert "symphony.evolution_record_outcome" not in app_web_handlers._FORWARD_REQ_METHODS
+ assert "symphony.evolution_rebuild" not in app_web_handlers._FORWARD_REQ_METHODS
+
+
# =====================================================================
# _normalize_feishu_conf 纯函数测试
# =====================================================================