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): migrate symphony orchestration and experience to core

kaichengs281d4a5e2e5a
diff --git a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
index 45d7f2dcf4..158ef36e65 100644
--- a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
+++ b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
@@ -16,7 +16,7 @@ symphony:
enabled: false
paths:
skills_root: ""
- score_dir: ""
+ graph_dir: ""
fingerprint:
scan:
diff --git a/docs/assets/images/symphony_score.png b/docs/assets/images/symphony_graph.png
similarity index 100%
rename from docs/assets/images/symphony_score.png
rename to docs/assets/images/symphony_graph.png
diff --git a/docs/en/Configuration.md b/docs/en/Configuration.md
index ae9bd5c2a8..1422531f31 100644
--- a/docs/en/Configuration.md
+++ b/docs/en/Configuration.md
@@ -379,7 +379,7 @@ The configuration panel exposes two related switches:
| Switch | Config key | Default | Purpose |
| --- | --- | --- | --- |
| **Enable Skill Retrieval** | `symphony.skill_retrieval.enabled` | `false` | Registers skill-tree retrieval tools such as `skill_branch_explore`, `skill_branch_peek`, and `skill_index_build` |
-| **Enable Skill Symphony** | `symphony.enabled` | `false` | Registers skill score and orchestration tools such as `symphony_read_score`, `symphony_refresh_score`, and `symphony_compose_score` |
+| **Enable Skill Symphony** | `symphony.enabled` | `false` | Registers skill score and orchestration tools such as `symphony_read_graph`, `symphony_refresh_graph`, and `symphony_compose_graph` |
The two switches are independent. Skill Retrieval answers "how to find candidate skills"; Skill Symphony answers "how to orchestrate candidate skills into a route". If only Skill Retrieval is enabled, the system only gets skill-tree retrieval. If only Skill Symphony is enabled, the system can read and refresh the skill score, but candidate skills do not automatically come from Skill Retrieval.
@@ -407,7 +407,7 @@ Common settings:
| Setting | Default | Description |
| --- | --- | --- |
| `symphony.paths.skills_root` | Empty string | Skill source directory; empty means the runtime default is used |
-| `symphony.paths.score_dir` | Empty string | Skill score artifact directory; empty means the runtime default is used |
+| `symphony.paths.graph_dir` | Empty string | Skill score artifact directory; empty means the runtime default is used |
| `symphony.fingerprint.scan.max_depth` | Empty | Maximum skill-file scan depth; empty means the runtime default is used |
| `symphony.fingerprint.extraction.workers` | `4` | Skill fingerprint extraction concurrency |
| `symphony.fingerprint.extraction.batch_size` | `2` | Skill fingerprint extraction batch size |
@@ -440,6 +440,8 @@ Common settings:
| `symphony.skill_retrieval.retrieve.flatten_tree` | `false` | Whether retrieval flattens the skill tree |
| `symphony.skill_retrieval.retrieve.max_exposure_depth` | `1` | Maximum tree depth exposed by one `skill_branch_explore` call |
+> ⚠️ `symphony.paths.score_dir` was renamed to `symphony.paths.graph_dir`; the legacy key is ignored and triggers a one-time migration warning. To keep previously built artifacts and evolution data, point `symphony.paths.graph_dir` at the old score directory.
+
> 📖 For details about Skill Retrieval, the skill score, and Skill Orchestration, see [Symphony: Skill Retrieval, Orchestration, and Dispatch](symphony.md).
---
diff --git a/docs/en/Symphony.md b/docs/en/Symphony.md
index d09e6bab81..e52c58ec8b 100644
--- a/docs/en/Symphony.md
+++ b/docs/en/Symphony.md
@@ -35,7 +35,7 @@ The important part is not listing skills in order. Skill Orchestration checks wh
The skill score is the graph used by orchestration. Each node represents a skill. Each edge means one skill's output can be used as another skill's input, in other words, a connectable relationship. It helps users understand possible skill combinations and gives orchestration candidate relationships to work from.
-![Skill score](../assets/images/symphony_score.png)
+![Skill score](../assets/images/symphony_graph.png)
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.
@@ -86,7 +86,7 @@ Skill Retrieval mainly finds skills. Skill Orchestration organizes candidate ski
### Runtime tools
-When Skill Retrieval is enabled, the agent receives skill-directory browsing tools. When Skill Symphony is enabled, the agent receives score and orchestration tools. Users usually do not need to call these tools manually; the system chooses them based on the task.
+When Skill Retrieval is enabled, the agent receives skill-directory browsing tools. When Skill Symphony is enabled, the agent receives graph and orchestration tools. Users usually do not need to call these tools manually; the system chooses them based on the task.
#### Skill Retrieval tools
@@ -96,17 +96,17 @@ When Skill Retrieval is enabled, the agent receives skill-directory browsing too
| `skill_branch_peek` | Shows a lightweight branch summary without expanding the full tree | Use when it is unclear whether a branch is worth expanding |
| `skill_index_build` | Builds or refreshes the local installed-skill tree index | Use only when retrieval tools explicitly report a missing or stale index |
-When `skill_branch_explore` returns a `skills` section, those entries are installed skills, not branch IDs. The agent narrows candidates by skill name, description, and returned `worker_id`. If orchestration is needed later, those `worker_id` values can be passed to `symphony_compose_score` as `candidate_skill_ids`.
+When `skill_branch_explore` returns a `skills` section, those entries are installed skills, not branch IDs. The agent narrows candidates by skill name, description, and returned `worker_id`. If orchestration is needed later, those `worker_id` values can be passed to `symphony_compose_graph` as `candidate_skill_ids`.
#### Skill Orchestration tools
| Tool | What it does | When to use |
|------|--------------|-------------|
-| `symphony_read_score` | Checks whether the skill score exists and whether it is stale | Before orchestration, when the current score state needs to be known |
-| `symphony_refresh_score` | Extracts installed-skill features and refreshes the skill score | When the score is missing, stale, or skills were newly installed or changed |
-| `symphony_compose_score` | Main orchestration entry. Builds an execution graph from the task goal, candidate skills, and skill score | When the user asks to use skills, or the task needs a skill chain, skill ordering, or a specialized tool chain |
+| `symphony_read_graph` | Checks whether the skill score exists and whether it is stale | Before orchestration, when the current score state needs to be known |
+| `symphony_refresh_graph` | Extracts installed-skill features and refreshes the skill score | When the score is missing, stale, or skills were newly installed or changed |
+| `symphony_compose_graph` | Main orchestration entry. Builds an execution graph from the task goal, candidate skills, and skill score | When the user asks to use skills, or the task needs a skill chain, skill ordering, or a specialized tool chain |
-The core parameter of `symphony_compose_score` is `query`, the original user task. The current orchestration mode is `fast`. If Skill Retrieval has already narrowed the candidate set, pass the `worker_id` list from `skill_branch_explore` into `candidate_skill_ids`; Symphony will compose a skill chain from those candidates and their connectable neighbors. If the result says no suitable skill is available, install the required skill from the **Skills** page, call `symphony_refresh_score` to refresh the score, and then compose again with the original task.
+The core parameter of `symphony_compose_graph` is `query`, the original user task. The current orchestration mode is `fast`. If Skill Retrieval has already narrowed the candidate set, pass the `worker_id` list from `skill_branch_explore` into `candidate_skill_ids`; Symphony will compose a skill chain from those candidates and their connectable neighbors. If the result says no suitable skill is available, install the required skill from the **Skills** page, call `symphony_refresh_graph` to refresh the score, and then compose again with the original task.
---
@@ -187,7 +187,7 @@ In **Related edges**:
| **Adjust minimum confidence** | Hide lower-confidence edges so you can focus on stronger skill handoffs |
| **Read score** | Reload the existing built skill score |
| **Incremental build** | Update the score after adding, removing, or changing skills |
-| **Pause build** | Pause a long-running score build while keeping completed cache and checkpoints |
+| **Cancel build** | Cancel a long-running score build while keeping completed cache and checkpoints |
| **Full rebuild** | Recompute everything when the score looks stale or incorrect |
| **Fit view** | Re-center and scale the visible graph |
@@ -274,7 +274,7 @@ After seeing the route, you can respond in one of these ways:
## Configuration
-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.
+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, cancel build, and full rebuild operations.
Advanced build, retrieval, and orchestration settings are configured in the user runtime config file:
@@ -288,15 +288,15 @@ Advanced build, retrieval, and orchestration settings are configured in the user
Whether to enable Symphony orchestration. The default template value is `false`.
-When enabled, new sessions register orchestration tools such as `symphony_read_score`, `symphony_refresh_score`, and `symphony_compose_score`. The agent can read or refresh the skill score and build a skill chain from candidate skills. When disabled, these tools are not registered and the agent does not use the skill score for orchestration.
+When enabled, new sessions register orchestration tools such as `symphony_read_graph`, `symphony_refresh_graph`, and `symphony_compose_graph`. The agent can read or refresh the skill score and build a skill chain from candidate skills. When disabled, these tools are not registered and the agent does not use the skill score for orchestration.
This switch controls Symphony orchestration tools. Skill Retrieval is still controlled separately by `symphony.skill_retrieval.enabled`: retrieval finds candidate skills, and orchestration builds an execution route from the task goal, candidate skills, and the skill score.
-#### `symphony.paths.skills_root` / `symphony.paths.score_dir`
+#### `symphony.paths.skills_root` / `symphony.paths.graph_dir`
The skill source directory and skill score artifact directory. Both default template values are empty strings, which means the runtime default directories are used.
-`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_refresh_graph` reads skills from `skills_root` and refreshes the skill score. `symphony_read_graph` and `symphony_compose_graph` read score artifacts from `graph_dir`. Configure these paths explicitly when the score needs to be cached in a fixed location or reused across runtime environments.
#### `symphony.build`
@@ -418,7 +418,7 @@ symphony:
enabled: true
paths:
skills_root: ""
- score_dir: ""
+ graph_dir: ""
build:
max_candidates_per_skill_relation: 32
@@ -514,9 +514,9 @@ No. Symphony only uses installed skills. Install new skills from the **Skills**
No. Symphony helps the Leader or agent find relevant skills and form a skill chain. Task decomposition, skill reading, tool execution, and team coordination still use JiuwenSwarm's existing runtime.
-### Is building the skill score the same as composing an execution score?
+### Is building the skill score the same as composing an execution graph?
-This is an easy distinction to miss: building the skill score is not composing an execution score. Building the skill score usually happens before a task arrives and focuses on which skills in the whole installed skill set may have stable connectable relationships. Composing an execution score happens after a task arrives and focuses on this specific request: which skills should be selected from the score, in what order they should run, and where additional inputs are needed.
+This is an easy distinction to miss: building the skill score is not composing an execution graph. Building the skill score usually happens before a task arrives and focuses on which skills in the whole installed skill set may have stable connectable relationships. Composing an execution graph happens after a task arrives and focuses on this specific request: which skills should be selected from the score, in what order they should run, and where additional inputs are needed.
---
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 f75c069415..773ab0db55 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"
@@ -96,17 +96,17 @@ skill_branch_explore 展开相关分支
| `skill_branch_peek` | 查看分支的轻量摘要和覆盖信息,不展开完整技能树 | 不确定某个分支是否值得展开时使用 |
| `skill_index_build` | 构建或刷新本地已安装技能树索引 | 仅当检索工具明确提示索引缺失或过期时调用 |
-当 `skill_branch_explore` 返回 `skills` 小节时,其中的条目是已安装技能,不是分支 ID。智能体会根据技能名称、描述和返回的 `worker_id` 缩小候选范围;如果后续需要编排,可以把候选技能的 `worker_id` 传给 `symphony_compose_score` 的 `candidate_skill_ids`。
+当 `skill_branch_explore` 返回 `skills` 小节时,其中的条目是已安装技能,不是分支 ID。智能体会根据技能名称、描述和返回的 `worker_id` 缩小候选范围;如果后续需要编排,可以把候选技能的 `worker_id` 传给 `symphony_compose_graph` 的 `candidate_skill_ids`。
#### 技能编排工具
| 工具 | 作用 | 使用时机 |
|------|------|----------|
-| `symphony_read_score` | 查看技能总谱是否存在、是否过期 | 编排前需要确认总谱状态时使用 |
-| `symphony_refresh_score` | 抽取已安装技能特征并刷新技能总谱 | 总谱缺失、过期,或安装新技能后需要更新关系图时使用 |
-| `symphony_compose_score` | 技能编排入口,基于任务目标、候选技能和技能总谱生成执行图 | 用户要求使用技能,或任务需要技能链、技能排序、专门工具链时使用 |
+| `symphony_read_graph` | 查看技能总谱是否存在、是否过期 | 编排前需要确认总谱状态时使用 |
+| `symphony_refresh_graph` | 抽取已安装技能特征并刷新技能总谱 | 总谱缺失、过期,或安装新技能后需要更新关系图时使用 |
+| `symphony_compose_graph` | 技能编排入口,基于任务目标、候选技能和技能总谱生成执行图 | 用户要求使用技能,或任务需要技能链、技能排序、专门工具链时使用 |
-`symphony_compose_score` 的核心参数是 `query`,即原始用户任务;当前编排模式为 `fast`。如果已经通过技能检索缩小了候选范围,可以把 `skill_branch_explore` 返回的 `worker_id` 列表传入 `candidate_skill_ids`,让 Symphony 在这些候选技能及其可衔接邻居中生成技能链。若编排结果提示缺少合适技能,需要先通过 **技能** 页面搜索并安装新技能,再调用 `symphony_refresh_score` 刷新总谱,最后用原始任务重新编排。
+`symphony_compose_graph` 的核心参数是 `query`,即原始用户任务;当前编排模式为 `fast`。如果已经通过技能检索缩小了候选范围,可以把 `skill_branch_explore` 返回的 `worker_id` 列表传入 `candidate_skill_ids`,让 Symphony 在这些候选技能及其可衔接邻居中生成技能链。若编排结果提示缺少合适技能,需要先通过 **技能** 页面搜索并安装新技能,再调用 `symphony_refresh_graph` 刷新总谱,最后用原始任务重新编排。
---
@@ -187,7 +187,7 @@ Symphony 只会使用已安装技能。请先在左侧导航栏 **技能** 页
| **调整最小置信度** | 过滤低置信度的边,便于聚焦更可靠的技能衔接关系 |
| **读谱** | 重新读取当前已经构建好的技能总谱 |
| **增量构建** | 在新增、删除或修改技能后,优先使用增量构建更新总谱 |
-| **暂停构建** | 总谱构建耗时较长时可暂停,已完成的缓存和 checkpoint 会保留 |
+| **取消构建** | 总谱构建耗时较长时可取消,已完成的缓存和 checkpoint 会保留 |
| **全量重新构建** | 当总谱异常、关系明显过旧或需要彻底重算时使用 |
| **适配视图** | 将当前可见图谱重新居中并缩放到合适大小 |
@@ -274,7 +274,7 @@ Symphony 只会使用已安装技能。请先在左侧导航栏 **技能** 页
## 配置说明
-当前 Web 配置页提供三个相关开关:**启用技能检索** 控制技能树检索工具,**启用技能编排** 控制技能总谱与编排工具,**启用动态图谱** 控制 Session 执行轨迹是否参与学习和后续编排。技能索引页提供索引构建、重新构建、取消构建、查看构建状态和查看索引树等操作;技能总谱页提供读谱、增量构建、暂停构建和全量重新构建等操作。
+当前 Web 配置页提供三个相关开关:**启用技能检索** 控制技能树检索工具,**启用技能编排** 控制技能总谱与编排工具,**启用动态图谱** 控制 Session 执行轨迹是否参与学习和后续编排。技能索引页提供索引构建、重新构建、取消构建、查看构建状态和查看索引树等操作;技能总谱页提供读谱、增量构建、取消构建和全量重新构建等操作。
构建、检索和编排的高级参数需要在用户运行时配置文件进行配置:
@@ -288,15 +288,15 @@ Symphony 只会使用已安装技能。请先在左侧导航栏 **技能** 页
是否启用技能交响乐的编排能力。默认模板值是 `false`。
-开启后,新会话会注册 `symphony_read_score`、`symphony_refresh_score`、`symphony_compose_score` 等编排工具。智能体可以读取或刷新技能总谱,并在已有候选技能基础上生成技能链。关闭后不注册这些工具,智能体不会使用技能总谱进行编排。
+开启后,新会话会注册 `symphony_read_graph`、`symphony_refresh_graph`、`symphony_compose_graph` 等编排工具。智能体可以读取或刷新技能总谱,并在已有候选技能基础上生成技能链。关闭后不注册这些工具,智能体不会使用技能总谱进行编排。
该开关控制的是 Symphony 的编排工具;技能检索仍由 `symphony.skill_retrieval.enabled` 单独控制。也就是说,检索负责找到候选技能,编排负责基于任务目标、候选技能和技能总谱生成执行路线。
-#### `symphony.paths.skills_root` / `symphony.paths.score_dir`
+#### `symphony.paths.skills_root` / `symphony.paths.graph_dir`
技能来源目录和技能总谱产物目录。默认模板值都是空字符串,表示使用运行时默认目录。
-`symphony_refresh_score` 会从 `skills_root` 读取技能并刷新技能总谱;`symphony_read_score` 和 `symphony_compose_score` 会读取 `score_dir` 下的总谱产物。需要把总谱缓存到固定位置、或者在不同运行环境之间复用总谱时,可以显式配置这些目录。
+`symphony_refresh_graph` 会从 `skills_root` 读取技能并刷新技能总谱;`symphony_read_graph` 和 `symphony_compose_graph` 会读取 `graph_dir` 下的总谱产物。需要把总谱缓存到固定位置、或者在不同运行环境之间复用总谱时,可以显式配置这些目录。
#### `symphony.build`
@@ -419,7 +419,7 @@ symphony:
enabled: true
paths:
skills_root: ""
- score_dir: ""
+ graph_dir: ""
build:
max_candidates_per_skill_relation: 32
@@ -519,7 +519,7 @@ symphony:
### 为什么技能总谱构建时间较长?
-总谱构建需要读取已安装技能,并分析技能之间的输入输出和语义衔接关系。技能越多、关系越复杂,耗时越长。构建完成后可以直接读谱,不需要每轮对话都重建。
+技能总谱构建需要读取已安装技能,并分析技能之间的输入输出和语义衔接关系。技能越多、关系越复杂,耗时越长。构建完成后可以直接读谱,不需要每轮对话都重建。
### 技能检索和技能总谱有什么区别?
@@ -537,9 +537,9 @@ symphony:
不会。Symphony 可以帮助 Leader 或普通智能体找到相关技能并形成技能链。具体如何拆解任务、读取技能、执行工具、组织团队,仍由 JiuwenSwarm 原有运行模式完成。
-### 构建总谱和谱写执行乐谱是一回事吗?
+### 构建总谱和生成执行图是一回事吗?
-这里有一个容易混淆的点:构建总谱不是谱写执行乐谱。构建总谱通常发生在任务到来之前,关注的是整个技能库里,哪些技能之间可能存在稳定的可衔接关系。谱写执行乐谱发生在任务到来之后,关注的是面对这次具体需求,应该从总谱中选出哪些技能、按什么顺序执行,以及哪里需要补充输入材料。
+这里有一个容易混淆的点:构建总谱不是生成执行图。构建总谱通常发生在任务到来之前,关注的是整个技能库里,哪些技能之间可能存在稳定的可衔接关系。生成执行图发生在任务到来之后,关注的是面对这次具体需求,应该从总谱中选出哪些技能、按什么顺序执行,以及哪里需要补充输入材料。
---
diff --git "a/docs/zh/\346\212\200\350\203\275.md" "b/docs/zh/\346\212\200\350\203\275.md"
index 35c44a0e58..63224796b6 100644
--- "a/docs/zh/\346\212\200\350\203\275.md"
+++ "b/docs/zh/\346\212\200\350\203\275.md"
@@ -612,4 +612,3 @@ allowed_tools: [webSearch, readFile]
### 优化后
再次调用,输出结果不仅包含气温、风速等基础项,还带上了紫外线强度
-
diff --git "a/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md" "b/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
index 3f1d308e7f..b7107d4936 100644
--- "a/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
+++ "b/docs/zh/\351\205\215\347\275\256\344\277\241\346\201\257.md"
@@ -377,7 +377,7 @@ permissions:
| 开关 | 对应配置 | 默认值 | 作用 |
| --- | --- | --- | --- |
| **启用技能检索** | `symphony.skill_retrieval.enabled` | `false` | 注册 `skill_branch_explore`、`skill_branch_peek`、`skill_index_build` 等技能树检索工具 |
-| **启用技能交响乐** | `symphony.enabled` | `false` | 注册 `symphony_read_score`、`symphony_refresh_score`、`symphony_compose_score` 等技能总谱与编排工具 |
+| **启用技能交响乐** | `symphony.enabled` | `false` | 注册 `symphony_read_graph`、`symphony_refresh_graph`、`symphony_compose_graph` 等技能总谱与编排工具 |
两个开关相互独立:技能检索解决“怎么找到候选技能”,技能交响乐解决“怎么把候选技能编排成路线”。如果只开启技能检索,系统只会获得技能树检索能力;如果只开启技能交响乐,系统可以读取和刷新技能总谱,但候选技能范围不会自动来自技能树检索。
@@ -405,7 +405,7 @@ permissions:
| 配置项 | 默认值 | 说明 |
| --- | --- | --- |
| `symphony.paths.skills_root` | 空字符串 | 技能来源目录;为空时使用运行时默认目录 |
-| `symphony.paths.score_dir` | 空字符串 | 技能总谱产物目录;为空时使用运行时默认目录 |
+| `symphony.paths.graph_dir` | 空字符串 | 技能总谱产物目录;为空时使用运行时默认目录 |
| `symphony.fingerprint.scan.max_depth` | 空 | 技能文件扫描最大深度;为空时使用运行时默认值 |
| `symphony.fingerprint.extraction.workers` | `4` | 技能指纹抽取并发数 |
| `symphony.fingerprint.extraction.batch_size` | `2` | 技能指纹抽取批大小 |
@@ -438,6 +438,8 @@ permissions:
| `symphony.skill_retrieval.retrieve.flatten_tree` | `false` | 检索时是否扁平化技能树 |
| `symphony.skill_retrieval.retrieve.max_exposure_depth` | `1` | 单次 `skill_branch_explore` 最多披露的树深度 |
+> ⚠️ `symphony.paths.score_dir` 已更名为 `symphony.paths.graph_dir`,旧键会被忽略并输出一次迁移告警;如需沿用既有构建产物与演进数据,请将 `symphony.paths.graph_dir` 指向原 score 目录。
+
> 📖 **详情**:关于技能检索、技能总谱和技能编排的完整说明,请参考 [Symphony:技能检索、编排与分发](symphony-技能编排与分发.md)。
---
diff --git a/jiuwenswarm/agents/harness/common/rails/symphony/orchestration_rail.py b/jiuwenswarm/agents/harness/common/rails/symphony/orchestration_rail.py
index 999e914a30..6f6e7445c7 100644
--- a/jiuwenswarm/agents/harness/common/rails/symphony/orchestration_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/symphony/orchestration_rail.py
@@ -23,7 +23,7 @@ class SymphonyOrchestrationRail(DeepAgentRail):
priority = 98
SECTION_NAME = "symphony_orchestration"
SECTION_PRIORITY = 42
- COMPOSE_TOOL_NAME = "symphony_compose_score"
+ COMPOSE_TOOL_NAME = "symphony_compose_graph"
def __init__(self, *, config_base: _ConfigBaseProvider = None) -> None:
super().__init__()
@@ -129,11 +129,11 @@ class SymphonyOrchestrationRail(DeepAgentRail):
When the user says to use skill(s) or 技能, or when you judge that skill
capabilities, skill chaining, skill ordering, or a specialized toolchain could
-help complete the task, you MUST call `symphony_compose_score` with the original
+help complete the task, you MUST call `symphony_compose_graph` with the original
user task as `query` before answering.
When you identify, inspect, or recommend installed Skills that are relevant to
the task, you MUST pass their exact identifiers or names as
-`symphony_compose_score.candidate_skill_ids`. Do not omit this field after
+`symphony_compose_graph.candidate_skill_ids`. Do not omit this field after
selecting candidate Skills. Do not choose the execution chain yourself;
Symphony owns ordering and graph composition. After it returns, present its
returned `content` directly to the user. If Symphony reports missing inputs,
@@ -142,8 +142,8 @@ ask for those inputs.
If Symphony reports no suitable candidates, a missing capability, or caveats
that point to a skill gap, use `search_skill` to discover external skills. When
installing a discovered skill is appropriate, call `install_skill`; after a
-successful install, call `symphony_refresh_score` and then call
-`symphony_compose_score` again with the original user task.
+successful install, call `symphony_refresh_graph` and then call
+`symphony_compose_graph` again with the original user task.
For clearly ordinary tasks that do not benefit from skill capabilities, continue
normally without Symphony.
diff --git a/jiuwenswarm/agents/harness/common/rails/symphony/tool_stream_events.py b/jiuwenswarm/agents/harness/common/rails/symphony/tool_stream_events.py
index 5c6f59102b..823ca02aac 100644
--- a/jiuwenswarm/agents/harness/common/rails/symphony/tool_stream_events.py
+++ b/jiuwenswarm/agents/harness/common/rails/symphony/tool_stream_events.py
@@ -20,11 +20,11 @@ from jiuwenswarm.common.utils import logger
class SymphonyToolStreamHandler:
"""Own Symphony-specific stream progress and completion behavior."""
- COMPOSE_TOOL_NAME = "symphony_compose_score"
+ COMPOSE_TOOL_NAME = "symphony_compose_graph"
_PROGRESS_TOKEN_KEY = "_symphony_tool_progress_token"
_RESULT_FIELDS = (
- "score_status",
- "score_build",
+ "graph_status",
+ "graph_build",
"direct_display",
"continue_after_display",
"followup_action",
diff --git a/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py b/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
index 48afd33a70..9bfac9ecba 100644
--- a/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
@@ -103,7 +103,7 @@ class SkillRetrievalToolkit:
"shortlist by Name and Description, then read a returned SKILL.md only after the skill "
"looks likely useful. "
"To guide Symphony composition, pass shortlisted skill worker_id values to "
- "symphony_compose_score.candidate_skill_ids. "
+ "symphony_compose_graph.candidate_skill_ids. "
"Do not read every skill or explore skill names as branch ids. "
"This is not an execution tool or a full execution plan. If the index is missing or stale, "
"follow the returned instruction to call skill_index_build once, then retry."
diff --git a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
index 7bb9d3028b..dac00d738b 100644
--- a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
@@ -3,68 +3,56 @@
from __future__ import annotations
import asyncio
-import inspect
import logging
-from types import SimpleNamespace
from typing import Any, Callable
from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
-from jiuwenswarm.extensions.registry import ExtensionRegistry
from jiuwenswarm.agents.harness.common.tool_progress_context import (
current_tool_progress,
)
from jiuwenswarm.symphony.config import load_symphony_config
+from jiuwenswarm.symphony.service import (
+ SwarmSymphonyService,
+ get_swarm_symphony_service,
+)
logger = logging.getLogger(__name__)
class SymphonyToolkit:
- """Expose Symphony extension RPC methods as model-callable tools."""
+ """Expose the process-local Symphony service as model-callable tools."""
+
+ def __init__(self, service: SwarmSymphonyService | None = None) -> None:
+ self._service = service
@staticmethod
def _resolve_timeout_s(default_s: float = 1800.0) -> float:
return default_s
- async def _call_rpc(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
+ async def _call_service(
+ self,
+ operation: str,
+ *args: Any,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
logger.info(
- "[SymphonyToolkit] calling RPC: method=%s params_keys=%s",
- method,
- sorted(params),
+ "[SymphonyToolkit] calling service: operation=%s",
+ operation,
)
+ timeout_s = self._resolve_timeout_s()
try:
- registry = ExtensionRegistry.get_instance()
- except RuntimeError as exc:
- return {
- "success": False,
- "detail": f"Symphony extension RPC unavailable: {method}: {exc}",
- }
-
- handler = registry.get_rpc_handler(method)
- if handler is None:
+ service = self._service or get_swarm_symphony_service()
+ handler = getattr(service, operation)
+ payload = await asyncio.wait_for(handler(*args, **kwargs), timeout=timeout_s)
+ except asyncio.TimeoutError:
return {
"success": False,
- "detail": f"Symphony extension RPC unavailable: {method}: handler not registered",
+ "detail": f"symphony.{operation}: timeout after {timeout_s}s",
}
-
- timeout_s = self._resolve_timeout_s()
- try:
- progress_callback = current_tool_progress()
- request = None
- if progress_callback is not None:
- request = SimpleNamespace(
- metadata={"symphony_progress_callback": progress_callback}
- )
- result = handler(params, request=request)
- payload = await asyncio.wait_for(
- result if inspect.isawaitable(result) else _return_value(result),
- timeout=timeout_s,
- )
- except asyncio.TimeoutError:
- return {"success": False, "detail": f"{method}: timeout after {timeout_s}s"}
except Exception as exc: # noqa: BLE001
- logger.exception("Symphony RPC failed: %s", method)
- return {"success": False, "detail": f"{method}: {exc}"}
+ logger.exception("Symphony service failed: %s", operation)
+ return {"success": False, "detail": f"symphony.{operation}: {exc}"}
return (
payload
@@ -81,15 +69,18 @@ class SymphonyToolkit:
"detail": "Symphony is disabled by config: symphony.enabled=false",
}
- async def score_status(self) -> dict[str, Any]:
+ async def graph_status(self) -> dict[str, Any]:
if not self.is_enabled():
- return self._disabled_payload("symphony.score_status")
- return await self._call_rpc("symphony.score_status", {})
+ return self._disabled_payload("symphony_read_graph")
+ return await self._call_service("graph_status")
- async def refresh_score(self) -> dict[str, Any]:
+ async def refresh_graph(self) -> dict[str, Any]:
if not self.is_enabled():
- return self._disabled_payload("symphony.build_score")
- return await self._call_rpc("symphony.build_score", {})
+ return self._disabled_payload("symphony_refresh_graph")
+ return await self._call_service(
+ "refresh_graph",
+ progress=current_tool_progress(),
+ )
@classmethod
def _compact_plan_payload(cls, payload: dict[str, Any]) -> dict[str, Any]:
@@ -116,14 +107,14 @@ class SymphonyToolkit:
if reason not in (None, ""):
compact["reason"] = reason
- score_status = payload.get("score_status")
- score_build = payload.get("score_build")
- if not bool(compact["success"]) and isinstance(score_status, dict):
- compact["score_status"] = cls._compact_score_status(score_status)
- if isinstance(score_build, dict) and (
- not bool(compact["success"]) or score_build.get("rebuilt") is True
+ graph_status = payload.get("graph_status")
+ graph_build = payload.get("graph_build")
+ if not bool(compact["success"]) and isinstance(graph_status, dict):
+ compact["graph_status"] = cls._compact_graph_status(graph_status)
+ if isinstance(graph_build, dict) and (
+ not bool(compact["success"]) or graph_build.get("rebuilt") is True
):
- compact["score_build"] = cls._compact_score_build(score_build)
+ compact["graph_build"] = cls._compact_graph_build(graph_build)
beam_search = planning_payload.get("beam_search")
if isinstance(beam_search, dict):
@@ -143,7 +134,7 @@ class SymphonyToolkit:
return compact
@staticmethod
- def _compact_score_status(status: dict[str, Any]) -> dict[str, Any]:
+ def _compact_graph_status(status: dict[str, Any]) -> dict[str, Any]:
compact = _copy_compact_fields(
status,
(
@@ -162,7 +153,7 @@ class SymphonyToolkit:
return compact
@classmethod
- def _compact_score_build(cls, update: dict[str, Any]) -> dict[str, Any]:
+ def _compact_graph_build(cls, update: dict[str, Any]) -> dict[str, Any]:
compact = _copy_compact_fields(
update,
(
@@ -177,7 +168,6 @@ class SymphonyToolkit:
"relation_reused_count",
"relation_resolved_count",
"version",
- "score_created_at",
"llm_total_tokens",
"reason",
"detail",
@@ -362,15 +352,6 @@ class SymphonyToolkit:
return
payload.setdefault("continue_after_display", False)
- @staticmethod
- def _failure_detail(payload: dict[str, Any], fallback: str) -> str:
- return str(
- payload.get("detail")
- or payload.get("reason")
- or payload.get("error")
- or fallback
- ).strip()
-
async def plan(
self,
query: str,
@@ -378,17 +359,21 @@ class SymphonyToolkit:
candidate_skill_ids: list[str] | None = None,
) -> dict[str, Any]:
if not self.is_enabled():
- return self._compact_plan_payload(self._disabled_payload("symphony.plan"))
- params: dict[str, Any] = {"query": str(query or "").strip()}
+ return self._compact_plan_payload(
+ self._disabled_payload("symphony_compose_graph")
+ )
+ query_text = str(query or "").strip()
mode_text = str(mode or "").strip()
- if mode_text:
- params["mode"] = mode_text
normalized_candidate_skill_ids = _normalize_candidate_skill_ids(
candidate_skill_ids
)
- if normalized_candidate_skill_ids is not None:
- params["candidate_skill_ids"] = normalized_candidate_skill_ids
- payload = await self._call_rpc("symphony.plan", params)
+ payload = await self._call_service(
+ "plan",
+ query_text,
+ mode=mode_text or None,
+ candidate_skill_ids=normalized_candidate_skill_ids,
+ progress=current_tool_progress(),
+ )
if isinstance(payload, dict):
self._attach_followup_control(payload)
return self._compact_plan_payload(payload)
@@ -424,19 +409,19 @@ class SymphonyToolkit:
return [
make_tool(
- "symphony_read_score",
- "Read whether the Symphony score exists or is stale before composing skill execution.",
+ "symphony_read_graph",
+ "Read whether the Symphony graph exists or is stale before composing skill execution.",
{"type": "object", "properties": {}},
- self.score_status,
+ self.graph_status,
),
make_tool(
- "symphony_refresh_score",
- "Extract installed skill features and refresh the Symphony score.",
+ "symphony_refresh_graph",
+ "Extract installed skill features and refresh the Symphony graph.",
{"type": "object", "properties": {}},
- self.refresh_score,
+ self.refresh_graph,
),
make_tool(
- "symphony_compose_score",
+ "symphony_compose_graph",
(
"MUST call before answering when the user says to use skill(s) "
"or 技能, or when skill capabilities, skill chaining, skill ordering, "
@@ -444,12 +429,12 @@ class SymphonyToolkit:
"inspect, or recommend installed Skills that are relevant to the task, you MUST "
"pass their exact identifiers or names as candidate_skill_ids. Do not omit "
"candidate_skill_ids after selecting candidate Skills. "
- "This is the Symphony composition entrypoint: it reads the score, refreshes stale "
- "or missing scores, then composes the skill execution graph from the provided "
- "candidates or a default score subgraph. If no suitable candidates or a missing "
+ "This is the Symphony composition entrypoint: it reads the graph, refreshes a stale "
+ "or missing graph, then composes the skill execution graph from the provided "
+ "candidates or a default graph subgraph. If no suitable candidates or a missing "
"capability is reported, use search_skill to discover external skills; when "
"installing a discovered skill is appropriate, call install_skill, then call "
- "symphony_refresh_score and retry this tool with the original query. "
+ "symphony_refresh_graph and retry this tool with the original query. "
"After it returns, present its content result directly to the user; "
"do not call individual skill tools just to manually recreate the plan. "
"Skip only clearly ordinary tasks that do not benefit from skill capabilities."
@@ -491,10 +476,6 @@ class SymphonyToolkit:
]
-async def _return_value(value: Any) -> Any:
- return value
-
-
def _copy_compact_fields(
payload: dict[str, Any],
keys: tuple[str, ...],
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx
index 92163f6e2f..c3307aa473 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillGraphPanel/index.tsx
@@ -12,10 +12,10 @@ import {
Focus,
GitBranch,
Loader2,
- Pause,
RefreshCw,
RotateCcw,
Search,
+ X,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { webRequest } from '../../services/webClient';
@@ -44,7 +44,7 @@ type BuildProgress = {
stage?: string;
label?: string;
percent?: number;
- status?: 'idle' | 'running' | 'success' | 'error' | 'paused';
+ status?: 'idle' | 'running' | 'success' | 'error' | 'cancelled';
current?: number;
total?: number;
ts?: string;
@@ -54,12 +54,12 @@ type BuildProgress = {
type SkillGraphPayload = {
success?: boolean;
detail?: string;
- score_dir?: string;
+ graph_dir?: string;
build_log?: BuildLogEntry[];
build_progress?: BuildProgress;
llm_token_usage?: LLMTokenUsageSummary;
manifest?: RawRecord;
- score_manifest?: RawRecord;
+ graph_manifest?: RawRecord;
orchestration_min_edge_confidence?: number;
graph?: {
nodes?: RawRecord[];
@@ -77,8 +77,10 @@ type SkillGraphPayload = {
type SkillGraphUpdate = {
success?: boolean;
detail?: string;
- paused?: boolean;
- score_dir?: string;
+ background?: boolean;
+ cancelled?: boolean;
+ build_status?: 'idle' | 'running' | 'success' | 'error' | 'cancelled';
+ graph_dir?: string;
build_log?: BuildLogEntry[];
build_progress?: BuildProgress;
llm_token_usage?: LLMTokenUsageSummary;
@@ -87,7 +89,7 @@ type SkillGraphUpdate = {
type SkillGraphStatus = {
success?: boolean;
detail?: string;
- score_dir?: string;
+ graph_dir?: string;
build_log?: BuildLogEntry[];
build_progress?: BuildProgress;
llm_token_usage?: LLMTokenUsageSummary;
@@ -153,7 +155,6 @@ const NODE_COLORS: Record<string, string> = {
unknown: '#7f8a99',
};
-const INDEX_UPDATE_TIMEOUT_MS = 1_800_000;
const DEFAULT_MIN_CONFIDENCE = 0.7;
type SymphonyBuildMode = 'incremental' | 'full';
@@ -162,8 +163,8 @@ type Translate = (key: string, options?: Record<string, unknown>) => string;
const BUILD_STAGE_TRANSLATION_KEYS: Record<string, string> = {
idle: 'idle',
'update.start': 'updateStart',
- 'update.pause_requested': 'updatePauseRequested',
- 'update.paused': 'updatePaused',
+ 'update.cancel_requested': 'updateCancelRequested',
+ 'update.cancelled': 'updateCancelled',
'scan.start': 'scanStart',
'scan.done': 'scanDone',
'diff.done': 'diffDone',
@@ -184,8 +185,8 @@ const BUILD_STAGE_TRANSLATION_KEYS: Record<string, string> = {
'graph.resolve.done': 'graphResolveDone',
'graph.materialize.start': 'graphMaterializeStart',
'graph.materialize.done': 'graphMaterializeDone',
- 'graph.score.start': 'graphScoreStart',
- 'graph.score.done': 'graphScoreDone',
+ 'graph.lookup.start': 'graphLookupStart',
+ 'graph.lookup.done': 'graphLookupDone',
'graph.build.done': 'graphBuildDone',
'artifact.graph.write.start': 'artifactGraphWriteStart',
'artifact.graph.write.done': 'artifactGraphWriteDone',
@@ -197,10 +198,12 @@ const BUILD_STAGE_TRANSLATION_KEYS: Record<string, string> = {
const SERVER_DETAIL_TRANSLATION_KEYS: Record<string, string> = {
'当前没有正在运行的技能总谱构建。': 'skills.graph.serverDetails.noRunningBuild',
- '已请求暂停技能总谱构建,已完成的缓存和 checkpoint 会保留。': 'skills.graph.serverDetails.pauseRequested',
- '已有技能总谱构建正在运行,请等待完成或先暂停当前构建。': 'skills.graph.serverDetails.buildRunning',
- '技能总谱构建已暂停,可再次执行增量构建继续。': 'skills.graph.serverDetails.buildPaused',
- '技能总谱不存在或不完整,请先构建总谱。': 'skills.graph.serverDetails.scoreMissing',
+ '技能总谱后台构建已启动。': 'skills.graph.serverDetails.buildStarted',
+ '技能总谱已在后台构建中。': 'skills.graph.serverDetails.buildRunning',
+ '已取消技能总谱构建,已完成的缓存和 checkpoint 会保留。': 'skills.graph.serverDetails.cancelRequested',
+ '已有技能总谱构建正在运行,请等待完成或先取消当前构建。': 'skills.graph.serverDetails.buildRunning',
+ '技能总谱构建已取消,可再次执行增量构建继续。': 'skills.graph.serverDetails.buildCancelled',
+ '技能总谱不存在或不完整,请先构建总谱。': 'skills.graph.serverDetails.graphMissing',
};
const SERVER_DETAIL_PREFIX_TRANSLATION_KEYS: Array<{ prefix: string; key: string }> = [
@@ -225,7 +228,7 @@ function confidenceValue(value: unknown, fallback: number): number {
}
function payloadManifest(payload: SkillGraphPayload | null | undefined): RawRecord {
- return asRecord(payload?.score_manifest ?? payload?.manifest);
+ return asRecord(payload?.graph_manifest ?? payload?.manifest);
}
function graphConfidenceFloor(payload: SkillGraphPayload | null | undefined): number {
@@ -282,7 +285,7 @@ function labelFromId(id: string): string {
function normalizeNode(raw: RawRecord, index: number, skillsById: Map<string, RawRecord>): GraphNode {
const rawId = asString(raw.id ?? raw.node_id ?? raw.skill_id, `node:${index}`);
const id = rawId.includes(':') ? rawId : `skill:${rawId}`;
- const skillId = id.replace(/^skill:/, '');
+ const skillId = id.replace(/^(?:skill|capability):/, '');
const skill = skillsById.get(skillId);
const properties = {
...asRecord(skill),
@@ -418,7 +421,7 @@ function isBuildRunningPayload(data: { build_progress?: BuildProgress }): boolea
}
function isTerminalBuildStatus(status: BuildProgress['status'] | undefined): boolean {
- return status === 'success' || status === 'error' || status === 'paused';
+ return status === 'success' || status === 'error' || status === 'cancelled';
}
function buildStageLabel(stage: string, fallback: string, t: Translate): string {
@@ -609,7 +612,7 @@ function isCompletedBuildLogEntry(entry: BuildLogEntry): boolean {
|| stage === 'graph.candidates.done'
|| stage === 'graph.resolve.done'
|| stage === 'graph.materialize.done'
- || stage === 'graph.score.done'
+ || stage === 'graph.lookup.done'
|| stage === 'graph.build.done'
|| stage === 'artifact.fingerprints.write.done'
|| stage === 'artifact.graph.write.done'
@@ -628,7 +631,7 @@ function isSupersededBuildStart(entry: BuildLogEntry, index: number, entries: Bu
'graph.candidates.start': 'graph.candidates.done',
'graph.resolve.start': 'graph.resolve.done',
'graph.materialize.start': 'graph.materialize.done',
- 'graph.score.start': 'graph.score.done',
+ 'graph.lookup.start': 'graph.lookup.done',
'graph.build.start': 'graph.build.done',
'artifact.graph.write.start': 'artifact.graph.write.done',
'state.write.start': 'state.write.done',
@@ -639,7 +642,7 @@ function isSupersededBuildStart(entry: BuildLogEntry, index: number, entries: Bu
function isTerminalBuildLogEntry(entry: BuildLogEntry): boolean {
const stage = asString(entry.stage);
- return stage === 'update.done' || stage === 'update.failed' || stage === 'update.paused';
+ return stage === 'update.done' || stage === 'update.failed' || stage === 'update.cancelled';
}
function buildLogTime(entry: BuildLogEntry): string {
@@ -693,7 +696,7 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
const [loading, setLoading] = useState(false);
const [updating, setUpdating] = useState(false);
const [buildMode, setBuildMode] = useState<SymphonyBuildMode | null>(null);
- const [pausingBuild, setPausingBuild] = useState(false);
+ const [cancellingBuild, setCancellingBuild] = useState(false);
const [error, setError] = useState<string | null>(null);
const [buildLog, setBuildLog] = useState<BuildLogEntry[]>([]);
const [buildProgress, setBuildProgress] = useState<BuildProgress | null>(null);
@@ -729,8 +732,8 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
}
}, []);
- const resetBuildUiOnTerminalStatus = useCallback((data: { detail?: string; paused?: boolean; build_progress?: BuildProgress }): boolean => {
- const status = data.build_progress?.status ?? (data.paused ? 'paused' : undefined);
+ const resetBuildUiOnTerminalStatus = useCallback((data: { detail?: string; cancelled?: boolean; build_progress?: BuildProgress }): boolean => {
+ const status = data.build_progress?.status ?? (data.cancelled ? 'cancelled' : undefined);
if (!isTerminalBuildStatus(status)) return false;
externalBuildRunningRef.current = false;
setUpdating(false);
@@ -894,7 +897,7 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
setError(null);
let keepLoading = false;
try {
- const data = await webRequest<SkillGraphPayload>('symphony.graph', {}, { timeoutMs: 60_000 });
+ const data = await webRequest<SkillGraphPayload>('skills.graph.get', {}, { timeoutMs: 60_000 });
applyBuildLog(data);
if (!data.success) {
if (isBuildRunningPayload(data)) {
@@ -930,7 +933,7 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
const restoreBuildStatus = useCallback(async (): Promise<boolean> => {
const data = await webRequest<SkillGraphStatus>(
- 'symphony.score_status',
+ 'skills.graph.status',
{},
{ timeoutMs: 60_000 },
);
@@ -962,50 +965,43 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
});
try {
const data = await webRequest<SkillGraphUpdate>(
- 'symphony.build_score',
+ 'skills.graph.build',
{ force },
- { timeoutMs: INDEX_UPDATE_TIMEOUT_MS },
+ { timeoutMs: 60_000 },
);
applyBuildLog(data);
- const isPaused = data.paused || data.build_progress?.status === 'paused';
- if (isPaused) {
- resetBuildUiOnTerminalStatus(data);
- return;
- }
if (!data.success) {
throw new Error(localizedServerDetail(data.detail, 'skills.graph.errors.refreshFailed', t));
}
- await loadGraph();
+ externalBuildRunningRef.current = true;
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
- } finally {
setUpdating(false);
setBuildMode(null);
}
- }, [applyBuildLog, loadGraph, resetBuildUiOnTerminalStatus, t]);
+ }, [applyBuildLog, t]);
- const pauseBuild = useCallback(async () => {
- setPausingBuild(true);
+ const cancelBuild = useCallback(async () => {
+ setCancellingBuild(true);
setShowBuildLogPanel(true);
setError(null);
try {
const data = await webRequest<SkillGraphUpdate>(
- 'symphony.pause_build',
+ 'skills.graph.cancel',
{},
{ timeoutMs: 60_000 },
);
applyBuildLog(data);
- const isPaused = data.paused || data.build_progress?.status === 'paused';
if (resetBuildUiOnTerminalStatus(data)) {
return;
}
- if (!data.success && !isPaused) {
- throw new Error(localizedServerDetail(data.detail, 'skills.graph.errors.pauseFailed', t));
+ if (!data.success && data.build_status !== 'idle') {
+ throw new Error(localizedServerDetail(data.detail, 'skills.graph.errors.cancelFailed', t));
}
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
- setPausingBuild(false);
+ setCancellingBuild(false);
}
}, [applyBuildLog, resetBuildUiOnTerminalStatus, t]);
@@ -1038,7 +1034,7 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
const poll = async () => {
try {
const data = await webRequest<SkillGraphStatus>(
- 'symphony.score_status',
+ 'skills.graph.status',
{},
{ timeoutMs: 60_000 },
);
@@ -1081,7 +1077,7 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
let nextDelay = 3000;
try {
const data = await webRequest<SkillGraphStatus>(
- 'symphony.score_status',
+ 'skills.graph.status',
{},
{ timeoutMs: 60_000 },
);
@@ -1355,9 +1351,9 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
);
const isGraphBuildRunning = buildProgress?.status === 'running';
- const isGraphBuildPaused = buildProgress?.status === 'paused';
+ const isGraphBuildCancelled = buildProgress?.status === 'cancelled';
const isBusy = loading || updating;
- const canPauseBuild = (updating || isGraphBuildRunning) && !pausingBuild;
+ const canCancelBuild = (updating || isGraphBuildRunning) && !cancellingBuild;
const isIncrementalBuild = updating && buildMode === 'incremental';
const isFullBuild = updating && buildMode === 'full';
const manifest = payloadManifest(payload);
@@ -1368,8 +1364,8 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
const progressLabel = buildProgressLabel(buildProgress, updating, t);
const progressTitle = isGraphBuildRunning
? t('skills.graph.status.refreshing')
- : isGraphBuildPaused
- ? t('skills.graph.status.paused')
+ : isGraphBuildCancelled
+ ? t('skills.graph.status.cancelled')
: progressLabel;
const recentBuildLog = compactBuildLog(buildLog).slice(-8);
const tokenUsageText = formatTokenUsage(tokenUsage, t);
@@ -1446,11 +1442,11 @@ export const SkillGraphPanel = forwardRef<SkillGraphPanelHandle, SkillGraphPanel
</button>
<button
type="button"
- onClick={pauseBuild}
- disabled={!canPauseBuild}
- title={t('skills.graph.actions.pauseBuild')}
+ onClick={cancelBuild}
+ disabled={!canCancelBuild}
+ title={t('skills.graph.actions.cancelBuild')}
>
- {pausingBuild ? <Loader2 size={16} className="skill-graph-panel__spin" aria-hidden="true" /> : <Pause size={16} aria-hidden="true" />}
+ {cancellingBuild ? <Loader2 size={16} className="skill-graph-panel__spin" aria-hidden="true" /> : <X size={16} aria-hidden="true" />}
</button>
<button
type="button"
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 1733aa3cc6..12ca575054 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -2124,13 +2124,13 @@
"actions": {
"read": "Read score",
"incrementalBuild": "Incremental build",
- "pauseBuild": "Pause build",
+ "cancelBuild": "Cancel build",
"fullRebuild": "Full rebuild",
"fitView": "Fit view"
},
"status": {
"refreshing": "Refreshing skill score",
- "paused": "Skill score build paused",
+ "cancelled": "Skill score build cancelled",
"reading": "Reading skill score",
"noBuildLogs": "No build logs",
"waitingBuildLogs": "Waiting for build logs...",
@@ -2140,21 +2140,22 @@
"errors": {
"readFailed": "Unable to read the skill score. Refresh the score first.",
"refreshFailed": "Failed to refresh the skill score",
- "pauseFailed": "Failed to pause the skill score build",
+ "cancelFailed": "Failed to cancel the skill score build",
"buildFailedWithDetail": "Symphony score build failed: {{detail}}"
},
"serverDetails": {
"noRunningBuild": "No skill score build is currently running.",
- "pauseRequested": "Skill score build pause requested. Completed cache and checkpoints will be kept.",
- "buildRunning": "A skill score build is already running. Wait for it to finish or pause the current build first.",
- "buildPaused": "Skill score build paused. Run an incremental build again to continue.",
- "scoreMissing": "The skill score is missing or incomplete. Build the score first."
+ "buildStarted": "Skill score background build started.",
+ "cancelRequested": "Skill score build cancelled. Completed cache and checkpoints will be kept.",
+ "buildRunning": "A skill score build is already running in the background.",
+ "buildCancelled": "Skill score build cancelled. Run an incremental build again to continue.",
+ "graphMissing": "The skill score is missing or incomplete. Build the score first."
},
"buildStages": {
"idle": "No build logs",
"updateStart": "Starting skill score build",
- "updatePauseRequested": "Pausing skill score build",
- "updatePaused": "Skill score build paused",
+ "updateCancelRequested": "Cancelling skill score build",
+ "updateCancelled": "Skill score build cancelled",
"scanStart": "Scanning skill directories",
"scanDone": "Skill directory scan complete",
"diffDone": "Checking skill changes",
@@ -2175,8 +2176,8 @@
"graphResolveDone": "Candidate relation resolution complete",
"graphMaterializeStart": "Generating score structure",
"graphMaterializeDone": "Score structure generated",
- "graphScoreStart": "Building score retrieval structure",
- "graphScoreDone": "Score retrieval structure built",
+ "graphLookupStart": "Building score lookup structure",
+ "graphLookupDone": "Score lookup structure built",
"graphBuildDone": "Skill relation graph built",
"artifactGraphWriteStart": "Writing score files",
"artifactGraphWriteDone": "Score files written",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 83e2137686..7da2fc8b8d 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -2111,13 +2111,13 @@
"actions": {
"read": "读谱",
"incrementalBuild": "增量构建",
- "pauseBuild": "暂停构建",
+ "cancelBuild": "取消构建",
"fullRebuild": "全量重新构建",
"fitView": "适配视图"
},
"status": {
"refreshing": "正在刷新技能总谱",
- "paused": "技能总谱构建已暂停",
+ "cancelled": "技能总谱构建已取消",
"reading": "正在读取技能总谱",
"noBuildLogs": "暂无构建日志",
"waitingBuildLogs": "等待构建日志...",
@@ -2127,21 +2127,22 @@
"errors": {
"readFailed": "无法读取技能总谱,请先刷新总谱。",
"refreshFailed": "技能总谱刷新失败",
- "pauseFailed": "技能总谱暂停失败",
+ "cancelFailed": "技能总谱取消失败",
"buildFailedWithDetail": "Symphony 总谱构建失败: {{detail}}"
},
"serverDetails": {
"noRunningBuild": "当前没有正在运行的技能总谱构建。",
- "pauseRequested": "已请求暂停技能总谱构建,已完成的缓存和 checkpoint 会保留。",
- "buildRunning": "已有技能总谱构建正在运行,请等待完成或先暂停当前构建。",
- "buildPaused": "技能总谱构建已暂停,可再次执行增量构建继续。",
- "scoreMissing": "技能总谱不存在或不完整,请先构建总谱。"
+ "buildStarted": "技能总谱后台构建已启动。",
+ "cancelRequested": "技能总谱构建已取消,已完成的缓存和 checkpoint 会保留。",
+ "buildRunning": "技能总谱已在后台构建中。",
+ "buildCancelled": "技能总谱构建已取消,可再次执行增量构建继续。",
+ "graphMissing": "技能总谱不存在或不完整,请先构建总谱。"
},
"buildStages": {
"idle": "暂无构建日志",
"updateStart": "开始构建技能总谱",
- "updatePauseRequested": "正在暂停技能总谱构建",
- "updatePaused": "技能总谱构建已暂停",
+ "updateCancelRequested": "正在取消技能总谱构建",
+ "updateCancelled": "技能总谱构建已取消",
"scanStart": "扫描技能目录",
"scanDone": "技能目录扫描完成",
"diffDone": "计算技能变更",
@@ -2162,8 +2163,8 @@
"graphResolveDone": "候选关系解析完成",
"graphMaterializeStart": "生成总谱结构",
"graphMaterializeDone": "总谱结构生成完成",
- "graphScoreStart": "构建乐谱检索结构",
- "graphScoreDone": "乐谱检索结构构建完成",
+ "graphLookupStart": "构建总谱检索结构",
+ "graphLookupDone": "总谱检索结构构建完成",
"graphBuildDone": "技能关系图构建完成",
"artifactGraphWriteStart": "写入总谱文件",
"artifactGraphWriteDone": "总谱文件写入完成",
diff --git a/jiuwenswarm/channels/web/frontend/tests/toolResultLifecycle.test.mjs b/jiuwenswarm/channels/web/frontend/tests/toolResultLifecycle.test.mjs
index ee34045594..306c23db0f 100644
--- a/jiuwenswarm/channels/web/frontend/tests/toolResultLifecycle.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/toolResultLifecycle.test.mjs
@@ -19,7 +19,7 @@ test('ordinary tool result is returned unchanged', () => {
test('final result inherits the last streamed beam graph when omitted', () => {
const beamSearch = { roundIndex: 2, graph: { nodes: [], edges: [] } };
- const incoming = result({ toolName: 'symphony_compose_score' });
+ const incoming = result({ toolName: 'symphony_compose_graph' });
assert.deepEqual(mergeToolResultProgress(result({ beamSearch }), incoming), { ...incoming, beamSearch });
});
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index 32f398e4ed..ca5b102c27 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -165,11 +165,12 @@ class ReqMethod(Enum):
SKILLS_ENTERPRISE_SOURCE_PROVIDERS = "skills.enterprise.source.providers"
SKILLS_ENTERPRISE_SOURCE_SEARCH = "skills.enterprise.source.search"
- SYMPHONY_BUILD_SCORE = "symphony.build_score"
- SYMPHONY_PAUSE_BUILD = "symphony.pause_build"
- SYMPHONY_SCORE_STATUS = "symphony.score_status"
- SYMPHONY_GRAPH = "symphony.graph"
- SYMPHONY_PLAN = "symphony.plan"
+ # Skill Graph Web panel transport. The implementation is provided by
+ # agent-core Symphony, while the public transport remains skill-domain API.
+ SKILLS_GRAPH_BUILD = "skills.graph.build"
+ SKILLS_GRAPH_STATUS = "skills.graph.status"
+ SKILLS_GRAPH_GET = "skills.graph.get"
+ SKILLS_GRAPH_CANCEL = "skills.graph.cancel"
PERSONAL_CONTEXT_RUNTIME_STATUS = "personal_context.runtime.status"
PERSONAL_CONTEXT_RUNTIME_START_COLLECTION = (
diff --git a/jiuwenswarm/extensions/registry.py b/jiuwenswarm/extensions/registry.py
index 1ac55c15da..6fe7cdc970 100644
--- a/jiuwenswarm/extensions/registry.py
+++ b/jiuwenswarm/extensions/registry.py
@@ -36,7 +36,6 @@ class ExtensionRegistry:
self._third_agent: ThirdAgentExtension | None = None
self._telemetry_provider: TelemetryProviderExtension | None = None
self._skill_source_extensions: dict[str, SkillSourceExtension] = {}
- self._rpc_handlers: dict[str, Callable] = {}
self.callback_framework = callback_framework
self._config = ExtensionConfig(config=config, logger=logger)
self._extension_local_tool_entries: list[ExtensionLocalToolEntry] = []
@@ -140,20 +139,6 @@ class ExtensionRegistry:
def list_skill_source_extensions(self) -> list[SkillSourceExtension]:
return [self._skill_source_extensions[key] for key in sorted(self._skill_source_extensions)]
- def register_rpc_handler(self, method: str, handler: Callable) -> None:
- method_name = str(method or "").strip()
- if not method_name:
- raise ValueError("rpc method is required")
- if not callable(handler):
- raise ValueError(f"rpc handler for {method_name} must be callable")
- self._rpc_handlers[method_name] = handler
-
- def get_rpc_handler(self, method: str) -> Callable | None:
- return self._rpc_handlers.get(str(method or "").strip())
-
- def list_rpc_methods(self) -> list[str]:
- return sorted(self._rpc_handlers)
-
def get_agent_server_client_extension(self) -> AgentServerClientExtension | None:
return self._agent_server_client
diff --git a/jiuwenswarm/extensions/symphony/__init__.py b/jiuwenswarm/extensions/symphony/__init__.py
deleted file mode 100644
index 61a87a4b1b..0000000000
--- a/jiuwenswarm/extensions/symphony/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from jiuwenswarm.extensions.symphony.extension import register_extensions
-
-__all__ = ["register_extensions"]
diff --git a/jiuwenswarm/extensions/symphony/extension.py b/jiuwenswarm/extensions/symphony/extension.py
deleted file mode 100644
index f792fb908a..0000000000
--- a/jiuwenswarm/extensions/symphony/extension.py
+++ /dev/null
@@ -1,832 +0,0 @@
-"""Symphony extension RPC handlers."""
-
-from __future__ import annotations
-
-import asyncio
-import json
-import logging
-from dataclasses import replace
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Any
-
-from jiuwenswarm.common.config import get_config
-from jiuwenswarm.extensions.sdk import BaseExtension
-from jiuwenswarm.server.runtime.skill import load_execution_disabled_skills
-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
-from jiuwenswarm.symphony.orchestration.language import (
- default_plan_title,
- resolve_orchestration_language,
-)
-from jiuwenswarm.symphony.orchestration.service import plan_from_score
-from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dir
-
-SYMPHONY_BUILD_SCORE = "symphony.build_score"
-SYMPHONY_PAUSE_BUILD = "symphony.pause_build"
-SYMPHONY_SCORE_STATUS = "symphony.score_status"
-SYMPHONY_GRAPH = "symphony.graph"
-SYMPHONY_PLAN = "symphony.plan"
-
-logger = logging.getLogger(__name__)
-
-
-def _candidate_skill_ids_from_params(value: Any) -> list[str] | None:
- if value is None:
- return None
- if not isinstance(value, (list, tuple)):
- return []
- output: list[str] = []
- seen: set[str] = set()
- for item in value:
- current_skill_id = str(item or "").strip()
- if not current_skill_id or current_skill_id in seen:
- continue
- seen.add(current_skill_id)
- output.append(current_skill_id)
- return output
-
-
-class SymphonyExtension(BaseExtension):
- """Register explicit Symphony RPC methods."""
-
- def __init__(self) -> None:
- self._registry = None
- self._build_guard = asyncio.Lock()
- self._active_build_task: asyncio.Task | None = None
-
- async def initialize(self, config) -> None:
- return None
-
- async def shutdown(self) -> None:
- return None
-
- def register(self, registry) -> None:
- self._registry = registry
- registry.register_rpc_handler(SYMPHONY_BUILD_SCORE, self.build_score)
- registry.register_rpc_handler(SYMPHONY_PAUSE_BUILD, self.pause_build)
- registry.register_rpc_handler(SYMPHONY_SCORE_STATUS, self.score_status)
- registry.register_rpc_handler(SYMPHONY_GRAPH, self.graph)
- registry.register_rpc_handler(SYMPHONY_PLAN, self.plan)
-
- async def score_status(
- self,
- params: dict[str, Any] | None = None,
- request: Any = None,
- ) -> dict[str, Any]:
- del params, request
- config = load_symphony_config()
- skills_root = config.paths.skills_root
- score_dir = config.paths.score_dir
- await self._repair_interrupted_build_state(score_dir)
-
- def status() -> dict[str, Any]:
- payload = score_status(
- skills_root,
- score_dir,
- symphony_config=config,
- ).to_dict()
- payload.update(_build_log_payload(score_dir))
- return payload
-
- return await asyncio.to_thread(status)
-
- async def build_score(
- self,
- params: dict[str, Any] | None = None,
- request: Any = None,
- ) -> dict[str, Any]:
- params = params or {}
- return await self._build_score(
- params, request, force=_param_bool(params.get("force"))
- )
-
- async def pause_build(
- self,
- params: dict[str, Any] | None = None,
- request: Any = None,
- ) -> dict[str, Any]:
- del params, request
- config = load_symphony_config()
- score_dir = config.paths.score_dir
- build_logger = _BuildProcessLogger(score_dir / "build_log.jsonl")
- async with self._build_guard:
- task = self._active_build_task
- if task is None or task.done():
- if task is not None:
- self._active_build_task = None
- _repair_interrupted_build_log(score_dir)
- build_log_payload = _build_log_payload(score_dir)
- is_paused = (
- build_log_payload["build_progress"].get("status") == "paused"
- )
- payload = {
- "success": True,
- "score_dir": str(score_dir),
- "paused": is_paused,
- "detail": (
- "技能总谱构建已暂停,可再次执行增量构建继续。"
- if is_paused
- else "当前没有正在运行的技能总谱构建。"
- ),
- }
- payload.update(build_log_payload)
- return payload
- build_logger.record("update.pause_requested")
- task.cancel("symphony.pause_build")
- build_logger.record("update.paused")
- payload = {
- "success": True,
- "score_dir": str(score_dir),
- "paused": True,
- "detail": "已请求暂停技能总谱构建,已完成的缓存和 checkpoint 会保留。",
- }
- payload.update(_build_log_payload(score_dir))
- return payload
-
- async def graph(
- self, params: dict[str, Any] | None = None, request: Any = None
- ) -> dict[str, Any]:
- del params, request
- config = load_symphony_config()
- score_dir = config.paths.score_dir
- orchestration_min_edge_confidence = config.orchestration.min_edge_confidence
- await self._repair_interrupted_build_state(score_dir)
-
- def load() -> dict[str, Any]:
- try:
- artifacts = filter_disabled_score_artifacts(
- load_score_artifacts(score_dir),
- load_execution_disabled_skills(),
- )
- except FileNotFoundError as exc:
- payload = _missing_artifacts_payload(score_dir, exc)
- payload["orchestration_min_edge_confidence"] = (
- orchestration_min_edge_confidence
- )
- payload.update(_build_log_payload(score_dir))
- return payload
- payload = {
- "success": True,
- "score_dir": str(artifacts.score_dir),
- "score_manifest": artifacts.manifest,
- "orchestration_min_edge_confidence": (
- orchestration_min_edge_confidence
- ),
- "skills": artifacts.skills,
- "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))
- return payload
-
- return await asyncio.to_thread(load)
-
- async def plan(
- self, params: dict[str, Any] | None = None, request: Any = None
- ) -> dict[str, Any]:
- params = params or {}
- query = str(params.get("query") or "").strip()
- if not query:
- return {"success": False, "detail": "query is required"}
- candidate_skill_ids = _candidate_skill_ids_from_params(
- params.get("candidate_skill_ids")
- )
- language = resolve_orchestration_language(
- get_config().get("preferred_language", "zh")
- )
- config = load_symphony_config()
- score_dir = config.paths.score_dir
- orchestration_config = config.orchestration
- requested_mode = str(params.get("mode") or "").strip()
- if requested_mode:
- try:
- requested_orchestration_config = symphony_config_from_dict(
- {"orchestration": {"mode": requested_mode}}
- ).orchestration
- except ValueError as exc:
- return {
- "success": False,
- "score_dir": str(score_dir),
- "query": query,
- "mode": orchestration_config.mode,
- "detail": str(exc),
- }
- orchestration_config = replace(
- orchestration_config,
- mode=requested_orchestration_config.mode,
- )
-
- status = await self.score_status(request=request)
- if not status.get("success"):
- return {
- "success": False,
- "detail": "symphony.score_status failed before planning",
- "score_status": status,
- }
- if _score_needs_build(status):
- score_build = await self.build_score(request=request)
- score_build["rebuilt"] = True
- if not score_build.get("success"):
- return {
- "success": False,
- "detail": "symphony.build_score failed before planning",
- "score_status": status,
- "score_build": score_build,
- }
- else:
- score_build = {
- "success": True,
- "rebuilt": False,
- "reason": "not_required",
- }
- progress_callback = _beam_progress_callback(request)
- payload = await plan_from_score(
- score_dir,
- 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,
- language=language,
- )
- if payload.get("success") is False:
- return {
- "success": False,
- "score_dir": str(score_dir),
- "query": query,
- "mode": orchestration_config.mode,
- "language": language,
- "score_status": status,
- "score_build": score_build,
- **payload,
- }
- presentation = _build_presentation(payload, language=language)
- return {
- "success": True,
- "score_dir": str(score_dir),
- "query": query,
- "mode": orchestration_config.mode,
- "language": language,
- "content": presentation["markdown"],
- "direct_display": True,
- "score_status": status,
- "score_build": score_build,
- "result": payload,
- }
-
- async def _build_score(
- self,
- params: dict[str, Any] | None,
- request: Any,
- *,
- force: bool,
- ) -> dict[str, Any]:
- del request
- del params
- config = load_symphony_config()
- skills_root = config.paths.skills_root
- score_dir = config.paths.score_dir
- current_task = asyncio.current_task()
- async with self._build_guard:
- active_task = self._active_build_task
- if (
- active_task is not None
- and active_task is not current_task
- and not active_task.done()
- ):
- payload = {
- "success": False,
- "score_dir": str(score_dir),
- "detail": "已有技能总谱构建正在运行,请等待完成或先暂停当前构建。",
- }
- payload.update(_build_log_payload(score_dir))
- return payload
- self._active_build_task = current_task
- build_logger = _BuildProcessLogger(score_dir / "build_log.jsonl")
- build_logger.reset()
- build_logger.record(
- "update.start",
- skills_root=str(skills_root),
- out_dir=str(score_dir),
- force=force,
- )
- try:
- result = (
- await service_build_score(
- skills_root,
- score_dir,
- LLMConfig.from_default_model(),
- force=force,
- symphony_config=config,
- build_log=build_logger.record,
- )
- ).to_dict()
- except asyncio.CancelledError:
- if _build_progress(_read_build_log(score_dir)).get("status") != "paused":
- build_logger.record("update.paused")
- payload = {
- "success": False,
- "score_dir": str(score_dir),
- "paused": True,
- "detail": "技能总谱构建已暂停,可再次执行增量构建继续。",
- }
- payload.update(_build_log_payload(score_dir))
- await self._clear_active_build_task(current_task)
- return payload
- except Exception as exc: # noqa: BLE001
- build_logger.record("update.failed", error=str(exc))
- payload = {
- "success": False,
- "score_dir": str(score_dir),
- "detail": f"Symphony 总谱构建失败: {exc}",
- }
- payload.update(_build_log_payload(score_dir))
- await self._clear_active_build_task(current_task)
- return payload
- build_logger.record("update.done", **result)
- result["success"] = True
- result.update(_build_log_payload(score_dir))
- await self._clear_active_build_task(current_task)
- return result
-
- async def _clear_active_build_task(self, task: asyncio.Task | None) -> None:
- async with self._build_guard:
- if self._active_build_task is task:
- self._active_build_task = None
-
- async def _repair_interrupted_build_state(self, score_dir: Path) -> bool:
- async with self._build_guard:
- task = self._active_build_task
- if task is not None and not task.done():
- return False
- if task is not None:
- self._active_build_task = None
- return await asyncio.to_thread(_repair_interrupted_build_log, score_dir)
-
-
-async def register_extensions(registry):
- extension = SymphonyExtension()
- extension.register(registry)
- return [extension]
-
-
-def _score_needs_build(status: dict[str, Any]) -> bool:
- if not bool(status.get("exists", False)) or bool(status.get("stale", False)):
- return True
- for key in ("added_count", "changed_count", "removed_count"):
- try:
- if int(status.get(key) or 0) > 0:
- return True
- except (TypeError, ValueError):
- continue
- return False
-
-
-def _missing_artifacts_payload(
- score_dir: Path, exc: FileNotFoundError
-) -> dict[str, Any]:
- return {
- "success": False,
- "score_dir": str(score_dir),
- "detail": "技能总谱不存在或不完整,请先构建总谱。",
- "error": str(exc),
- }
-
-
-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
- if isinstance(value, bool):
- return value
- if isinstance(value, str):
- return value.strip().lower() in {"1", "true", "yes", "on"}
- return bool(value)
-
-
-def _beam_progress_callback(request: Any):
- async def callback(event: dict[str, Any]) -> None:
- await _emit_beam_progress_event(request, event)
-
- return callback
-
-
-async def _emit_beam_progress_event(request: Any, event: dict[str, Any]) -> None:
- if request is None:
- return
- payload = {
- "event_type": "symphony.beam_search.update",
- "beam_search_event": event,
- }
- metadata = getattr(request, "metadata", None)
- if isinstance(metadata, dict):
- metadata_callback = metadata.get("symphony_progress_callback")
- if callable(metadata_callback):
- result = metadata_callback(event)
- if asyncio.iscoroutine(result):
- await result
- return
-
- for name in ("write_stream", "send_event", "send_stream"):
- writer = getattr(request, name, None)
- if not callable(writer):
- continue
- result = writer(payload)
- if asyncio.iscoroutine(result):
- await result
- return
-
-
-_BUILD_STAGE_LABELS = {
- "update.start": "开始构建技能总谱",
- "update.pause_requested": "正在暂停技能总谱构建",
- "update.paused": "技能总谱构建已暂停",
- "scan.start": "扫描技能目录",
- "scan.done": "技能目录扫描完成",
- "diff.done": "计算技能变更",
- "fingerprint.reuse": "复用技能指纹",
- "fingerprint.parse.start": "解析技能指纹",
- "fingerprint.extract.start": "提取技能指纹",
- "fingerprint.normalize.start": "规范化技能指纹",
- "fingerprint.done": "技能指纹处理完成",
- "artifact.fingerprints.write.start": "写入技能指纹文件",
- "artifact.fingerprints.write.done": "技能指纹文件写入完成",
- "graph.build.start": "构建技能关系图",
- "graph.registry.start": "注册技能节点",
- "graph.registry.done": "技能节点注册完成",
- "graph.candidates.start": "生成候选关系",
- "graph.candidates.done": "候选关系生成完成",
- "graph.resolve.start": "解析候选关系",
- "graph.resolve.progress": "解析候选关系",
- "graph.resolve.done": "候选关系解析完成",
- "graph.materialize.start": "生成总谱结构",
- "graph.materialize.done": "总谱结构生成完成",
- "graph.score.start": "构建乐谱检索结构",
- "graph.score.done": "乐谱检索结构构建完成",
- "graph.build.done": "技能关系图构建完成",
- "artifact.graph.write.start": "写入总谱文件",
- "artifact.graph.write.done": "总谱文件写入完成",
- "state.write.start": "写入总谱状态",
- "state.write.done": "总谱状态写入完成",
- "update.failed": "总谱构建失败",
- "update.done": "总谱构建完成",
-}
-
-_BUILD_STAGE_PROGRESS = {
- "update.start": 3,
- "update.pause_requested": 100,
- "update.paused": 100,
- "scan.start": 8,
- "scan.done": 14,
- "diff.done": 20,
- "artifact.fingerprints.write.start": 52,
- "artifact.fingerprints.write.done": 55,
- "graph.build.start": 58,
- "graph.registry.start": 63,
- "graph.registry.done": 65,
- "graph.candidates.start": 66,
- "graph.candidates.done": 70,
- "graph.resolve.start": 72,
- "graph.resolve.done": 84,
- "graph.materialize.start": 86,
- "graph.materialize.done": 88,
- "graph.score.start": 90,
- "graph.score.done": 92,
- "graph.build.done": 94,
- "artifact.graph.write.start": 95,
- "artifact.graph.write.done": 96,
- "state.write.start": 98,
- "state.write.done": 99,
- "update.failed": 100,
- "update.done": 100,
-}
-
-
-def _build_log_payload(score_dir: Path | str, *, limit: int = 80) -> dict[str, Any]:
- resolved_score_dir = Path(score_dir)
- entries = _read_build_log(resolved_score_dir, limit=limit)
- token_usage = _build_token_usage_payload(resolved_score_dir, entries)
- build_progress = _build_progress(entries)
- if token_usage:
- build_progress["llm_token_usage"] = token_usage
- return {
- "build_log": entries,
- "build_progress": build_progress,
- "llm_token_usage": token_usage,
- }
-
-
-def _read_build_log(score_dir: Path, *, limit: int = 80) -> list[dict[str, Any]]:
- log_path = score_dir / "build_log.jsonl"
- if not log_path.is_file():
- return []
- try:
- lines = log_path.read_text(encoding="utf-8").splitlines()
- except OSError:
- return []
- entries: list[dict[str, Any]] = []
- for line in lines[-max(1, limit):]:
- try:
- payload = json.loads(line)
- except json.JSONDecodeError:
- continue
- if isinstance(payload, dict) and payload.get("stage"):
- entries.append(_normalize_build_log_entry(payload))
- return entries
-
-
-def _repair_interrupted_build_log(score_dir: Path) -> bool:
- """Close an orphaned running log after its owning process has disappeared.
-
- Callers must hold the extension build guard and first rule out a live task.
- """
- if _build_progress(_read_build_log(score_dir)).get("status") != "running":
- return False
- _BuildProcessLogger(score_dir / "build_log.jsonl").record(
- "update.paused",
- reason="process_interrupted",
- )
- return True
-
-
-def _normalize_build_log_entry(payload: dict[str, Any]) -> dict[str, Any]:
- stage = str(payload.get("stage") or "")
- entry = dict(payload)
- entry["stage"] = stage
- entry["label"] = _BUILD_STAGE_LABELS.get(stage, stage)
- _clamp_build_log_count(entry)
- return entry
-
-
-def _clamp_build_log_count(entry: dict[str, Any]) -> None:
- if "current" not in entry or "total" not in entry:
- return
- try:
- total = int(entry.get("total") or 0)
- current = int(entry.get("current") or 0)
- except (TypeError, ValueError):
- return
- if total <= 0:
- return
- entry["total"] = total
- entry["current"] = max(0, min(current, total))
-
-
-def _build_progress(entries: list[dict[str, Any]]) -> dict[str, Any]:
- if not entries:
- return {
- "stage": "idle",
- "label": "暂无构建日志",
- "percent": 0,
- "status": "idle",
- }
- latest = _latest_effective_build_log_entry(entries)
- stage = str(latest.get("stage") or "")
- status = "running"
- if stage == "update.done":
- status = "success"
- elif stage == "update.failed":
- status = "error"
- elif stage == "update.paused":
- status = "paused"
- return {
- "stage": stage,
- "label": str(latest.get("label") or _BUILD_STAGE_LABELS.get(stage, stage)),
- "percent": _build_stage_percent(stage, latest),
- "status": status,
- "current": latest.get("current"),
- "total": latest.get("total"),
- "ts": latest.get("ts"),
- }
-
-
-def _latest_effective_build_log_entry(entries: list[dict[str, Any]]) -> dict[str, Any]:
- if not entries:
- return {}
- for entry in reversed(entries):
- if str(entry.get("stage") or "") in {
- "update.done",
- "update.failed",
- "update.paused",
- }:
- return entry
- return entries[-1]
-
-
-def _build_token_usage_payload(
- score_dir: Path, entries: list[dict[str, Any]]
-) -> dict[str, Any]:
- status = _build_progress(entries).get("status")
- if status == "running":
- current = _current_token_usage_summary()
- if _has_token_usage(current):
- return current
- return {}
-
- for usage in (
- _read_manifest_token_usage(score_dir),
- _read_json_token_usage(score_dir / "llm_token_usage.json"),
- ):
- if _has_token_usage(usage):
- return usage
-
- return {}
-
-
-def _current_token_usage_summary() -> dict[str, Any]:
- try:
- from jiuwenswarm.symphony.llm import get_llm_token_usage_summary
-
- usage = get_llm_token_usage_summary()
- except Exception: # noqa: BLE001
- return {}
- return usage if isinstance(usage, dict) else {}
-
-
-def _read_manifest_token_usage(score_dir: Path) -> dict[str, Any]:
- try:
- payload = json.loads(
- (resolve_score_artifact_dir(score_dir) / "score_manifest.json").read_text(
- encoding="utf-8"
- )
- )
- except (OSError, json.JSONDecodeError):
- return {}
- if not isinstance(payload, dict):
- return {}
- llm = payload.get("llm")
- if not isinstance(llm, dict):
- return {}
- usage = llm.get("token_usage")
- return usage if isinstance(usage, dict) else {}
-
-
-def _read_json_token_usage(path: Path) -> dict[str, Any]:
- try:
- usage = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- return {}
- return usage if isinstance(usage, dict) else {}
-
-
-def _has_token_usage(usage: dict[str, Any]) -> bool:
- total = usage.get("total")
- if not isinstance(total, dict):
- return False
- try:
- return int(total.get("total_tokens") or 0) > 0
- except (TypeError, ValueError):
- return False
-
-
-def _build_stage_percent(stage: str, entry: dict[str, Any]) -> int:
- if stage == "graph.resolve.progress":
- return _progress_between(entry, start=72, end=84)
- if stage.startswith("fingerprint."):
- return _progress_between(entry, start=24, end=48)
- return int(_BUILD_STAGE_PROGRESS.get(stage, 0))
-
-
-def _progress_between(entry: dict[str, Any], *, start: int, end: int) -> int:
- try:
- current = int(entry.get("current") or 0)
- total = int(entry.get("total") or 0)
- except (TypeError, ValueError):
- return start
- if total <= 0:
- return start
- ratio = max(0.0, min(1.0, current / total))
- return int(round(start + (end - start) * ratio))
-
-
-class _BuildProcessLogger:
- def __init__(self, path: Path) -> None:
- self.path = path
-
- def reset(self) -> None:
- self.path.parent.mkdir(parents=True, exist_ok=True)
- self.path.write_text("", encoding="utf-8")
-
- def record(self, stage: str, **details: Any) -> None:
- payload = {
- "ts": datetime.now(timezone.utc).isoformat(),
- "stage": stage,
- **details,
- }
- self.path.parent.mkdir(parents=True, exist_ok=True)
- with self.path.open("a", encoding="utf-8") as handle:
- handle.write(json.dumps(payload, ensure_ascii=False, default=str) + "\n")
- logger.info("[SymphonyBuild] %s: %s", stage, _compact_details(details))
-
-
-def _compact_details(details: dict[str, Any]) -> str:
- if not details:
- return "{}"
- rendered = json.dumps(details, ensure_ascii=False, default=str)
- return rendered if len(rendered) <= 500 else rendered[:497] + "..."
-
-
-def _build_presentation(
- payload: dict[str, Any],
- *,
- language: str = "cn",
-) -> dict[str, str]:
- plan = select_primary_plan(payload)
- title = str(plan.get("title") or default_plan_title(language)).strip()
- mermaid = _plan_to_mermaid(plan, payload.get("execution_graph") or {})
- lines = [
- f"## {title}",
- "",
- "```mermaid",
- mermaid,
- "```",
- ]
- reason = str(plan.get("reason") or payload.get("reason") or "").strip()
- if reason:
- lines.extend(["", reason])
- steps = plan.get("steps") if isinstance(plan, dict) else []
- if isinstance(steps, list) and steps:
- confirmation = (
- "Would you like to proceed with the orchestration plan above?"
- if language == "en"
- else "是否按照上述编排结果执行?"
- )
- lines.extend(["", confirmation])
- return {"markdown": "\n".join(lines), "mermaid": mermaid}
-
-
-def _plan_to_mermaid(plan: dict[str, Any], graph: dict[str, Any]) -> str:
- steps = plan.get("steps") if isinstance(plan, dict) else []
- edges = graph.get("edges") if isinstance(graph, dict) else []
- labels = {
- str(step.get("skill_id") or ""): str(
- step.get("skill_name") or step.get("name") or step.get("skill_id") or ""
- )
- for step in steps or []
- if isinstance(step, dict)
- }
- node_ids = [skill_id for skill_id in labels if skill_id]
- for edge in edges or []:
- source = str(edge.get("source") or "")
- target = str(edge.get("target") or "")
- if source and source not in node_ids:
- node_ids.append(source)
- if target and target not in node_ids:
- node_ids.append(target)
- if not node_ids:
- return 'flowchart LR\n none["No Symphony plan"]'
-
- node_keys = {
- node_id: f"N{index}" for index, node_id in enumerate(node_ids, start=1)
- }
- lines = ["flowchart LR"]
- for node_id in node_ids:
- lines.append(
- f' {node_keys[node_id]}["{_mermaid_escape(labels.get(node_id) or node_id)}"]'
- )
- for edge in edges or []:
- source = str(edge.get("source") or "")
- target = str(edge.get("target") or "")
- if source in node_keys and target in node_keys:
- lines.append(f" {node_keys[source]} --> {node_keys[target]}")
- return "\n".join(lines)
-
-
-def _mermaid_escape(value: str) -> str:
- return str(value or "").replace("\\", "\\\\").replace('"', '\\"')[:80]
diff --git a/jiuwenswarm/extensions/symphony/extension.yaml b/jiuwenswarm/extensions/symphony/extension.yaml
deleted file mode 100644
index 1e73e7c890..0000000000
--- a/jiuwenswarm/extensions/symphony/extension.yaml
+++ /dev/null
@@ -1,11 +0,0 @@
-id: symphony
-name: symphony
-version: 0.1.0
-description: Build Symphony scores and plan explicit skill execution paths.
-author: jiuwenswarm
-min_jiuwenswarm_version: "0.2.0"
-dependencies:
- json-repair: ">=0.30.0"
- rich: ">=13.7.0"
-config_schema:
- type: object
diff --git a/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md b/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md
deleted file mode 100644
index 52d11c66b9..0000000000
--- a/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md
+++ /dev/null
@@ -1,35 +0,0 @@
----
-name: symphony-assistant
-description: Must use first when skill capabilities may help complete a task.
-allowed_tools:
- - symphony_compose_score
- - symphony_read_score
- - symphony_refresh_score
- - skill_branch_peek
- - skill_branch_explore
- - skill_index_build
----
-
-# Symphony Assistant
-
-Use this skill when a task may benefit from selecting, combining, ordering, or discovering skill capabilities.
-
-## Workflow
-
-1. If the user says to use skill(s) or 技能, or if skill capabilities, skill chaining, skill ordering, or a specialized toolchain could help, always call `symphony_compose_score` with the original user task as `query`.
-2. When you identify, inspect, or recommend installed Skills that are relevant to the task, pass their exact identifiers or names as `symphony_compose_score.candidate_skill_ids`. Do not omit this field after selecting candidate Skills.
-3. Select the planning mode from task complexity: use `fast` for simple tasks, short execution chains, or clear candidate skills; use `beam` for complex multi-step tasks, multiple possible skill paths, or tasks that require discovering prerequisite skills through bidirectional search. Omit `mode` to use the configured default.
-4. Do not manually inspect skill folders or choose the execution chain yourself; Symphony owns ordering and graph composition.
-5. Treat `symphony_compose_score` as the planning entrypoint: it reads the Symphony score, refreshes missing or stale scores, and returns the user-facing plan Markdown and Mermaid execution graph.
-6. The `symphony_compose_score` result may already be displayed directly to the user; otherwise, present its returned `content` directly.
-7. Treat the returned plan, Mermaid graph, structured missing inputs, and caveats as the source of truth.
-8. Do not call individual skill tools just to manually recreate or verify the Symphony plan.
-9. If Symphony reports missing inputs, ask the user for those inputs instead of inventing them.
-10. If Symphony reports no suitable candidates, a missing capability, or caveats that point to a skill gap, use `search_skill` to discover external skills. When installing a discovered skill is appropriate, call `install_skill`; after a successful install, call `symphony_refresh_score` and then call `symphony_compose_score` again with the original user task.
-11. For clearly ordinary tasks that do not benefit from skill capabilities, do not use Symphony.
-
-## Notes
-
-- `symphony_compose_score` reads the current Symphony score, refreshes it when missing or stale, and then plans the skill execution graph from provided `candidate_skill_ids` or the default score subgraph.
-- External skills must first be discovered and installed through the skill tools, then added to the score with `symphony_refresh_score`, before they can participate in Symphony planning.
-- Use `symphony_read_score` and `symphony_refresh_score` directly only when the user explicitly asks to read or refresh the Symphony score.
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index 5f6297c93a..741a70df00 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -265,11 +265,6 @@ CLI_FORWARD_REQ_METHODS = frozenset(
"skills.evolution.archives",
"skills.evolution.rollback",
"skills.evolution.rebuild",
- "symphony.build_score",
- "symphony.pause_build",
- "symphony.score_status",
- "symphony.graph",
- "symphony.plan",
"plugins.list",
"plugins.install",
"plugins.uninstall",
@@ -382,11 +377,6 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset(
"skills.evolution.archives",
"skills.evolution.rollback",
"skills.evolution.rebuild",
- "symphony.build_score",
- "symphony.pause_build",
- "symphony.score_status",
- "symphony.graph",
- "symphony.plan",
"plugins.list",
"plugins.install",
"plugins.uninstall",
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 99d23b0434..383298d0e5 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -697,11 +697,10 @@ _FORWARD_REQ_METHODS = frozenset({
"skills.enterprise.uninstall",
"skills.enterprise.source.providers",
"skills.enterprise.source.search",
- "symphony.build_score",
- "symphony.pause_build",
- "symphony.score_status",
- "symphony.graph",
- "symphony.plan",
+ "skills.graph.build",
+ "skills.graph.status",
+ "skills.graph.get",
+ "skills.graph.cancel",
"personal_context.runtime.status",
"personal_context.runtime.start_collection",
"personal_context.runtime.stop_collection",
@@ -863,11 +862,10 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
"skills.enterprise.uninstall",
"skills.enterprise.source.providers",
"skills.enterprise.source.search",
- "symphony.build_score",
- "symphony.pause_build",
- "symphony.score_status",
- "symphony.graph",
- "symphony.plan",
+ "skills.graph.build",
+ "skills.graph.status",
+ "skills.graph.get",
+ "skills.graph.cancel",
"personal_context.runtime.status",
"personal_context.runtime.start_collection",
"personal_context.runtime.stop_collection",
diff --git a/jiuwenswarm/gateway/routing/agent_rest_map.py b/jiuwenswarm/gateway/routing/agent_rest_map.py
index a9b9e2a28a..a180c387f3 100644
--- a/jiuwenswarm/gateway/routing/agent_rest_map.py
+++ b/jiuwenswarm/gateway/routing/agent_rest_map.py
@@ -205,11 +205,6 @@ _ROUTE_ROWS: tuple[tuple[str, str, str], ...] = (
("browser.runtime_restart", "POST", "/runtime/browser/actions/restart"),
("proactive.tick", "POST", "/proactive/actions/tick"),
("acp.tool_response", "POST", "/acp/tool-responses"),
- ("symphony.plan", "POST", "/symphony/actions/plan"),
- ("symphony.build_score", "POST", "/symphony/actions/build-score"),
- ("symphony.pause_build", "POST", "/symphony/actions/pause-build"),
- ("symphony.score_status", "GET", "/symphony/score-status"),
- ("symphony.graph", "GET", "/symphony/graph"),
("channel.feishu.get_conf", "GET", "/channels/feishu/config"),
("channel.feishu.set_conf", "PUT", "/channels/feishu/config"),
("channel.xiaoyi.get_conf", "GET", "/channels/xiaoyi/config"),
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 56f9efb4df..6870358500 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -36,7 +36,7 @@ symphony:
enabled: false
paths:
skills_root: ""
- score_dir: ""
+ graph_dir: ""
fingerprint:
scan:
diff --git a/jiuwenswarm/server/agent_http_routes.py b/jiuwenswarm/server/agent_http_routes.py
index 7639b3ac16..8b83feff19 100644
--- a/jiuwenswarm/server/agent_http_routes.py
+++ b/jiuwenswarm/server/agent_http_routes.py
@@ -426,12 +426,6 @@ ROUTES: list[RouteSpec] = [
RouteSpec("POST", "/runtime/browser/actions/restart", ReqMethod.BROWSER_RUNTIME_RESTART.value),
RouteSpec("POST", "/proactive/actions/tick", ReqMethod.PROACTIVE_TICK.value),
RouteSpec("POST", "/acp/tool-responses", ReqMethod.ACP_TOOL_RESPONSE.value),
- # --- Symphony(乐谱式编排)---
- RouteSpec("POST", "/symphony/actions/plan", ReqMethod.SYMPHONY_PLAN.value),
- RouteSpec("POST", "/symphony/actions/build-score", ReqMethod.SYMPHONY_BUILD_SCORE.value),
- RouteSpec("POST", "/symphony/actions/pause-build", ReqMethod.SYMPHONY_PAUSE_BUILD.value),
- RouteSpec("GET", "/symphony/score-status", ReqMethod.SYMPHONY_SCORE_STATUS.value),
- RouteSpec("GET", "/symphony/graph", ReqMethod.SYMPHONY_GRAPH.value),
# --- 渠道配置 ---
RouteSpec("GET", "/channels/feishu/config", ReqMethod.CHANNEL_FEISHU_GET_CONF.value),
RouteSpec("PUT", "/channels/feishu/config", ReqMethod.CHANNEL_FEISHU_SET_CONF.value),
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 8377e95a25..e21488ae47 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -12,7 +12,6 @@ from __future__ import annotations
import asyncio
from dataclasses import replace
-import inspect
import json
import logging
import os
@@ -708,6 +707,10 @@ _SKILL_ROUTES: dict[ReqMethod, str] = {
ReqMethod.SKILLS_RETRIEVAL_INDEX_CANCEL: "handle_skills_retrieval_index_cancel",
ReqMethod.SKILLS_RETRIEVAL_SEARCH: "handle_skills_retrieval_search",
ReqMethod.SKILLS_RETRIEVAL_TREE: "handle_skills_retrieval_tree",
+ ReqMethod.SKILLS_GRAPH_BUILD: "handle_skills_graph_build",
+ ReqMethod.SKILLS_GRAPH_STATUS: "handle_skills_graph_status",
+ ReqMethod.SKILLS_GRAPH_GET: "handle_skills_graph_get",
+ ReqMethod.SKILLS_GRAPH_CANCEL: "handle_skills_graph_cancel",
ReqMethod.SKILLS_EVOLUTION_STATUS: "handle_skills_evolution_status",
ReqMethod.SKILLS_EVOLUTION_GET: "handle_skills_evolution_get",
ReqMethod.SKILLS_EVOLUTION_SAVE: "handle_skills_evolution_save",
@@ -770,16 +773,6 @@ _PLUGIN_ROUTES: dict[ReqMethod, str] = {
ReqMethod.PLUGINS_RELOAD: "handle_plugins_reload",
}
-_SYMPHONY_METHODS: frozenset[ReqMethod] = frozenset(
- {
- ReqMethod.SYMPHONY_BUILD_SCORE,
- ReqMethod.SYMPHONY_PAUSE_BUILD,
- ReqMethod.SYMPHONY_SCORE_STATUS,
- ReqMethod.SYMPHONY_GRAPH,
- ReqMethod.SYMPHONY_PLAN,
- }
-)
-
_SKILL_COMMAND_REGEX = re.compile(
r"^/skills use\s+(?P<skill_names>[^,]+)\s*,\s*(?P<query>.*)$"
)
@@ -2436,111 +2429,6 @@ class JiuWenSwarm:
metadata=request.metadata,
)
- async def _handle_symphony_request(self, request: AgentRequest) -> AgentResponse | None:
- """处理 Symphony extension RPC 请求."""
- if request.req_method not in _SYMPHONY_METHODS:
- return None
-
- method = request.req_method.value
- try:
- handler = ExtensionRegistry.get_instance().get_rpc_handler(method)
- if handler is None:
- payload = {
- "success": False,
- "detail": f"Symphony extension RPC unavailable: {method}: handler not registered",
- }
- else:
- result = handler(request.params or {}, request=request)
- payload = await result if inspect.isawaitable(result) else result
- if not isinstance(payload, dict):
- payload = {"success": True, "result": payload}
- except Exception as exc: # noqa: BLE001
- logger.exception("[JiuWenSwarm] Symphony RPC failed: %s", method)
- return AgentResponse(
- request_id=request.request_id,
- channel_id=request.channel_id,
- ok=False,
- payload={"success": False, "detail": f"{method}: {exc}"},
- metadata=request.metadata,
- )
-
- return AgentResponse(
- request_id=request.request_id,
- channel_id=request.channel_id,
- ok=True,
- payload=payload,
- metadata=request.metadata,
- )
-
- async def _handle_symphony_request_stream(
- self,
- request: AgentRequest,
- ) -> AsyncIterator[AgentResponseChunk]:
- """Stream Symphony RPC progress events, then the final RPC payload."""
- if request.req_method not in _SYMPHONY_METHODS:
- return
-
- queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
-
- async def progress_callback(event: dict[str, Any]) -> None:
- await queue.put(event)
-
- metadata = dict(request.metadata or {})
- metadata["symphony_progress_callback"] = progress_callback
- stream_request = replace(request, metadata=metadata)
- task = asyncio.create_task(self._handle_symphony_request(stream_request))
-
- try:
- while not task.done() or not queue.empty():
- try:
- event = await asyncio.wait_for(queue.get(), timeout=0.1)
- except asyncio.TimeoutError:
- continue
- yield AgentResponseChunk(
- request_id=request.request_id,
- channel_id=request.channel_id,
- payload={
- "event_type": event.get("type")
- or "symphony.beam_search.update",
- "beam_search_event": event,
- },
- is_complete=False,
- )
- response = await task
- except Exception as exc:
- logger.exception("[JiuWenSwarm] Symphony stream failed: %s", exc)
- yield AgentResponseChunk(
- request_id=request.request_id,
- channel_id=request.channel_id,
- payload={"event_type": "chat.error", "error": str(exc)},
- is_complete=False,
- )
- yield AgentResponseChunk(
- request_id=request.request_id,
- channel_id=request.channel_id,
- payload=None,
- is_complete=True,
- )
- return
-
- payload = dict(response.payload or {}) if response is not None else {}
- payload.setdefault(
- "event_type",
- f"{request.req_method.value if request.req_method else 'symphony'}.result",
- )
- yield AgentResponseChunk(
- request_id=request.request_id,
- channel_id=request.channel_id,
- payload=payload,
- is_complete=False,
- )
- yield AgentResponseChunk(
- request_id=request.request_id,
- channel_id=request.channel_id,
- payload=None,
- is_complete=True,
- )
-
async def _process_interrupt(self, request: AgentRequest) -> AgentResponse:
"""处理 interrupt 请求.
@@ -2837,7 +2725,7 @@ class JiuWenSwarm:
metadata=request.metadata,
)
- # 无状态请求(skills / skilldev / plugins / symphony)不需要 adapter,
+ # 无状态请求(skills / skilldev / plugins / Skill Graph)不需要 adapter,
# 在 _ensure_adapter 之前检查,避免触发 adapter 懒初始化。
# COMMAND_GOAL 已在上方单独处理(其内部按需 ensure),不影响本顺序。
skilldev_response = await self._handle_skilldev_request(request)
@@ -2852,10 +2740,6 @@ class JiuWenSwarm:
if plugins_response is not None:
return plugins_response
- symphony_response = await self._handle_symphony_request(request)
- if symphony_response is not None:
- return symphony_response
-
adapter = self._ensure_adapter(mode=self._adapter_mode_for_request(request))
heartbeat_response = await adapter.handle_heartbeat(request)
@@ -3267,18 +3151,12 @@ class JiuWenSwarm:
)
return
- if request.req_method in _SYMPHONY_METHODS:
- async for chunk in self._handle_symphony_request_stream(request):
- yield chunk
- return
-
- # 无状态 RPC(skills / plugins / symphony)不需要 adapter,
+ # 无状态 RPC(skills / plugins / Skill Graph)不需要 adapter,
# 委托给非流式 handler 并包装为单个 chunk,避免触发 adapter 懒初始化。
# skilldev 已由上面的流式分支处理,这里不会再命中。
for stateless_handler in (
self._handle_skills_request,
self._handle_plugins_request,
- self._handle_symphony_request,
):
stateless_response = await stateless_handler(request)
if stateless_response is not None:
diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.py
index 3c898ecbaa..a041a0d7b0 100644
--- a/jiuwenswarm/server/runtime/skill/skill_manager.py
+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py
@@ -1041,6 +1041,39 @@ class SkillManager:
language = str((params or {}).get("language") or "cn").strip() or "cn"
return await asyncio.to_thread(get_skill_retrieval_tree, self, language=language)
+ async def handle_skills_graph_build(self, params: dict) -> dict:
+ """Start a background Skill Graph build."""
+ from jiuwenswarm.symphony.service import get_swarm_symphony_service
+
+ value = (params or {}).get("force", False)
+ force = (
+ value.strip().lower() in {"1", "true", "yes", "on"}
+ if isinstance(value, str)
+ else bool(value)
+ )
+ return await get_swarm_symphony_service().start_refresh_graph(force=force)
+
+ async def handle_skills_graph_status(self, params: dict) -> dict:
+ """Return Skill Graph build and freshness status."""
+ from jiuwenswarm.symphony.service import get_swarm_symphony_service
+
+ del params
+ return await get_swarm_symphony_service().graph_status()
+
+ async def handle_skills_graph_get(self, params: dict) -> dict:
+ """Return the current published Skill Graph."""
+ from jiuwenswarm.symphony.service import get_swarm_symphony_service
+
+ del params
+ return await get_swarm_symphony_service().graph()
+
+ async def handle_skills_graph_cancel(self, params: dict) -> dict:
+ """Cancel the active Skill Graph build while retaining checkpoints."""
+ from jiuwenswarm.symphony.service import get_swarm_symphony_service
+
+ del params
+ return await get_swarm_symphony_service().cancel_build()
+
async def handle_skills_evolution_status(self, params: dict) -> dict:
"""检查某个 skill 是否存在 evolutions.json."""
name = str(params.get("name") or "").strip()
diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.py
index c1241b01a9..deedd61b0a 100644
--- a/jiuwenswarm/server/utils/stream_utils.py
+++ b/jiuwenswarm/server/utils/stream_utils.py
@@ -48,8 +48,8 @@ def build_tool_result_payload(result_info: Any) -> dict[str, Any]:
"is_error",
"error",
"summary",
- "score_status",
- "score_build",
+ "graph_status",
+ "graph_build",
"direct_display",
"display_format",
"mermaid",
diff --git a/jiuwenswarm/symphony/adapter.py b/jiuwenswarm/symphony/adapter.py
new file mode 100644
index 0000000000..1997630b1d
--- /dev/null
+++ b/jiuwenswarm/symphony/adapter.py
@@ -0,0 +1,165 @@
+"""JiuwenSwarm adapters for the public :mod:`openjiuwen.symphony` API."""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import asdict, is_dataclass
+from typing import Any
+
+from openjiuwen.symphony import (
+ ArtifactSpec,
+ CapabilityFingerprint,
+ OrchestrationConfig,
+ ParameterSpec,
+)
+
+from jiuwenswarm.symphony.config import SymphonyConfig
+from jiuwenswarm.symphony.llm import LLMConfig, create_model_response_observer
+
+
+def capability_from_skill(value: Any) -> CapabilityFingerprint:
+ """Map an extracted JiuwenSwarm Skill fingerprint to a public capability."""
+
+ payload = value.to_dict() if hasattr(value, "to_dict") else dict(value)
+ capability_id = str(payload.get("capability_id") or payload.get("id") or "").strip()
+ if not capability_id:
+ raise ValueError("Skill fingerprint requires an id.")
+ capability_type = str(
+ payload.get("capability_type") or payload.get("type") or "skill"
+ ).strip()
+ return CapabilityFingerprint(
+ capability_id=capability_id,
+ capability_type=capability_type,
+ name=str(payload.get("name") or capability_id),
+ description=str(payload.get("description") or ""),
+ version=str(payload.get("version") or "1.0.0"),
+ inputs=[
+ item
+ if isinstance(item, ParameterSpec)
+ else ParameterSpec(
+ name=str(_field(item, "name") or "input"),
+ type=str(_field(item, "type") or "unknown"),
+ required=bool(_field(item, "required", True)),
+ description=str(_field(item, "description") or ""),
+ default=_field(item, "default"),
+ )
+ for item in payload.get("inputs", [])
+ ],
+ outputs=[
+ item
+ if isinstance(item, ArtifactSpec)
+ else ArtifactSpec(
+ name=str(_field(item, "name") or "result"),
+ type=str(_field(item, "type") or "unknown"),
+ description=str(_field(item, "description") or ""),
+ )
+ for item in payload.get("outputs", [])
+ ],
+ static_data=dict(payload.get("static_data") or {}),
+ )
+
+
+def capabilities_from_skills(values: Iterable[Any]) -> list[CapabilityFingerprint]:
+ return [capability_from_skill(value) for value in values]
+
+
+def candidate_ids_from_skill_ids(value: Any) -> list[str] | None:
+ if value is None:
+ return None
+ if not isinstance(value, (list, tuple)):
+ return []
+ output: list[str] = []
+ seen: set[str] = set()
+ for item in value:
+ candidate_id = str(item or "").strip()
+ if candidate_id and candidate_id not in seen:
+ output.append(candidate_id)
+ seen.add(candidate_id)
+ return output
+
+
+def orchestration_config_from_swarm(
+ config: SymphonyConfig,
+ *,
+ mode: str | None = None,
+) -> OrchestrationConfig:
+ orchestration = config.orchestration
+ return OrchestrationConfig(
+ mode=mode or orchestration.mode,
+ top_k=orchestration.top_k,
+ max_depth=orchestration.max_depth,
+ min_edge_confidence=orchestration.min_edge_confidence,
+ dynamic_graph_enabled=config.evolution.enabled,
+ )
+
+
+def graph_build_orchestration_config_from_swarm(
+ config: SymphonyConfig,
+) -> OrchestrationConfig:
+ """Use build-time relation thresholds without changing planning policy."""
+
+ orchestration = config.orchestration
+ return OrchestrationConfig(
+ mode=orchestration.mode,
+ top_k=orchestration.top_k,
+ max_depth=orchestration.max_depth,
+ min_edge_confidence=config.build.min_edge_confidence,
+ dynamic_graph_enabled=config.evolution.enabled,
+ )
+
+
+def graph_config_from_swarm(config: SymphonyConfig) -> dict[str, Any]:
+ build = config.build
+ if is_dataclass(build) and not isinstance(build, type):
+ return asdict(build)
+ graph_config: dict[str, Any] = {}
+ for key in (
+ "workers",
+ "batch_size",
+ "max_candidates_per_skill_relation",
+ "require_consensus",
+ "min_edge_confidence",
+ ):
+ graph_config[key] = getattr(build, key)
+ return graph_config
+
+
+def llm_config_signature(config: LLMConfig) -> str:
+ """Hash all client-affecting settings without retaining sensitive text."""
+
+ return config.identity_digest()
+
+
+def model_from_config(config: LLMConfig):
+ return config.create_model()
+
+
+def model_response_observer_from_config(config: LLMConfig):
+ return create_model_response_observer(config)
+
+
+def swarm_plan_from_public(value: Any) -> Any:
+ """Restore the Agent-tool field vocabulary while core stays capability-first."""
+
+ key_mapping = {
+ "capability_id": "skill_id",
+ "capability_ids": "skill_ids",
+ "candidate_ids": "candidate_skill_ids",
+ "candidate_count": "candidate_skill_count",
+ }
+ if isinstance(value, dict):
+ return {
+ key_mapping.get(key, key): swarm_plan_from_public(item)
+ for key, item in value.items()
+ }
+ if isinstance(value, list):
+ return [swarm_plan_from_public(item) for item in value]
+ if isinstance(value, tuple):
+ return [swarm_plan_from_public(item) for item in value]
+ return value
+
+
+def _field(value: Any, name: str, default: Any = None) -> Any:
+ if isinstance(value, dict):
+ return value.get(name, default)
+ return getattr(value, name, default)
diff --git a/jiuwenswarm/symphony/build.py b/jiuwenswarm/symphony/build.py
index ce5f03473a..b90261ca28 100644
--- a/jiuwenswarm/symphony/build.py
+++ b/jiuwenswarm/symphony/build.py
@@ -1,18 +1,21 @@
-"""Symphony Score build APIs."""
+"""Symphony graph build APIs."""
from __future__ import annotations
import json
import hashlib
+import logging
import os
+import shutil
import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
+from openjiuwen.symphony import SymphonyRuntime
+
from jiuwenswarm.symphony.config import (
- SymphonyBuildConfig,
SymphonyConfig,
default_symphony_config,
)
@@ -31,34 +34,37 @@ from jiuwenswarm.symphony.fingerprint import (
from jiuwenswarm.symphony.fingerprint.extract.extractor import (
SCHEMA_EXTRACTION_PROTOCOL_VERSION,
)
-from jiuwenswarm.symphony.graph.candidates import CandidateGenerator
-from jiuwenswarm.symphony.graph.matcher import (
- CachedOntologyMatcher,
- OntologyMatcher,
- OpenAICompatibleOntologyMatcher,
+from jiuwenswarm.symphony.adapter import (
+ capabilities_from_skills,
+ graph_build_orchestration_config_from_swarm,
+ graph_config_from_swarm,
+ llm_config_signature,
+ model_from_config,
+ model_response_observer_from_config,
+)
+from jiuwenswarm.symphony.llm import (
+ get_llm_token_usage_summary,
+ reset_llm_token_usage,
)
-from jiuwenswarm.symphony.graph.pipeline import GraphBuilder
-from jiuwenswarm.symphony.graph.writer import write_graph_build_result
-from jiuwenswarm.symphony.llm import reset_llm_token_usage
-from jiuwenswarm.symphony.score_state import (
- SCORE_STATE_FILENAME,
- ScoreStateBuilder,
- load_score_state,
- write_score_state,
+from jiuwenswarm.symphony.graph_state import (
+ GRAPH_STATE_FILENAME,
+ GraphStateBuilder,
+ load_graph_state,
+ write_graph_state,
)
-from jiuwenswarm.symphony.score_storage import (
- build_artifact_dir,
+from jiuwenswarm.symphony.graph_storage import (
build_run_dir,
latest_incomplete_build,
- publish_artifact_dir,
- score_exists,
+ graph_exists,
)
+logger = logging.getLogger(__name__)
+
@dataclass(frozen=True)
-class ScoreStatus:
+class GraphStatus:
success: bool
- score_dir: str
+ graph_dir: str
exists: bool
stale: bool
skill_count: int
@@ -72,7 +78,7 @@ class ScoreStatus:
def to_dict(self) -> dict[str, Any]:
return {
"success": self.success,
- "score_dir": self.score_dir,
+ "graph_dir": self.graph_dir,
"exists": self.exists,
"stale": self.stale,
"skill_count": self.skill_count,
@@ -86,9 +92,9 @@ class ScoreStatus:
@dataclass(frozen=True)
-class ScoreBuildResult:
+class GraphBuildResult:
success: bool
- score_dir: str
+ graph_dir: str
skill_count: int
reused_count: int
extracted_count: int
@@ -103,7 +109,7 @@ class ScoreBuildResult:
def to_dict(self) -> dict[str, Any]:
return {
"success": self.success,
- "score_dir": self.score_dir,
+ "graph_dir": self.graph_dir,
"skill_count": self.skill_count,
"reused_count": self.reused_count,
"extracted_count": self.extracted_count,
@@ -117,8 +123,8 @@ class ScoreBuildResult:
}
-class ScoreBuildRuntimeFactory:
- """Create default runtime adapters for a Symphony Score build."""
+class GraphBuildRuntimeFactory:
+ """Create default runtime adapters for a Symphony graph build."""
@staticmethod
def schema_extractor(
@@ -126,7 +132,9 @@ class ScoreBuildRuntimeFactory:
extraction_config: Any,
) -> SkillSchemaExtractor:
if llm_config is None:
- raise ValueError("llm_config is required when schema_extractor is not provided")
+ raise ValueError(
+ "llm_config is required when schema_extractor is not provided"
+ )
return LLMSchemaExtractor(
llm_config,
body_limit=extraction_config.body_limit,
@@ -139,73 +147,49 @@ class ScoreBuildRuntimeFactory:
normalization_config: Any,
) -> Any:
if llm_config is None:
- raise ValueError("llm_config is required when io_name_resolver is not provided")
+ raise ValueError(
+ "llm_config is required when io_name_resolver is not provided"
+ )
return LLMIONameResolver(
llm_config,
batch_size=normalization_config.batch_size,
)
- @staticmethod
- def matcher(
- llm_config: LLMConfig | None,
- *,
- build_config: SymphonyBuildConfig,
- build_log: Callable[..., None] | None = None,
- ) -> OntologyMatcher:
- if llm_config is None:
- raise ValueError("llm_config is required when matcher is not provided")
- return OpenAICompatibleOntologyMatcher(
- llm_config,
- batch_size=build_config.batch_size,
- max_workers=build_config.workers,
- require_consensus=build_config.require_consensus,
- thresholds={"can_feed": build_config.min_edge_confidence},
- progress=(
- lambda event, current, total, details: _record_build_log(
- build_log,
- "graph.resolve.progress",
- event=event,
- current=current,
- total=total,
- details=details,
- )
- ),
- )
-
-class SymphonyScoreBuilder:
- """Build and refresh the offline Symphony Score."""
+class SymphonyGraphBuilder:
+ """Build and refresh the offline Symphony graph."""
def __init__(
self,
*,
scanner: SkillFolderScanner | None = None,
parser: SkillManifestParser | None = None,
- runtime_factory: ScoreBuildRuntimeFactory | None = None,
- state_builder: ScoreStateBuilder | None = None,
+ runtime_factory: GraphBuildRuntimeFactory | None = None,
+ state_builder: GraphStateBuilder | None = None,
) -> None:
self.scanner = scanner or SkillFolderScanner()
self.parser = parser or SkillManifestParser()
- self.runtime_factory = runtime_factory or ScoreBuildRuntimeFactory()
- self.state_builder = state_builder or ScoreStateBuilder()
+ self.runtime_factory = runtime_factory or GraphBuildRuntimeFactory()
+ self.state_builder = state_builder or GraphStateBuilder()
def status(
self,
skills_root: str | Path,
- score_dir: str | Path,
+ graph_dir: str | Path,
*,
+ llm_config: LLMConfig | None = None,
symphony_config: SymphonyConfig | None = None,
- ) -> ScoreStatus:
+ ) -> GraphStatus:
runtime_config = symphony_config or default_symphony_config()
- output_dir = Path(score_dir).resolve()
+ output_dir = Path(graph_dir).resolve()
folders = self.scanner.scan(
skills_root,
max_depth=runtime_config.fingerprint.scan.max_depth,
)
current_hashes = self.state_builder.folder_hashes(folders)
- state = load_score_state(output_dir)
+ state = load_graph_state(output_dir)
active_entries = state.active_entries()
- exists = score_exists(output_dir)
+ exists = graph_exists(output_dir)
added = [path for path in current_hashes if path not in active_entries]
changed = [
path
@@ -214,16 +198,53 @@ class SymphonyScoreBuilder:
]
removed = [path for path in active_entries if path not in current_hashes]
stale = (not exists) or bool(added or changed or removed)
+ if exists and not stale:
+ try:
+ artifact = (
+ SymphonyRuntime(
+ graph_artifact_root=output_dir,
+ capability_provider=(),
+ model=None,
+ )
+ .orchestration.read()
+ .to_dict()
+ )
+ capabilities = capabilities_from_skills(
+ artifact.get("capabilities") or []
+ )
+ source_snapshot = artifact.get("source_snapshot")
+ expected_snapshot = _graph_status_source_snapshot(
+ capabilities=capabilities,
+ current_hashes=current_hashes,
+ runtime_config=runtime_config,
+ llm_config=llm_config,
+ artifact_source_snapshot=(
+ source_snapshot if isinstance(source_snapshot, dict) else {}
+ ),
+ )
+ identity_runtime = SymphonyRuntime(
+ graph_artifact_root=output_dir,
+ capability_provider=capabilities,
+ model=None,
+ orchestration_config=graph_build_orchestration_config_from_swarm(
+ runtime_config
+ ),
+ source_snapshot=expected_snapshot,
+ graph_config=graph_config_from_swarm(runtime_config),
+ )
+ stale = not identity_runtime.orchestration.status().fresh
+ except (FileNotFoundError, ValueError):
+ stale = True
resume_from = latest_incomplete_build(output_dir)
- detail = "score is fresh"
+ detail = "graph is fresh"
if not exists:
- detail = "Symphony Score is missing"
+ detail = "Symphony graph is missing"
elif stale:
- detail = "Symphony Score is stale"
+ detail = "Symphony graph is stale"
- return ScoreStatus(
+ return GraphStatus(
success=True,
- score_dir=str(output_dir),
+ graph_dir=str(output_dir),
exists=exists,
stale=stale,
skill_count=len(folders),
@@ -238,31 +259,30 @@ class SymphonyScoreBuilder:
async def build(
self,
skills_root: str | Path,
- score_dir: str | Path,
+ graph_dir: str | Path,
llm_config: LLMConfig | None = None,
*,
force: bool = False,
schema_extractor: SkillSchemaExtractor | None = None,
- matcher: OntologyMatcher | None = None,
io_name_resolver: Any | None = None,
build_log: Callable[..., None] | None = None,
symphony_config: SymphonyConfig | None = None,
resume: bool = True,
- ) -> ScoreBuildResult:
+ ) -> GraphBuildResult:
runtime_config = symphony_config or default_symphony_config()
- output_dir = Path(score_dir).resolve()
+ output_dir = Path(graph_dir).resolve()
output_dir.mkdir(parents=True, exist_ok=True)
reset_llm_token_usage()
run_id = _new_run_id()
checkpoint = _BuildCheckpoint(build_run_dir(output_dir, run_id))
- artifact_dir = build_artifact_dir(output_dir, run_id)
+ artifact_dir = build_run_dir(output_dir, run_id) / "artifacts"
artifact_dir.mkdir(parents=True, exist_ok=True)
resume_from = latest_incomplete_build(output_dir) if resume else None
checkpoint.record(
"update.start",
status="running",
skills_root=str(skills_root),
- score_dir=str(output_dir),
+ graph_dir=str(output_dir),
artifact_dir=str(artifact_dir),
force=force,
resume_from=str(resume_from) if resume_from is not None else "",
@@ -337,148 +357,186 @@ class SymphonyScoreBuilder:
fingerprint_count=len(extraction_result.fingerprints),
workers=runtime_config.build.workers,
)
- matcher = matcher or self.runtime_factory.matcher(
- llm_config,
- build_config=runtime_config.build,
- build_log=build_log,
- )
- if not force:
- matcher = CachedOntologyMatcher(
- matcher,
- output_dir / "cache" / "relation_matches.json",
- fingerprints=extraction_result.fingerprints,
- )
- 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,
- progress=build_log,
- )
- relation_cache_stats = getattr(matcher, "stats", None)
- relation_reused_count = int(getattr(relation_cache_stats, "reused_count", 0) or 0)
- relation_resolved_count = int(
- getattr(relation_cache_stats, "resolved_count", 0) or 0
- )
- checkpoint.record(
- "graph.done",
- status="running",
- edge_count=len(graph_result.graph.edges),
- relation_reused_count=relation_reused_count,
- relation_resolved_count=relation_resolved_count,
- )
- _record_build_log(
- build_log,
- "graph.build.done",
- candidate_count=len(graph_result.candidates),
- match_count=len(graph_result.llm_matches),
- edge_count=len(graph_result.graph.edges),
- diagnostics_count=len(graph_result.diagnostics),
- relation_reused_count=relation_reused_count,
- relation_resolved_count=relation_resolved_count,
+ capabilities = capabilities_from_skills(extraction_result.fingerprints)
+ source_snapshot = _graph_source_snapshot(
+ capabilities=capabilities,
+ current_hashes=extraction_result.current_hashes,
+ runtime_config=runtime_config,
+ llm_config=llm_config,
)
- _record_build_log(build_log, "artifact.graph.write.start")
- write_graph_build_result(graph_result, artifact_dir)
- _write_io_vocab(extraction_result.io_name_vocab, artifact_dir)
- _record_build_log(build_log, "artifact.graph.write.done")
-
new_state = self.state_builder.next_state(
folders=extraction_result.folders,
current_hashes=extraction_result.current_hashes,
fingerprints_by_path=extraction_result.fingerprints_by_path,
- old_state=load_score_state(output_dir),
+ old_state=load_graph_state(output_dir),
removed_paths=extraction_result.removed_paths,
)
- _record_build_log(
- build_log,
- "state.write.start",
- path=str(artifact_dir / SCORE_STATE_FILENAME),
+ prepared_graph: dict[str, Any] = {}
+ graph_resolution: dict[str, Any] = {}
+
+ def prepare_artifact(version_dir: Path) -> None:
+ """Complete the version before agent-core switches ``current.json``."""
+
+ graph_payload = json.loads(
+ (version_dir / "graph.json").read_text(encoding="utf-8")
+ )
+ prepared_graph.update(graph_payload)
+ edge_count = len(graph_payload.get("edges") or [])
+ relation_reused_count, relation_resolved_count = _relation_cache_counts(
+ graph_payload, force=force
+ )
+ graph_diagnostics = list(graph_payload.get("diagnostics") or [])
+ candidate_count = _nonnegative_int(
+ graph_resolution.get("candidate_count"),
+ fallback=0,
+ )
+ match_count = _nonnegative_int(
+ graph_resolution.get("match_count"),
+ fallback=edge_count,
+ )
+ accepted_match_count = _nonnegative_int(
+ graph_resolution.get("accepted_match_count"),
+ fallback=edge_count,
+ )
+ checkpoint.record(
+ "graph.done",
+ status="running",
+ edge_count=edge_count,
+ relation_reused_count=relation_reused_count,
+ relation_resolved_count=relation_resolved_count,
+ )
+ _record_build_log(
+ build_log,
+ "graph.build.done",
+ candidate_count=candidate_count,
+ match_count=match_count,
+ accepted_match_count=accepted_match_count,
+ edge_count=edge_count,
+ diagnostics_count=len(graph_diagnostics),
+ relation_reused_count=relation_reused_count,
+ relation_resolved_count=relation_resolved_count,
+ )
+ checkpoint.record("publish.start", status="running")
+ _record_build_log(build_log, "artifact.graph.write.start")
+ write_extraction_result(extraction_result, version_dir)
+ _write_io_vocab(extraction_result.io_name_vocab, version_dir)
+ _write_json_artifact(
+ get_llm_token_usage_summary(),
+ version_dir / "llm_token_usage.json",
+ )
+ _record_build_log(build_log, "artifact.graph.write.done")
+ _record_build_log(
+ build_log,
+ "state.write.start",
+ path=str(version_dir / GRAPH_STATE_FILENAME),
+ )
+ write_graph_state(new_state, version_dir)
+ _record_build_log(build_log, "state.write.done")
+
+ runtime = SymphonyRuntime(
+ graph_artifact_root=output_dir,
+ capability_provider=capabilities,
+ model=model_from_config(llm_config),
+ model_response_observer=(
+ model_response_observer_from_config(llm_config)
+ if llm_config is not None
+ else None
+ ),
+ orchestration_config=graph_build_orchestration_config_from_swarm(
+ runtime_config
+ ),
+ source_snapshot=source_snapshot,
+ graph_config=graph_config_from_swarm(runtime_config),
+ prepare_artifact=prepare_artifact,
)
- write_score_state(new_state, artifact_dir)
- _record_build_log(build_log, "state.write.done")
- checkpoint.record("publish.start", status="running")
- published_dir = publish_artifact_dir(
- output_dir,
- artifact_dir,
- version=run_id,
+ checkpoint.record("graph.start", status="running")
+ graph_build = await runtime.orchestration.build(
+ force=force,
+ progress=_public_progress_adapter(
+ build_log,
+ graph_resolution=graph_resolution,
+ ),
+ )
+ graph_payload = prepared_graph or runtime.orchestration.read().to_dict()
+ edge_count = len(graph_payload.get("edges") or [])
+ graph_diagnostics = list(graph_payload.get("diagnostics") or [])
+ relation_reused_count, relation_resolved_count = _relation_cache_counts(
+ graph_payload,
+ force=force,
)
+ published_dir = graph_build.graph_path.parent
checkpoint.record(
"publish.done",
status="success",
- version=run_id,
+ version=graph_build.version,
published_dir=str(published_dir),
)
+ _cleanup_published_build_artifacts(artifact_dir)
- return ScoreBuildResult(
+ return GraphBuildResult(
success=True,
- score_dir=str(output_dir),
+ graph_dir=str(output_dir),
skill_count=len(extraction_result.folders),
reused_count=extraction_result.reused_count,
extracted_count=extraction_result.extracted_count,
removed_count=len(extraction_result.removed_paths),
- edge_count=len(graph_result.graph.edges),
+ edge_count=edge_count,
diagnostics_count=(
- len(extraction_result.diagnostics) + len(graph_result.diagnostics)
+ len(extraction_result.diagnostics) + len(graph_diagnostics)
),
relation_reused_count=relation_reused_count,
relation_resolved_count=relation_resolved_count,
- version=run_id,
+ version=graph_build.version,
)
-def score_status(
+def graph_status(
skills_root: str | Path,
- score_dir: str | Path,
+ graph_dir: str | Path,
*,
scanner: SkillFolderScanner | None = None,
+ llm_config: LLMConfig | None = None,
symphony_config: SymphonyConfig | None = None,
-) -> ScoreStatus:
- """Report whether a Score exists and differs from the Skill folders."""
+) -> GraphStatus:
+ """Report whether a graph exists and differs from the Skill folders."""
- return SymphonyScoreBuilder(scanner=scanner).status(
+ return SymphonyGraphBuilder(scanner=scanner).status(
skills_root,
- score_dir,
+ graph_dir,
+ llm_config=llm_config,
symphony_config=symphony_config,
)
-async def build_score(
+async def build_graph(
skills_root: str | Path,
- score_dir: str | Path,
+ graph_dir: str | Path,
llm_config: LLMConfig | None = None,
*,
workers: int = 1,
force: bool = False,
schema_extractor: SkillSchemaExtractor | None = None,
- matcher: OntologyMatcher | None = None,
io_name_resolver: Any | None = None,
scanner: SkillFolderScanner | None = None,
parser: SkillManifestParser | None = None,
build_log: Callable[..., None] | None = None,
symphony_config: SymphonyConfig | None = None,
- runtime_factory: ScoreBuildRuntimeFactory | None = None,
+ runtime_factory: GraphBuildRuntimeFactory | None = None,
resume: bool = True,
-) -> ScoreBuildResult:
- """Build or refresh the offline Symphony Score."""
+) -> GraphBuildResult:
+ """Build or refresh the offline Symphony graph."""
del workers
- return await SymphonyScoreBuilder(
+ return await SymphonyGraphBuilder(
scanner=scanner,
parser=parser,
runtime_factory=runtime_factory,
).build(
skills_root,
- score_dir,
+ graph_dir,
llm_config,
force=force,
schema_extractor=schema_extractor,
- matcher=matcher,
io_name_resolver=io_name_resolver,
build_log=build_log,
symphony_config=symphony_config,
@@ -507,18 +565,65 @@ def _fingerprint_progress_adapter(
return record
-def _record_build_log(build_log: Callable[..., None] | None, stage: str, **details: Any) -> None:
+def _public_progress_adapter(
+ build_log: Callable[..., None] | None,
+ *,
+ graph_resolution: dict[str, Any] | None = None,
+) -> Callable[[dict[str, Any]], None] | None:
+ if build_log is None and graph_resolution is None:
+ return None
+
+ def record(event: dict[str, Any]) -> None:
+ stage = str(event.get("event") or "graph.progress")
+ if stage in {
+ "build_started",
+ "build_published",
+ "build_failed",
+ "build_cancelled",
+ }:
+ return
+ details = {key: value for key, value in event.items() if key != "event"}
+ if stage == "graph.resolve.done" and graph_resolution is not None:
+ graph_resolution.clear()
+ graph_resolution.update(details)
+ _record_build_log(build_log, stage, **details)
+
+ return record
+
+
+def _record_build_log(
+ build_log: Callable[..., None] | None, stage: str, **details: Any
+) -> None:
if build_log is not None:
build_log(stage, **details)
-def _write_io_vocab(payload: dict[str, Any], score_dir: Path) -> None:
- (score_dir / "io_name_vocab.json").write_text(
+def _write_io_vocab(payload: dict[str, Any], graph_dir: Path) -> None:
+ _write_json_artifact(payload, graph_dir / "io_name_vocab.json")
+
+
+def _write_json_artifact(payload: dict[str, Any], path: Path) -> None:
+ path.write_text(
json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8",
)
+def _cleanup_published_build_artifacts(artifact_dir: Path) -> None:
+ """Best-effort removal of the duplicate pre-publish artifact snapshot."""
+
+ try:
+ shutil.rmtree(artifact_dir)
+ except FileNotFoundError:
+ return
+ except OSError:
+ logger.warning(
+ "Failed to clean published Symphony build artifacts: %s",
+ artifact_dir,
+ exc_info=True,
+ )
+
+
class _BuildCheckpoint:
def __init__(self, run_dir: Path) -> None:
self.run_dir = run_dir
@@ -579,6 +684,99 @@ def _llm_signature(llm_config: LLMConfig | None) -> dict[str, Any]:
}
+def _graph_source_snapshot(
+ *,
+ capabilities: list[Any],
+ current_hashes: dict[str, str],
+ runtime_config: SymphonyConfig,
+ llm_config: LLMConfig | None,
+) -> dict[str, Any]:
+ return {
+ "schema_version": "JiuwenSwarm-symphony-graph-source-v1",
+ "capabilities_sha256": _capabilities_signature(capabilities),
+ "current_hashes": dict(sorted(current_hashes.items())),
+ "fingerprint_sha256": _fingerprint_signature(runtime_config, llm_config),
+ "fingerprint_config_sha256": _fingerprint_config_signature(runtime_config),
+ "graph_config": graph_config_from_swarm(runtime_config),
+ "llm_sha256": (
+ llm_config_signature(llm_config) if llm_config is not None else ""
+ ),
+ }
+
+
+def _graph_status_source_snapshot(
+ *,
+ capabilities: list[Any],
+ current_hashes: dict[str, str],
+ runtime_config: SymphonyConfig,
+ llm_config: LLMConfig | None,
+ artifact_source_snapshot: dict[str, Any],
+) -> dict[str, Any]:
+ fingerprint_sha256 = artifact_source_snapshot.get("fingerprint_sha256", "")
+ llm_sha256 = artifact_source_snapshot.get("llm_sha256", "")
+ if llm_config is not None:
+ fingerprint_sha256 = _fingerprint_signature(runtime_config, llm_config)
+ llm_sha256 = llm_config_signature(llm_config)
+ return {
+ "schema_version": "JiuwenSwarm-symphony-graph-source-v1",
+ "capabilities_sha256": _capabilities_signature(capabilities),
+ "current_hashes": dict(sorted(current_hashes.items())),
+ "fingerprint_sha256": fingerprint_sha256,
+ "fingerprint_config_sha256": _fingerprint_config_signature(runtime_config),
+ "graph_config": graph_config_from_swarm(runtime_config),
+ "llm_sha256": llm_sha256,
+ }
+
+
+def _capabilities_signature(capabilities: list[Any]) -> str:
+ payloads = [
+ item.to_dict() if hasattr(item, "to_dict") else dict(item)
+ for item in capabilities
+ ]
+ payloads.sort(
+ key=lambda item: str(item.get("capability_id") or item.get("id") or "")
+ )
+ return _stable_hash(payloads)
+
+
+def _fingerprint_config_signature(runtime_config: SymphonyConfig) -> str:
+ return _stable_hash(
+ {
+ "extraction_protocol": SCHEMA_EXTRACTION_PROTOCOL_VERSION,
+ "fingerprint": asdict(runtime_config.fingerprint),
+ }
+ )
+
+
+def _relation_cache_counts(
+ graph_payload: dict[str, Any],
+ *,
+ force: bool,
+) -> tuple[int, int]:
+ edge_count = len(graph_payload.get("edges") or [])
+ config = graph_payload.get("config")
+ llm = config.get("llm") if isinstance(config, dict) else None
+ relation_cache = llm.get("relation_cache") if isinstance(llm, dict) else None
+ if not isinstance(relation_cache, dict):
+ return 0, edge_count
+ reused_count = _nonnegative_int(
+ relation_cache.get("reused_count"),
+ fallback=0,
+ )
+ resolved_count = _nonnegative_int(
+ relation_cache.get("resolved_count"),
+ fallback=edge_count,
+ )
+ return (0 if force else reused_count), resolved_count
+
+
+def _nonnegative_int(value: Any, *, fallback: int) -> int:
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError, OverflowError):
+ return fallback
+
+
def _stable_hash(payload: Any) -> str:
return hashlib.sha256(
json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode(
diff --git a/jiuwenswarm/symphony/config.py b/jiuwenswarm/symphony/config.py
index e99bb59146..8140916256 100644
--- a/jiuwenswarm/symphony/config.py
+++ b/jiuwenswarm/symphony/config.py
@@ -3,12 +3,16 @@
from __future__ import annotations
import functools
+import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from jiuwenswarm.common.utils import get_agent_workspace_dir
+logger = logging.getLogger(__name__)
+
+_legacy_score_dir_warned = False
DEFAULT_FINGERPRINT_EXTRACTION_WORKERS = 1
DEFAULT_FINGERPRINT_EXTRACTION_BATCH_SIZE = 1
@@ -38,7 +42,7 @@ DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE = 0.5
@dataclass(frozen=True)
class SymphonyPathsConfig:
skills_root: Path
- score_dir: Path
+ graph_dir: Path
@dataclass(frozen=True)
@@ -122,6 +126,7 @@ def default_symphony_config() -> SymphonyConfig:
def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:
data = raw if isinstance(raw, dict) else {}
paths = data.get("paths") if isinstance(data.get("paths"), dict) else {}
+ _warn_legacy_score_dir(paths)
fingerprint = (
data.get("fingerprint") if isinstance(data.get("fingerprint"), dict) else {}
)
@@ -151,9 +156,9 @@ def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:
paths.get("skills_root"),
get_agent_workspace_dir() / "skills",
),
- score_dir=_resolve_path(
- paths.get("score_dir"),
- get_agent_workspace_dir() / "symphony" / "score",
+ graph_dir=_resolve_path(
+ paths.get("graph_dir"),
+ get_agent_workspace_dir() / "symphony" / "graph",
),
),
fingerprint=SymphonyFingerprintConfig(
@@ -242,6 +247,21 @@ def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:
)
+def _warn_legacy_score_dir(paths: dict[str, Any]) -> None:
+ # load_symphony_config 每轮聊天都会重跑,旧键迁移告警进程内只发一次。
+ global _legacy_score_dir_warned
+ if _legacy_score_dir_warned:
+ return
+ if not str(paths.get("score_dir") or "").strip():
+ return
+ _legacy_score_dir_warned = True
+ logger.warning(
+ "配置项 symphony.paths.score_dir 已更名为 symphony.paths.graph_dir,"
+ "旧键将被忽略;如需沿用既有构建产物与演进数据,"
+ "请将 symphony.paths.graph_dir 指向原 score 目录。"
+ )
+
+
@functools.lru_cache(maxsize=256)
def _resolve_path(value: Any, default: Path) -> Path:
# [PERF] load_symphony_config 每轮聊天都会重跑,symphony_config_from_dict
diff --git a/jiuwenswarm/symphony/evolution/aggregate.py b/jiuwenswarm/symphony/evolution/aggregate.py
index 291ad7d96d..d879ed684f 100644
--- a/jiuwenswarm/symphony/evolution/aggregate.py
+++ b/jiuwenswarm/symphony/evolution/aggregate.py
@@ -36,7 +36,7 @@ RUNTIME_WEIGHT_MAX = 2.0
def build_overlay_from_events(
events: list[dict[str, Any]],
*,
- base_score_version: str | None = None,
+ base_graph_version: str | None = None,
) -> dict[str, Any]:
"""Build a runtime overlay from append-only evolution events."""
@@ -129,7 +129,7 @@ def build_overlay_from_events(
}
return {
"schema_version": OVERLAY_SCHEMA_VERSION,
- "base_score_version": base_score_version or "",
+ "base_graph_version": base_graph_version or "",
"generated_at": generated_at,
"events": {
"count": len(events),
diff --git a/jiuwenswarm/symphony/evolution/models.py b/jiuwenswarm/symphony/evolution/models.py
index ea19529e9b..b26ff7ac2e 100644
--- a/jiuwenswarm/symphony/evolution/models.py
+++ b/jiuwenswarm/symphony/evolution/models.py
@@ -38,7 +38,7 @@ def edge_key(source: Any, target: Any, relation_type: str = CAN_FEED) -> str:
def skill_id(node_id: Any) -> str:
text = str(node_id or "")
- return text.removeprefix("skill:")
+ return text.removeprefix("skill:").removeprefix("capability:")
def normalize_edge(item: Any) -> dict[str, Any] | None:
diff --git a/jiuwenswarm/symphony/evolution/service.py b/jiuwenswarm/symphony/evolution/service.py
index 6b69b306df..612588515b 100644
--- a/jiuwenswarm/symphony/evolution/service.py
+++ b/jiuwenswarm/symphony/evolution/service.py
@@ -31,41 +31,41 @@ from jiuwenswarm.symphony.evolution.store import (
)
-def load_dynamic_overlay(score_dir: str | Path) -> dict[str, Any] | None:
+def load_dynamic_overlay(graph_dir: str | Path) -> dict[str, Any] | None:
"""Load the current dynamic overlay if it exists."""
- return read_overlay(score_dir)
+ return read_overlay(graph_dir)
def rebuild_dynamic_overlay(
- score_dir: str | Path,
+ graph_dir: str | Path,
*,
- base_score_version: str | None = None,
+ base_graph_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)
+ events = read_events(graph_dir)
overlay = build_overlay_from_events(
events,
- base_score_version=base_score_version,
+ base_graph_version=base_graph_version,
)
- write_overlay(score_dir, overlay)
+ write_overlay(graph_dir, overlay)
return overlay
-def evolution_status(score_dir: str | Path) -> dict[str, Any]:
+def evolution_status(graph_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)
+ events = read_events(graph_dir)
+ overlay = read_overlay(graph_dir)
+ overlay_mtime = overlay_file_mtime(graph_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)),
+ "graph_dir": str(graph_dir),
+ "event_log": str(events_path(graph_dir)),
+ "overlay_path": str(overlay_path(graph_dir)),
"event_count": len(events),
"last_event_at": _last_event_ts(events),
"overlay_exists": overlay is not None,
@@ -82,7 +82,7 @@ def evolution_status(score_dir: str | Path) -> dict[str, Any]:
session_feedback_status,
)
- payload["session_feedback"] = session_feedback_status(score_dir)
+ payload["session_feedback"] = session_feedback_status(graph_dir)
except Exception: # noqa: BLE001
payload["session_feedback"] = {
"source": "session_history",
@@ -92,7 +92,7 @@ def evolution_status(score_dir: str | Path) -> dict[str, Any]:
def record_plan_outcome(
- score_dir: str | Path,
+ graph_dir: str | Path,
*,
plan_id: str,
outcome: str,
@@ -155,16 +155,16 @@ def record_plan_outcome(
existing = next(
(
item
- for item in read_events(score_dir)
+ for item in read_events(graph_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)
+ append_event(graph_dir, event)
if rebuild_overlay:
- rebuild_dynamic_overlay(score_dir)
+ rebuild_dynamic_overlay(graph_dir)
return event
diff --git a/jiuwenswarm/symphony/evolution/session_consumer.py b/jiuwenswarm/symphony/evolution/session_consumer.py
index a9228447d2..c3d824e468 100644
--- a/jiuwenswarm/symphony/evolution/session_consumer.py
+++ b/jiuwenswarm/symphony/evolution/session_consumer.py
@@ -19,7 +19,7 @@ from jiuwenswarm.server.runtime.session.session_history import (
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
+from jiuwenswarm.symphony.graph_storage import resolve_graph_artifact_dir
LOGGER = logging.getLogger(__name__)
@@ -32,9 +32,9 @@ _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",
+ "symphony_compose_graph",
+ "symphony_read_graph",
+ "symphony_refresh_graph",
}
_CONTINUATION_RE = re.compile(
r"(?:"
@@ -62,8 +62,8 @@ _EXECUTOR = ThreadPoolExecutor(
)
-def session_feedback_state_path(score_dir: str | Path) -> Path:
- return Path(score_dir) / "evolution" / SESSION_FEEDBACK_STATE_FILE
+def session_feedback_state_path(graph_dir: str | Path) -> Path:
+ return Path(graph_dir) / "evolution" / SESSION_FEEDBACK_STATE_FILE
def schedule_session_evolution_consume(
@@ -80,12 +80,12 @@ def schedule_session_evolution_consume(
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)
+ graph_dir = resolve_graph_artifact_dir(config.paths.graph_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)
+ schedule_key = (str(graph_dir), clean_session_id, clean_request_id)
with _SCHEDULE_LOCK:
if schedule_key in _SCHEDULED:
return False
@@ -95,7 +95,7 @@ def schedule_session_evolution_consume(
_consume_after_history_ready,
clean_session_id,
clean_request_id,
- score_dir,
+ graph_dir,
)
future.add_done_callback(lambda current: _on_consume_done(schedule_key, current))
return True
@@ -104,14 +104,14 @@ def schedule_session_evolution_consume(
def _consume_after_history_ready(
session_id: str,
request_id: str,
- score_dir: Path,
+ graph_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,
+ graph_dir=graph_dir,
history_limit_bytes=history_limit,
)
@@ -139,7 +139,7 @@ def consume_session_history(
session_id: str,
*,
completed_request_id: str = "",
- score_dir: str | Path | None = None,
+ graph_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."""
@@ -147,7 +147,7 @@ def consume_session_history(
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:
+ if graph_dir is None:
config = load_symphony_config()
if not config.enabled or not config.evolution.enabled:
return {
@@ -156,12 +156,12 @@ def consume_session_history(
"recorded": False,
"source": SESSION_FEEDBACK_SOURCE,
}
- score_dir = resolve_score_artifact_dir(config.paths.score_dir)
- resolved_score_dir = Path(score_dir).resolve()
+ graph_dir = resolve_graph_artifact_dir(config.paths.graph_dir)
+ resolved_graph_dir = Path(graph_dir).resolve()
history_path = get_read_history_path(clean_session_id)
with _STATE_LOCK:
- state = _read_state(resolved_score_dir)
+ state = _read_state(resolved_graph_dir)
sessions = state.setdefault("sessions", {})
session_state = dict(sessions.get(clean_session_id) or {})
try:
@@ -175,7 +175,7 @@ def consume_session_history(
records,
session_id=clean_session_id,
session_state=session_state,
- score_dir=resolved_score_dir,
+ graph_dir=resolved_graph_dir,
)
session_state.update(cursor)
session_state["updated_at"] = _utc_now()
@@ -184,11 +184,11 @@ def consume_session_history(
state["last_error"] = ""
state["updated_at"] = _utc_now()
_prune_sessions(sessions)
- _write_state(resolved_score_dir, state)
+ _write_state(resolved_graph_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)
+ _write_state(resolved_graph_dir, state)
LOGGER.exception(
"Failed to consume Symphony session feedback: session_id=%s request_id=%s",
clean_session_id,
@@ -212,23 +212,23 @@ def consume_session_history(
}
-def session_feedback_status(score_dir: str | Path) -> dict[str, Any]:
+def session_feedback_status(graph_dir: str | Path) -> dict[str, Any]:
"""Return frontend-safe observability for the session feedback worker."""
- resolved_score_dir = Path(score_dir).resolve()
+ resolved_graph_dir = Path(graph_dir).resolve()
with _STATE_LOCK:
- state = _read_state(resolved_score_dir)
+ state = _read_state(resolved_graph_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)
+ 1 for item in _SCHEDULED if item[0] == str(resolved_graph_dir)
)
return {
"available": True,
"source": SESSION_FEEDBACK_SOURCE,
"mode": "incremental_async",
- "state_path": str(session_feedback_state_path(resolved_score_dir)),
+ "state_path": str(session_feedback_state_path(resolved_graph_dir)),
"tracked_session_count": len(sessions),
"pending_plan_count": sum(
1
@@ -251,7 +251,7 @@ def _consume_records(
*,
session_id: str,
session_state: dict[str, Any],
- score_dir: Path,
+ graph_dir: Path,
) -> list[dict[str, Any]]:
pending = (
dict(session_state.get("pending_plan") or {})
@@ -260,7 +260,7 @@ def _consume_records(
)
results: list[dict[str, Any]] = []
for request_id, request_records in _group_by_request(records):
- markers = _plan_markers(request_records, score_dir=score_dir)
+ markers = _plan_markers(request_records, graph_dir=graph_dir)
if markers:
# A new plan supersedes an older plan that the user never executed.
@@ -271,7 +271,7 @@ def _consume_records(
request_records,
session_id=session_id,
request_id=request_id,
- score_dir=score_dir,
+ graph_dir=graph_dir,
same_turn=False,
)
if result is not None:
@@ -292,7 +292,7 @@ def _consume_records(
trailing_records,
session_id=session_id,
request_id=request_id,
- score_dir=score_dir,
+ graph_dir=graph_dir,
same_turn=True,
)
if result is not None:
@@ -312,7 +312,7 @@ def _consume_execution_turn(
*,
session_id: str,
request_id: str,
- score_dir: Path,
+ graph_dir: Path,
same_turn: bool,
) -> dict[str, Any] | None:
correlation = _execution_correlation(pending, records, same_turn=same_turn)
@@ -339,7 +339,7 @@ def _consume_execution_turn(
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,
+ graph_dir,
plan_id=str(pending["plan_id"]),
query=str(pending.get("query") or ""),
outcome=outcome,
@@ -379,13 +379,13 @@ def _consume_execution_turn(
def _plan_markers(
records: list[dict[str, Any]],
*,
- score_dir: Path,
+ graph_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":
+ if str(record.get("tool_name") or "") != "symphony_compose_graph":
continue
raw_output = record.get("raw_output")
if not isinstance(raw_output, dict):
@@ -396,7 +396,7 @@ def _plan_markers(
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):
+ if not plan_id or not _graph_dir_matches(raw_output.get("graph_dir"), graph_dir):
continue
selected_skill_ids = []
for step in plan.get("steps") or []:
@@ -807,8 +807,8 @@ def _read_new_jsonl_records(
}
-def _read_state(score_dir: Path) -> dict[str, Any]:
- path = session_feedback_state_path(score_dir)
+def _read_state(graph_dir: Path) -> dict[str, Any]:
+ path = session_feedback_state_path(graph_dir)
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
@@ -822,8 +822,8 @@ def _read_state(score_dir: Path) -> dict[str, Any]:
return payload
-def _write_state(score_dir: Path, state: dict[str, Any]) -> None:
- path = session_feedback_state_path(score_dir)
+def _write_state(graph_dir: Path, state: dict[str, Any]) -> None:
+ path = session_feedback_state_path(graph_dir)
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_suffix(".json.tmp")
tmp_path.write_text(
@@ -859,7 +859,7 @@ def _update_state_stats(
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":
+ if record.get("tool_name") != "symphony_compose_graph":
return False
raw_output = record.get("raw_output")
if not isinstance(raw_output, dict):
@@ -881,12 +881,12 @@ def _prune_sessions(sessions: dict[str, Any]) -> None:
sessions.update(ordered[:_MAX_TRACKED_SESSIONS])
-def _score_dir_matches(value: Any, score_dir: Path) -> bool:
+def _graph_dir_matches(value: Any, graph_dir: Path) -> bool:
text = str(value or "").strip()
if not text:
return True
try:
- return Path(text).resolve() == score_dir.resolve()
+ return Path(text).resolve() == graph_dir.resolve()
except OSError:
return False
diff --git a/jiuwenswarm/symphony/evolution/store.py b/jiuwenswarm/symphony/evolution/store.py
index 5319a5d391..86e2db3b5f 100644
--- a/jiuwenswarm/symphony/evolution/store.py
+++ b/jiuwenswarm/symphony/evolution/store.py
@@ -22,33 +22,33 @@ def evolution_store_transaction() -> Iterator[None]:
yield
-def evolution_dir(score_dir: str | Path) -> Path:
- return Path(score_dir) / EVENT_DIR
+def evolution_dir(graph_dir: str | Path) -> Path:
+ return Path(graph_dir) / EVENT_DIR
-def events_path(score_dir: str | Path) -> Path:
- return evolution_dir(score_dir) / EVENTS_FILE
+def events_path(graph_dir: str | Path) -> Path:
+ return evolution_dir(graph_dir) / EVENTS_FILE
-def overlay_path(score_dir: str | Path) -> Path:
- return evolution_dir(score_dir) / OVERLAY_FILE
+def overlay_path(graph_dir: str | Path) -> Path:
+ return evolution_dir(graph_dir) / OVERLAY_FILE
-def append_event(score_dir: str | Path, event: dict[str, Any]) -> None:
+def append_event(graph_dir: str | Path, event: dict[str, Any]) -> None:
with _STORE_LOCK:
- path = events_path(score_dir)
+ path = events_path(graph_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,
+ graph_dir: str | Path,
*,
limit: int | None = None,
) -> list[dict[str, Any]]:
with _STORE_LOCK:
- path = events_path(score_dir)
+ path = events_path(graph_dir)
if not path.is_file():
return []
try:
@@ -68,9 +68,9 @@ def read_events(
return events
-def write_overlay(score_dir: str | Path, overlay: dict[str, Any]) -> None:
+def write_overlay(graph_dir: str | Path, overlay: dict[str, Any]) -> None:
with _STORE_LOCK:
- path = overlay_path(score_dir)
+ path = overlay_path(graph_dir)
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_suffix(".json.tmp")
tmp_path.write_text(
@@ -80,9 +80,9 @@ def write_overlay(score_dir: str | Path, overlay: dict[str, Any]) -> None:
tmp_path.replace(path)
-def read_overlay(score_dir: str | Path) -> dict[str, Any] | None:
+def read_overlay(graph_dir: str | Path) -> dict[str, Any] | None:
with _STORE_LOCK:
- path = overlay_path(score_dir)
+ path = overlay_path(graph_dir)
if not path.is_file():
return None
try:
@@ -92,9 +92,9 @@ def read_overlay(score_dir: str | Path) -> dict[str, Any] | None:
return payload if isinstance(payload, dict) else None
-def overlay_file_mtime(score_dir: str | Path) -> float | None:
+def overlay_file_mtime(graph_dir: str | Path) -> float | None:
with _STORE_LOCK:
- path = overlay_path(score_dir)
+ path = overlay_path(graph_dir)
try:
return path.stat().st_mtime
except OSError:
diff --git a/jiuwenswarm/symphony/experience/__init__.py b/jiuwenswarm/symphony/experience/__init__.py
deleted file mode 100644
index 5ba54642ec..0000000000
--- a/jiuwenswarm/symphony/experience/__init__.py
+++ /dev/null
@@ -1,58 +0,0 @@
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
- from .bank import ExperienceBank
- from .distiller import TraceDistiller
- from .cluster import cluster_traces, ClusteredQuery
- from .collector import ExperienceBaseBuilder
- from .embed import EmbeddingClient
- from .retriever import ExperienceRetriever
-
-from .evaluator import TraceEvaluator
-from .models import TraceRecord, DistilledPattern, ExperienceBankBuildConfig
-from .trace import (
- list_session_ids,
- parse_all_sessions,
- parse_session,
- parse_and_store,
- load_all_records,
- clear_store,
-)
-
-__all__ = [
- "TraceRecord",
- "DistilledPattern",
- "ExperienceBankBuildConfig",
- "list_session_ids",
- "parse_session",
- "parse_all_sessions",
- "TraceEvaluator",
- "parse_and_store",
- "load_all_records",
- "clear_store",
- "ExperienceBank",
- "TraceDistiller",
- "cluster_traces",
- "ClusteredQuery",
- "ExperienceBaseBuilder",
- 'EmbeddingClient',
- 'ExperienceRetriever'
-]
-
-
-def __getattr__(name):
- """Lazy import for modules that depend on optional packages (faiss, etc.)."""
- lazy = {
- "ExperienceBank": ".bank",
- "TraceDistiller": ".distiller",
- "cluster_traces": ".cluster",
- "ClusteredQuery": ".cluster",
- "ExperienceBaseBuilder": ".collector",
- "EmbeddingClient": ".embed",
- "ExperienceRetriever": ".retriever",
- }
- if name in lazy:
- import importlib
- mod = importlib.import_module(lazy[name], __package__)
- return getattr(mod, name)
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/jiuwenswarm/symphony/experience/bank.py b/jiuwenswarm/symphony/experience/bank.py
deleted file mode 100644
index 8864d99c9e..0000000000
--- a/jiuwenswarm/symphony/experience/bank.py
+++ /dev/null
@@ -1,568 +0,0 @@
-from __future__ import annotations
-
-import hashlib
-import json
-import logging
-import os
-import threading
-import time
-from dataclasses import dataclass
-from pathlib import Path
-
-import faiss
-import numpy as np
-
-from .embed import EmbeddingClient
-from .models import ExperienceItem
-
-LOGGER = logging.getLogger(__name__)
-
-_META_FILE = "meta.json"
-_SCALAR_DIR = "scalar"
-_SCALAR_FILE = "metadata.jsonl"
-_VECTOR_DIR = "vector"
-_FAISS_FILE = "faiss_index.bin"
-_EMBED_FILE = "embeddings.npy"
-_HASH_CHUNK_SIZE = 8192
-
-
-@dataclass
-class _KnowledgeMeta:
- version: int = 1
- vector_count: int = 0
- vector_algorithm: str = "Flat"
- vector_dimension: int = 0
- vector_sha256: str = ""
- scalar_sha256: str = ""
- embeddings_sha256: str = ""
-
-
-def _win_retry(func, retries: int = 3, delay: float = 0.1):
- """Retry a callable on Windows file-lock errors."""
- for i in range(retries):
- try:
- return func()
- except OSError:
- if i == retries - 1:
- raise
- time.sleep(delay)
- return None # Unreachable, satisfies static analysis
-
-
-def _sha256_file(path: Path) -> str:
- h = hashlib.sha256()
- with _win_retry(lambda: open(path, "rb")) as f:
- for chunk in iter(lambda: f.read(_HASH_CHUNK_SIZE), b""):
- h.update(chunk)
- return h.hexdigest()
-
-
-
-
-def _build_faiss_index(algorithm: str, dim: int) -> tuple[faiss.Index, str]:
- actual_algorithm = algorithm
- try:
- index = faiss.index_factory(dim, algorithm, faiss.METRIC_INNER_PRODUCT)
- except (RuntimeError, ValueError) as exc:
- LOGGER.warning(
- "ExperienceBank: index_factory failed for '%s' (dim=%d): %s",
- algorithm, dim, exc,
- exc_info=True,
- )
- raise
-
- # IVF-style indices need training before adding vectors
- if isinstance(index, faiss.IndexIVF):
- index.nprobe = 10 # reasonable default for search recall
-
- return index, actual_algorithm
-
-
-def _write_atomic(source: Path, target: Path) -> None:
- """Atomically replace *target* with *source* (Windows-safe)."""
- if not source.exists():
- return
- try:
- _win_retry(lambda: os.replace(str(source), str(target)), retries=5, delay=0.2)
- except FileNotFoundError:
- LOGGER.warning("_write_atomic: source, target file vanished/locked during replace")
- raise
- except Exception:
- LOGGER.warning("_write_atomic failed", exc_info=True)
- raise
-
-
-class ExperienceBank:
- """Persistent knowledge base for experience items.
-
- Storage layout (directory-based)::
-
- experience_kb/
- ├── meta.json # integrity manifest
- ├── scalar/
- │ └── metadata.jsonl # item metadata (no embeddings)
- └── vector/
- ├── faiss_index.bin # FAISS index
- └── embeddings.npy # embedding matrix
-
- All items are loaded into memory; FAISS provides fast search.
- """
-
- def __init__(
- self,
- index_dir: str | Path,
- embedding_client: EmbeddingClient,
- *,
- vector_algorithm: str = "Flat",
- ) -> None:
- self._dir = Path(index_dir)
- self._embedder = embedding_client
- self._vector_algorithm = vector_algorithm
- self._items: list[ExperienceItem] = []
- self._id_index: dict[str, ExperienceItem] = {}
- self._skills: set[frozenset] = set()
- self._embedding_matrix: np.ndarray | None = None
- self._faiss_index: faiss.Index | None = None
- self._write_lock = threading.Lock()
- self._next_id_counter = 0
- self._load()
-
- # ------------------------------------------------------------------
- # CRUD
- # ------------------------------------------------------------------
-
- @property
- def items(self) -> list[ExperienceItem]:
- return list(self._items)
-
- @property
- def count(self) -> int:
- return len(self._items)
-
- def exist(self, skills: list[str]) -> bool:
- return frozenset(skills) in self._skills
-
- def add(self, item: ExperienceItem) -> None:
- """Add a new experience item to the KB and persist."""
- with self._write_lock:
- self._items.append(item)
- self._id_index[item.id] = item
- self._skills.add(frozenset(item.skill_ids))
- self._rebuild_index()
- self._persist()
-
- def add_batch(self, items: list[ExperienceItem]) -> None:
- """Add multiple items at once, rebuilding index and persisting only once."""
- if not items:
- return
- with self._write_lock:
- for item in items:
- self._items.append(item)
- self._id_index[item.id] = item
- self._skills.add(frozenset(item.skill_ids))
- self._rebuild_index()
- self._persist()
-
- def remove(self, item_id: str) -> bool:
- """Remove an item by id. Returns True if found and removed."""
- with self._write_lock:
- item = self._id_index.pop(item_id, None)
- if item is None:
- return False
- self._items = [i for i in self._items if i.id != item_id]
- self._skills.discard(frozenset(item.skill_ids))
- self._rebuild_index()
- self._persist()
- return True
-
- # ------------------------------------------------------------------
- # FAISS search
- # ------------------------------------------------------------------
-
- def search_by_embedding(
- self,
- query: str,
- top_k: int = 1,
- threshold: float = 0.80,
- ) -> list[tuple[float, ExperienceItem]]:
- """Search the KB by embedding similarity using FAISS.
-
- Returns a list of (similarity_score, item) sorted descending.
- Items below threshold are excluded.
- """
- if self._faiss_index is None or not self._items:
- return []
-
- query_emb = self._embedder.embed(query)
- query_vec = np.asarray([query_emb], dtype=np.float32)
-
- k = min(top_k, len(self._items))
- distances, indices = self._faiss_index.search(query_vec, k)
-
- results = []
- for i in range(k):
- if i >= len(indices[0]):
- break
- idx = int(indices[0][i])
- score = float(distances[0][i])
- if score >= threshold and idx < len(self._items):
- results.append((score, self._items[idx]))
-
- return results
-
- def search_with_skill_ids(
- self,
- query: str,
- top_k: int = 1,
- threshold: float = 0.80,
- ) -> list[str]:
- """Convenience: return just the skill_ids of the best match."""
- results = self.search_by_embedding(query, top_k=top_k, threshold=threshold)
- skills: list[str] = []
- for _sim, item in results:
- for sid in item.skill_ids:
- if sid not in skills:
- skills.append(sid)
- return skills
-
- # ------------------------------------------------------------------
- # Persistence
- # ------------------------------------------------------------------
-
- def _load(self) -> None:
- meta_path = self._dir / _META_FILE
- scalar_path = self._dir / _SCALAR_DIR / _SCALAR_FILE
- vector_dir = self._dir / _VECTOR_DIR
- faiss_path = vector_dir / _FAISS_FILE
- emb_path = vector_dir / _EMBED_FILE
-
- meta_exists = meta_path.exists()
- scalar_exists = scalar_path.exists()
- faiss_exist = faiss_path.exists()
- emb_exists = emb_path.exists()
-
- if not any([meta_exists, scalar_exists, faiss_exist, emb_exists]):
- LOGGER.info("ExperienceBank: index directory is empty, starting empty")
- return
-
- if not meta_exists:
- raise FileNotFoundError(
- f"ExperienceBank: meta.json missing but other index files present"
- )
- if not scalar_exists:
- raise FileNotFoundError(
- f"ExperienceBank: scalar/metadata.jsonl missing but other index files present "
- )
- if not faiss_path.exists():
- raise FileNotFoundError(
- f"ExperienceBank: vector/{_FAISS_FILE} missing but other index files present"
- )
- if not emb_path.exists():
- raise FileNotFoundError(
- f"ExperienceBank: vector/{_EMBED_FILE} missing but other index files present"
- )
-
- try:
- meta_data = json.loads(meta_path.read_text(encoding="utf-8"))
- meta = _KnowledgeMeta(**meta_data)
- except Exception as exc:
- LOGGER.error("ExperienceBank: failed to parse manifest: %s", exc, exc_info=True)
- raise
-
- if not self._validate_hashes(meta, scalar_path, faiss_path, emb_path):
- raise ValueError(
- "ExperienceBank: integrity check failed — manifest does not match on-disk files"
- )
-
- try:
- # 1. Load scalar metadata
- with open(scalar_path, "r", encoding="utf-8") as f:
- for line in f:
- line = line.strip()
- if not line:
- continue
- data = json.loads(line)
- item = ExperienceItem.from_dict(data)
- self._items.append(item)
- self._id_index[item.id] = item
- self._skills.add(frozenset(item.skill_ids))
-
- # 2. Load embeddings matrix and re-hydrate in-memory items
- self._embedding_matrix = np.load(str(emb_path))
- # Re-normalize to ensure IndexFlatIP inner product = cosine similarity
- if self._embedding_matrix is not None and len(self._embedding_matrix) > 0:
- norms = np.linalg.norm(self._embedding_matrix, axis=1, keepdims=True)
- norms[norms == 0] = 1.0
- self._embedding_matrix = self._embedding_matrix / norms
- for i, item in enumerate(self._items):
- if i < len(self._embedding_matrix):
- item.embedding = self._embedding_matrix[i].tolist()
-
- # 3. Load FAISS index
- self._faiss_index = faiss.read_index(str(faiss_path))
-
- if not self._validate_counts(meta):
- raise ValueError(
- "ExperienceBank: integrity check failed — manifest counts do not match loaded data"
- )
-
- # 4. Initialize ID counter from max existing ID
- if self._items:
- max_id = 0
- for item in self._items:
- if item.id.startswith("exp_"):
- try:
- num = int(item.id.split("_")[1])
- max_id = max(max_id, num)
- except (IndexError, ValueError) as exc:
- LOGGER.warning(
- "ExperienceBank: malformed item id %r while initializing id counter: %s",
- item.id, exc,
- exc_info=True,
- )
- raise
- self._next_id_counter = max_id + 1
-
- LOGGER.info("ExperienceBank: loaded %d items", len(self._items))
- except Exception as exc:
- LOGGER.error("ExperienceBank: failed to load data: %s", exc, exc_info=True)
- raise
-
-
- @staticmethod
- def _validate_hashes(
- meta: _KnowledgeMeta,
- scalar_path: Path,
- faiss_path: Path,
- emb_path: Path,
- ) -> bool:
- """Return True iff the manifest declares all three sha256 values
- and each matches the corresponding on-disk file.
-
- All three fields (scalar_sha256, vector_sha256, embeddings_sha256)
- MUST be non-empty and MUST hash-match their files. An empty field
- is treated as a corrupt/missing manifest entry — return False.
- File existence is already enforced by ``_load``'s pre-check.
- """
- if not meta.scalar_sha256:
- LOGGER.error("ExperienceBank: manifest missing scalar_sha256")
- return False
- scalar_actual = _sha256_file(scalar_path)
- if scalar_actual != meta.scalar_sha256:
- LOGGER.error("ExperienceBank: scalar sha256 mismatch")
- return False
-
- if not meta.vector_sha256:
- LOGGER.error("ExperienceBank: manifest missing vector_sha256")
- return False
- faiss_actual = _sha256_file(faiss_path)
- if faiss_actual != meta.vector_sha256:
- LOGGER.error("ExperienceBank: faiss sha256 mismatch")
- return False
-
- if not meta.embeddings_sha256:
- LOGGER.error("ExperienceBank: manifest missing embeddings_sha256")
- return False
- emb_actual = _sha256_file(emb_path)
- if emb_actual != meta.embeddings_sha256:
- LOGGER.error("ExperienceBank: embeddings sha256 mismatch")
- return False
-
- return True
-
- def _validate_counts(self, meta: _KnowledgeMeta) -> bool:
- """Return True iff loaded in-memory data matches the manifest counts.
-
- Runs after scalar + embedding data is loaded — compares against
- ``self._items`` and ``self._embedding_matrix``. The manifest's
- ``vector_count`` must equal BOTH the number of loaded items AND
- the number of embedding rows; a mismatch between items and
- embedding rows (even if both are non-zero) is also a failure.
- """
- if meta.vector_count != len(self._items):
- LOGGER.error(
- "ExperienceBank: vector_count mismatch — manifest=%d, items=%d",
- meta.vector_count, len(self._items),
- )
- return False
- if self._embedding_matrix is None:
- LOGGER.error("ExperienceBank: embeddings matrix not loaded")
- return False
- if len(self._embedding_matrix) != meta.vector_count:
- LOGGER.error(
- "ExperienceBank: embedding row count mismatch — manifest=%d, rows=%d",
- meta.vector_count, len(self._embedding_matrix),
- )
- return False
-
- if meta.vector_dimension and self._embedding_matrix is not None:
- actual_dim = self._embedding_matrix.shape[1]
- if meta.vector_dimension != actual_dim:
- LOGGER.error(
- "ExperienceBank: vector_dimension mismatch — manifest=%d, actual=%d",
- meta.vector_dimension, actual_dim,
- )
- return False
-
- return True
-
-
- def _persist(self) -> None:
- """Persist to index_dir atomically with an integrity manifest."""
- # Ensure root directory exists first
-
- if self._faiss_index is None or self._embedding_matrix is None:
- LOGGER.error("faiss index or embedding matrix is None")
- return
- self._dir.mkdir(parents=True, exist_ok=True)
-
- scalar_dir = self._dir / _SCALAR_DIR
- vector_dir = self._dir / _VECTOR_DIR
- scalar_dir.mkdir(parents=True, exist_ok=True)
- vector_dir.mkdir(parents=True, exist_ok=True)
-
- scalar_path = scalar_dir / _SCALAR_FILE
- faiss_path = vector_dir / _FAISS_FILE
- emb_path = vector_dir / _EMBED_FILE
-
- tmp_scalar = scalar_dir / (_SCALAR_FILE + ".tmp")
- tmp_faiss = vector_dir / "faiss_tmp"
-
- tmp_emb_src = vector_dir / "embed_tmp"
- tmp_emb = tmp_emb_src.with_suffix(".npy")
- tmp_meta = self._dir / (_META_FILE + ".tmp")
-
- written_tmps: list[Path] = []
- try:
- with open(tmp_scalar, "w", encoding="utf-8") as f:
- for item in self._items:
- f.write(json.dumps(item.to_dict(), ensure_ascii=False) + "\n")
- written_tmps.append(tmp_scalar)
-
-
- faiss.write_index(self._faiss_index, str(tmp_faiss))
- written_tmps.append(tmp_faiss)
-
-
- np.save(str(tmp_emb_src), self._embedding_matrix)
- written_tmps.append(tmp_emb)
-
- dim = self._embedding_matrix.shape[1] if self._embedding_matrix is not None else 0
- meta = _KnowledgeMeta(
- vector_count=len(self._items),
- vector_algorithm=self._vector_algorithm,
- vector_dimension=dim,
- vector_sha256=_sha256_file(tmp_faiss),
- scalar_sha256=_sha256_file(tmp_scalar),
- embeddings_sha256=_sha256_file(tmp_emb),
- )
- tmp_meta.write_text(
- json.dumps(meta.__dict__, ensure_ascii=False, indent=2) + "\n",
- encoding="utf-8",
- )
- written_tmps.append(tmp_meta)
-
- _write_atomic(tmp_faiss, faiss_path)
- _write_atomic(tmp_emb, emb_path)
- _write_atomic(tmp_scalar, scalar_path)
- _write_atomic(tmp_meta, self._dir / _META_FILE)
- except Exception:
- LOGGER.error(
- "ExperienceBank: persist failed, cleaning up temp files",
- exc_info=True,
- )
- for p in written_tmps:
- try:
- p.unlink(missing_ok=True)
- except OSError:
- LOGGER.warning("ExperienceBank: failed to clean up temp file", exc_info=True)
- raise
-
- # ------------------------------------------------------------------
- # Index management
- # ------------------------------------------------------------------
-
- def _rebuild_index(self) -> None:
- """Rebuild FAISS index and embedding matrix from current _items."""
- if not self._items:
- self._faiss_index = None
- self._embedding_matrix = None
- return
-
- embeddings = []
- for item in self._items:
- if item.embedding:
- embeddings.append(item.embedding)
-
- if not embeddings:
- self._faiss_index = None
- self._embedding_matrix = None
- return
-
- arr = np.array(embeddings, dtype=np.float32)
- dim = arr.shape[1]
-
- index, actual_algorithm = _build_faiss_index(self._vector_algorithm, dim)
- self._vector_algorithm = actual_algorithm
-
- # IVF-style indices require training on the dataset first
- if isinstance(index, faiss.IndexIVF):
- if len(arr) >= index.nlist:
- index.train(arr)
- else:
- # Too few vectors for IVF; fall back to Flat
- LOGGER.info(
- "ExperienceBank: too few vectors (%d) for IVF nlist=%d, falling back to Flat",
- len(arr), index.nlist,
- )
- index = faiss.index_factory(dim, "Flat", faiss.METRIC_INNER_PRODUCT)
- self._vector_algorithm = "Flat"
- index.add(arr)
-
- self._faiss_index = index
- self._embedding_matrix = arr
-
- # ------------------------------------------------------------------
- # Helpers
- # ------------------------------------------------------------------
-
- def generate_id(self) -> str:
- cid = self._next_id_counter
- self._next_id_counter += 1
- return f"exp_{cid:04d}"
-
- def create_item(
- self,
- query_pattern: str,
- query_examples: list[str],
- skill_ids: list[str],
- success_count: int = 1,
- ) -> ExperienceItem:
- """Create an ExperienceItem with auto-generated embedding and id.
-
- The embedding is derived from ``query_pattern`` only — a generalized
- template carries the skill's intent cleanly, while concatenating raw
- query_examples would dilute it with concrete entities and let
- same-domain (but wrong) skills cross the threshold. ``query_examples``
- is still stored on the item for display / debugging, just not embedded.
- """
- text_for_embedding = query_pattern or ""
- embedding = self._embedder.embed(text_for_embedding)
-
- return ExperienceItem(
- id=self.generate_id(),
- query_pattern=query_pattern,
- query_examples=query_examples,
- skill_ids=skill_ids,
- success_count=success_count,
- embedding=embedding,
- created_at=_now(),
- last_hit_at=_now(),
- )
-
-
-def _now() -> float:
- return time.time()
-
-
-__all__ = ["ExperienceBank"]
diff --git a/jiuwenswarm/symphony/experience/cluster.py b/jiuwenswarm/symphony/experience/cluster.py
deleted file mode 100644
index 400922065a..0000000000
--- a/jiuwenswarm/symphony/experience/cluster.py
+++ /dev/null
@@ -1,194 +0,0 @@
-"""
-Semantic clustering of execution traces.
-
-Groups traces first by skill set, then clusters queries within each group
-via FAISS K-Means (cosine distance).
-"""
-
-from __future__ import annotations
-
-import logging
-import random
-from dataclasses import dataclass
-
-import numpy as np
-
-from .embed import EmbeddingClient
-from .models import TraceRecord
-
-LOGGER = logging.getLogger(__name__)
-
-
-@dataclass
-class ClusteredQuery:
- """One semantic cluster of traces."""
-
- cluster_id: int
- centroid_query: str
- member_traces: list[TraceRecord]
- success_traces: list[TraceRecord]
- failure_traces: list[TraceRecord]
-
-
-def cluster_traces(
- traces: list[TraceRecord],
- embedder: EmbeddingClient,
- n_clusters: int | None = None,
- min_cluster_size: int = 1,
- max_k: int = 8,
-) -> list[ClusteredQuery]:
- """Cluster traces: first by skill set, then by semantic similarity.
-
- 1. Partition traces by their skill set (frozenset of skill_ids).
- 2. Within each group, embed ALL distinct queries (no sampling — preserves
- sub-ability coverage) and cluster via FAISS K-Means.
- 3. K is adaptive per skill: min(max_k, max(2, round(sqrt(n/2)))), so small
- skills get few clusters, large skills are capped at max_k.
- 4. Split each semantic cluster into success buckets.
- """
- if not traces:
- return []
-
- # Stage 1: group by skill set
- skill_groups: dict[frozenset, list[TraceRecord]] = {}
- for t in traces:
- key = frozenset(t.skills) if t.skills else frozenset()
- skill_groups.setdefault(key, []).append(t)
-
- result: list[ClusteredQuery] = []
- cluster_id_counter = 0
-
- # Stage 2: semantic clustering within each skill group
- for skill_key in sorted(skill_groups.keys(), key=lambda s: sorted(s)):
- group_traces = skill_groups.get(skill_key, [])
- if not group_traces:
- continue
- successes = [t for t in group_traces if t.success]
- # Cluster on the FULL set of distinct queries per skill — no sampling,
- # so sub-abilities of large skills are preserved. LLM distillation
- # caps its own input examples separately via max_success_examples.
- queries = [t.query for t in successes]
- embeddings = embedder.embed_batch(queries)
-
- # Adaptive k: sqrt(n/2), capped at max_k, at least 2.
- n = len(queries)
- if n_clusters is not None:
- k = n_clusters
- else:
- k = min(max_k, max(2, round((n / 2) ** 0.5)))
-
- labels = _faiss_cluster(
- embeddings,
- max_iterations=50,
- n_clusters=k,
- min_cluster_size=min_cluster_size,
- )
-
- local_clusters: dict[int, list[int]] = {}
- for i, label in enumerate(labels):
- if label >= 0:
- local_clusters.setdefault(label, []).append(i)
-
- for _local_id in sorted(local_clusters.keys()):
- indices = local_clusters.get(_local_id, [])
- members = [successes[i] for i in indices]
-
- # Filter clusters smaller than the configured min_cluster_size
- if len(members) < min_cluster_size:
- continue
-
- cluster_query = populate_cluster(cluster_id_counter, embeddings, indices, members)
- result.append(cluster_query)
- cluster_id_counter += 1
-
- return result
-
-
-def populate_cluster(
- cluster_id_counter: int,
- embeddings: list[list[float]],
- indices: list[int],
- members: list[TraceRecord],
-) -> ClusteredQuery:
- success_traces = [t for t in members if t.success]
- failure_traces = []
-
- # Find centroid: member whose embedding is closest to the group mean
- member_embeddings = np.array(
- [embeddings[i] for i in indices],
- dtype=np.float32,
- )
- centroid = member_embeddings.mean(axis=0)
- sims = member_embeddings @ centroid
- centroid_idx = int(sims.argmax())
- cluster_query = ClusteredQuery(
- cluster_id=cluster_id_counter,
- centroid_query=members[centroid_idx].query,
- member_traces=members,
- success_traces=success_traces,
- failure_traces=failure_traces,
- )
- return cluster_query
-
-
-def _faiss_cluster(
- embeddings: list[list[float]],
- *,
- n_clusters: int | None = None,
- max_iterations: int = 50,
- min_cluster_size: int = 1,
-) -> list[int]:
- """Cluster embeddings using FAISS K-Means with cosine distance.
-
- Returns list of cluster labels (-1 = noise / too-small cluster).
- Falls back to all-in-one cluster if FAISS is unavailable.
- """
- n = len(embeddings)
- if n == 0:
- return []
- if n < min_cluster_size:
- return [-1] * n
-
- try:
- import faiss
- except ImportError:
- LOGGER.warning("FAISS not available, falling back to single-cluster")
- return [0] * n
-
- # Normalize vectors for inner-product = cosine similarity
- arr = np.array(embeddings, dtype=np.float32)
-
- # Auto-determine k: aim for clusters of 3-8 items
- if n_clusters is None:
- k = max(2, n // 5)
- else:
- k = max(1, min(n_clusters, n))
- k = min(k, n)
- if k < 2:
- # Too few points for meaningful clustering — treat as single cluster
- return [0] * n
-
- # FAISS K-Means with cosine distance (via inner product on normalized vectors)
- dim = arr.shape[1]
- kmeans = faiss.Kmeans(
- dim,
- k,
- niter=max_iterations,
- verbose=False,
- gpu=False,
- spherical=True, # enforces cosine similarity
- min_points_per_centroid=min_cluster_size,
- seed=42,
- )
- kmeans.train(arr)
- _, labels = kmeans.index.search(arr, 1)
- labels = labels.flatten().tolist()
-
- # Mark clusters smaller than min_cluster_size as noise (-1)
- from collections import Counter
- counts = Counter(labels)
- final = [-1 if counts[x] < min_cluster_size else x for x in labels]
- return final
-
-
-__all__ = ["ClusteredQuery", "cluster_traces"]
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/collector.py b/jiuwenswarm/symphony/experience/collector.py
deleted file mode 100644
index c76a386512..0000000000
--- a/jiuwenswarm/symphony/experience/collector.py
+++ /dev/null
@@ -1,477 +0,0 @@
-from __future__ import annotations
-
-import logging
-import random
-import threading
-import time
-from collections import defaultdict
-from typing import Any
-
-import numpy as np
-
-from .bank import ExperienceBank
-from .cluster import ClusteredQuery, cluster_traces, _faiss_cluster, populate_cluster
-from .distiller import TraceDistiller
-from .embed import EmbeddingClient
-from .models import ExperienceBankBuildConfig, DistilledPattern, ExperienceItem, TraceRecord
-
-LOGGER = logging.getLogger(__name__)
-
-
-class ExperienceBaseBuilder:
- """Build an ``ExperienceBank`` index from parsed traces via
- cluster → distill → persist pipeline.
- """
-
- def __init__(
- self,
- kb: ExperienceBank,
- embedding_client: EmbeddingClient,
- llm_client: Any,
- llm_model: str,
- *,
- skills_info: list[dict[str, str]] | None = None,
- build_config: ExperienceBankBuildConfig | None = None,
- ) -> None:
- self._kb = kb
- self._embedder = embedding_client
- if not llm_client:
- raise ValueError("ExperienceBaseBuilder requires llm_client for distillation.")
- self._llm = llm_client
- if not llm_model:
- raise ValueError("ExperienceBaseBuilder requires llm_model for distillation.")
- self._llm_model = llm_model
- self._skills_info = skills_info
- self._config = build_config or ExperienceBankBuildConfig()
- self._min_cluster_size = self._config.min_cluster_size
- self._max_workers = self._config.max_workers
- self._max_success_examples = self._config.max_success_examples
- self._pending: list[TraceRecord] = []
- self._flush_threshold = self._config.pending_flush_threshold
- self._min_hits = self._config.min_hits_for_pattern
- self._pattern_merge_threshold = self._config.pattern_merge_threshold
- self._query_examples_count = self._config.query_examples_count
- self._skill_cluster_num = self._config.skill_cluster_num
- self._lock = threading.Lock()
-
- def build(self, traces: list[TraceRecord]) -> int:
- """Build the experience KB from a list of parsed ``TraceRecord``.
-
- Pipeline stages:
- 1. **Cluster** — group by skill set, then semantic cluster via FAISS
- 2. **Distill** — LLM distills each cluster into a generalized pattern
- 3. **Write** — write distilled patterns into ``ExperienceBank``
-
- Returns the number of experience items created.
-
- Raises:
- ValueError: if the target KB already contains entries (full
- rebuild only — use a fresh directory to avoid accidental data loss).
- """
- if self._kb.count > 0:
- LOGGER.error(
- "ExperienceBaseBuilder: refusing to build — "
- "target KB directory is not empty (existing %d entries). "
- "This is a full-build operation; use a fresh directory to avoid overwriting data.",
- self._kb.count,
- )
- raise ValueError(
- f"KB directory is not empty: {self._kb.count} entries exist. "
- f"ExperienceBaseBuilder performs a full build and will overwrite existing data. "
- f"Use a fresh directory or clear the KB first."
- )
-
- t0 = time.monotonic()
-
- if not traces:
- LOGGER.warning("TraceIndexBuilder: no traces provided, skipping")
- return 0
-
- valid_traces = self._filter_valid_traces(traces)
- if not valid_traces:
- LOGGER.warning("TraceIndexBuilder: no valid traces after filtering, skipping")
- return 0
-
- # --- Cluster ---
- t1 = time.monotonic()
- clusters = cluster_traces(
- valid_traces, self._embedder,
- n_clusters=self._skill_cluster_num,
- min_cluster_size=self._min_cluster_size,
- )
- cluster_elapsed = time.monotonic() - t1
- LOGGER.info(
- "TraceIndexBuilder: clustering done: %d clusters in %.2fs",
- len(clusters), cluster_elapsed,
- )
-
- if not clusters:
- LOGGER.warning("TraceIndexBuilder: no clusters formed, skipping")
- return 0
-
- # --- Distill ---
- t2 = time.monotonic()
- distiller = TraceDistiller(
- self._llm,
- self._llm_model,
- skills_info=self._skills_info,
- max_workers=self._max_workers,
- max_success_examples=self._max_success_examples,
- )
- distilled = distiller.run(clusters)
- distill_elapsed = time.monotonic() - t2
- LOGGER.info(
- "TraceIndexBuilder: distillation done: %d patterns in %.2fs",
- len(distilled), distill_elapsed,
- )
-
- # --- Write to KB ---
- t3 = time.monotonic()
- cluster_by_id = {c.cluster_id: c for c in clusters}
-
- valid_patterns = [p for p in distilled if p.pattern_description]
- merged_patterns = self._merge_similar_patterns(valid_patterns, cluster_by_id)
- batch_items = []
- sample_n = max(0, self._query_examples_count)
- rng = random.Random(42)
- for pattern in merged_patterns:
- top_skills = pattern.effective_skills if pattern.effective_skills else []
- cluster = cluster_by_id.get(pattern.cluster_id)
- examples = (
- [trace.query for trace in cluster.success_traces]
- if cluster
- else [pattern.pattern_description]
- )
- if sample_n == 0:
- sampled = []
- elif len(examples) > sample_n:
- sampled = rng.sample(examples, sample_n)
- else:
- sampled = list(examples)
- item = self._kb.create_item(
- query_pattern=pattern.pattern_description,
- query_examples=sampled,
- skill_ids=top_skills,
- success_count=len(cluster.success_traces) if cluster else 0,
- )
- batch_items.append(item)
-
- self._kb.add_batch(batch_items)
- created = len(batch_items)
- build_index_elapsed = time.monotonic() - t3
- total_elapsed = time.monotonic() - t0
- LOGGER.info(
- "TraceIndexBuilder: build index done: %d entries in %.2fs",
- created, build_index_elapsed,
- )
- LOGGER.info(
- "TraceIndexBuilder: pipeline total: %.2fs, created %d entries",
- total_elapsed, created,
- )
- return created
-
- @staticmethod
- def _filter_valid_traces(traces: list[TraceRecord]) -> list[TraceRecord]:
- """Drop traces that are not success or carry no skills.
-
- Both conditions make a trace useless for positive-pattern distillation:
- failures have no skill signal to reinforce, and skill-less traces
- cannot be partitioned by skill set in clustering.
- """
- valid_traces: list[TraceRecord] = []
- dropped = 0
- for t in traces:
- if not t.success or not t.skills:
- dropped += 1
- continue
- valid_traces.append(t)
- if dropped > 0:
- LOGGER.warning(
- "ExperienceBaseBuilder: dropped %d invalid trace(s) "
- "(success=False or no skills) out of %d provided",
- dropped, len(traces),
- )
- return valid_traces
-
- def add(self, trace: TraceRecord) -> None:
- """Record a successful query-skill mapping.
-
- This adds to the pending buffer. Call flush() to cluster and persist.
- """
- if not trace.success or not trace.skills:
- reason = "success=False" if not trace.success else "no skills associated"
- LOGGER.error(
- "ExperienceBaseBuilder: rejecting trace %s: %s",
- getattr(trace, "trace_id", "<unknown>"), reason,
- )
- return
- with self._lock:
- self._pending.append(trace)
- pending_count = len(self._pending)
-
- # Auto-flush if buffer is large enough (non-blocking)
- if pending_count >= self._flush_threshold:
- with self._lock:
- snapshot = list(self._pending)
- self._pending.clear()
- # Flush outside the lock to avoid blocking add() during LLM calls
- self._flush_snapshot(snapshot)
-
- def flush(self) -> int:
- """Cluster pending records and merge into the KB.
-
- Returns the number of new experience items created.
- Blocks until complete — use for graceful shutdown only.
- """
- with self._lock:
- if not self._pending:
- return 0
- pending = list(self._pending)
- self._pending.clear()
-
- return self._flush_snapshot(pending, force=True)
-
- def _flush_snapshot(self, pending: list[TraceRecord], force: bool = False) -> int:
- """Flush a snapshot of pending records. Safe to call from any thread."""
- if not pending:
- return 0
-
- # Step 1: group by skill_ids to reduce noise first
- by_skill = defaultdict(list)
- for r in pending:
- by_skill[tuple(sorted(r.skills))].append(r)
-
- created = 0
- for skill_key, records in by_skill.items():
- created += self._cluster_and_merge(records, list(skill_key), force=force)
-
- LOGGER.info(
- "ExperienceBaseBuilder: flushed %d pending records, created %d experience items",
- len(pending), created,
- )
- return created
-
- def _merge_similar_patterns(
- self,
- patterns: list[DistilledPattern],
- cluster_by_id: dict[int, ClusteredQuery],
- ) -> list[DistilledPattern]:
- if len(patterns) <= 1 or self._pattern_merge_threshold >= 1.0:
- return list(patterns)
-
- threshold = float(self._pattern_merge_threshold)
-
- def skill_bucket_key(p: DistilledPattern) -> frozenset:
- return frozenset(p.effective_skills)
-
- buckets: dict[frozenset, list[int]] = defaultdict(list)
- for i, p in enumerate(patterns):
- buckets[skill_bucket_key(p)].append(i)
-
- def success_count(i: int) -> int:
- c = cluster_by_id.get(patterns[i].cluster_id)
- return len(c.success_traces) if c else 0
-
- merged: list[DistilledPattern] = []
- synthetic_counter = 1
- for bucket_indices in buckets.values():
- ordered = sorted(
- bucket_indices,
- key=success_count,
- reverse=True,
- )
- if len(ordered) == 1:
- merged.append(patterns[ordered[0]])
- continue
-
- descriptions = [patterns[i].pattern_description for i in ordered]
- embeddings = self._embedder.embed_batch(descriptions)
- arr = np.asarray(embeddings, dtype=np.float32)
- norms = np.linalg.norm(arr, axis=1, keepdims=True)
- norms[norms == 0] = 1.0
- unit = arr / norms
- local_sim = unit @ unit.T # cosine similarity within bucket
- n = len(ordered)
- triu_mask = np.triu(np.ones((n, n), dtype=bool), k=1)
-
- assigned = np.zeros(n, dtype=bool)
- while True:
- avail_mask = (~assigned)[:, None] & (~assigned)[None, :] & triu_mask
- sim_view = np.where(avail_mask, local_sim, -np.inf)
- if not np.isfinite(sim_view).any() or float(sim_view.max()) < threshold:
- for pos in np.nonzero(~assigned)[0]:
- merged.append(patterns[ordered[int(pos)]])
- break
-
- flat = int(np.argmax(sim_view))
- i, j = flat // n, flat % n
-
- group: list[int] = [i, j]
- assigned[i] = True
- assigned[j] = True
- while True:
- candidates = np.nonzero(~assigned)[0]
- if len(candidates) == 0:
- break
- sub = local_sim[np.ix_(group, candidates)]
- # SINGLE-LINKAGE: a candidate joins if it is ≥threshold to
- # ANY member of the group (not ALL members). This lets
- # transitively-similar patterns merge even when two members
- # of the group are only loosely similar to each other.
- best_per_candidate = sub.max(axis=0) # max sim vs group, per candidate
- score = np.where(
- np.any(sub >= threshold, axis=0), best_per_candidate, -np.inf,
- )
- if not np.isfinite(score).any():
- break
- pick = int(candidates[int(np.argmax(score))])
- group.append(pick)
- assigned[pick] = True
-
- # Re-distill a fresh pattern covering the merged group: feed the
- # group's existing patterns + pooled representative queries to
- # the LLM so the survivor pattern subsumes all sub-abilities
- # rather than just copying the success_count-max one.
- rep = patterns[ordered[group[0]]]
- pooled: list[TraceRecord] = []
- group_patterns: list[str] = []
- for pos in group:
- pat = patterns[ordered[pos]]
- group_patterns.append(pat.pattern_description)
- cluster = cluster_by_id.get(pat.cluster_id)
- if cluster:
- pooled.extend(cluster.success_traces)
- merged_pattern = self._redistill_merged(
- rep, group_patterns, pooled
- )
- synthetic_id = -synthetic_counter
- synthetic_counter += 1
- cluster_by_id[synthetic_id] = ClusteredQuery(
- cluster_id=synthetic_id,
- centroid_query=merged_pattern,
- member_traces=list(pooled),
- success_traces=list(pooled),
- failure_traces=[],
- )
- merged.append(DistilledPattern(
- cluster_id=synthetic_id,
- effective_skills=rep.effective_skills,
- pattern_description=merged_pattern,
- ))
-
- LOGGER.info(
- "TraceIndexBuilder: merged %d patterns (threshold=%.2f, single-linkage greedy, bucketed-by-skill)",
- len(merged), threshold,
- )
- return merged
-
- def _redistill_merged(
- self,
- rep: DistilledPattern,
- group_patterns: list[str],
- pooled: list[TraceRecord],
- ) -> str:
- """Produce a survivor pattern for a merged group via the LLM.
-
- Feeds the group's existing clean patterns to TraceDistiller's merge
- routine, which returns one pattern subsuming all sub-abilities. The
- LLM also sees a sample of pooled success queries for real phrasing.
- Falls back to the rep pattern on any failure.
- """
- # Dedup patterns, keep order, drop empties.
- seen: set[str] = set()
- uniq: list[str] = []
- for p in group_patterns:
- if p and p not in seen:
- seen.add(p)
- uniq.append(p)
- skill = (rep.effective_skills or [""])[0] if rep.effective_skills else ""
- distiller = TraceDistiller(
- self._llm,
- self._llm_model,
- skills_info=self._skills_info,
- max_workers=self._max_workers,
- max_success_examples=self._max_success_examples,
- )
- return distiller.distill_merged_pattern(skill, uniq, rep.pattern_description)
-
- # ------------------------------------------------------------------
- # Internal
- # ------------------------------------------------------------------
-
- def _cluster_and_merge(
- self,
- records: list[TraceRecord],
- skill_ids: list[str],
- force: bool = False,
- ) -> int:
- """Embed records, cluster by semantic similarity, name each cluster,
- dedup against existing KB, and write to KB.
-
- Mirrors the full-build path: adaptive K-Means clustering (via
- ``cluster_traces``) → LLM distillation → single-linkage merge of the
- NEW patterns → batch-dedup against existing items → one ``add_batch``
- write (avoids the O(N) write-amplification of per-item ``add``).
-
- Returns number of items created.
- """
- if len(records) < self._min_hits and not force:
- # Too few records — put back into pending for later
- self._pending.extend(records)
- return 0
-
- # Stage 1: cluster via the shared adaptive-K routine (same as full build)
- clusters = cluster_traces(
- records, self._embedder,
- n_clusters=self._skill_cluster_num,
- min_cluster_size=self._min_cluster_size,
- )
- if not clusters:
- if not force:
- self._pending.extend(records)
- return 0
-
- # Stage 2: distill each new cluster into a pattern
- distiller = TraceDistiller(
- self._llm,
- self._llm_model,
- skills_info=self._skills_info,
- max_workers=self._max_workers,
- max_success_examples=self._max_success_examples,
- )
- distilled = distiller.run(clusters)
- valid_patterns = [p for p in distilled if p.pattern_description]
- if not valid_patterns:
- return 0
-
- # Stage 3: single-linkage merge among the NEW patterns (same logic as
- # full build) so transitive duplicates within this batch collapse first.
- cluster_by_id = {c.cluster_id: c for c in clusters}
- merged_patterns = self._merge_similar_patterns(valid_patterns, cluster_by_id)
-
- # Stage 4: dedup each new pattern against existing KB items with the
- # same skill set. Skip if an existing item is already ≥threshold similar
- # (single-linkage already collapsed within-batch duplicates; this only
- # guards cross-batch). Collect survivors for one batched write.
- sample_n = max(0, self._query_examples_count)
- new_items: list[ExperienceItem] = []
- for pat in merged_patterns:
- examples = [t.query for t in cluster_by_id.get(pat.cluster_id, None).success_traces] \
- if cluster_by_id.get(pat.cluster_id) else []
- if self._kb.exist(pat.effective_skills):
- # Same-skill items already exist — skip if any is similar enough
- hits = self._kb.search_by_embedding(pat.pattern_description, threshold=self._pattern_merge_threshold)
- if any(set(it.skill_ids) == set(pat.effective_skills) for _s, it in hits):
- continue
- new_items.append(self._kb.create_item(
- query_pattern=pat.pattern_description,
- query_examples=examples[:sample_n] if sample_n else [],
- skill_ids=list(pat.effective_skills),
- ))
-
- # Stage 5: ONE batched write (single index rebuild + single persist)
- if new_items:
- self._kb.add_batch(new_items)
- return len(new_items)
-
-__all__ = ["ExperienceBaseBuilder"]
diff --git a/jiuwenswarm/symphony/experience/distiller.py b/jiuwenswarm/symphony/experience/distiller.py
deleted file mode 100644
index a734ab9643..0000000000
--- a/jiuwenswarm/symphony/experience/distiller.py
+++ /dev/null
@@ -1,319 +0,0 @@
-"""LLM-based distillation of skill patterns from clustered traces."""
-
-from __future__ import annotations
-
-import json
-import logging
-import time
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from typing import Any
-
-from .cluster import ClusteredQuery
-from .models import DistilledPattern
-
-LOGGER = logging.getLogger(__name__)
-
-_LLM_MAX_RETRIES = 4
-
-_DISTILL_PATTERN_PROMPT = """\
-You are generating a query pattern for ONE target skill. The pattern must capture the TYPICAL USER INTENT for this skill, blending two sources:
-
-1. SKILL DESCRIPTION (semantic anchor + DISCRIMINATOR): defines what this skill does. The pattern's core meaning MUST stay within this skill's capability, AND MUST preserve the SKILL-SPECIFIC DISCRIMINATOR WORDS from the description verbatim — the skill's name, its signature objects, and its hallmark action. These words are what distinguish this skill from same-domain neighbors; do NOT generalize them into neutral placeholders.
-
-2. SUCCESSFUL QUERIES (real phrasing): show how users actually phrase requests that involve this skill. Borrow natural verbs, objects, and sentence structure from them — but ONLY the clause that maps to the TARGET skill's capability.
-
-CRITICAL — compound queries: The successful queries are COMPOUND (multiple skills per sentence). Extract ONLY the clause that maps to the TARGET skill's description. Any clause belonging to a DIFFERENT skill (e.g. translation when target is docx, marketing when target is docx) must be DROPPED from the pattern entirely — do NOT mention it even as "input" or "context"; replace its output with a neutral placeholder like [内容] if needed. If no clause matches the target skill, derive the pattern purely from the description.
-
-Discriminator principle (most important rule): same-domain skills must produce distinguishable patterns. Preserve each skill's signature word so its pattern does not collide with neighbors:
-- skill "tencent-docs" (腾讯文档): keep "腾讯文档"/"在线文档" — NOT just "[文档]"
-- skill "document-processor" (二维码生成器): keep "二维码" — NOT "[文档]"
-- skill "react-best-practices" (前端代码审计): keep "前端代码" + "审计/优化" — to distinguish from UI-design skills
-- skill "awesome-design-md" (UI设计): keep "UI设计页面" — to distinguish from code-audit skills
-Generalize ONLY truly variable entities unrelated to the skill domain (e.g. [人名][地点][日期]); keep domain entities concrete. The pattern must read like a standalone request for ONLY this skill, carrying its signature word.
-
----
-
-SKILL DESCRIPTION (target):
-{used_skills}
-
-REPRESENTATIVE QUERY:
-{centroid_query}
-
-SUCCESSFUL QUERIES (compound — extract only target-skill clauses):
-{member_queries}
-
-Produce a JSON object: {{"pattern_description": "<standalone pattern, preserving skill-specific discriminator words>"}}
-
-Examples:
-- Compound queries: "拍这张法语菜单翻译并朗读,根据功效写三个促销口号,做成Word"
-Target skill: photo-translate-speak (拍照识别外文并翻译朗读)
-Output: {{"pattern_description": "帮我把这张[语言]的[菜单/标签/说明书]拍下来,识别文字翻译成中文并朗读给我听"}}
-Target skill: docx (创建编辑Word文档)
-Output: {{"pattern_description": "把[内容]做成Word文档,包含[表格/图文/排版要求]"}}
-Target skill: marketing-ideas (生成营销促销文案)
-Output: {{"pattern_description": "参考[产品信息]写一份针对[目标群体]的营销促销文案,包含[数量]个促销口号"}}
-- Discriminator examples (same domain, distinguishable):
-Target skill: tencent-docs (腾讯文档)
-Output: {{"pattern_description": "在腾讯文档里[创建/编辑]一个[在线文档/在线表格],记录[内容]"}}
-Target skill: document-processor (二维码生成器)
-Output: {{"pattern_description": "帮我把这段[网址/图片/文本]转成二维码"}}
-
-Output ONLY valid JSON. No markdown, no explanation.
-"""
-
-
-class TraceDistiller:
- """Extract effective/ineffective skill patterns from clustered execution traces.
-
- Usage::
-
- distiller = TraceDistiller(
- llm_client=llm,
- llm_model="qwen3-32b",
- skills_info=[{"name": "web_search", "description": "..."}],
- max_workers=8,
- )
- patterns = distiller.run(clusters)
- """
-
- def __init__(
- self,
- llm_client: Any,
- llm_model: str,
- *,
- skills_info: list[dict[str, str]] | None = None,
- max_workers: int = 8,
- max_success_examples: int = 20,
- ) -> None:
- self._llm_model = llm_model
- if not llm_client or not llm_model:
- raise ValueError("TraceDistiller requires both llm_client and llm_model.")
- self._llm = llm_client
- self._max_workers = max_workers
- self._max_examples = max_success_examples
-
- # Build skill name → description map
- self._skills_by_name: dict[str, str] = {}
- if skills_info:
- for s in skills_info:
- self._skills_by_name[s["name"]] = s.get("description", "")
-
- def run(self, clusters: list[ClusteredQuery]) -> list[DistilledPattern]:
- """Run distillation in parallel across clusters."""
- results: list[DistilledPattern | None] = [None] * len(clusters)
-
- with ThreadPoolExecutor(max_workers=self._max_workers) as executor:
- future_to_idx: dict[Any, int] = {}
- for i, cluster in enumerate(clusters):
- LOGGER.info("TraceDistiller: submitting cluster %d (id=%d)", i, cluster.cluster_id)
- future = executor.submit(self._distill_one, cluster)
- future_to_idx[future] = i
-
- for future in as_completed(future_to_idx):
- idx = future_to_idx[future]
- try:
- results[idx] = future.result()
- LOGGER.info("TraceDistiller: finished cluster %d", idx)
- except Exception as exc:
- # Skip the failed cluster rather than aborting the whole run.
- # A single transient LLM error (rate limit, server hiccup, bad
- # JSON) should not discard the patterns distilled for all other
- # clusters. Downstream `build()` already drops empty patterns,
- # so leaving results[idx] = None is safe.
- LOGGER.error(
- "TraceDistiller: failed cluster %d (id=%d): %s (type=%s) — skipping",
- idx, clusters[idx].cluster_id, exc,
- type(exc).__name__,
- )
- results[idx] = None
-
- return [r for r in results if r is not None]
-
- def _distill_one(self, cluster: ClusteredQuery) -> DistilledPattern | None:
- success_traces = cluster.success_traces
- effective_skills = list(success_traces[0].skills) if success_traces else []
-
- success_queries = [t.query for t in success_traces]
- used_skill_names = set(effective_skills)
-
- prompt = self._build_prompt(cluster, success_queries, used_skill_names)
-
- messages = [
- {
- "role": "system",
- "content": (
- "You are an expert at generalizing query patterns. "
- "Output only valid JSON."
- ),
- },
- {"role": "user", "content": prompt},
- ]
- try:
- content = self._llm_call_with_retry(messages)
- if not content:
- raise RuntimeError(
- f"LLM returned empty content for cluster {cluster.cluster_id}"
- )
- pattern_description = self._parse_response(content, cluster.cluster_id)
- except Exception as exc:
- raise RuntimeError(
- f"LLM call failed for cluster {cluster.cluster_id}: {exc}"
- ) from exc
-
- if not pattern_description:
- return None
-
- return DistilledPattern(
- cluster_id=cluster.cluster_id,
- effective_skills=effective_skills,
- pattern_description=pattern_description,
- )
-
- def _llm_call_with_retry(self, messages: list[dict]) -> str:
- """Call the LLM with retry/backoff on transient errors (429/5xx/transport).
-
- 400-class client errors and JSON-parse issues are surfaced immediately
- by the caller; here we only retry on rate-limit / server / transport
- errors so a single 429 doesn't abort the whole multi-thousand-call
- distillation run.
- """
- from openai import APIStatusError, RateLimitError
-
- last_exc: Exception | None = None
- for attempt in range(_LLM_MAX_RETRIES):
- try:
- response = self._llm.chat.completions.create(
- model=self._llm_model,
- messages=messages,
- max_tokens=256,
- stream=False,
- extra_body={"enable_thinking": False, "thinking": {"type": "disabled"}},
- )
- return response.choices[0].message.content or ""
- except (RateLimitError, OSError) as exc:
- last_exc = exc
- wait = min(2 ** attempt, 30)
- LOGGER.warning(
- "TraceDistiller: transient LLM error (attempt %d), retrying in %ds: %s",
- attempt + 1, wait, exc,
- )
- time.sleep(wait)
- except APIStatusError as exc:
- status = getattr(exc, "status_code", None)
- if status is not None and 400 <= status < 500:
- # Client error — retrying won't fix it.
- raise
- last_exc = exc
- wait = min(2 ** attempt, 30)
- LOGGER.warning(
- "TraceDistiller: LLM server error %s (attempt %d), retrying in %ds",
- status, attempt + 1, wait,
- )
- time.sleep(wait)
- raise RuntimeError(f"LLM call failed after {_LLM_MAX_RETRIES} retries: {last_exc}")
-
- _MERGE_PATTERN_PROMPT = """\
-You are merging several semantically-overlapping query patterns for the SAME skill into ONE survivor pattern. Each input pattern already expresses the target skill's intent cleanly; your job is to produce a single generalized pattern that subsumes ALL of them without losing any sub-ability.
-
-Rules:
-- Preserve the SKILL-SPECIFIC DISCRIMINATOR WORDS already present in the inputs (skill name, signature objects, hallmark action).
-- Union the variable placeholders across inputs (e.g. if one pattern has [物体/文字] and another has [色泽/摆盘], combine into [物体/文字/色泽/摆盘]).
-- Keep domain entities concrete; do NOT over-generalize.
-- The output must read like a single standalone request for ONLY this skill, covering every sub-ability seen in the inputs.
-- Drop any clause that does not appear in ANY input pattern (don't invent new sub-tasks).
-
-SKILL (target):
-{skill}
-
-EXISTING PATTERNS (merge these):
-{patterns}
-
-Output JSON: {{"pattern_description": "<one merged pattern subsuming all inputs>"}}
-Output ONLY valid JSON. No markdown, no explanation.
-"""
-
- def distill_merged_pattern(
- self,
- skill: str,
- patterns: list[str],
- fallback: str,
- ) -> str:
- """Merge N same-skill patterns into one survivor pattern via the LLM.
-
- On any failure (LLM error, empty/invalid output), fall back to
- ``fallback`` (typically the success_count-max pattern) so merging
- never drops a group on the floor.
- """
- if not patterns:
- return fallback
- if len(patterns) == 1:
- return patterns[0]
- desc = self._skills_by_name.get(skill, "")
- skill_line = f"- {skill}: {desc}" if desc else f"- {skill}"
- pat_text = "\n".join(f"- {p!r}" for p in patterns)
- prompt = self._MERGE_PATTERN_PROMPT.format(skill=skill_line, patterns=pat_text)
- try:
- content = self._llm_call_with_retry([
- {"role": "system", "content": "Output only valid JSON."},
- {"role": "user", "content": prompt},
- ])
- merged = self._parse_response(content, -1)
- return merged or fallback
- except Exception as exc:
- LOGGER.warning(
- "TraceDistiller: merge-distill failed for skill=%s (%s); using fallback pattern",
- skill, type(exc).__name__,
- )
- return fallback
-
- def _build_prompt(
- self,
- cluster: ClusteredQuery,
- success_queries: list[str],
- used_skill_names: set[str] | None = None,
- ) -> str:
- queries_text = "\n".join(f"- {q!r}" for q in success_queries[: self._max_examples])
- if not queries_text:
- queries_text = " (no successful traces)"
-
- skills_text = ""
- if self._skills_by_name and used_skill_names:
- lines = []
- for name in sorted(used_skill_names):
- desc = self._skills_by_name.get(name, "")
- if desc:
- lines.append(f"- {name}: {desc}")
- else:
- lines.append(f"- {name}")
- if lines:
- skills_text = "\n".join(lines)
- if not skills_text:
- skills_text = " (no skill descriptions available)"
-
- return _DISTILL_PATTERN_PROMPT.format(
- cluster_id=cluster.cluster_id,
- centroid_query=cluster.centroid_query,
- member_queries=queries_text,
- used_skills=skills_text,
- )
-
- @staticmethod
- def _parse_response(response: str, cluster_id: int) -> str:
- raw = response.strip()
- if raw.startswith("```"):
- raw = raw.split("\n", 1)[-1].rsplit("```", 1)[0].strip()
- if raw.startswith("json"):
- raw = raw[4:].strip()
-
- try:
- data = json.loads(raw)
- except json.JSONDecodeError:
- LOGGER.error(
- "TraceDistiller: failed to parse JSON for cluster %d", cluster_id
- )
- return ""
-
- return data.get("pattern_description", "")
-
-
-__all__ = ["TraceDistiller"]
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/embed.py b/jiuwenswarm/symphony/experience/embed.py
deleted file mode 100644
index 1c9bda8e4e..0000000000
--- a/jiuwenswarm/symphony/experience/embed.py
+++ /dev/null
@@ -1,210 +0,0 @@
-from __future__ import annotations
-
-import logging
-import time
-from typing import Any
-
-LOGGER = logging.getLogger(__name__)
-
-
-class EmbeddingClient:
- """Minimal embedding client wrapping any OpenAI-compatible embeddings endpoint.
-
- Supports two backends:
- 1. OpenAI-compatible API (base_url + api_key) — calls /v1/embeddings
- 2. Local sentence-transformers model (model_name) — runs locally
-
- Pass exactly one of (base_url, api_key) or model_name.
- """
-
- def __init__(
- self,
- *,
- base_url: str | None = None,
- api_key: str = "",
- model: str = "",
- model_name: str = "",
- normalize: bool = True,
- dimension: int | None = None,
- api_batch_size: int | None = None,
- api_timeout: float = 60.0,
- ) -> None:
- self._backend: str = ""
- self._normalize = bool(normalize)
- self._dimension = dimension
- self._total_tokens: int = 0
- # Max texts per API call. DashScope text-embedding-v3 rejects lists longer
- # than 10 (HTTP 400 "batch size ... should not be larger than 10"); a
- # self-hosted OpenAI-compatible server (e.g. local bge-m3) typically has
- # no such cap, so callers using those should pass api_batch_size=64+.
- self._api_batch_size = 10 if api_batch_size is None else int(api_batch_size)
- self._api_max_retries = 5
- self._api_timeout = float(api_timeout)
-
- # Path 1: OpenAI-compatible API
- if base_url:
- try:
- from openai import OpenAI
- self._api_client = OpenAI(
- base_url=base_url, api_key=api_key or "dummy", timeout=self._api_timeout,
- )
- self._api_model = str(model or "text-embedding-3-small")
- self._backend = "openai_api"
- LOGGER.info("EmbeddingClient: using OpenAI-compatible API, model=%s", self._api_model)
- return
- except ImportError:
- pass
-
- # Path 2: Local sentence-transformers
- if model_name:
- try:
- from sentence_transformers import SentenceTransformer
- self._st_model = SentenceTransformer(model_name)
- self._backend = "sentence_transformers"
- LOGGER.info("EmbeddingClient: using local sentence-transformers, model=%s", model_name)
- return
- except ImportError:
- pass
-
- raise RuntimeError(
- "EmbeddingClient: could not initialize any embedding backend.\n"
- "Option 1: install 'openai' and provide base_url.\n"
- "Option 2: install 'sentence-transformers' and provide model_name."
- )
-
- @property
- def dimension(self) -> int | None:
- """Return the configured embedding vector dimension, or None if unset."""
- return self._dimension
-
- def reset_token_counter(self) -> int:
- """Reset and return the accumulated token counter."""
- prev = self._total_tokens
- self._total_tokens = 0
- return prev
-
- def embed(self, text: str) -> list[float]:
- """Return a normalized embedding vector for the given text."""
- if self._backend == "openai_api":
- return self._embed_api(text)
- if self._backend == "sentence_transformers":
- return self._embed_local(text)
- raise RuntimeError("No embedding backend initialized")
-
- def embed_batch(self, texts: list[str]) -> list[list[float]]:
- """Return embeddings for multiple texts."""
- if self._backend == "openai_api":
- return self._embed_api_batch(texts)
- if self._backend == "sentence_transformers":
- vecs = self._st_model.encode(texts, normalize_embeddings=self._normalize, show_progress_bar=False)
- return vecs.tolist()
- raise RuntimeError("No embedding backend initialized")
-
- # -- private --
-
- def _embed_api(self, text: str) -> list[float]:
- return self._embed_api_batch([text])[0]
-
- def _embed_api_batch(self, texts: list[str]) -> list[list[float]]:
- """Batch API embedding with retry/backoff.
-
- Splits into sub-batches (``_api_batch_size`` each), one API call per
- sub-batch. DashScope/OpenAI accept a list under ``input`` and return
- one embedding per element (indexed by ``data[i].index``). Retries on
- transient errors (429 / 5xx / connection) with exponential backoff.
- """
- results: list[list[float]] = [None] * len(texts) # type: ignore[list-item]
- batch = self._api_batch_size
- for start in range(0, len(texts), batch):
- chunk = texts[start:start + batch]
- vecs = self._embed_api_call(chunk)
- for i, v in enumerate(vecs):
- results[start + i] = v
- # Should be fully filled by now; guard against any None just in case.
- for i, r in enumerate(results):
- if r is None:
- results[i] = self._embed_api_call([texts[i]])[0]
- return results
-
- def _embed_api_call(self, texts: list[str]) -> list[list[float]]:
- from openai import (
- APITimeoutError,
- APIStatusError,
- APIConnectionError,
- BadRequestError,
- RateLimitError,
- )
- params: dict[str, Any] = {"input": texts, "model": self._api_model}
- if self._dimension is not None:
- params["dimensions"] = self._dimension
- last_exc: Exception | None = None
- for attempt in range(self._api_max_retries):
- try:
- resp = self._api_client.embeddings.create(**params)
- # Preserve input order via the data[].index field
- by_index: dict[int, list[float]] = {}
- for d in resp.data:
- by_index[int(getattr(d, "index", len(by_index)))] = list(d.embedding)
- vecs = [by_index[i] for i in range(len(texts))]
- usage = getattr(resp, "usage", None)
- if usage is not None:
- self._total_tokens += getattr(usage, "total_tokens", 0) or 0
- if self._normalize:
- vecs = [_l2_normalize(v) for v in vecs]
- return vecs
- except BadRequestError as exc:
- # 400 — caller error (e.g. too many texts, bad params).
- # Retrying won't help; surface immediately.
- raise RuntimeError(
- f"EmbeddingClient: embeddings.create bad request (batch={len(texts)}): {exc}"
- ) from exc
- except RateLimitError as exc:
- last_exc = exc
- wait = min(2 ** attempt, 30)
- LOGGER.warning(
- "EmbeddingClient: rate limited on batch of %d (attempt %d), retrying in %ds",
- len(texts), attempt + 1, wait,
- )
- time.sleep(wait)
- except (APITimeoutError, APIConnectionError, OSError) as exc:
- # Transient transport/timeout errors — retry with backoff.
- last_exc = exc
- wait = min(2 ** attempt, 30)
- LOGGER.warning(
- "EmbeddingClient: transient error on batch of %d (attempt %d): %s, retrying in %ds",
- len(texts), attempt + 1, type(exc).__name__, wait,
- )
- time.sleep(wait)
- except APIStatusError as exc:
- # HTTP status error. 4xx (except rate-limit caught above) is a
- # caller error — surface immediately. 5xx retries.
- status = getattr(exc, "status_code", None)
- if status is not None and 400 <= status < 500:
- raise RuntimeError(
- f"EmbeddingClient: embeddings.create client error {status} "
- f"(batch={len(texts)}): {exc}"
- ) from exc
- last_exc = exc
- wait = min(2 ** attempt, 30)
- LOGGER.warning(
- "EmbeddingClient: API error on batch of %d (attempt %d): %s, retrying in %ds",
- len(texts), attempt + 1, exc, wait,
- )
- time.sleep(wait)
- raise RuntimeError(
- f"EmbeddingClient: embeddings.create failed after {self._api_max_retries} retries: {last_exc}"
- )
-
- def _embed_local(self, text: str) -> list[float]:
- vec = self._st_model.encode(text, normalize_embeddings=self._normalize).tolist()
- return vec
-
-
-def _l2_normalize(vec: list[float]) -> list[float]:
- norm = sum(x * x for x in vec) ** 0.5
- if norm == 0:
- return vec
- return [x / norm for x in vec]
-
-
-__all__ = ["EmbeddingClient"]
diff --git a/jiuwenswarm/symphony/experience/evaluator.py b/jiuwenswarm/symphony/experience/evaluator.py
deleted file mode 100644
index 880cea1aa4..0000000000
--- a/jiuwenswarm/symphony/experience/evaluator.py
+++ /dev/null
@@ -1,291 +0,0 @@
-"""LLM-based trace evaluator: judge whether the skills used in a trace were correctly selected."""
-
-from __future__ import annotations
-
-import json
-import logging
-from typing import Any
-
-from .models import TraceRecord
-
-LOGGER = logging.getLogger(__name__)
-
-_SKILL_CORRECTNESS_PROMPT = """\
-You are a judge that evaluates whether the skills used in a conversation were correctly selected for the user's task.
-
-User query: {query}
-Assistant result: {result}
-
-Determine if the skills used were appropriate for this task. Output ONLY valid JSON with this schema:
-{{"success": true/false, "error_type": "<type or null>", "error_detail": "<reason or null>"}}
-
-A skill selection is "correct" (success=true) when the chosen skills directly address the user's need, their capabilities match what the task requires, and there isn't a clearly better alternative skill available.
-
-A skill selection is "incorrect" (success=false) when:
-- "wrong_skill": The skill doesn't match the task requirements or a different skill would have been much more appropriate.
-- "skill_error": The skill was the right choice but encountered an execution error (tool failure, exception, etc).
-- "incomplete": The skill started but did not finish the task.
-- "refusal": The skill refused to perform the task.
-- "empty": The skill returned an empty or meaningless result.
-
-For incorrect selections, provide a brief error_detail explaining why the skill choice was wrong or what went wrong.
-"""
-
-_SKILL_CORRECTNESS_PROMPT_ENHANCED = """\
-You are a judge that evaluates whether the skills used in a conversation were correctly selected for the user's task, based on the full interaction process.
-
-User query: {query}
-Skills used: {skills_used}
-Interaction process: {interaction_summary}
-Assistant result: {result}
-
-Determine if the skills used were the RIGHT choice for this task. Consider:
-1. Whether each skill's capabilities match what the task requires.
-2. Whether there is a clearly better alternative skill that should have been used instead.
-3. Whether the skill selection directly addresses the user's need.
-
-Output ONLY valid JSON with this schema:
-{{"success": true/false, "error_type": "<type or null>", "error_detail": "<reason or null>"}}
-
-A skill selection is "correct" (success=true) when the chosen skills directly address the user's need, their capabilities match what the task requires, and there isn't a clearly better alternative skill available.
-
-A skill selection is "incorrect" (success=false) when:
-- "wrong_skill": The skill doesn't match the task requirements or a different skill would have been much more appropriate.
-- "skill_error": The skill was the right choice but encountered an execution error (tool failure, exception, etc).
-- "incomplete": The skill started but did not finish the task.
-- "refusal": The skill refused to perform the task.
-- "empty": The skill returned an empty or meaningless result.
-
-For incorrect selections, provide a brief error_detail explaining why the skill choice was wrong or what went wrong.
-"""
-
-
-def _truncate(text: str, max_len: int) -> str:
- if len(text) <= max_len:
- return text
- return text[:max_len - 3] + "..."
-
-
-def _format_skills(skills: list[str]) -> str:
- if not skills:
- return "(no skills used)"
- return ", ".join(skills)
-
-
-def _summarize_messages(messages: list[dict], max_len: int = 3000) -> str:
- """Extract a concise interaction summary from the message history."""
- parts: list[str] = []
- for msg in messages:
- role = msg.get("role", "")
- content = msg.get("content", "")
-
- if role == "user":
- text = content if isinstance(content, str) else str(content)
- if text.strip():
- parts.append(f"[User] {text.strip()}")
-
- elif role == "assistant":
- reasoning = msg.get("reasoning", "")
- tool_call = msg.get("tool_call")
- if reasoning:
- parts.append(f"[Reasoning] {_truncate(reasoning.strip(), 200)}")
- if tool_call and isinstance(tool_call, dict):
- tc_name = tool_call.get("name", "")
- if tc_name == "skill_tool":
- try:
- raw_args = tool_call.get("arguments", {})
- args = (
- json.loads(raw_args)
- if isinstance(raw_args, str)
- else raw_args
- )
- skill_name = args.get("skill_name", "")
- parts.append(f"[Skill Call: {skill_name}]")
- except (json.JSONDecodeError, TypeError):
- parts.append(f"[Skill Call: skill_tool]")
- else:
- parts.append(f"[Tool Call: {tc_name}]")
- if content and isinstance(content, str) and not tool_call:
- if len(content) > 50:
- parts.append(f"[Assistant] {_truncate(content.strip(), 200)}")
-
- elif role == "tool":
- text = content if isinstance(content, str) else str(content)
- if text.strip():
- parts.append(f"[Tool Result] {_truncate(text.strip(), 300)}")
-
- summary = "\n".join(parts)
- if len(summary) > max_len:
- summary = _truncate(summary, max_len)
- return summary
-
-
-class TraceEvaluator:
- """Judge whether the skills used in each TraceRecord were correctly selected via LLM.
-
- When ``messages`` are available, uses an enhanced prompt that includes
- the full interaction process and skill selection context. Otherwise, falls back
- to the simple query+result prompt.
-
- ``success=True`` means the skill selection was correct — these traces are
- used to build experience patterns. ``success=False`` means the skills were
- incorrectly chosen or the execution failed — these traces are excluded from
- the experience bank.
-
- Usage::
-
- evaluator = TraceEvaluator(llm_client=openai_client, llm_model="qwen3-32b")
- records = parse_session("session_abc")
- evaluator.evaluate(records)
- # records[0].success / .error_type / .error_detail are now filled
- """
-
- def __init__(
- self,
- llm_client: Any | None = None,
- llm_model: str = "",
- ) -> None:
- self._llm_model = str(llm_model or "").strip()
- self._llm = llm_client if llm_client is not None else None
-
- def evaluate(self, records: list[TraceRecord]) -> list[TraceRecord]:
- """Judge skill correctness for each record, skip those with empty skills, return a new processed list."""
- result = []
- for record in records:
- if not record.skills:
- continue
- self._judge_one(record)
- result.append(record)
- return result
-
- def _judge_one(self, record: TraceRecord) -> None:
- if not self._llm or not self._llm_model:
- self._fallback(record)
- return
-
- query = record.query or ""
- result = record.result or ""
-
- if not query:
- record.success = False
- record.error_type = "empty"
- record.error_detail = "No user query found"
- return
-
- if not result:
- record.success = False
- record.error_type = "empty"
- record.error_detail = "Skill returned empty result"
- return
-
- # Use enhanced prompt when messages are available
- if record.messages:
- prompt = _SKILL_CORRECTNESS_PROMPT_ENHANCED.format(
- query=query,
- skills_used=_format_skills(record.skills),
- interaction_summary=_summarize_messages(record.messages),
- result=result,
- )
- system_msg = (
- "You evaluate whether the skills used were correctly selected for the user's task. "
- "Output only valid JSON.")
- else:
- prompt = _SKILL_CORRECTNESS_PROMPT.format(query=query, result=result)
- system_msg = (
- "You evaluate whether the skills used were correctly selected for the user's task. "
- "Output only valid JSON."
- )
- try:
- response = self._llm.chat.completions.create(
- model=self._llm_model,
- messages=[
- {"role": "system", "content": system_msg},
- {"role": "user", "content": prompt},
- ],
- max_tokens=256,
- stream=False,
- extra_body={"enable_thinking": False, "thinking": {"type": "disabled"}},
- )
- content = response.choices[0].message.content
- if content:
- self._parse_judge_response(content, record)
- else:
- self._fallback(record)
- except Exception as exc:
- LOGGER.warning("TraceEvaluator: LLM call failed for trace %s: %s", record.trace_id, exc)
- self._fallback(record)
-
- @staticmethod
- def _parse_judge_response(response: str, record: TraceRecord) -> None:
- raw = response.strip()
- if raw.startswith("```"):
- raw = raw.split("\n", 1)[-1].rsplit("```", 1)[0].strip()
- if raw.startswith("json"):
- raw = raw[4:].strip()
-
- try:
- data = json.loads(raw)
- except json.JSONDecodeError:
- LOGGER.warning("TraceEvaluator: failed to parse JSON for trace %s", record.trace_id)
- TraceEvaluator._fallback(record)
- return
-
- success = bool(data.get("success", False))
- record.success = success
- if success:
- record.error_type = None
- record.error_detail = None
- else:
- record.error_type = data.get("error_type") or "error"
- record.error_detail = data.get("error_detail") or ""
-
- @staticmethod
- def _fallback(record: TraceRecord) -> None:
- """Conservative fallback when LLM evaluation is unavailable or fails.
-
- Without the LLM we cannot reliably judge whether the skill selection
- was correct, so the safe choice is to NOT treat a record as a positive
- sample: default to ``success=False`` with ``error_type="unevaluated"``
- so it is excluded from the experience bank rather than polluting it
- with unverified successes.
-
- Only clearly-failing cases (no query, no result, or an execution error
- already flagged upstream) are given a more specific ``error_type``;
- everything else is conservatively marked ``unevaluated``. Result
- length is deliberately not used as a correctness signal.
- """
- query = (record.query or "").strip()
- result = record.result or ""
-
- # Defensive: result should already be a str (parser normalizes it),
- # but the fallback must not assume that.
- if not isinstance(result, str):
- result = "" if result is None else str(result)
-
- if not query:
- record.success = False
- record.error_type = "empty"
- record.error_detail = "No user query found"
- return
-
- if not result.strip():
- record.success = False
- record.error_type = "empty"
- record.error_detail = "Skill returned empty result"
- return
-
- # Upstream already flagged an execution error (e.g. skill raised) —
- # keep that classification, it is more precise than "unevaluated".
- if record.error_type:
- record.success = False
- if not record.error_detail:
- record.error_detail = "Upstream-flagged error, not LLM-evaluated"
- return
-
- # Cannot judge without the LLM — conservatively exclude from the KB.
- record.success = False
- record.error_type = "unevaluated"
- record.error_detail = "LLM evaluation unavailable; conservatively excluded"
-
-
-__all__ = ["TraceEvaluator"]
diff --git a/jiuwenswarm/symphony/experience/models.py b/jiuwenswarm/symphony/experience/models.py
deleted file mode 100644
index cd61f31a4e..0000000000
--- a/jiuwenswarm/symphony/experience/models.py
+++ /dev/null
@@ -1,122 +0,0 @@
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-from typing import Any
-
-
-@dataclass
-class ExperienceItem:
- """One entry in the experience base.
-
- Each item represents a class of queries that map to one or more skills.
- """
-
- id: str
- query_pattern: str = ""
- query_examples: list[str] = field(default_factory=list)
- skill_ids: list[str] = field(default_factory=list)
- success_count: int = 1
- embedding: list[float] = field(default_factory=list)
- created_at: float = 0.0
- last_hit_at: float = 0.0
-
- def to_dict(self) -> dict:
- return {
- "id": self.id,
- "query_pattern": self.query_pattern,
- "query_examples": self.query_examples,
- "skill_ids": self.skill_ids,
- "success_count": self.success_count,
- "created_at": self.created_at,
- "last_hit_at": self.last_hit_at,
- }
-
- @classmethod
- def from_dict(cls, data: dict) -> ExperienceItem:
- return cls(
- id=data["id"],
- query_pattern=data.get("query_pattern", ""),
- query_examples=list(data.get("query_examples", [])),
- skill_ids=list(data.get("skill_ids", [])),
- success_count=int(data.get("success_count", 1)),
- embedding=list(data.get("embedding", [])),
- created_at=float(data.get("created_at", 0.0)),
- last_hit_at=float(data.get("last_hit_at", 0.0)),
- )
-
-
-@dataclass
-class TraceRecord:
- trace_id: str
- query: str = ""
- skills: list[str] = field(default_factory=list)
- messages: list[dict] = field(default_factory=list)
- result: str = ""
- error_type: str | None = None
- error_detail: str | None = None
- success: bool = False
-
- def to_dict(self) -> dict:
- return {
- "trace_id": self.trace_id,
- "query": self.query,
- "skills": self.skills,
- "messages": self.messages,
- "result": self.result,
- "error_type": self.error_type,
- "error_detail": self.error_detail,
- "success": self.success,
- }
-
- @classmethod
- def from_dict(cls, data: dict) -> TraceRecord:
- return cls(
- trace_id=data["trace_id"],
- query=data.get("query", ""),
- skills=list(data.get("skills", [])),
- messages=list(data.get("messages", [])),
- result=data.get("result", ""),
- error_type=data.get("error_type"),
- error_detail=data.get("error_detail"),
- success=bool(data.get("success", False)),
- )
-
-
-@dataclass
-class ExperienceBankBuildConfig:
- """Configuration for ExperienceBaseBuilder pipeline."""
-
- min_cluster_size: int = 1
- max_workers: int = 8
- max_success_examples: int = 20
- pending_flush_threshold: int = 20
- min_hits_for_pattern: int = 1
- skill_cluster_num: int | None = None
- pattern_merge_threshold: float = 0.9
- query_examples_count: int = 5
-
-
-@dataclass
-class DistilledPattern:
- """Distilled knowledge pattern from one cluster."""
-
- cluster_id: int
- effective_skills: list[str] = field(default_factory=list)
- pattern_description: str = ""
-
- def to_dict(self) -> dict[str, Any]:
- """Serialize to a JSON-serializable dict."""
- return {
- "cluster_id": self.cluster_id,
- "effective_skills": self.effective_skills,
- "pattern_description": self.pattern_description,
- }
-
- @classmethod
- def from_dict(cls, d: dict) -> DistilledPattern:
- """Deserialize from a dict."""
- return cls(
- cluster_id=d["cluster_id"],
- effective_skills=list(d.get("effective_skills", [])),
- pattern_description=str(d.get("pattern_description", "")),
- )
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/retriever.py b/jiuwenswarm/symphony/experience/retriever.py
deleted file mode 100644
index 6afd0d9e7f..0000000000
--- a/jiuwenswarm/symphony/experience/retriever.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from __future__ import annotations
-
-from .bank import ExperienceBank
-
-
-class ExperienceRetriever:
- """Fast-path retriever that queries the experience knowledge base.
-
- On hit: returns skill_ids from the matched experience item.
- On miss: returns None so the caller falls through to tree retrieval.
- """
-
- def __init__(
- self,
- kb: ExperienceBank,
- *,
- threshold: float = 0.80,
- top_k: int = 1,
- ) -> None:
- self._kb = kb
- self._threshold = threshold
- self._top_k = top_k
-
- def search(self, query: str) -> list[str]:
- """Search the experience KB."""
- results = self._kb.search_by_embedding(
- query, top_k=self._top_k, threshold=self._threshold
- )
- if not results:
- return []
- return list(dict.fromkeys(
- skill_id for result in results for skill_id in result[1].skill_ids
- ))
-
-
-__all__ = ["ExperienceRetriever"]
diff --git a/jiuwenswarm/symphony/experience/trace/__init__.py b/jiuwenswarm/symphony/experience/trace/__init__.py
deleted file mode 100644
index e81a828ce9..0000000000
--- a/jiuwenswarm/symphony/experience/trace/__init__.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from .parser import list_session_ids, parse_all_sessions, parse_session
-from .store import clear_store, load_all_records, parse_and_store
-
-__all__ = [
- "list_session_ids",
- "parse_session",
- "parse_all_sessions",
- "parse_and_store",
- "load_all_records",
- "clear_store",
-]
diff --git a/jiuwenswarm/symphony/experience/trace/parser.py b/jiuwenswarm/symphony/experience/trace/parser.py
deleted file mode 100644
index 7f566c5992..0000000000
--- a/jiuwenswarm/symphony/experience/trace/parser.py
+++ /dev/null
@@ -1,239 +0,0 @@
-"""Session trace parser for experience distillation."""
-
-from __future__ import annotations
-
-import json
-import logging
-from pathlib import Path
-
-from jiuwenswarm.common.utils import get_agent_sessions_dir
-
-from ..models import TraceRecord
-
-LOGGER = logging.getLogger(__name__)
-
-_SESSION_DIR = get_agent_sessions_dir()
-
-
-def list_session_ids() -> list[str]:
- """Return all session IDs from the sessions directory, excluding heartbeat directories."""
- if not _SESSION_DIR.exists() or not _SESSION_DIR.is_dir():
- return []
- return [
- d.name
- for d in _SESSION_DIR.iterdir()
- if d.is_dir() and not d.name.startswith("heartbeat_")
- ]
-
-
-def _read_json(path: Path) -> object | None:
- if not path.exists():
- return None
- try:
- return json.loads(path.read_text(encoding="utf-8"))
- except Exception:
- LOGGER.error("Failed to read trace file")
- return None
-
-
-def _extract_text(content) -> str:
- """Extract plain text from content which may be None, str, or a list of content blocks."""
- if content is None:
- return ""
- if isinstance(content, str):
- return content
- if isinstance(content, list):
- texts = []
- for block in content:
- if isinstance(block, str):
- texts.append(block)
- elif isinstance(block, dict) and block.get("type") == "text":
- texts.append(block.get("text", ""))
- return "".join(texts)
- return str(content)
-
-
-def _extract_skills_from_tool_call(tool_call: dict) -> list[str]:
- """Extract skill names from a tool_call record.
-
- Recognizes several patterns:
- - ``skill_tool``: arguments contain ``skill_name``
- - ``symphony_compose_score``: arguments contain ``candidate_skill_ids``
- or the result's ``raw_output.plan.steps[].skill_id``
- """
- name = tool_call.get("name", "")
- args_raw = tool_call.get("arguments", "{}")
- try:
- args = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
- except json.JSONDecodeError:
- args = {}
-
- if name == "skill_tool":
- skill_name = args.get("skill_name", "")
- return [skill_name] if skill_name else []
-
- if name == "symphony_compose_score":
- # Primary: candidate_skill_ids from arguments
- candidate_ids = args.get("candidate_skill_ids", [])
- if isinstance(candidate_ids, list) and candidate_ids:
- return [s for s in candidate_ids if isinstance(s, str) and s]
- # Fallback: skill_ids from the result's raw_output.plan.steps
- result_raw = tool_call.get("result")
- raw_output = tool_call.get("raw_output")
- # result may be a string representation of a dict
- if raw_output is None and result_raw is not None:
- if isinstance(result_raw, str):
- try:
- raw_output = json.loads(result_raw)
- except json.JSONDecodeError:
- # Python-style repr (single quotes); try ast.literal_eval
- try:
- import ast
- raw_output = ast.literal_eval(result_raw)
- except Exception:
- raw_output = None
- elif isinstance(result_raw, dict):
- raw_output = result_raw
- if isinstance(raw_output, dict):
- plan = raw_output.get("plan")
- if isinstance(plan, dict):
- steps = plan.get("steps", [])
- if isinstance(steps, list):
- skill_ids = []
- for step in steps:
- if isinstance(step, dict):
- sid = step.get("skill_id") or step.get("name")
- if sid and isinstance(sid, str) and sid not in skill_ids:
- skill_ids.append(sid)
- if skill_ids:
- return skill_ids
-
- return []
-
-
-def _extract_skills_from_raw_output(raw_output: dict) -> list[str]:
- """Extract skill names from a tool_result's raw_output.
-
- Used for ``symphony_compose_score`` results where the plan.steps
- contain the selected skill_ids.
- """
- skill_ids: list[str] = []
- plan = raw_output.get("plan")
- if isinstance(plan, dict):
- steps = plan.get("steps", [])
- if isinstance(steps, list):
- for step in steps:
- if isinstance(step, dict):
- sid = step.get("skill_id") or step.get("name")
- if sid and isinstance(sid, str) and sid not in skill_ids:
- skill_ids.append(sid)
- return skill_ids
-
-
-def parse_session(session_id: str) -> list[TraceRecord]:
- """Parse a single session directory into TraceRecords.
-
- Uses request_id as traceId. A new request_id indicates a new user query segment.
- Skill names are extracted from ``skill_tool`` and ``symphony_compose_score`` calls.
- """
- session_dir = _SESSION_DIR / session_id
- if not session_dir.is_dir():
- return []
-
- metadata = _read_json(session_dir / "metadata.json")
- if metadata is None or not isinstance(metadata, dict):
- return []
-
- history_data = _read_json(session_dir / "history.json")
- if history_data is None:
- history_data = []
- if not isinstance(history_data, list):
- history_data = []
-
- current_request_id = ""
- query = ""
- reasoning = ""
- assistant_content = ""
- skills = []
- trace_records = []
- messages = []
-
- def _flush_record():
- # Commit accumulated assistant_content/reasoning before flushing
- if assistant_content:
- messages.append({"role": "assistant", "content": assistant_content, "reasoning": reasoning})
- if not query or not current_request_id:
- return
- # result from the last assistant message, not tool result
- result = ""
- for msg in reversed(messages):
- if msg.get("role") == "assistant":
- result = _extract_text(msg.get("content", ""))
- break
- trace_records.append(TraceRecord(
- trace_id=current_request_id,
- query=query,
- skills=skills,
- messages=messages,
- result=result,
- ))
-
- for record in history_data:
- if not isinstance(record, dict):
- continue
- request_id = record.get("request_id", "")
- if request_id and request_id != current_request_id:
- _flush_record()
- current_request_id = request_id
- query = ""
- messages = []
- skills = []
- reasoning = ""
- assistant_content = ""
- if record.get("role") == "user":
- query = _extract_text(record.get("content")).strip()
- elif record.get("role") == "assistant":
- event_type = record.get("event_type", "")
- if event_type == "chat.reasoning":
- reasoning += _extract_text(record.get("content")).strip()
- elif event_type == "chat.delta":
- assistant_content += _extract_text(record.get("content")).strip()
- elif event_type == "chat.final":
- assistant_content = _extract_text(record.get("content")).strip()
- elif event_type == "chat.tool_call":
- tool_call = record.get("tool_call") or {}
- if isinstance(tool_call, dict):
- extracted = _extract_skills_from_tool_call(tool_call)
- for s in extracted:
- if s and s not in skills:
- skills.append(s)
- messages.append({"role": "assistant", "content": assistant_content, "reasoning": reasoning,
- "tool_call": tool_call})
- assistant_content = ""
- reasoning = ""
- elif event_type == "chat.tool_result":
- tool_result = _extract_text(record.get("result")).strip()
- messages.append({"role": "tool", "content": tool_result})
- # Extract skills from raw_output (e.g. symphony_compose_score plan)
- raw_output = record.get("raw_output")
- if isinstance(raw_output, dict):
- tool_name = record.get("tool_name", "")
- if tool_name == "symphony_compose_score":
- extracted = _extract_skills_from_raw_output(raw_output)
- for s in extracted:
- if s and s not in skills:
- skills.append(s)
- elif event_type == "chat.error":
- messages.append({"role": "assistant", "content": _extract_text(record.get("content")).strip()})
- _flush_record()
- return trace_records
-
-
-def parse_all_sessions() -> list[TraceRecord]:
- """Parse all sessions into TraceRecords, skipping unparseable ones."""
- records: list[TraceRecord] = []
- for session_id in list_session_ids():
- trace_records = parse_session(session_id)
- if trace_records:
- records.extend(trace_records)
- return records
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/trace/store.py b/jiuwenswarm/symphony/experience/trace/store.py
deleted file mode 100644
index 0ac58822ce..0000000000
--- a/jiuwenswarm/symphony/experience/trace/store.py
+++ /dev/null
@@ -1,126 +0,0 @@
-"""Persistent store for parsed trace records.
-
-Provides helpers for persisting and loading TraceRecord objects,
-as well as a convenience function that parses only new sessions
-and stores their traces.
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-from pathlib import Path
-
-from .parser import list_session_ids, parse_session, parse_all_sessions
-from ..models import TraceRecord
-
-LOGGER = logging.getLogger(__name__)
-
-
-def _store_dir() -> Path:
- """Return the directory where processed traces are stored."""
- from jiuwenswarm.common.utils import get_agent_sessions_dir
- base = get_agent_sessions_dir()
- store = base.parent / "trace_store"
- store.mkdir(parents=True, exist_ok=True)
- return store
-
-
-def _processed_index_path() -> Path:
- """Path to the JSON file tracking which sessions have been processed."""
- return _store_dir() / "processed_index.json"
-
-
-def _records_path() -> Path:
- """Path to the JSONL file holding all stored TraceRecords."""
- return _store_dir() / "records.jsonl"
-
-
-def _load_processed_index() -> set[str]:
- """Load the set of session IDs that have already been processed."""
- path = _processed_index_path()
- if not path.exists():
- return set()
- try:
- data = json.loads(path.read_text(encoding="utf-8"))
- return set(data.get("processed_ids", []))
- except Exception:
- LOGGER.warning("Failed to read processed index, starting fresh", exc_info=True)
- return set()
-
-
-def _save_processed_index(ids: set[str]) -> None:
- """Save the set of processed session IDs."""
- path = _processed_index_path()
- data = {"processed_ids": sorted(ids)}
- path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
-
-
-def parse_and_store() -> list[TraceRecord]:
- """Parse only new (unprocessed) sessions and append their traces to the store.
-
- Returns the list of newly parsed TraceRecords.
- """
- all_ids = set(list_session_ids())
- already_processed = _load_processed_index()
- new_ids = sorted(all_ids - already_processed)
-
- if not new_ids:
- LOGGER.info("parse_and_store: no new sessions to process")
- return []
-
- new_records: list[TraceRecord] = []
- for session_id in new_ids:
- traces = parse_session(session_id)
- if traces:
- new_records.extend(traces)
-
- if new_records:
- # Append to records.jsonl
- records_path = _records_path()
- with open(records_path, "a", encoding="utf-8") as f:
- for record in new_records:
- f.write(json.dumps(record.to_dict(), ensure_ascii=False) + "\n")
- LOGGER.info("parse_and_store: stored %d new traces from %d sessions", len(new_records), len(new_ids))
-
- # Update processed index
- _save_processed_index(already_processed | set(new_ids))
-
- return new_records
-
-
-def load_all_records() -> list[TraceRecord]:
- """Load all stored TraceRecords from the records.jsonl file."""
- records_path = _records_path()
- if not records_path.exists():
- return []
-
- records: list[TraceRecord] = []
- try:
- with open(records_path, "r", encoding="utf-8") as f:
- for line in f:
- line = line.strip()
- if not line:
- continue
- try:
- data = json.loads(line)
- records.append(TraceRecord.from_dict(data))
- except json.JSONDecodeError:
- LOGGER.warning("Skipping malformed record line")
- except Exception:
- LOGGER.warning("Failed to load records", exc_info=True)
-
- LOGGER.info("load_all_records: loaded %d records", len(records))
- return records
-
-
-def clear_store() -> None:
- """Remove all stored traces and the processed index."""
- store = _store_dir()
- for path in [store / "records.jsonl", store / "processed_index.json"]:
- if path.exists():
- path.unlink()
- LOGGER.info("clear_store: store cleared")
-
-
-__all__ = ["parse_and_store", "load_all_records", "clear_store"]
diff --git a/jiuwenswarm/symphony/fingerprint/incremental.py b/jiuwenswarm/symphony/fingerprint/incremental.py
index 5bc7204b07..ce68a526bc 100644
--- a/jiuwenswarm/symphony/fingerprint/incremental.py
+++ b/jiuwenswarm/symphony/fingerprint/incremental.py
@@ -21,8 +21,8 @@ from jiuwenswarm.symphony.fingerprint.normalize import (
IONameVocabulary,
SkillFingerprintNormalizer,
)
-from jiuwenswarm.symphony.score_state import load_score_state
-from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dir
+from jiuwenswarm.symphony.graph_state import load_graph_state
+from jiuwenswarm.symphony.graph_storage import resolve_graph_artifact_dir
IndexedSkillFolder = tuple[int, SkillFolder]
@@ -37,13 +37,13 @@ class FingerprintReusePlan:
class IncrementalFingerprintStore:
- """Load prior Score artifacts and decide what must be re-extracted."""
+ """Load prior graph artifacts and decide what must be re-extracted."""
def __init__(self, output_dir: Path, *, signature: str = "") -> None:
self.output_dir = output_dir
self.signature = signature
self.cache = FingerprintResultCache(output_dir, signature=signature)
- self.old_state = load_score_state(output_dir)
+ self.old_state = load_graph_state(output_dir)
self.old_fingerprints = load_fingerprints(output_dir)
self.old_fingerprints_by_id = {item.id: item for item in self.old_fingerprints}
@@ -114,15 +114,15 @@ class IncrementalFingerprintStore:
class FingerprintResultCache:
"""Per-skill normalized fingerprint cache.
- The cache is intentionally outside published Score artifacts. A failed build
+ The cache is intentionally outside published graph artifacts. A failed build
may still leave valid per-skill extraction results that can be reused by the
next build.
"""
- def __init__(self, score_dir: Path, *, signature: str = "") -> None:
- self.score_dir = Path(score_dir).resolve()
+ def __init__(self, graph_dir: Path, *, signature: str = "") -> None:
+ self.graph_dir = Path(graph_dir).resolve()
self.signature = signature
- self.root = self.score_dir / "cache" / "fingerprints"
+ self.root = self.graph_dir / "cache" / "fingerprints"
def load(
self,
@@ -188,22 +188,26 @@ class FingerprintResultCache:
def load_fingerprints(output_dir: Path) -> list[Fingerprint]:
- path = resolve_score_artifact_dir(output_dir) / "fingerprints.json"
+ path = resolve_graph_artifact_dir(output_dir) / "fingerprints.json"
if not path.exists():
return []
- payload = json.loads(path.read_text(encoding="utf-8"))
- return [
- Fingerprint.from_dict(item)
- for item in payload.get("fingerprints", [])
- if isinstance(item, dict)
- ]
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ return [
+ Fingerprint.from_dict(item)
+ for item in payload.get("fingerprints", [])
+ if isinstance(item, dict)
+ ]
+ except (OSError, ValueError, AttributeError, TypeError):
+ # fingerprints.json 损坏时按无缓存处理,走重建路径自愈。
+ return []
def load_io_name_vocabulary(
output_dir: Path,
normalizer: SkillFingerprintNormalizer,
) -> IONameVocabulary:
- path = resolve_score_artifact_dir(output_dir) / "io_name_vocab.json"
+ path = resolve_graph_artifact_dir(output_dir) / "io_name_vocab.json"
if not path.exists():
return IONameVocabulary.from_config(normalizer.config)
return IONameVocabulary.load(path, normalizer.config)
diff --git a/jiuwenswarm/symphony/graph/__init__.py b/jiuwenswarm/symphony/graph/__init__.py
deleted file mode 100644
index 2a907fb1f2..0000000000
--- a/jiuwenswarm/symphony/graph/__init__.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""Offline Skill graph construction."""
-
-from jiuwenswarm.symphony.graph.builders import ScoreLookupBuilder, SkillGraphBuilder
-from jiuwenswarm.symphony.graph.candidates import CandidateGenerator
-from jiuwenswarm.symphony.graph.matcher import (
- DEFAULT_THRESHOLDS,
- OntologyMatcher,
- OpenAICompatibleOntologyMatcher,
- validate_llm_matches,
-)
-from jiuwenswarm.symphony.graph.models import (
- ALLOWED_RELATION_TYPES,
- BuildManifest,
- GraphBuildResult,
- GraphDiagnostic,
- GraphEdge,
- GraphNode,
- LLMMatch,
- RelationCandidate,
- ScoreLookup,
- SkillGraph,
- SkillRegistry,
-)
-from jiuwenswarm.symphony.graph.pipeline import GraphBuilder
-from jiuwenswarm.symphony.graph.registry import SkillRegistryBuilder
-from jiuwenswarm.symphony.graph.writer import write_graph_build_result, write_json_file
-
-__all__ = [
- "ALLOWED_RELATION_TYPES",
- "BuildManifest",
- "CandidateGenerator",
- "DEFAULT_THRESHOLDS",
- "GraphBuilder",
- "GraphBuildResult",
- "GraphDiagnostic",
- "GraphEdge",
- "GraphNode",
- "LLMMatch",
- "OntologyMatcher",
- "OpenAICompatibleOntologyMatcher",
- "RelationCandidate",
- "ScoreLookup",
- "ScoreLookupBuilder",
- "SkillGraph",
- "SkillGraphBuilder",
- "SkillRegistry",
- "SkillRegistryBuilder",
- "validate_llm_matches",
- "write_graph_build_result",
- "write_json_file",
-]
diff --git a/jiuwenswarm/symphony/graph/builders.py b/jiuwenswarm/symphony/graph/builders.py
deleted file mode 100644
index 5be7899dbd..0000000000
--- a/jiuwenswarm/symphony/graph/builders.py
+++ /dev/null
@@ -1,204 +0,0 @@
-"""Build typed Skill graph and Score lookup artifacts."""
-
-from __future__ import annotations
-
-from collections import defaultdict
-from typing import Dict, Iterable, List, Set
-
-from jiuwenswarm.symphony.graph.lexicon import (
- ArtifactLexicon,
- DEFAULT_GRAPH_STOP_TERMS,
-)
-from jiuwenswarm.symphony.graph.models import (
- GraphEdge,
- GraphNode,
- LLMMatch,
- ScoreLookup,
- SkillGraph,
- SkillRegistry,
-)
-
-
-IO_NAMES_EXCLUDED_FROM_EXACT_LOOKUP = frozenset(
- {
- "dependencies",
- "path",
- }
-)
-_GRAPH_TERM_LEXICON = ArtifactLexicon.create(
- stop_terms=DEFAULT_GRAPH_STOP_TERMS,
- min_token_length=3,
-)
-
-
-class SkillGraphBuilder:
- """Build Skill graph nodes and accepted can_feed edges."""
-
- @staticmethod
- def build(
- registry: SkillRegistry,
- llm_matches: Iterable[LLMMatch],
- ) -> SkillGraph:
- nodes: Dict[str, GraphNode] = {}
- edges: Dict[str, GraphEdge] = {}
-
- for skill in registry.ordered_skills():
- nodes.setdefault(
- f"skill:{skill.id}",
- GraphNode(
- id=f"skill:{skill.id}",
- type="skill",
- label=skill.name or skill.id,
- properties={
- "skill_id": skill.id,
- "name": skill.name,
- "description": skill.description,
- "version": skill.version,
- "inputs": [item.to_dict() for item in skill.inputs],
- "outputs": [item.to_dict() for item in skill.outputs],
- },
- ),
- )
-
- for match in llm_matches:
- if not match.accepted or match.relation_type != "can_feed":
- continue
- edge = GraphEdge(
- source=f"skill:{match.source_id}",
- target=f"skill:{match.target_id}",
- type=match.relation_type,
- confidence=match.confidence,
- method=match.method,
- evidence={
- "candidate_id": match.candidate_id,
- "reasons": match.reasons,
- "supporting_fields": match.supporting_fields,
- },
- )
- edges.setdefault(edge.key, edge)
-
- ordered_nodes = []
- for node_id in sorted(nodes):
- node = nodes.get(node_id)
- if node is not None:
- ordered_nodes.append(node)
- return SkillGraph(
- nodes=ordered_nodes,
- edges=sorted(edges.values(), key=lambda edge: edge.key),
- )
-
-
-class ScoreLookupBuilder:
- """Build deterministic lookup tables for online Score retrieval."""
-
- def __init__(
- self,
- *,
- generic_io_names: Iterable[str] = IO_NAMES_EXCLUDED_FROM_EXACT_LOOKUP,
- max_io_bucket_size: int = 16,
- max_text_bucket_size: int = 24,
- ) -> None:
- self.lexicon = ArtifactLexicon.create(
- stop_terms=DEFAULT_GRAPH_STOP_TERMS,
- min_token_length=3,
- generic_io_names=generic_io_names,
- )
- self.max_io_bucket_size = max(1, max_io_bucket_size)
- self.max_text_bucket_size = max(2, max_text_bucket_size)
-
- def build(self, registry: SkillRegistry, graph: SkillGraph) -> ScoreLookup:
- by_output: Dict[str, Set[str]] = defaultdict(set)
- by_input: Dict[str, Set[str]] = defaultdict(set)
- by_data_type: Dict[str, Set[str]] = defaultdict(set)
- by_text_term: Dict[str, Set[str]] = defaultdict(set)
-
- for skill in registry.ordered_skills():
- for output in skill.outputs:
- if not self.lexicon.is_generic_io_name(output.name):
- by_output[output.name].add(skill.id)
- by_data_type[output.type].add(skill.id)
- for parameter in skill.inputs:
- if not self.lexicon.is_generic_io_name(parameter.name):
- by_input[parameter.name].add(skill.id)
- by_data_type[parameter.type].add(skill.id)
- for term in _skill_terms(skill):
- by_text_term[term].add(skill.id)
-
- neighbors: Dict[str, Set[str]] = defaultdict(set)
- upstream_by_input: Dict[str, Set[str]] = defaultdict(set)
- downstream_by_output: Dict[str, Set[str]] = defaultdict(set)
- skill_inputs = {
- skill.id: {parameter.name for parameter in skill.inputs}
- for skill in registry.ordered_skills()
- }
- skill_outputs = {
- skill.id: {output.name for output in skill.outputs}
- for skill in registry.ordered_skills()
- }
-
- for edge in graph.edges:
- if edge.source.startswith("skill:") and edge.target.startswith("skill:"):
- source_id = edge.source.removeprefix("skill:")
- target_id = edge.target.removeprefix("skill:")
- neighbors[source_id].add(target_id)
- if edge.type != "can_feed":
- continue
- shared = sorted(
- skill_outputs.get(source_id, set())
- & skill_inputs.get(target_id, set())
- )
- for name in shared:
- if self.lexicon.is_generic_io_name(name):
- continue
- upstream_by_input[name].add(source_id)
- downstream_by_output[name].add(target_id)
-
- return ScoreLookup(
- by_output=_freeze_lookup(
- by_output,
- max_bucket_size=self.max_io_bucket_size,
- ),
- by_input=_freeze_lookup(
- by_input,
- max_bucket_size=self.max_io_bucket_size,
- ),
- by_data_type=_freeze_lookup(by_data_type),
- neighbors=_freeze_lookup(neighbors),
- upstream_by_input=_freeze_lookup(
- upstream_by_input,
- max_bucket_size=self.max_io_bucket_size,
- ),
- downstream_by_output=_freeze_lookup(
- downstream_by_output,
- max_bucket_size=self.max_io_bucket_size,
- ),
- by_text_term=_freeze_lookup(
- by_text_term,
- max_bucket_size=self.max_text_bucket_size,
- ),
- )
-
-
-def _freeze_lookup(
- lookup: Dict[str, Set[str]],
- *,
- max_bucket_size: int | None = None,
-) -> Dict[str, List[str]]:
- frozen = {}
- for key, values in sorted(lookup.items()):
- if max_bucket_size is not None and len(values) > max_bucket_size:
- continue
- frozen[key] = sorted(values)
- return frozen
-
-
-def _skill_terms(skill) -> Set[str]:
- chunks: List[str] = [skill.id, skill.name, skill.description]
- chunks.extend(item.name for item in skill.inputs)
- chunks.extend(item.description for item in skill.inputs)
- chunks.extend(item.name for item in skill.outputs)
- chunks.extend(item.description for item in skill.outputs)
- terms: Set[str] = set()
- for chunk in chunks:
- terms.update(_GRAPH_TERM_LEXICON.tokenize(chunk))
- return terms
diff --git a/jiuwenswarm/symphony/graph/candidates/__init__.py b/jiuwenswarm/symphony/graph/candidates/__init__.py
deleted file mode 100644
index f517243421..0000000000
--- a/jiuwenswarm/symphony/graph/candidates/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""Candidate relation generation for Skill graph."""
-
-from jiuwenswarm.symphony.graph.candidates.generator import CandidateGenerator
-
-__all__ = ["CandidateGenerator"]
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/graph/candidates/generator.py b/jiuwenswarm/symphony/graph/candidates/generator.py
deleted file mode 100644
index 0f8406e67f..0000000000
--- a/jiuwenswarm/symphony/graph/candidates/generator.py
+++ /dev/null
@@ -1,727 +0,0 @@
-"""Deterministic high-recall relation candidate generation."""
-
-from __future__ import annotations
-
-import logging
-from collections import defaultdict
-from typing import Dict, Iterable, List, MutableMapping, Set, Tuple
-
-from jiuwenswarm.symphony.fingerprint.models import (
- ArtifactSpec,
- ParameterSpec,
- Fingerprint,
-)
-from jiuwenswarm.symphony.fingerprint.normalize.data_type_vocab import (
- DataTypeVocabulary,
-)
-from jiuwenswarm.symphony.graph.lexicon import (
- ArtifactLexicon,
- DEFAULT_GRAPH_STOP_TERMS,
-)
-from jiuwenswarm.symphony.graph.models import (
- ALLOWED_RELATION_TYPES,
- RelationCandidate,
- SkillRegistry,
-)
-
-
-PRIORITY_RANK = {"high": 3, "medium": 2, "low": 1}
-# These names are too broad for exact-name edge generation. They are still
-# available for text indexing and semantic evidence; only exact I/O matching
-# treats them as generic.
-IO_NAMES_EXCLUDED_FROM_EDGE_BUILDING = frozenset(
- {
- "dependencies",
- "path",
- }
-)
-# Textual coercion is intentionally limited to inputs whose names clearly mean
-# "free-form content". This is a graph-generation heuristic, not a DataType.
-GENERIC_CONTENT_INPUT_NAMES = frozenset(
- {
- "body",
- "content",
- "prompt",
- "query",
- "question",
- "text",
- "sources",
- }
-)
-_GRAPH_TERM_LEXICON = ArtifactLexicon.create(
- stop_terms=DEFAULT_GRAPH_STOP_TERMS,
- min_token_length=3,
-)
-LOGGER = logging.getLogger("jiuwenswarm.symphony.graph.candidates")
-
-
-class CandidateGenerator:
- """Generate high-recall Skill-Skill relation candidates."""
-
- def __init__(
- self,
- *,
- max_candidates_per_skill_relation: int = 32,
- max_port_mappings_per_candidate: int = 12,
- generic_io_names: Iterable[str] = IO_NAMES_EXCLUDED_FROM_EDGE_BUILDING,
- max_exact_io_pair_fanout: int = 64,
- ) -> None:
- self.max_candidates_per_skill_relation = max_candidates_per_skill_relation
- self.max_port_mappings_per_candidate = max(1, max_port_mappings_per_candidate)
- self.evidence_merger = CandidateEvidenceMerger(
- max_port_mappings=self.max_port_mappings_per_candidate,
- )
- self.lexicon = ArtifactLexicon.create(
- stop_terms=DEFAULT_GRAPH_STOP_TERMS,
- min_token_length=3,
- generic_io_names=generic_io_names,
- )
- self.max_exact_io_pair_fanout = max(1, max_exact_io_pair_fanout)
-
- def generate(self, registry: SkillRegistry) -> List[RelationCandidate]:
- skills = registry.ordered_skills()
- skill_terms = {skill.id: _skill_terms(skill) for skill in skills}
- indexes = CandidateIndexes.from_skills(skills)
- candidates: Dict[Tuple[str, str], RelationCandidate] = {}
-
- LOGGER.debug("candidate_generation_start skill_count=%s", len(skills))
- self._add_exact_io_candidates(indexes, candidates)
- self._add_semantic_overlap_candidates(skills, skill_terms, candidates)
- self._add_textual_coercion_candidates(skills, skill_terms, candidates)
-
- ordered = sorted(
- candidates.values(),
- key=lambda item: (
- item.source_id,
- -PRIORITY_RANK.get(item.priority, 0),
- item.target_id,
- ",".join(item.relation_hints),
- ),
- )
- limited = self._limit_per_skill_relation(ordered)
- LOGGER.debug(
- "candidate_generation_done generated_count=%s emitted_count=%s",
- len(ordered),
- len(limited),
- )
- return limited
-
- def _add_exact_io_candidates(
- self,
- indexes: "CandidateIndexes",
- candidates: MutableMapping[Tuple[str, str], RelationCandidate],
- ) -> None:
- for name in sorted(set(indexes.by_output_name) & set(indexes.by_input_name)):
- if self.lexicon.is_generic_io_name(name):
- LOGGER.debug(
- "candidate_skipped reason=generic_io_name "
- "method=exact_io_match name=%s output_skills=%s input_skills=%s",
- name,
- ",".join(sorted(indexes.by_output_name[name])),
- ",".join(sorted(indexes.by_input_name[name])),
- )
- continue
- pair_fanout = (
- len(indexes.by_output_name[name]) * len(indexes.by_input_name[name])
- )
- if pair_fanout > self.max_exact_io_pair_fanout:
- LOGGER.debug(
- "candidate_skipped reason=max_exact_io_pair_fanout "
- "method=exact_io_match name=%s fanout=%s limit=%s "
- "output_skills=%s input_skills=%s",
- name,
- pair_fanout,
- self.max_exact_io_pair_fanout,
- ",".join(sorted(indexes.by_output_name[name])),
- ",".join(sorted(indexes.by_input_name[name])),
- )
- continue
- for source_id in sorted(indexes.by_output_name[name]):
- for target_id in sorted(indexes.by_input_name[name]):
- if source_id == target_id:
- continue
- source_outputs = indexes.outputs_by_skill_name[(source_id, name)]
- target_inputs = indexes.inputs_by_skill_name[(target_id, name)]
- port_mappings = []
- for output in source_outputs:
- for parameter in target_inputs:
- if not _can_feed_by_exact_or_subtype(
- output.type,
- parameter.type,
- ):
- continue
- port_mappings.append(
- _port_mapping(
- output,
- parameter,
- match_method="exact_io_match",
- match_reason=_match_reason_exact_io(
- output.type,
- parameter.type,
- ),
- )
- )
- if not port_mappings:
- continue
- self._merge_candidate(
- candidates,
- RelationCandidate(
- source_id=source_id,
- target_id=target_id,
- relation_hints=["can_feed"],
- candidate_methods=["exact_io_match"],
- priority="high",
- evidence={
- "matched_terms": [name],
- "source_outputs": [
- item.to_dict() for item in source_outputs
- ],
- "target_inputs": [
- item.to_dict() for item in target_inputs
- ],
- "port_mappings": port_mappings,
- },
- ),
- )
-
- def _add_semantic_overlap_candidates(
- self,
- skills: List[Fingerprint],
- skill_terms: Dict[str, Set[str]],
- candidates: MutableMapping[Tuple[str, str], RelationCandidate],
- ) -> None:
- for source in skills:
- source_terms = skill_terms[source.id]
- for target in skills:
- if source.id == target.id:
- continue
- target_terms = skill_terms[target.id]
- shared_terms = sorted(source_terms & target_terms)
- for output in source.outputs:
- for parameter in target.inputs:
- if (
- output.name == parameter.name
- and self.lexicon.is_generic_io_name(output.name)
- ):
- continue
- uses_remote_reference = _can_feed_by_remote_reference(
- output,
- parameter,
- )
- if not uses_remote_reference:
- if not _can_feed_by_type(output.type, parameter.type):
- continue
- if not _has_semantic_overlap(output, parameter):
- continue
- mapping = _port_mapping(
- output,
- parameter,
- match_method="semantic_overlap_match",
- match_reason=(
- _match_reason_remote_reference(output, parameter)
- if uses_remote_reference
- else _match_reason_semantic_overlap(output, parameter)
- ),
- )
- self._merge_candidate(
- candidates,
- RelationCandidate(
- source_id=source.id,
- target_id=target.id,
- relation_hints=["can_feed"],
- candidate_methods=["semantic_overlap_match"],
- priority="medium",
- evidence={
- "matched_terms": shared_terms,
- "source_outputs": [output.to_dict()],
- "target_inputs": [parameter.to_dict()],
- "port_mappings": [mapping],
- "matched_types": [
- f"{output.type}->{parameter.type}"
- ],
- },
- ),
- )
-
- def _add_textual_coercion_candidates(
- self,
- skills: List[Fingerprint],
- skill_terms: Dict[str, Set[str]],
- candidates: MutableMapping[Tuple[str, str], RelationCandidate],
- ) -> None:
- for source in skills:
- source_terms = skill_terms[source.id]
- for target in skills:
- if source.id == target.id:
- continue
- target_terms = skill_terms[target.id]
- shared_terms = sorted(source_terms & target_terms)
- for output in source.outputs:
- for parameter in target.inputs:
- if not _can_feed_by_type(output.type, parameter.type):
- continue
- input_terms = _tokenize(
- f"{parameter.name} {parameter.description}"
- )
- if not _can_feed_via_textual_coercion(
- output,
- parameter,
- input_terms,
- ):
- continue
- mapping = _port_mapping(
- output,
- parameter,
- match_method="textual_coercion_match",
- match_reason=_match_reason_textual_coercion(
- output,
- parameter,
- ),
- )
- self._merge_candidate(
- candidates,
- RelationCandidate(
- source_id=source.id,
- target_id=target.id,
- relation_hints=["can_feed"],
- candidate_methods=["textual_coercion_match"],
- priority="low",
- evidence={
- "matched_terms": shared_terms,
- "source_outputs": [output.to_dict()],
- "target_inputs": [parameter.to_dict()],
- "port_mappings": [mapping],
- "matched_types": [
- f"{output.type}->{parameter.type}"
- ],
- },
- ),
- )
-
- def _merge_candidate(
- self,
- candidates: MutableMapping[Tuple[str, str], RelationCandidate],
- candidate: RelationCandidate,
- ) -> None:
- relation_hints = [
- hint for hint in candidate.relation_hints if hint in ALLOWED_RELATION_TYPES
- ]
- if not relation_hints:
- return
- _debug_candidate_generated(candidate, relation_hints)
- key = (candidate.source_id, candidate.target_id)
- existing = candidates.get(key)
- if existing is None:
- candidates[key] = self.evidence_merger.create(candidate, relation_hints)
- return
-
- candidates[key] = self.evidence_merger.merge(existing, candidate, relation_hints)
-
- def _limit_per_skill_relation(
- self, candidates: List[RelationCandidate]
- ) -> List[RelationCandidate]:
- buckets: Dict[str, List[RelationCandidate]] = defaultdict(list)
- for candidate in candidates:
- buckets[candidate.source_id].append(candidate)
-
- limited: List[RelationCandidate] = []
- for key in sorted(buckets):
- ordered_bucket = sorted(
- buckets[key],
- key=lambda item: (
- -PRIORITY_RANK.get(item.priority, 0),
- _candidate_quality_rank(item),
- item.target_id,
- ",".join(item.relation_hints),
- ),
- )
- kept = ordered_bucket[: self.max_candidates_per_skill_relation]
- dropped = ordered_bucket[self.max_candidates_per_skill_relation:]
- limited.extend(kept)
- for candidate in dropped:
- LOGGER.debug(
- "candidate_skipped reason=max_candidates_per_skill_relation "
- "source=%s target=%s priority=%s methods=%s "
- "relation_hints=%s limit=%s",
- candidate.source_id,
- candidate.target_id,
- candidate.priority,
- ",".join(candidate.candidate_methods),
- ",".join(candidate.relation_hints),
- self.max_candidates_per_skill_relation,
- )
- return sorted(
- limited,
- key=lambda item: (
- item.source_id,
- -PRIORITY_RANK.get(item.priority, 0),
- item.target_id,
- ",".join(item.relation_hints),
- ),
- )
-
-
-class CandidateIndexes:
- def __init__(self) -> None:
- self.by_output_name: Dict[str, Set[str]] = defaultdict(set)
- self.by_input_name: Dict[str, Set[str]] = defaultdict(set)
- self.outputs_by_skill_name: Dict[Tuple[str, str], List[ArtifactSpec]] = (
- defaultdict(list)
- )
- self.inputs_by_skill_name: Dict[Tuple[str, str], List[ParameterSpec]] = (
- defaultdict(list)
- )
-
- @classmethod
- def from_skills(cls, skills: Iterable[Fingerprint]) -> "CandidateIndexes":
- indexes = cls()
- for skill in skills:
- for output in skill.outputs:
- indexes.by_output_name[output.name].add(skill.id)
- indexes.outputs_by_skill_name[(skill.id, output.name)].append(output)
- for parameter in skill.inputs:
- indexes.by_input_name[parameter.name].add(skill.id)
- indexes.inputs_by_skill_name[(skill.id, parameter.name)].append(
- parameter
- )
- return indexes
-
-
-class CandidateEvidenceMerger:
- """Merge directional evidence for repeated source-target candidates."""
-
- def __init__(self, *, max_port_mappings: int) -> None:
- self.max_port_mappings = max(1, max_port_mappings)
-
- def create(
- self,
- candidate: RelationCandidate,
- relation_hints: List[str],
- ) -> RelationCandidate:
- return self._limit_port_mappings(
- RelationCandidate(
- source_id=candidate.source_id,
- target_id=candidate.target_id,
- relation_hints=sorted(set(relation_hints)),
- candidate_methods=sorted(set(candidate.candidate_methods)),
- priority=candidate.priority,
- evidence=self._directional_evidence(candidate),
- )
- )
-
- def merge(
- self,
- existing: RelationCandidate,
- candidate: RelationCandidate,
- relation_hints: List[str],
- ) -> RelationCandidate:
- priority = (
- candidate.priority
- if PRIORITY_RANK.get(candidate.priority, 0)
- > PRIORITY_RANK.get(existing.priority, 0)
- else existing.priority
- )
- evidence = _merge_directional_evidence(
- existing.evidence,
- self._directional_evidence(candidate),
- )
- return self._limit_port_mappings(
- RelationCandidate(
- source_id=existing.source_id,
- target_id=existing.target_id,
- relation_hints=sorted(set(existing.relation_hints) | set(relation_hints)),
- candidate_methods=sorted(
- set(existing.candidate_methods) | set(candidate.candidate_methods)
- ),
- priority=priority,
- evidence=evidence,
- )
- )
-
- @staticmethod
- def _directional_evidence(candidate: RelationCandidate) -> Dict[str, object]:
- direction_key = f"{candidate.source_id}->{candidate.target_id}"
- return {"directions": {direction_key: candidate.evidence}}
-
- def _limit_port_mappings(self, candidate: RelationCandidate) -> RelationCandidate:
- return _limit_port_mappings_for_candidate(candidate, self.max_port_mappings)
-
-
-def _merge_evidence(
- left: Dict[str, object],
- right: Dict[str, object],
-) -> Dict[str, object]:
- merged = dict(left)
- for key, value in right.items():
- if key not in merged:
- merged[key] = value
- continue
- if isinstance(merged[key], list) and isinstance(value, list):
- merged_value = _dedupe_list(merged[key] + value)
- if key == "matched_types":
- merged[key] = sorted(str(item) for item in merged_value)
- else:
- merged[key] = merged_value
- return merged
-
-
-def _merge_directional_evidence(
- left: Dict[str, object],
- right: Dict[str, object],
-) -> Dict[str, object]:
- merged = dict(left)
- directions = dict(merged.get("directions", {}))
- for direction, evidence in dict(right.get("directions", {})).items():
- if (
- direction in directions
- and isinstance(directions[direction], dict)
- and isinstance(evidence, dict)
- ):
- directions[direction] = _merge_evidence(directions[direction], evidence)
- else:
- directions[direction] = evidence
- merged["directions"] = directions
- return merged
-
-
-def _limit_port_mappings_for_candidate(
- candidate: RelationCandidate,
- max_port_mappings: int,
-) -> RelationCandidate:
- directions = {}
- for direction, evidence in dict(candidate.evidence.get("directions", {})).items():
- if not isinstance(evidence, dict):
- directions[direction] = evidence
- continue
- limited_evidence = dict(evidence)
- mappings = [
- mapping
- for mapping in limited_evidence.get("port_mappings", [])
- if isinstance(mapping, dict)
- ]
- limited_evidence["port_mappings"] = _dedupe_port_mappings(
- sorted(mappings, key=_port_mapping_sort_key)
- )[:max_port_mappings]
- directions[direction] = limited_evidence
- return RelationCandidate(
- source_id=candidate.source_id,
- target_id=candidate.target_id,
- relation_hints=candidate.relation_hints,
- candidate_methods=candidate.candidate_methods,
- priority=candidate.priority,
- evidence={**candidate.evidence, "directions": directions},
- )
-
-
-def _candidate_quality_rank(candidate: RelationCandidate) -> tuple[int, int, int, int]:
- port_mapping_count = 0
- content_input_count = 0
- for evidence in dict(candidate.evidence.get("directions", {})).values():
- if not isinstance(evidence, dict):
- continue
- mappings = [
- mapping
- for mapping in evidence.get("port_mappings", [])
- if isinstance(mapping, dict)
- ]
- port_mapping_count += len(mappings)
- for mapping in mappings:
- target_input = str(mapping.get("target_input") or "")
- if target_input in GENERIC_CONTENT_INPUT_NAMES:
- content_input_count += 1
- for item in evidence.get("target_inputs", []):
- if not isinstance(item, dict):
- continue
- if str(item.get("name") or "") in GENERIC_CONTENT_INPUT_NAMES:
- content_input_count += 1
- return (
- -len(set(candidate.candidate_methods)),
- -int(port_mapping_count > 0),
- -port_mapping_count,
- -content_input_count,
- )
-
-
-def _dedupe_port_mappings(values: List[dict]) -> List[dict]:
- seen = set()
- result = []
- for value in values:
- marker = (
- value.get("source_output"),
- value.get("source_type"),
- value.get("target_input"),
- value.get("target_type"),
- )
- if marker in seen:
- continue
- seen.add(marker)
- result.append(value)
- return result
-
-
-def _port_mapping_sort_key(mapping: dict) -> tuple[int, str, str]:
- method_rank = 0 if mapping.get("match_method") == "exact_io_match" else 1
- return (
- method_rank,
- str(mapping.get("source_output") or ""),
- str(mapping.get("target_input") or ""),
- )
-
-
-def _dedupe_list(values: List[object]) -> List[object]:
- seen = set()
- result = []
- for value in values:
- marker = repr(value)
- if marker in seen:
- continue
- seen.add(marker)
- result.append(value)
- return result
-
-
-def _debug_candidate_generated(
- candidate: RelationCandidate,
- relation_hints: List[str],
-) -> None:
- if not LOGGER.isEnabledFor(logging.DEBUG):
- return
- evidence = candidate.evidence
- LOGGER.debug(
- "candidate_generated source=%s target=%s priority=%s methods=%s "
- "relation_hints=%s matched_terms=%s matched_types=%s",
- candidate.source_id,
- candidate.target_id,
- candidate.priority,
- ",".join(candidate.candidate_methods),
- ",".join(relation_hints),
- ",".join(str(item) for item in evidence.get("matched_terms", [])),
- ",".join(str(item) for item in evidence.get("matched_types", [])),
- )
-
-
-_DATA_TYPE_VOCAB = DataTypeVocabulary.default()
-
-
-def _skill_terms(skill: Fingerprint) -> Set[str]:
- terms: Set[str] = set()
- chunks = [skill.id, skill.name, skill.description]
- chunks.extend(item.name for item in skill.inputs)
- chunks.extend(item.description for item in skill.inputs)
- chunks.extend(item.name for item in skill.outputs)
- chunks.extend(item.description for item in skill.outputs)
- for chunk in chunks:
- terms.update(_tokenize(chunk))
- return terms
-
-
-def _has_semantic_overlap(
- output: ArtifactSpec,
- parameter: ParameterSpec,
-) -> bool:
- if output.name == parameter.name:
- return True
- output_terms = _tokenize(f"{output.name} {output.description}")
- input_terms = _tokenize(f"{parameter.name} {parameter.description}")
- return bool(output_terms & input_terms)
-
-
-def _can_feed_by_type(output_type: str, input_type: str) -> bool:
- return _DATA_TYPE_VOCAB.can_feed_by_type(output_type, input_type)
-
-
-def _can_feed_by_remote_reference(output: ArtifactSpec, parameter: ParameterSpec) -> bool:
- if output.type != "url":
- return False
- if parameter.type not in {"file", "image", "text"}:
- return False
- return _accepts_remote_reference(parameter)
-
-
-def _accepts_remote_reference(parameter: ParameterSpec) -> bool:
- inference = _DATA_TYPE_VOCAB.infer_from_io_semantics(
- parameter.name,
- parameter.description,
- )
- return inference is not None and inference.data_type == "url"
-
-
-def _can_feed_by_exact_or_subtype(output_type: str, input_type: str) -> bool:
- if output_type == input_type:
- return True
- return _DATA_TYPE_VOCAB.is_subtype(output_type, input_type)
-
-
-def _can_feed_via_textual_coercion(
- output: ArtifactSpec,
- parameter: ParameterSpec,
- input_terms: Set[str],
-) -> bool:
- if output.type not in _DATA_TYPE_VOCAB.CONTENT_CARRIER_TYPES:
- return False
- if parameter.type not in _DATA_TYPE_VOCAB.CONTENT_CARRIER_TYPES:
- return False
- if not _is_generic_content_input(parameter, input_terms):
- return False
- return True
-
-
-def _is_generic_content_input(parameter: ParameterSpec, input_terms: Set[str]) -> bool:
- return parameter.name in GENERIC_CONTENT_INPUT_NAMES or bool(
- input_terms & GENERIC_CONTENT_INPUT_NAMES
- )
-
-
-def _port_mapping(
- output: ArtifactSpec,
- parameter: ParameterSpec,
- *,
- match_method: str,
- match_reason: str,
-) -> dict:
- return {
- "source_output": output.name,
- "source_type": output.type,
- "target_input": parameter.name,
- "target_type": parameter.type,
- "match_reason": match_reason,
- "match_method": match_method,
- }
-
-
-def _match_reason_exact_io(output_type: str, input_type: str) -> str:
- if output_type == input_type:
- return "source output and target input share the same normalized name and type"
- return (
- f"source output type '{output_type}' is a subtype of "
- f"target input type '{input_type}'"
- )
-
-
-def _match_reason_semantic_overlap(
- output: ArtifactSpec,
- parameter: ParameterSpec,
-) -> str:
- if output.name == parameter.name:
- return "source output and target input share the same normalized name"
- return "source output and target input share semantic terms"
-
-
-def _match_reason_remote_reference(
- output: ArtifactSpec,
- parameter: ParameterSpec,
-) -> str:
- del output, parameter
- return "source output URL can satisfy target file-like input that accepts remote references"
-
-
-def _match_reason_textual_coercion(
- output: ArtifactSpec,
- parameter: ParameterSpec,
-) -> str:
- del output, parameter
- return "textual output can be coerced to generic content input"
-
-
-def _tokenize(text: str) -> Set[str]:
- return _GRAPH_TERM_LEXICON.tokenize(text)
diff --git a/jiuwenswarm/symphony/graph/lexicon.py b/jiuwenswarm/symphony/graph/lexicon.py
deleted file mode 100644
index 0f8655ed20..0000000000
--- a/jiuwenswarm/symphony/graph/lexicon.py
+++ /dev/null
@@ -1,103 +0,0 @@
-"""Shared lexical helpers for Skill graph candidate generation and indexing."""
-
-from __future__ import annotations
-
-import re
-import unicodedata
-from dataclasses import dataclass
-from typing import Iterable
-
-DEFAULT_GRAPH_STOP_TERMS = frozenset(
- {
- "and",
- "are",
- "for",
- "from",
- "into",
- "the",
- "this",
- "that",
- "with",
- }
-)
-
-DEFAULT_PLANNING_STOP_TERMS = frozenset(
- {
- "a",
- "an",
- "and",
- "are",
- "for",
- "from",
- "in",
- "into",
- "of",
- "on",
- "the",
- "this",
- "that",
- "to",
- "with",
- }
-)
-
-_ASCII_TOKEN_RE = re.compile(r"[a-z0-9]+")
-_CJK_CHUNK_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff]+")
-
-
-@dataclass(frozen=True)
-class ArtifactLexicon:
- """Tokenization and generic-name rules for one graph lexical profile."""
-
- stop_terms: frozenset[str]
- min_token_length: int
- generic_io_names: frozenset[str] = frozenset()
-
- @classmethod
- def create(
- cls,
- *,
- stop_terms: Iterable[str],
- min_token_length: int,
- generic_io_names: Iterable[str] = (),
- ) -> "ArtifactLexicon":
- return cls(
- stop_terms=frozenset(normalize_text(term) for term in stop_terms),
- min_token_length=max(1, int(min_token_length)),
- generic_io_names=normalize_terms(generic_io_names),
- )
-
- def tokenize(self, text: str) -> set[str]:
- normalized = normalize_text(text)
- tokens = set()
-
- for token in _ASCII_TOKEN_RE.findall(normalized):
- if len(token) >= self.min_token_length and token not in self.stop_terms:
- tokens.add(token)
-
- for chunk in _CJK_CHUNK_RE.findall(normalized):
- if len(chunk) < 2:
- continue
- tokens.update(_cjk_terms(chunk))
-
- return tokens
-
- def is_generic_io_name(self, name: object) -> bool:
- return normalize_text(name) in self.generic_io_names
-
-
-def normalize_text(text: object) -> str:
- return unicodedata.normalize("NFKC", str(text)).lower()
-
-
-def normalize_terms(terms: Iterable[str]) -> frozenset[str]:
- return frozenset(normalize_text(term) for term in terms)
-
-
-def _cjk_terms(chunk: str) -> set[str]:
- terms = {chunk}
- if len(chunk) == 2:
- return terms
- for index in range(len(chunk) - 1):
- terms.add(chunk[index: index + 2])
- return terms
diff --git a/jiuwenswarm/symphony/graph/matcher/__init__.py b/jiuwenswarm/symphony/graph/matcher/__init__.py
deleted file mode 100644
index 1146a3654e..0000000000
--- a/jiuwenswarm/symphony/graph/matcher/__init__.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""LLM-backed relation matching for Skill graph."""
-
-from jiuwenswarm.symphony.graph.matcher.matcher import (
- CachedOntologyMatcher,
- DEFAULT_THRESHOLDS,
- OntologyMatcher,
- OpenAICompatibleOntologyMatcher,
- validate_llm_matches,
-)
-
-__all__ = [
- "DEFAULT_THRESHOLDS",
- "CachedOntologyMatcher",
- "OntologyMatcher",
- "OpenAICompatibleOntologyMatcher",
- "validate_llm_matches",
-]
diff --git a/jiuwenswarm/symphony/graph/matcher/cache.py b/jiuwenswarm/symphony/graph/matcher/cache.py
deleted file mode 100644
index 125b303893..0000000000
--- a/jiuwenswarm/symphony/graph/matcher/cache.py
+++ /dev/null
@@ -1,279 +0,0 @@
-"""Persistent cache for ontology relation matching."""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import os
-from dataclasses import dataclass
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Any, Iterable
-
-from jiuwenswarm.symphony.fingerprint.models import Fingerprint
-from jiuwenswarm.symphony.graph.models import LLMMatch, RelationCandidate, SkillRegistry
-
-
-@dataclass(frozen=True)
-class RelationCacheStats:
- reused_count: int = 0
- resolved_count: int = 0
- stored_count: int = 0
-
-
-class CachedOntologyMatcher:
- """Wrap an ontology matcher with a per-candidate persistent cache."""
-
- def __init__(
- self,
- matcher: Any,
- cache_path: str | Path,
- *,
- fingerprints: Iterable[Fingerprint],
- ) -> None:
- self.matcher = matcher
- self.cache = RelationMatchCache(
- cache_path,
- matcher_signature=_matcher_signature(matcher),
- fingerprints=fingerprints,
- )
- self.diagnostics = []
- self.stats = RelationCacheStats()
-
- async def match(
- self,
- registry: SkillRegistry,
- candidates: Iterable[RelationCandidate],
- ) -> list[LLMMatch]:
- candidate_list = list(candidates)
- cached_matches: list[tuple[int, list[LLMMatch]]] = []
- misses: list[tuple[int, RelationCandidate]] = []
- reused_count = 0
- for index, candidate in enumerate(candidate_list):
- matches = self.cache.load(candidate)
- if matches is None:
- misses.append((index, candidate))
- continue
- cached_matches.append((index, matches))
- reused_count += 1
-
- resolved_by_index: dict[int, list[LLMMatch]] = {}
- diagnostics: list[Any] = []
- if misses:
- # 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)
- )
- resolved_by_candidate = _matches_by_candidate(
- miss_candidates,
- resolved_matches,
- )
- for index, candidate in window:
- matches = resolved_by_candidate.get(candidate.key, [])
- resolved_by_index[index] = matches
- self.cache.store(candidate, matches)
- self.cache.flush()
- if hasattr(self.matcher, "diagnostics"):
- diagnostics.extend(list(self.matcher.diagnostics))
-
- combined: list[tuple[int, LLMMatch]] = []
- for index, matches in cached_matches:
- combined.extend((index, match) for match in matches)
- for index, matches in resolved_by_index.items():
- combined.extend((index, match) for match in matches)
-
- if diagnostics:
- self.diagnostics = diagnostics
- elif hasattr(self.matcher, "diagnostics"):
- self.diagnostics = list(self.matcher.diagnostics)
- self.stats = RelationCacheStats(
- reused_count=reused_count,
- resolved_count=len(misses),
- stored_count=len(misses),
- )
- ordered_matches = []
- for _index, match in sorted(
- combined,
- key=lambda item: (item[0], item[1].source_id, item[1].target_id),
- ):
- ordered_matches.append(match)
- return ordered_matches
-
- def manifest_metadata(self) -> dict[str, Any]:
- if hasattr(self.matcher, "manifest_metadata"):
- metadata = dict(self.matcher.manifest_metadata())
- else:
- metadata = {"matcher": self.matcher.__class__.__name__}
- metadata["relation_cache"] = {
- "schema_version": "Symphony-relation-match-cache-v1",
- "reused_count": self.stats.reused_count,
- "resolved_count": self.stats.resolved_count,
- }
- return metadata
-
- @property
- def thresholds(self) -> dict[str, float]:
- return dict(getattr(self.matcher, "thresholds", {}))
-
-
-class RelationMatchCache:
- """JSON cache keyed by candidate evidence, fingerprints, and matcher config."""
-
- def __init__(
- self,
- path: str | Path,
- *,
- matcher_signature: dict[str, Any],
- fingerprints: Iterable[Fingerprint],
- ) -> None:
- self.path = Path(path).resolve()
- self.matcher_signature = matcher_signature
- self.fingerprint_hashes = {
- item.id: _stable_sha256(item.graph_identity_dict())
- for item in fingerprints
- }
- self._records = self._load()
- self._dirty = False
-
- def load(self, candidate: RelationCandidate) -> list[LLMMatch] | None:
- record = self._records.get(self._key(candidate))
- if not isinstance(record, dict):
- return None
- if record.get("schema_version") != "Symphony-relation-match-cache-v1":
- return None
- return [
- _match_from_dict(item)
- for item in record.get("matches", [])
- if isinstance(item, dict)
- ]
-
- def store(self, candidate: RelationCandidate, matches: list[LLMMatch]) -> None:
- self._records[self._key(candidate)] = {
- "schema_version": "Symphony-relation-match-cache-v1",
- "candidate_id": candidate.key,
- "matches": [match.to_dict() for match in matches],
- "updated_at": datetime.now(timezone.utc).isoformat(),
- }
- self._dirty = True
-
- def flush(self) -> None:
- if not self._dirty:
- return
- self.path.parent.mkdir(parents=True, exist_ok=True)
- payload = {
- "schema_version": "Symphony-relation-match-cache-index-v1",
- "records": self._records,
- }
- tmp = self.path.with_suffix(self.path.suffix + ".tmp")
- tmp.write_text(
- json.dumps(payload, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
- os.replace(tmp, self.path)
- self._dirty = False
-
- def _load(self) -> dict[str, Any]:
- if not self.path.is_file():
- return {}
- try:
- payload = json.loads(self.path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- return {}
- records = payload.get("records")
- return records if isinstance(records, dict) else {}
-
- def _key(self, candidate: RelationCandidate) -> str:
- source_hash = self.fingerprint_hashes.get(candidate.source_id, "")
- target_hash = self.fingerprint_hashes.get(candidate.target_id, "")
- payload = {
- "candidate": candidate.to_dict(),
- "source_fingerprint_hash": source_hash,
- "target_fingerprint_hash": target_hash,
- "matcher": self.matcher_signature,
- }
- return _stable_sha256(payload)
-
-
-def _matches_by_candidate(
- candidates: list[RelationCandidate],
- matches: list[LLMMatch],
-) -> dict[str, list[LLMMatch]]:
- candidate_by_pair = {}
- for candidate in candidates:
- candidate_by_pair[(candidate.source_id, candidate.target_id)] = candidate.key
- candidate_by_pair[(candidate.target_id, candidate.source_id)] = candidate.key
- output: dict[str, list[LLMMatch]] = {candidate.key: [] for candidate in candidates}
- for match in matches:
- candidate_key = match.candidate_id or candidate_by_pair.get(
- (match.source_id, match.target_id)
- )
- if candidate_key in output:
- output[candidate_key].append(match)
- return output
-
-
-def _matcher_signature(matcher: Any) -> dict[str, Any]:
- if hasattr(matcher, "manifest_metadata"):
- metadata = dict(matcher.manifest_metadata())
- else:
- metadata = {"matcher": matcher.__class__.__name__}
- metadata.pop("api_key", None)
- metadata.pop("base_url", None)
- thresholds = getattr(matcher, "thresholds", None)
- if thresholds is not None:
- metadata["thresholds"] = dict(thresholds)
- return metadata
-
-
-def _matcher_batch_size(matcher: Any) -> int:
- try:
- return max(1, int(getattr(matcher, "batch_size", 0) or 0))
- except (TypeError, ValueError):
- 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]
- for index in range(0, len(values), max(1, size))
- ]
-
-
-def _match_from_dict(payload: dict[str, Any]) -> LLMMatch:
- return LLMMatch(
- source_id=str(payload.get("source_id") or ""),
- target_id=str(payload.get("target_id") or ""),
- relation_type=str(payload.get("relation_type") or ""),
- confidence=float(payload.get("confidence") or 0.0),
- method=str(payload.get("method") or "llm_ontology_match"),
- reasons=[str(item) for item in payload.get("reasons", [])],
- supporting_fields=(
- payload.get("supporting_fields")
- if isinstance(payload.get("supporting_fields"), dict)
- else {}
- ),
- candidate_id=payload.get("candidate_id"),
- accepted=bool(payload.get("accepted", False)),
- diagnostics=[str(item) for item in payload.get("diagnostics", [])],
- raw=payload.get("raw") if isinstance(payload.get("raw"), dict) else {},
- )
-
-
-def _stable_sha256(payload: Any) -> str:
- return hashlib.sha256(
- json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
- ).hexdigest()
diff --git a/jiuwenswarm/symphony/graph/matcher/consensus.py b/jiuwenswarm/symphony/graph/matcher/consensus.py
deleted file mode 100644
index 05a6ad9a33..0000000000
--- a/jiuwenswarm/symphony/graph/matcher/consensus.py
+++ /dev/null
@@ -1,180 +0,0 @@
-"""Consensus merging for order-swapped LLM relation matching."""
-
-from __future__ import annotations
-
-from typing import Any, Dict, List, Optional
-
-from jiuwenswarm.symphony.graph.models import GraphDiagnostic, LLMMatch
-
-
-def consensus_matches(
- first_matches: List[LLMMatch],
- second_matches: List[LLMMatch],
-) -> tuple[List[LLMMatch], List[GraphDiagnostic]]:
- first_by_key = {
- _match_key(match): match for match in first_matches if match.accepted
- }
- second_by_key = {
- _match_key(match): match for match in second_matches if match.accepted
- }
- first_all_by_key = _matches_by_key(first_matches)
- second_all_by_key = _matches_by_key(second_matches)
- first_by_candidate = _matches_by_candidate(first_matches)
- second_by_candidate = _matches_by_candidate(second_matches)
- shared_keys = sorted(set(first_by_key) & set(second_by_key))
- consensus: List[LLMMatch] = []
- diagnostics: List[GraphDiagnostic] = []
-
- for key in shared_keys:
- first = first_by_key[key]
- second = second_by_key[key]
- consensus.append(
- LLMMatch(
- source_id=first.source_id,
- target_id=first.target_id,
- relation_type=first.relation_type,
- confidence=min(first.confidence, second.confidence),
- method="llm_consensus_match",
- reasons=_dedupe_strings(first.reasons + second.reasons),
- supporting_fields=_merge_supporting_fields(
- first.supporting_fields,
- second.supporting_fields,
- ),
- candidate_id=first.candidate_id,
- accepted=True,
- raw={
- "first": first.raw,
- "second": second.raw,
- "first_confidence": first.confidence,
- "second_confidence": second.confidence,
- },
- )
- )
-
- for key in sorted(set(first_by_key) ^ set(second_by_key)):
- match = first_by_key.get(key) or second_by_key[key]
- present_in = "first_run" if key in first_by_key else "second_run"
- missing_from = "second_run" if present_in == "first_run" else "first_run"
- diagnostics.append(
- GraphDiagnostic(
- stage="llm_match",
- severity="info",
- code="no_consensus_match",
- message="LLM match did not appear in both order-swapped runs.",
- skill_id=match.source_id,
- details={
- "candidate_id": match.candidate_id,
- "source_id": match.source_id,
- "target_id": match.target_id,
- "relation_type": match.relation_type,
- "present_in": present_in,
- "missing_consensus_from": missing_from,
- "consensus_key": _match_key_details(key),
- "first_run": _consensus_run_details(
- accepted_match=first_by_key.get(key),
- same_key_matches=first_all_by_key.get(key, []),
- same_candidate_matches=first_by_candidate.get(
- match.candidate_id, []
- ),
- ),
- "second_run": _consensus_run_details(
- accepted_match=second_by_key.get(key),
- same_key_matches=second_all_by_key.get(key, []),
- same_candidate_matches=second_by_candidate.get(
- match.candidate_id, []
- ),
- ),
- "match": match.to_dict(),
- },
- )
- )
-
- return consensus, diagnostics
-
-
-def _matches_by_key(
- matches: List[LLMMatch],
-) -> Dict[tuple[str, str, str, Optional[str]], List[LLMMatch]]:
- grouped: Dict[tuple[str, str, str, Optional[str]], List[LLMMatch]] = {}
- for match in matches:
- grouped.setdefault(_match_key(match), []).append(match)
- return grouped
-
-
-def _matches_by_candidate(
- matches: List[LLMMatch],
-) -> Dict[Optional[str], List[LLMMatch]]:
- grouped: Dict[Optional[str], List[LLMMatch]] = {}
- for match in matches:
- grouped.setdefault(match.candidate_id, []).append(match)
- return grouped
-
-
-def _consensus_run_details(
- *,
- accepted_match: Optional[LLMMatch],
- same_key_matches: List[LLMMatch],
- same_candidate_matches: List[LLMMatch],
-) -> Dict[str, Any]:
- if accepted_match is not None:
- status = "accepted"
- elif same_key_matches:
- status = "same_key_not_accepted"
- elif same_candidate_matches:
- status = "same_candidate_different_match"
- else:
- status = "not_returned"
-
- return {
- "status": status,
- "accepted_match": (
- accepted_match.to_dict() if accepted_match is not None else None
- ),
- "same_key_matches": [match.to_dict() for match in same_key_matches],
- "same_candidate_matches": [
- match.to_dict() for match in same_candidate_matches
- ],
- }
-
-
-def _match_key(match: LLMMatch) -> tuple[str, str, str, Optional[str]]:
- return (
- match.source_id,
- match.target_id,
- match.relation_type,
- match.candidate_id,
- )
-
-
-def _match_key_details(
- key: tuple[str, str, str, Optional[str]]
-) -> Dict[str, Optional[str]]:
- source_id, target_id, relation_type, candidate_id = key
- return {
- "source_id": source_id,
- "target_id": target_id,
- "relation_type": relation_type,
- "candidate_id": candidate_id,
- }
-
-
-def _dedupe_strings(values: List[str]) -> List[str]:
- seen = set()
- result = []
- for value in values:
- if value in seen:
- continue
- seen.add(value)
- result.append(value)
- return result
-
-
-def _merge_supporting_fields(left: Dict[str, Any], right: Dict[str, Any]) -> Dict[str, Any]:
- merged = dict(left)
- for key, value in right.items():
- if key not in merged:
- merged[key] = value
- continue
- if isinstance(merged[key], list) and isinstance(value, list):
- merged[key] = _dedupe_strings([str(item) for item in merged[key] + value])
- return merged
diff --git a/jiuwenswarm/symphony/graph/matcher/constants.py b/jiuwenswarm/symphony/graph/matcher/constants.py
deleted file mode 100644
index ea3c923a2f..0000000000
--- a/jiuwenswarm/symphony/graph/matcher/constants.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""Shared matcher constants."""
-
-DEFAULT_THRESHOLDS = {
- "can_feed": 0.7,
-}
diff --git a/jiuwenswarm/symphony/graph/matcher/matcher.py b/jiuwenswarm/symphony/graph/matcher/matcher.py
deleted file mode 100644
index b23b09bee2..0000000000
--- a/jiuwenswarm/symphony/graph/matcher/matcher.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""LLM-backed ontology relation matching."""
-
-from jiuwenswarm.symphony.graph.matcher.openai import (
- DEFAULT_THRESHOLDS,
- MatchProgress,
- OntologyMatcher,
- OpenAICompatibleOntologyMatcher,
-)
-from jiuwenswarm.symphony.graph.matcher.cache import CachedOntologyMatcher
-from jiuwenswarm.symphony.graph.matcher.validation import validate_llm_matches
-
-__all__ = [
- "DEFAULT_THRESHOLDS",
- "CachedOntologyMatcher",
- "MatchProgress",
- "OntologyMatcher",
- "OpenAICompatibleOntologyMatcher",
- "validate_llm_matches",
-]
diff --git a/jiuwenswarm/symphony/graph/matcher/openai.py b/jiuwenswarm/symphony/graph/matcher/openai.py
deleted file mode 100644
index 8dee072b99..0000000000
--- a/jiuwenswarm/symphony/graph/matcher/openai.py
+++ /dev/null
@@ -1,279 +0,0 @@
-"""OpenAI-compatible ontology relation matcher."""
-
-from __future__ import annotations
-
-import asyncio
-import json
-from typing import Any, Awaitable, Dict, Iterable, List, Optional, Protocol
-
-from jiuwenswarm.symphony.graph.matcher.constants import DEFAULT_THRESHOLDS
-from jiuwenswarm.symphony.graph.matcher.consensus import consensus_matches
-from jiuwenswarm.symphony.graph.matcher.prompt import (
- SYSTEM_PROMPT,
- build_llm_context,
- expand_compact_llm_response,
-)
-from jiuwenswarm.symphony.graph.matcher.validation import validate_llm_matches
-from jiuwenswarm.symphony.graph.models import GraphDiagnostic, LLMMatch, RelationCandidate, SkillRegistry
-from jiuwenswarm.symphony.llm import (
- LLMConfig,
- create_llm_client,
- llm_usage_context,
- thinking_disabled_request_overrides,
-)
-
-
-class OntologyMatcher(Protocol):
- """Protocol for relation candidate matchers."""
-
- async def match(
- self,
- registry: SkillRegistry,
- candidates: Iterable[RelationCandidate],
- ) -> List[LLMMatch]:
- ...
-
-
-class MatchProgress(Protocol):
- """Progress callback for LLM candidate matching."""
-
- def __call__(self, event: str, current: int, total: int, details: Dict[str, Any]) -> None:
- ...
-
-
-class OpenAICompatibleOntologyMatcher:
- """Validate relation candidates through an OpenAI-compatible chat endpoint."""
-
- def __init__(
- self,
- config: LLMConfig,
- *,
- batch_size: int = 12,
- max_workers: int = 1,
- require_consensus: bool = True,
- prompt_version: str = "Orchestration-graph-match-v2",
- thresholds: Optional[Dict[str, float]] = None,
- progress: Optional[MatchProgress] = None,
- ) -> None:
- self.config = config
- self.batch_size = batch_size
- self.max_workers = max(1, max_workers)
- self.require_consensus = require_consensus
- self.prompt_version = prompt_version
- self.thresholds = thresholds if thresholds is not None else DEFAULT_THRESHOLDS
- self.progress = progress
- self.client = create_llm_client(config)
- self.diagnostics: List[GraphDiagnostic] = []
-
- async def match(
- self,
- registry: SkillRegistry,
- candidates: Iterable[RelationCandidate],
- ) -> List[LLMMatch]:
- candidate_list = list(candidates)
- matches: List[LLMMatch] = []
- self.diagnostics = []
- total_batches = (
- (len(candidate_list) + self.batch_size - 1) // self.batch_size
- if candidate_list
- else 0
- )
- self._emit_progress(
- "matching_start",
- 0,
- total_batches,
- {
- "candidate_count": len(candidate_list),
- "batch_size": self.batch_size,
- "max_workers": self.max_workers,
- "consensus_runs": 2 if self.require_consensus else 1,
- },
- )
- batches = []
- for batch_index, start in enumerate(
- range(0, len(candidate_list), self.batch_size),
- start=1,
- ):
- batches.append(
- (batch_index, candidate_list[start: start + self.batch_size])
- )
- batch_sizes = {batch_index: len(batch) for batch_index, batch in batches}
- request_semaphore = asyncio.Semaphore(self.max_workers)
- results = await _gather_cancel_on_error(
- *(
- self._match_batch(
- registry,
- batch,
- batch_index,
- total_batches,
- request_semaphore=request_semaphore,
- )
- for batch_index, batch in batches
- )
- )
-
- for batch_index, batch_matches, batch_diagnostics in sorted(
- results,
- key=lambda item: item[0],
- ):
- self.diagnostics.extend(batch_diagnostics)
- matches.extend(batch_matches)
- self._emit_progress(
- "batch_done",
- batch_index,
- total_batches,
- {
- "candidate_count": batch_sizes[batch_index],
- "match_count": len(batch_matches),
- "accepted_count": len(
- [match for match in batch_matches if match.accepted]
- ),
- "diagnostics_count": len(batch_diagnostics),
- },
- )
- self._emit_progress(
- "matching_done",
- total_batches,
- total_batches,
- {
- "match_count": len(matches),
- "accepted_count": len([match for match in matches if match.accepted]),
- "diagnostics_count": len(self.diagnostics),
- },
- )
- return matches
-
- def manifest_metadata(self) -> Dict[str, Any]:
- return {
- "model": self.config.model,
- "backend": self.config.backend,
- "temperature": self.config.temperature,
- "prompt_version": self.prompt_version,
- "batch_size": self.batch_size,
- "max_workers": self.max_workers,
- "require_consensus": self.require_consensus,
- "consensus_runs": 2 if self.require_consensus else 1,
- }
-
- async def _match_batch(
- self,
- registry: SkillRegistry,
- batch: List[RelationCandidate],
- batch_index: int,
- total_batches: int,
- *,
- request_semaphore: asyncio.Semaphore,
- ) -> tuple[int, List[LLMMatch], List[GraphDiagnostic]]:
- self._emit_progress(
- "batch_start",
- batch_index,
- total_batches,
- {
- "candidate_count": len(batch),
- "candidate_ids": [candidate.key for candidate in batch],
- "consensus_runs": 2 if self.require_consensus else 1,
- },
- )
-
- async def request(
- *,
- reverse_skill_order: bool,
- ) -> tuple[List[LLMMatch], List[GraphDiagnostic]]:
- async with request_semaphore:
- return await self._request_and_validate_batch(
- registry,
- batch,
- reverse_skill_order=reverse_skill_order,
- )
-
- if not self.require_consensus:
- first_matches, first_diagnostics = await request(
- reverse_skill_order=False,
- )
- return batch_index, first_matches, first_diagnostics
-
- first_result, second_result = await _gather_cancel_on_error(
- request(reverse_skill_order=False),
- request(reverse_skill_order=True),
- )
- first_matches, first_diagnostics = first_result
- second_matches, second_diagnostics = second_result
- agreed_matches, consensus_diagnostics = consensus_matches(
- first_matches,
- second_matches,
- )
- return (
- batch_index,
- agreed_matches,
- first_diagnostics + second_diagnostics + consensus_diagnostics,
- )
-
- async def _request_and_validate_batch(
- self,
- registry: SkillRegistry,
- batch: List[RelationCandidate],
- *,
- reverse_skill_order: bool,
- ) -> tuple[List[LLMMatch], List[GraphDiagnostic]]:
- payload = build_llm_context(
- registry,
- batch,
- reverse_skill_order=reverse_skill_order,
- )
- operation = (
- "ontology_matching_reverse"
- if reverse_skill_order
- else "ontology_matching_forward"
- )
- with llm_usage_context("graph_construction", operation):
- content = await self.client.complete_json_async(
- system_prompt=SYSTEM_PROMPT,
- user_content=json.dumps(
- payload,
- ensure_ascii=False,
- separators=(",", ":"),
- ),
- timeout=200,
- error_context="LLM graph matching",
- request_overrides=thinking_disabled_request_overrides(),
- )
- try:
- raw_payload = json.loads(content)
- except json.JSONDecodeError as exc:
- raise RuntimeError(
- "LLM graph matching response is not valid JSON. "
- f"content_prefix={content[:1000]!r}"
- ) from exc
- expanded_payload, protocol_diagnostics = expand_compact_llm_response(
- raw_payload,
- batch,
- )
- batch_matches, batch_diagnostics = validate_llm_matches(
- expanded_payload,
- registry,
- batch,
- thresholds=self.thresholds,
- )
- return batch_matches, protocol_diagnostics + batch_diagnostics
-
- def _emit_progress(
- self,
- event: str,
- current: int,
- total: int,
- details: Dict[str, Any],
- ) -> None:
- if self.progress is None:
- return
- self.progress(event, current, total, details)
-
-
-async def _gather_cancel_on_error(*awaitables: Awaitable[Any]) -> List[Any]:
- tasks = [asyncio.ensure_future(awaitable) for awaitable in awaitables]
- try:
- return list(await asyncio.gather(*tasks))
- except BaseException:
- for task in tasks:
- task.cancel()
- await asyncio.gather(*tasks, return_exceptions=True)
- raise
diff --git a/jiuwenswarm/symphony/graph/matcher/prompt.py b/jiuwenswarm/symphony/graph/matcher/prompt.py
deleted file mode 100644
index ef973bd3e1..0000000000
--- a/jiuwenswarm/symphony/graph/matcher/prompt.py
+++ /dev/null
@@ -1,271 +0,0 @@
-"""Compact prompt protocol for LLM relation matching."""
-
-from __future__ import annotations
-
-from typing import Any, Dict, List
-
-from jiuwenswarm.symphony.fingerprint.models import Fingerprint
-from jiuwenswarm.symphony.graph.models import (
- GraphDiagnostic,
- RelationCandidate,
- SkillRegistry,
-)
-from jiuwenswarm.symphony.shared.llm_payload import prune_empty
-
-_MAX_SKILL_DESCRIPTION_LENGTH = 240
-_MAX_PORT_DESCRIPTION_LENGTH = 160
-_MAX_REASON_LENGTH = 160
-
-
-def build_llm_context(
- registry: SkillRegistry,
- candidates: List[RelationCandidate],
- *,
- reverse_skill_order: bool = False,
-) -> Dict[str, Any]:
- indexed = [
- (f"c{index}", candidate)
- for index, candidate in enumerate(candidates, start=1)
- ]
- if reverse_skill_order:
- indexed.reverse()
- return {
- "candidates": [
- _candidate_context(candidate_id, registry, candidate)
- for candidate_id, candidate in indexed
- ]
- }
-
-
-def expand_compact_llm_response(
- payload: Dict[str, Any],
- candidates: List[RelationCandidate],
-) -> tuple[Dict[str, Any], List[GraphDiagnostic]]:
- candidates_by_id = {
- f"c{index}": candidate
- for index, candidate in enumerate(candidates, start=1)
- }
- matches = payload.get("matches", [])
- if not isinstance(matches, list):
- return {"matches": matches}, []
-
- expanded = []
- diagnostics = []
- seen = set()
- for item in matches:
- if not isinstance(item, dict):
- diagnostics.append(_protocol_diagnostic(
- "invalid_match_item",
- "Compact LLM match item must be an object.",
- ))
- continue
- candidate_id = str(item.get("id") or "").strip()
- if candidate_id not in candidates_by_id:
- diagnostics.append(_protocol_diagnostic(
- "unknown_candidate_id",
- f"Compact LLM match returned unknown candidate id: {candidate_id!r}.",
- ))
- continue
- if candidate_id in seen:
- diagnostics.append(_protocol_diagnostic(
- "duplicate_candidate_id",
- f"Compact LLM match repeated candidate id: {candidate_id!r}.",
- ))
- continue
- seen.add(candidate_id)
- candidate = candidates_by_id[candidate_id]
- direction = str(item.get("direction") or "forward").strip().lower()
- if direction not in {"forward", "reverse"}:
- diagnostics.append(_protocol_diagnostic(
- "invalid_candidate_direction",
- f"Compact LLM match returned invalid direction: {direction!r}.",
- ))
- continue
- source_id, target_id = _directed_ids(candidate, direction)
- evidence = _directional_evidence(candidate, source_id, target_id)
- if not evidence:
- diagnostics.append(_protocol_diagnostic(
- "unsupported_candidate_direction",
- f"Candidate {candidate_id!r} has no evidence for {direction}.",
- ))
- continue
- reason = str(item.get("reason") or "").strip()[:_MAX_REASON_LENGTH]
- expanded.append({
- "candidate_id": candidate.key,
- "source_id": source_id,
- "target_id": target_id,
- "relation_type": "can_feed",
- "confidence": item.get("confidence", 0),
- "method": "llm_ontology_match",
- "reasons": [reason] if reason else [],
- "supporting_fields": _supporting_fields(evidence),
- })
- return {"matches": expanded}, diagnostics
-
-
-def _candidate_context(
- candidate_id: str,
- registry: SkillRegistry,
- candidate: RelationCandidate,
-) -> Dict[str, Any]:
- source = registry.skills[candidate.source_id]
- target = registry.skills[candidate.target_id]
- directions = {}
- for direction, source_id, target_id in (
- ("forward", candidate.source_id, candidate.target_id),
- ("reverse", candidate.target_id, candidate.source_id),
- ):
- evidence = _directional_evidence(candidate, source_id, target_id)
- if evidence:
- directions[direction] = _evidence_context(evidence)
- return {
- "id": candidate_id,
- "source": _skill_context(source),
- "target": _skill_context(target),
- "directions": directions,
- }
-
-
-def _skill_context(skill: Fingerprint) -> Dict[str, str]:
- return prune_empty({
- "name": skill.name,
- "description": skill.description[:_MAX_SKILL_DESCRIPTION_LENGTH],
- })
-
-
-def _evidence_context(evidence: Dict[str, Any]) -> Dict[str, Any]:
- outputs = _compact_fields(evidence.get("source_outputs", []))
- inputs = _compact_fields(evidence.get("target_inputs", []))
- ports = []
- seen = set()
- for mapping in evidence.get("port_mappings", []):
- if not isinstance(mapping, dict):
- continue
- port = prune_empty({
- "output": mapping.get("source_output"),
- "output_type": mapping.get("source_type"),
- "input": mapping.get("target_input"),
- "input_type": mapping.get("target_type"),
- })
- marker = tuple(sorted(port.items()))
- if not port or marker in seen:
- continue
- seen.add(marker)
- ports.append(port)
- return prune_empty({
- "outputs": outputs,
- "inputs": inputs,
- "ports": ports,
- })
-
-
-def _compact_fields(values: Any) -> List[Dict[str, Any]]:
- output = []
- seen = set()
- for item in values if isinstance(values, list) else []:
- if not isinstance(item, dict):
- continue
- field = prune_empty({
- "name": item.get("name"),
- "type": item.get("type"),
- "required": item.get("required"),
- "description": str(item.get("description") or "")[
- :_MAX_PORT_DESCRIPTION_LENGTH
- ],
- })
- marker = (
- field.get("name"),
- field.get("type"),
- field.get("required"),
- )
- if marker in seen:
- continue
- seen.add(marker)
- output.append(field)
- return output
-
-
-def _directional_evidence(
- candidate: RelationCandidate,
- source_id: str,
- target_id: str,
-) -> Dict[str, Any]:
- directions = candidate.evidence.get("directions", {})
- if isinstance(directions, dict):
- evidence = directions.get(f"{source_id}->{target_id}")
- if isinstance(evidence, dict):
- return evidence
- if "directions" in candidate.evidence:
- return {}
- if source_id == candidate.source_id and target_id == candidate.target_id:
- return candidate.evidence
- return {}
-
-
-def _directed_ids(
- candidate: RelationCandidate,
- direction: str,
-) -> tuple[str, str]:
- if direction == "reverse":
- return candidate.target_id, candidate.source_id
- return candidate.source_id, candidate.target_id
-
-
-def _supporting_fields(evidence: Dict[str, Any]) -> Dict[str, Any]:
- pairs = []
- source_outputs = set()
- target_inputs = set()
- for mapping in evidence.get("port_mappings", []):
- if not isinstance(mapping, dict):
- continue
- source_output = str(mapping.get("source_output") or "").strip()
- target_input = str(mapping.get("target_input") or "").strip()
- if not source_output or not target_input:
- continue
- pair = {
- "source_output": source_output,
- "target_input": target_input,
- }
- if pair not in pairs:
- pairs.append(pair)
- source_outputs.add(source_output)
- target_inputs.add(target_input)
- if not pairs:
- source_outputs.update(_field_names(evidence.get("source_outputs", [])))
- target_inputs.update(_field_names(evidence.get("target_inputs", [])))
- return prune_empty({
- "port_mappings": pairs,
- "source_outputs": sorted(source_outputs),
- "target_inputs": sorted(target_inputs),
- })
-
-
-def _field_names(values: Any) -> List[str]:
- if not isinstance(values, list):
- return []
- names: List[str] = []
- for item in values:
- if isinstance(item, dict) and item.get("name"):
- names.append(str(item["name"]))
- return names
-
-
-def _protocol_diagnostic(code: str, message: str) -> GraphDiagnostic:
- return GraphDiagnostic(
- stage="llm_match",
- severity="warning",
- code=code,
- message=message,
- )
-
-
-SYSTEM_PROMPT = """Validate whether each candidate Skill output can feed the target input.
-
-Return JSON only:
-{"matches":[{"id":"c1","direction":"forward|reverse","confidence":0.0,"reason":"optional short reason"}]}
-
-Return at most one judgment per candidate id. Use only directions and ports
-present in the request. Omit invalid relations or assign low confidence.
-Confidence must be between 0 and 1. Keep reason to one short sentence when
-useful; do not repeat request data or invent Skills, ports or relations.
-"""
diff --git a/jiuwenswarm/symphony/graph/matcher/validation.py b/jiuwenswarm/symphony/graph/matcher/validation.py
deleted file mode 100644
index 41354ee269..0000000000
--- a/jiuwenswarm/symphony/graph/matcher/validation.py
+++ /dev/null
@@ -1,251 +0,0 @@
-"""Validate raw LLM relation match payloads."""
-
-from __future__ import annotations
-
-from typing import Any, Dict, Iterable, List, Optional
-
-from jiuwenswarm.symphony.graph.matcher.constants import DEFAULT_THRESHOLDS
-from jiuwenswarm.symphony.graph.models import (
- ALLOWED_RELATION_TYPES,
- GraphDiagnostic,
- LLMMatch,
- RelationCandidate,
- SkillRegistry,
-)
-
-
-def validate_llm_matches(
- payload: Dict[str, Any],
- registry: SkillRegistry,
- candidates: Iterable[RelationCandidate],
- *,
- thresholds: Optional[Dict[str, float]] = None,
-) -> tuple[List[LLMMatch], List[GraphDiagnostic]]:
- """Normalize and validate raw LLM matches."""
-
- thresholds = thresholds if thresholds is not None else DEFAULT_THRESHOLDS
- candidate_by_key = {candidate.key: candidate for candidate in candidates}
- candidates_by_pair = {}
- for candidate in candidates:
- candidates_by_pair[(candidate.source_id, candidate.target_id)] = candidate
- candidates_by_pair[(candidate.target_id, candidate.source_id)] = candidate
- matches: List[LLMMatch] = []
- diagnostics: List[GraphDiagnostic] = []
-
- raw_matches = payload.get("matches", [])
- if not isinstance(raw_matches, list):
- return [], [
- GraphDiagnostic(
- stage="llm_match",
- severity="error",
- code="invalid_matches_payload",
- message="LLM payload field 'matches' must be a list.",
- )
- ]
-
- for index, raw in enumerate(raw_matches):
- if not isinstance(raw, dict):
- diagnostics.append(
- GraphDiagnostic(
- stage="llm_match",
- severity="warning",
- code="invalid_match_item",
- message="LLM match item is not an object.",
- details={"index": index, "item": raw},
- )
- )
- continue
-
- match, item_diagnostics = _normalize_match(
- raw, registry, candidate_by_key, candidates_by_pair, thresholds
- )
- diagnostics.extend(item_diagnostics)
- if match is not None:
- matches.append(match)
-
- return matches, diagnostics
-
-
-def _normalize_match(
- raw: Dict[str, Any],
- registry: SkillRegistry,
- candidate_by_key: Dict[str, RelationCandidate],
- candidates_by_pair: Dict[tuple[str, str], RelationCandidate],
- thresholds: Dict[str, float],
-) -> tuple[Optional[LLMMatch], List[GraphDiagnostic]]:
- diagnostics: List[GraphDiagnostic] = []
- source_id = str(raw.get("source_id") or "")
- target_id = str(raw.get("target_id") or "")
- relation_type = str(raw.get("relation_type") or "")
- candidate_id = raw.get("candidate_id")
- candidate_id = str(candidate_id) if candidate_id else None
-
- errors: List[str] = []
- if source_id not in registry.skills:
- errors.append("source_id does not exist")
- if target_id not in registry.skills:
- errors.append("target_id does not exist")
- if relation_type not in ALLOWED_RELATION_TYPES:
- errors.append("relation_type is not allowed")
-
- candidate = None
- if candidate_id:
- candidate = candidate_by_key.get(candidate_id)
- if candidate is None:
- candidate = candidates_by_pair.get((source_id, target_id))
- if candidate is None:
- errors.append("match does not correspond to an input candidate")
- elif relation_type not in candidate.relation_hints:
- errors.append("relation_type is not allowed for the input candidate")
-
- try:
- confidence = float(raw.get("confidence", 0))
- except (TypeError, ValueError):
- confidence = 0
- errors.append("confidence is not numeric")
- if confidence < 0 or confidence > 1:
- errors.append("confidence must be between 0 and 1")
- confidence = max(0, min(1, confidence))
-
- reasons = [str(item) for item in raw.get("reasons", []) if str(item).strip()]
- supporting_fields = raw.get("supporting_fields")
- if not isinstance(supporting_fields, dict):
- supporting_fields = {}
-
- if relation_type == "can_feed" and candidate is not None:
- source_outputs = set(_field_names(supporting_fields.get("source_outputs", [])))
- target_inputs = set(_field_names(supporting_fields.get("target_inputs", [])))
- requested_port_mappings = _port_mapping_pairs(
- supporting_fields.get("port_mappings", [])
- )
- directional_evidence = _directional_evidence(
- candidate,
- source_id,
- target_id,
- )
- evidence_port_mappings = _port_mapping_pairs(
- directional_evidence.get("port_mappings", [])
- )
- evidence_outputs = {
- item.get("name")
- for item in directional_evidence.get("source_outputs", [])
- if isinstance(item, dict)
- }
- evidence_inputs = {
- item.get("name")
- for item in directional_evidence.get("target_inputs", [])
- if isinstance(item, dict)
- }
- if requested_port_mappings:
- if not requested_port_mappings <= evidence_port_mappings:
- errors.append("port_mappings do not match candidate evidence")
- supporting_fields = _complete_supporting_fields_from_port_mappings(
- supporting_fields,
- requested_port_mappings,
- )
- elif source_outputs and target_inputs:
- if not (source_outputs & evidence_outputs and target_inputs & evidence_inputs):
- errors.append("supporting_fields do not match candidate evidence")
- elif not ((evidence_outputs and evidence_inputs) or evidence_port_mappings):
- errors.append("can_feed has no supported output/input pair")
-
- accepted = not errors and confidence >= thresholds.get(relation_type, 1.0)
- match = LLMMatch(
- source_id=source_id,
- target_id=target_id,
- relation_type=relation_type,
- confidence=confidence,
- method=str(raw.get("method") or "llm_ontology_match"),
- reasons=reasons,
- supporting_fields=supporting_fields,
- candidate_id=candidate.key if candidate is not None else candidate_id,
- accepted=accepted,
- diagnostics=errors,
- raw=raw,
- )
-
- if errors:
- diagnostics.append(
- GraphDiagnostic(
- stage="llm_match",
- severity="warning",
- code="rejected_llm_match",
- message="LLM match failed validation.",
- skill_id=source_id or None,
- details={"errors": errors, "match": raw},
- )
- )
- elif not accepted:
- diagnostics.append(
- GraphDiagnostic(
- stage="llm_match",
- severity="info",
- code="low_confidence_llm_match",
- message="LLM match is below the relation threshold.",
- skill_id=source_id,
- details={
- "threshold": thresholds.get(relation_type),
- "match": match.to_dict(),
- },
- )
- )
-
- return match, diagnostics
-
-
-def _field_names(values: Any) -> List[str]:
- if not isinstance(values, list):
- return []
- names = []
- for value in values:
- if isinstance(value, str):
- names.append(_field_name_from_string(value))
- elif isinstance(value, dict) and value.get("name"):
- names.append(str(value["name"]))
- return [name for name in names if name]
-
-
-def _field_name_from_string(value: str) -> str:
- text = str(value).strip()
- if not text:
- return ""
- head = text.split(":", 1)[0].strip()
- head = head.split("(", 1)[0].strip()
- return head
-
-
-def _port_mapping_pairs(values: Any) -> set[tuple[str, str]]:
- if not isinstance(values, list):
- return set()
- pairs = set()
- for value in values:
- if not isinstance(value, dict):
- continue
- source_output = str(value.get("source_output") or "").strip()
- target_input = str(value.get("target_input") or "").strip()
- if source_output and target_input:
- pairs.add((source_output, target_input))
- return pairs
-
-
-def _complete_supporting_fields_from_port_mappings(
- supporting_fields: Dict[str, Any],
- pairs: set[tuple[str, str]],
-) -> Dict[str, Any]:
- completed = dict(supporting_fields)
- completed.setdefault("source_outputs", sorted({source for source, _ in pairs}))
- completed.setdefault("target_inputs", sorted({target for _, target in pairs}))
- return completed
-
-
-def _directional_evidence(
- candidate: RelationCandidate,
- source_id: str,
- target_id: str,
-) -> Dict[str, Any]:
- directions = candidate.evidence.get("directions", {})
- if isinstance(directions, dict):
- evidence = directions.get(f"{source_id}->{target_id}")
- if isinstance(evidence, dict):
- return evidence
- return candidate.evidence
diff --git a/jiuwenswarm/symphony/graph/models.py b/jiuwenswarm/symphony/graph/models.py
deleted file mode 100644
index 154acdf93b..0000000000
--- a/jiuwenswarm/symphony/graph/models.py
+++ /dev/null
@@ -1,255 +0,0 @@
-"""Data contracts for offline Skill graph construction."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-from datetime import datetime, timezone
-from typing import Any, Dict, List, Optional
-
-from jiuwenswarm.symphony.fingerprint.models import Fingerprint
-
-
-ALLOWED_RELATION_TYPES = frozenset(
- {
- "can_feed",
- }
-)
-
-
-@dataclass(frozen=True)
-class GraphDiagnostic:
- """Structured diagnostic emitted during graph construction."""
-
- stage: str
- severity: str
- code: str
- message: str
- skill_id: Optional[str] = None
- details: Dict[str, Any] = field(default_factory=dict)
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "skill_id": self.skill_id,
- "stage": self.stage,
- "severity": self.severity,
- "code": self.code,
- "message": self.message,
- "details": self.details,
- }
-
-
-@dataclass(frozen=True)
-class SkillRegistry:
- """Validated Skill registry keyed by Skill ID."""
-
- skills: Dict[str, Fingerprint]
- diagnostics: List[GraphDiagnostic] = field(default_factory=list)
-
- def ordered_skills(self) -> List[Fingerprint]:
- return [self.skills[skill_id] for skill_id in sorted(self.skills)]
-
-
-@dataclass(frozen=True)
-class RelationCandidate:
- """A cheap, deterministic Skill pair candidate for LLM review."""
-
- source_id: str
- target_id: str
- relation_hints: List[str]
- candidate_methods: List[str]
- priority: str
- evidence: Dict[str, Any] = field(default_factory=dict)
-
- @property
- def key(self) -> str:
- return f"{self.source_id}->{self.target_id}"
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "candidate_id": self.key,
- "source_id": self.source_id,
- "target_id": self.target_id,
- "relation_hints": list(self.relation_hints),
- "candidate_methods": list(self.candidate_methods),
- "priority": self.priority,
- "evidence": self.evidence,
- }
-
-
-@dataclass(frozen=True)
-class LLMMatch:
- """LLM relation judgment, after schema-level normalization."""
-
- source_id: str
- target_id: str
- relation_type: str
- confidence: float
- method: str = "llm_ontology_match"
- reasons: List[str] = field(default_factory=list)
- supporting_fields: Dict[str, Any] = field(default_factory=dict)
- candidate_id: Optional[str] = None
- accepted: bool = False
- diagnostics: List[str] = field(default_factory=list)
- raw: Dict[str, Any] = field(default_factory=dict)
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "candidate_id": self.candidate_id,
- "source_id": self.source_id,
- "target_id": self.target_id,
- "relation_type": self.relation_type,
- "confidence": self.confidence,
- "method": self.method,
- "reasons": list(self.reasons),
- "supporting_fields": self.supporting_fields,
- "accepted": self.accepted,
- "diagnostics": list(self.diagnostics),
- "raw": self.raw,
- }
-
-
-@dataclass(frozen=True)
-class GraphNode:
- """A typed graph node."""
-
- id: str
- type: str
- label: str
- properties: Dict[str, Any] = field(default_factory=dict)
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "id": self.id,
- "type": self.type,
- "label": self.label,
- "properties": self.properties,
- }
-
-
-@dataclass(frozen=True)
-class GraphEdge:
- """A typed graph edge."""
-
- source: str
- target: str
- type: str
- confidence: float = 1.0
- method: str = "deterministic"
- evidence: Dict[str, Any] = field(default_factory=dict)
-
- @property
- def key(self) -> str:
- return f"{self.source}->{self.target}:{self.type}"
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "source": self.source,
- "target": self.target,
- "type": self.type,
- "confidence": self.confidence,
- "method": self.method,
- "evidence": self.evidence,
- }
-
-
-@dataclass(frozen=True)
-class SkillGraph:
- """Skill graph nodes and typed edges."""
-
- nodes: List[GraphNode]
- edges: List[GraphEdge]
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "nodes": [node.to_dict() for node in self.nodes],
- "edges": [edge.to_dict() for edge in self.edges],
- }
-
-
-@dataclass(frozen=True)
-class ScoreLookup:
- """Lookup tables used by online Score retrieval and planning."""
-
- by_output: Dict[str, List[str]]
- by_input: Dict[str, List[str]]
- by_data_type: Dict[str, List[str]]
- neighbors: Dict[str, List[str]]
- upstream_by_input: Dict[str, List[str]]
- downstream_by_output: Dict[str, List[str]]
- by_text_term: Dict[str, List[str]]
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "by_output": self.by_output,
- "by_input": self.by_input,
- "by_data_type": self.by_data_type,
- "neighbors": self.neighbors,
- "upstream_by_input": self.upstream_by_input,
- "downstream_by_output": self.downstream_by_output,
- "by_text_term": self.by_text_term,
- }
-
-
-@dataclass(frozen=True)
-class BuildManifest:
- """Manifest used as the online loading entrypoint."""
-
- schema_version: str = "Orchestration-score-v1"
- artifacts: Dict[str, str] = field(
- default_factory=lambda: {
- "skills": "skills.json",
- "graph": "skill_graph.json",
- "score_lookup": "score_lookup.json",
- "llm_matches": "llm_matches.json",
- "diagnostics": "diagnostics.json",
- "io_name_vocab": "io_name_vocab.json",
- }
- )
- thresholds: Dict[str, float] = field(
- default_factory=lambda: {
- "can_feed": 0.7,
- }
- )
- planning_defaults: Dict[str, Any] = field(
- default_factory=lambda: {
- "min_edge_confidence": 0.7,
- "max_depth": 4,
- "max_plans": 20,
- "max_branch": 8,
- "max_entry_skills": 40,
- "top_m": 12,
- "top_k": 3,
- "include_candidates": True,
- "conservative_reject": True,
- "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()
- )
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "schema_version": self.schema_version,
- "artifacts": self.artifacts,
- "thresholds": self.thresholds,
- "planning_defaults": self.planning_defaults,
- "candidate_generation": self.candidate_generation,
- "llm": self.llm,
- "created_at": self.created_at,
- }
-
-
-@dataclass(frozen=True)
-class GraphBuildResult:
- """Complete graph build result."""
-
- manifest: BuildManifest
- skills: List[Fingerprint]
- candidates: List[RelationCandidate]
- llm_matches: List[LLMMatch]
- graph: SkillGraph
- lookup: ScoreLookup
- diagnostics: List[GraphDiagnostic] = field(default_factory=list)
diff --git a/jiuwenswarm/symphony/graph/pipeline.py b/jiuwenswarm/symphony/graph/pipeline.py
deleted file mode 100644
index 685a7a32ec..0000000000
--- a/jiuwenswarm/symphony/graph/pipeline.py
+++ /dev/null
@@ -1,172 +0,0 @@
-"""Offline graph construction orchestration."""
-
-from __future__ import annotations
-
-from typing import Any, Callable, Iterable, Optional
-
-from jiuwenswarm.symphony.llm import get_llm_token_usage_summary
-from jiuwenswarm.symphony.graph.builders import ScoreLookupBuilder, SkillGraphBuilder
-from jiuwenswarm.symphony.graph.candidates import CandidateGenerator
-from jiuwenswarm.symphony.graph.matcher import (
- DEFAULT_THRESHOLDS,
- OntologyMatcher,
-)
-from jiuwenswarm.symphony.graph.models import BuildManifest, GraphBuildResult, GraphDiagnostic
-from jiuwenswarm.symphony.graph.registry import SkillRegistryBuilder
-from jiuwenswarm.symphony.fingerprint.models import Fingerprint
-
-GraphProgress = Callable[..., None]
-
-
-class GraphBuilder:
- """Build Skill graph artifacts from normalized Skill fingerprints."""
-
- def __init__(
- self,
- *,
- matcher: OntologyMatcher,
- registry_builder: Optional[SkillRegistryBuilder] = None,
- candidate_generator: Optional[CandidateGenerator] = None,
- graph_builder: Optional[SkillGraphBuilder] = None,
- lookup_builder: Optional[ScoreLookupBuilder] = None,
- ) -> None:
- self.matcher = matcher
- self.registry_builder = registry_builder or SkillRegistryBuilder()
- self.candidate_generator = candidate_generator or CandidateGenerator()
- self.graph_builder = graph_builder or SkillGraphBuilder()
- self.lookup_builder = lookup_builder or ScoreLookupBuilder()
-
- async def __call__(
- self,
- fingerprints: Iterable[Fingerprint],
- *,
- progress: GraphProgress | None = None,
- ) -> GraphBuildResult:
- return await self.build(fingerprints, progress=progress)
-
- async def build(
- self,
- fingerprints: Iterable[Fingerprint],
- *,
- progress: GraphProgress | None = None,
- ) -> GraphBuildResult:
- fingerprints = list(fingerprints)
- diagnostics: list[GraphDiagnostic] = []
- _emit_progress(progress, "graph.registry.start", fingerprint_count=len(fingerprints))
- registry = self.registry_builder.register(fingerprints)
- diagnostics.extend(registry.diagnostics)
- _emit_progress(
- progress,
- "graph.registry.done",
- skill_count=len(registry.skills),
- diagnostics_count=len(registry.diagnostics),
- )
-
- _emit_progress(progress, "graph.candidates.start", skill_count=len(registry.skills))
- candidates = self.candidate_generator.generate(registry)
- _emit_progress(progress, "graph.candidates.done", candidate_count=len(candidates))
-
- _emit_progress(progress, "graph.resolve.start", candidate_count=len(candidates))
- llm_matches = await self.matcher.match(registry, candidates)
- relation_diagnostics = self._relation_diagnostics(llm_matches)
- diagnostics.extend(relation_diagnostics)
- _emit_progress(
- progress,
- "graph.resolve.done",
- candidate_count=len(candidates),
- match_count=len(llm_matches),
- accepted_match_count=sum(1 for match in llm_matches if match.accepted),
- diagnostics_count=len(relation_diagnostics),
- )
-
- _emit_progress(progress, "graph.materialize.start", match_count=len(llm_matches))
- graph = self.graph_builder.build(registry, llm_matches)
- _emit_progress(
- progress,
- "graph.materialize.done",
- node_count=len(graph.nodes),
- edge_count=len(graph.edges),
- )
-
- _emit_progress(
- progress,
- "graph.score.start",
- node_count=len(graph.nodes),
- edge_count=len(graph.edges),
- )
- lookup = self.lookup_builder.build(registry, graph)
- _emit_progress(progress, "graph.score.done")
-
- llm_metadata = _matcher_metadata(self.matcher)
- 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,
- )
-
- return GraphBuildResult(
- manifest=manifest,
- skills=registry.ordered_skills(),
- candidates=candidates,
- llm_matches=llm_matches,
- graph=graph,
- lookup=lookup,
- diagnostics=diagnostics,
- )
-
- def _relation_diagnostics(self, llm_matches: list) -> list[GraphDiagnostic]:
- diagnostics: list[GraphDiagnostic] = []
- matcher_diagnostics = []
- if hasattr(self.matcher, "diagnostics"):
- matcher_diagnostics = list(self.matcher.diagnostics)
- diagnostics.extend(matcher_diagnostics)
-
- for match in llm_matches:
- if matcher_diagnostics:
- continue
- for message in match.diagnostics:
- diagnostics.append(
- GraphDiagnostic(
- stage="llm_match",
- severity="warning",
- code="match_diagnostic",
- message=message,
- skill_id=match.source_id,
- details={"match": match.to_dict()},
- )
- )
- return diagnostics
-
-
-def _emit_progress(progress: GraphProgress | None, stage: str, **details: Any) -> None:
- if progress is not None:
- progress(stage, **details)
-
-
-def _matcher_metadata(matcher: OntologyMatcher) -> dict:
- if hasattr(matcher, "manifest_metadata"):
- return matcher.manifest_metadata()
- return {"matcher": matcher.__class__.__name__}
-
-
-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/graph/registry.py b/jiuwenswarm/symphony/graph/registry.py
deleted file mode 100644
index a9e0787c98..0000000000
--- a/jiuwenswarm/symphony/graph/registry.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""Skill registry validation for graph construction."""
-
-from __future__ import annotations
-
-from typing import Iterable, List
-
-from jiuwenswarm.symphony.graph.models import GraphDiagnostic, SkillRegistry
-from jiuwenswarm.symphony.fingerprint.models import Fingerprint
-
-
-class SkillRegistryBuilder:
- """Register normalized Skill fingerprints by stable ID."""
-
- @staticmethod
- def register(fingerprints: Iterable[Fingerprint]) -> SkillRegistry:
- skills = {}
- diagnostics: List[GraphDiagnostic] = []
-
- for fingerprint in sorted(fingerprints, key=lambda item: item.id):
- if fingerprint.type != "skill":
- diagnostics.append(
- GraphDiagnostic(
- stage="registry",
- severity="error",
- code="unsupported_fingerprint_type",
- message=(
- "Skill Graph only accepts fingerprints with "
- "type='skill'."
- ),
- details={"type": fingerprint.type, "id": fingerprint.id},
- )
- )
- continue
-
- if not fingerprint.id:
- diagnostics.append(
- GraphDiagnostic(
- stage="registry",
- severity="error",
- code="missing_skill_id",
- message="Skill fingerprint is missing an id.",
- details={"skill": fingerprint.to_dict()},
- )
- )
- continue
-
- if fingerprint.id in skills:
- diagnostics.append(
- GraphDiagnostic(
- stage="registry",
- severity="error",
- code="duplicate_skill_id",
- message=f"Duplicate Skill id: {fingerprint.id}",
- skill_id=fingerprint.id,
- )
- )
- continue
-
- if not fingerprint.outputs:
- diagnostics.append(
- GraphDiagnostic(
- stage="registry",
- severity="warning",
- code="missing_outputs",
- message="Skill has no declared outputs.",
- skill_id=fingerprint.id,
- )
- )
-
- skills[fingerprint.id] = fingerprint
-
- return SkillRegistry(skills=skills, diagnostics=diagnostics)
diff --git a/jiuwenswarm/symphony/graph/writer.py b/jiuwenswarm/symphony/graph/writer.py
deleted file mode 100644
index c2a1b93904..0000000000
--- a/jiuwenswarm/symphony/graph/writer.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""Write graph build artifacts to disk."""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-from typing import Any, Dict, Union
-
-from jiuwenswarm.symphony.graph.models import GraphBuildResult
-
-
-def write_json_file(path: Path, data: Dict[str, Any]) -> None:
- """Write JSON with stable formatting."""
-
- path.write_text(
- json.dumps(data, ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
-
-
-def write_graph_build_result(
- result: GraphBuildResult,
- out_dir: Union[Path, str],
-) -> None:
- """Write all graph build artifacts to an output directory."""
-
- output_path = Path(out_dir)
- output_path.mkdir(parents=True, exist_ok=True)
-
- write_json_file(output_path / "score_manifest.json", result.manifest.to_dict())
- write_json_file(
- output_path / "skills.json",
- {"skills": [skill.to_dict() for skill in result.skills]},
- )
- write_json_file(output_path / "skill_graph.json", result.graph.to_dict())
- write_json_file(output_path / "score_lookup.json", result.lookup.to_dict())
- write_json_file(
- output_path / "llm_matches.json",
- {
- "candidates": [candidate.to_dict() for candidate in result.candidates],
- "matches": [match.to_dict() for match in result.llm_matches],
- },
- )
- write_json_file(
- output_path / "diagnostics.json",
- {"diagnostics": [diagnostic.to_dict() for diagnostic in result.diagnostics]},
- )
diff --git a/jiuwenswarm/symphony/score_state.py b/jiuwenswarm/symphony/graph_state.py
similarity index 72%
rename from jiuwenswarm/symphony/score_state.py
rename to jiuwenswarm/symphony/graph_state.py
index 80050d021c..130baf2ada 100644
--- a/jiuwenswarm/symphony/score_state.py
+++ b/jiuwenswarm/symphony/graph_state.py
@@ -1,4 +1,4 @@
-"""Persistent state for Symphony Score builds."""
+"""Persistent state for Symphony graph builds."""
from __future__ import annotations
@@ -10,14 +10,14 @@ from pathlib import Path
from typing import Any, Iterable
from jiuwenswarm.symphony.fingerprint.models import Fingerprint
-from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dir
+from jiuwenswarm.symphony.graph_storage import resolve_graph_artifact_dir
-SCORE_STATE_FILENAME = "score_state.json"
+GRAPH_STATE_FILENAME = "graph_state.json"
@dataclass(frozen=True)
-class ScoreStateEntry:
- """State tracked for one Skill folder in a Score build."""
+class GraphStateEntry:
+ """State tracked for one Skill folder in a graph build."""
skill_id: str
relative_path: str
@@ -37,7 +37,7 @@ class ScoreStateEntry:
}
@classmethod
- def from_dict(cls, payload: dict[str, Any]) -> "ScoreStateEntry":
+ def from_dict(cls, payload: dict[str, Any]) -> "GraphStateEntry":
return cls(
skill_id=str(payload.get("skill_id") or ""),
relative_path=str(payload.get("relative_path") or ""),
@@ -49,13 +49,13 @@ class ScoreStateEntry:
@dataclass(frozen=True)
-class ScoreState:
- """Serializable incremental Score state."""
+class GraphState:
+ """Serializable incremental graph state."""
- schema_version: str = "Symphony-score-state-v1"
- skills: dict[str, ScoreStateEntry] = field(default_factory=dict)
+ schema_version: str = "Symphony-graph-state-v1"
+ skills: dict[str, GraphStateEntry] = field(default_factory=dict)
- def active_entries(self) -> dict[str, ScoreStateEntry]:
+ def active_entries(self) -> dict[str, GraphStateEntry]:
return {
path: entry
for path, entry in self.skills.items()
@@ -72,16 +72,16 @@ class ScoreState:
}
@classmethod
- def from_dict(cls, payload: dict[str, Any]) -> "ScoreState":
+ def from_dict(cls, payload: dict[str, Any]) -> "GraphState":
raw_skills = payload.get("skills") or {}
- skills: dict[str, ScoreStateEntry] = {}
+ skills: dict[str, GraphStateEntry] = {}
if isinstance(raw_skills, dict):
for key, value in raw_skills.items():
if not isinstance(value, dict):
continue
- entry = ScoreStateEntry.from_dict(value)
+ entry = GraphStateEntry.from_dict(value)
relative_path = entry.relative_path or str(key)
- skills[relative_path] = ScoreStateEntry(
+ skills[relative_path] = GraphStateEntry(
skill_id=entry.skill_id,
relative_path=relative_path,
skill_md_sha256=entry.skill_md_sha256,
@@ -90,13 +90,13 @@ class ScoreState:
updated_at=entry.updated_at,
)
return cls(
- schema_version=str(payload.get("schema_version") or "Symphony-score-state-v1"),
+ schema_version=str(payload.get("schema_version") or "Symphony-graph-state-v1"),
skills=skills,
)
-class ScoreStateBuilder:
- """Compute folder hashes and the next persistent Score state."""
+class GraphStateBuilder:
+ """Compute folder hashes and the next persistent graph state."""
def folder_hashes(self, folders: Iterable[Any]) -> dict[str, str]:
return {
@@ -110,14 +110,14 @@ class ScoreStateBuilder:
folders: list[Any],
current_hashes: dict[str, str],
fingerprints_by_path: dict[str, Fingerprint],
- old_state: ScoreState,
+ old_state: GraphState,
removed_paths: set[str],
- ) -> ScoreState:
+ ) -> GraphState:
now = datetime.now(timezone.utc).isoformat()
- entries: dict[str, ScoreStateEntry] = {}
+ entries: dict[str, GraphStateEntry] = {}
for folder in folders:
fingerprint = fingerprints_by_path[folder.relative_path]
- entries[folder.relative_path] = ScoreStateEntry(
+ entries[folder.relative_path] = GraphStateEntry(
skill_id=fingerprint.id,
relative_path=folder.relative_path,
skill_md_sha256=current_hashes[folder.relative_path],
@@ -130,7 +130,7 @@ class ScoreStateBuilder:
old_entry = old_state.skills.get(relative_path)
if old_entry is None:
continue
- entries[relative_path] = ScoreStateEntry(
+ entries[relative_path] = GraphStateEntry(
skill_id=old_entry.skill_id,
relative_path=relative_path,
skill_md_sha256=old_entry.skill_md_sha256,
@@ -138,7 +138,7 @@ class ScoreStateBuilder:
status="removed",
updated_at=now,
)
- return ScoreState(skills=entries)
+ return GraphState(skills=entries)
@staticmethod
def fingerprint_hash(fingerprint: Fingerprint) -> str:
@@ -154,21 +154,21 @@ class ScoreStateBuilder:
return hashlib.sha256(path.read_bytes()).hexdigest()
-def load_score_state(score_dir: str | Path) -> ScoreState:
- """Load score_state.json, returning an empty state when it is missing."""
+def load_graph_state(graph_dir: str | Path) -> GraphState:
+ """Load graph_state.json, returning an empty state when it is missing."""
- path = resolve_score_artifact_dir(score_dir) / SCORE_STATE_FILENAME
+ path = resolve_graph_artifact_dir(graph_dir) / GRAPH_STATE_FILENAME
if not path.exists():
- return ScoreState()
- return ScoreState.from_dict(json.loads(path.read_text(encoding="utf-8")))
+ return GraphState()
+ return GraphState.from_dict(json.loads(path.read_text(encoding="utf-8")))
-def write_score_state(state: ScoreState, score_dir: str | Path) -> None:
- """Write score_state.json with stable formatting."""
+def write_graph_state(state: GraphState, graph_dir: str | Path) -> None:
+ """Write graph_state.json with stable formatting."""
- output_path = Path(score_dir)
+ output_path = Path(graph_dir)
output_path.mkdir(parents=True, exist_ok=True)
- (output_path / SCORE_STATE_FILENAME).write_text(
+ (output_path / GRAPH_STATE_FILENAME).write_text(
json.dumps(state.to_dict(), ensure_ascii=False, indent=2),
encoding="utf-8",
)
diff --git a/jiuwenswarm/symphony/graph_storage.py b/jiuwenswarm/symphony/graph_storage.py
new file mode 100644
index 0000000000..c3fde379cd
--- /dev/null
+++ b/jiuwenswarm/symphony/graph_storage.py
@@ -0,0 +1,131 @@
+"""Versioned storage helpers for Symphony graph artifacts."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+CURRENT_POINTER_FILENAME = "current.json"
+BUILD_RUNS_DIRNAME = ".build_runs"
+
+
+@dataclass(frozen=True)
+class GraphPointer:
+ """Pointer to the currently published graph version."""
+
+ version: str
+ path: str
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "schema_version": "1.0",
+ "version": self.version,
+ "path": self.path,
+ }
+
+ @classmethod
+ def from_dict(cls, payload: dict[str, Any]) -> "GraphPointer":
+ if not isinstance(payload, dict):
+ raise ValueError("Invalid Symphony graph pointer.") # noqa: TRY004
+ version = str(payload.get("version") or "").strip()
+ path = str(payload.get("path") or payload.get("artifact") or "").strip()
+ if path.endswith("/graph.json"):
+ path = str(Path(path).parent)
+ if not version or not path:
+ raise ValueError("Invalid Symphony graph pointer.")
+ return cls(version=version, path=path)
+
+
+def resolve_graph_artifact_dir(graph_dir: str | Path) -> Path:
+ """Return the directory containing the currently readable artifacts.
+
+ New builds publish versioned artifacts behind ``current.json``. Older
+ layouts stored artifacts directly in ``graph_dir``; this helper keeps that
+ legacy layout readable. A corrupt or escaping pointer falls back to the
+ root directory so status checks and rebuilds can self-heal.
+ """
+
+ root = Path(graph_dir).resolve()
+ pointer_path = root / CURRENT_POINTER_FILENAME
+ if not pointer_path.is_file():
+ return root
+
+ try:
+ pointer = GraphPointer.from_dict(
+ json.loads(pointer_path.read_text(encoding="utf-8"))
+ )
+ candidate = (root / pointer.path).resolve()
+ if not _is_relative_to(candidate, root):
+ raise ValueError(
+ f"Symphony graph pointer escapes graph_dir: {candidate}"
+ )
+ except (OSError, ValueError):
+ return root
+ return candidate
+
+
+def graph_manifest_path(graph_dir: str | Path) -> Path:
+ """Return the public graph artifact used as the existence marker."""
+
+ return resolve_graph_artifact_dir(graph_dir) / "graph.json"
+
+
+def graph_exists(graph_dir: str | Path) -> bool:
+ root = Path(graph_dir).resolve()
+ pointer_path = root / CURRENT_POINTER_FILENAME
+ if not pointer_path.is_file():
+ return False
+ try:
+ pointer = json.loads(pointer_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return False
+ if not isinstance(pointer, dict):
+ return False
+ schema_version = str(pointer.get("schema_version") or "")
+ return schema_version.startswith("1.") and graph_manifest_path(root).is_file()
+
+
+def build_runs_dir(graph_dir: str | Path) -> Path:
+ return Path(graph_dir).resolve() / BUILD_RUNS_DIRNAME
+
+
+def build_run_dir(graph_dir: str | Path, run_id: str) -> Path:
+ return build_runs_dir(graph_dir) / run_id
+
+
+def latest_incomplete_build(graph_dir: str | Path) -> Path | None:
+ runs_root = build_runs_dir(graph_dir)
+ if not runs_root.is_dir():
+ return None
+ candidates = []
+ for child in runs_root.iterdir():
+ checkpoint = child / "checkpoint.json"
+ if not checkpoint.is_file():
+ continue
+ try:
+ payload = json.loads(checkpoint.read_text(encoding="utf-8"))
+ except json.JSONDecodeError:
+ continue
+ candidates.append(
+ (
+ str(payload.get("updated_at") or ""),
+ str(payload.get("status") or ""),
+ child,
+ )
+ )
+ if not candidates:
+ return None
+ _updated_at, status, path = sorted(candidates, key=lambda item: item[0])[-1]
+ if status in {"running", "failed"}:
+ return path
+ return None
+
+
+def _is_relative_to(path: Path, root: Path) -> bool:
+ try:
+ path.relative_to(root)
+ except ValueError:
+ return False
+ return True
diff --git a/jiuwenswarm/symphony/llm.py b/jiuwenswarm/symphony/llm.py
index 9053006081..ac9a56ea74 100644
--- a/jiuwenswarm/symphony/llm.py
+++ b/jiuwenswarm/symphony/llm.py
@@ -2,8 +2,10 @@
from __future__ import annotations
+import hashlib
import json
from collections import defaultdict
+from collections.abc import Mapping
from contextlib import contextmanager
from contextvars import ContextVar
from copy import deepcopy
@@ -13,6 +15,8 @@ from typing import Any, Dict, Iterator, List, Optional
from jiuwenswarm.common.reasoning_injector import inject_reasoning_params
+LLM_IDENTITY_SCHEMA_VERSION = "JiuwenSwarm-llm-identity-v1"
+
@dataclass(frozen=True)
class LLMConfig:
@@ -36,16 +40,21 @@ class LLMConfig:
models = {}
default_models = models.get("defaults")
has_default_model = (
- isinstance(default_models, list)
- and bool(default_models)
+ isinstance(default_models, list) and bool(default_models)
) or isinstance(models.get("default"), dict)
if not has_default_model:
- raise RuntimeError("No JiuwenSwarm default model is configured in config.yaml.")
+ raise RuntimeError(
+ "No JiuwenSwarm default model is configured in config.yaml."
+ )
defaults = get_default_models(config)
if not defaults:
- raise RuntimeError("No JiuwenSwarm default model is configured in config.yaml.")
- entry = next((item for item in defaults if item.get("is_default") is True), defaults[0])
+ raise RuntimeError(
+ "No JiuwenSwarm default model is configured in config.yaml."
+ )
+ entry = next(
+ (item for item in defaults if item.get("is_default") is True), defaults[0]
+ )
return cls.from_model_entry(entry or {})
@classmethod
@@ -114,6 +123,32 @@ class LLMConfig:
request_config["top_p"] = self.top_p
return request_config
+ def create_model(self):
+ """Create the native openJiuwen model used by orchestration."""
+
+ from openjiuwen.core.foundation.llm import (
+ Model,
+ ModelClientConfig,
+ ModelRequestConfig,
+ )
+
+ return Model(
+ model_client_config=ModelClientConfig(**self.model_client_kwargs()),
+ model_config=ModelRequestConfig(**self.model_request_kwargs()),
+ )
+
+ def identity_digest(self) -> str:
+ """Hash every effective client/request setting without exposing values."""
+
+ return _stable_identity_sha256(
+ {
+ "schema_version": LLM_IDENTITY_SCHEMA_VERSION,
+ "backend": self.backend,
+ "client_config": self.model_client_kwargs(),
+ "request_config": self.model_request_kwargs(),
+ }
+ )
+
@dataclass(frozen=True)
class LLMTokenUsageRecord:
@@ -230,6 +265,20 @@ def create_llm_client(config: LLMConfig) -> "JiuwenSwarmChatClient":
return JiuwenSwarmChatClient(config)
+def create_model_response_observer(config: LLMConfig):
+ """Bridge native orchestration model responses to the existing usage tracker."""
+
+ def observe(response: Any, stage: str, operation: str | None) -> None:
+ with llm_usage_context(stage, operation):
+ _record_usage_from_response(
+ config=config,
+ response=response,
+ operation=operation or "orchestration",
+ )
+
+ return observe
+
+
def thinking_disabled_request_overrides() -> Dict[str, Any]:
"""Return isolated provider-compatible controls that disable thinking."""
return {
@@ -309,19 +358,8 @@ class JiuwenSwarmChatClient:
timeout: Optional[int],
request_overrides: Optional[Dict[str, Any]],
) -> Any:
- from openjiuwen.core.foundation.llm import (
- Model,
- ModelClientConfig,
- ModelRequestConfig,
- )
-
if self._model is None:
- self._model = Model(
- model_client_config=ModelClientConfig(
- **self.config.model_client_kwargs()
- ),
- model_config=ModelRequestConfig(**self.config.model_request_kwargs()),
- )
+ self._model = self.config.create_model()
invoke_kwargs: Dict[str, Any] = {}
if timeout is not None:
@@ -340,6 +378,41 @@ class JiuwenSwarmChatClient:
)
+def _stable_identity_sha256(value: Any) -> str:
+ canonical = _canonical_identity_value(value)
+ serialized = json.dumps(
+ canonical,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
+
+
+def _canonical_identity_value(value: Any) -> Any:
+ if isinstance(value, Mapping):
+ return {
+ str(key): _canonical_identity_value(item)
+ for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))
+ }
+ if isinstance(value, (list, tuple)):
+ return [_canonical_identity_value(item) for item in value]
+ if isinstance(value, (set, frozenset)):
+ normalized = [_canonical_identity_value(item) for item in value]
+ return sorted(
+ normalized,
+ key=lambda item: json.dumps(
+ item,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ),
+ )
+ if value is None or isinstance(value, (str, int, float, bool)):
+ return value
+ return str(value)
+
+
def _record_usage_from_response(
*,
config: LLMConfig,
diff --git a/jiuwenswarm/symphony/orchestration/utils/naming.py b/jiuwenswarm/symphony/models/cid/naming.py
similarity index 100%
rename from jiuwenswarm/symphony/orchestration/utils/naming.py
rename to jiuwenswarm/symphony/models/cid/naming.py
diff --git a/jiuwenswarm/symphony/models/cid/tree.py b/jiuwenswarm/symphony/models/cid/tree.py
index c087fe4506..3fad6dbd0b 100644
--- a/jiuwenswarm/symphony/models/cid/tree.py
+++ b/jiuwenswarm/symphony/models/cid/tree.py
@@ -6,7 +6,7 @@ from dataclasses import replace
from importlib import import_module
from typing import Any, Iterable, List, Tuple
-from orchestration.utils.naming import fuzzy_name_distance, normalize_name_key, to_pascal_case
+from .naming import fuzzy_name_distance, normalize_name_key, to_pascal_case
from .node_spec import CID, NodeSpec, NodeType
@@ -231,9 +231,8 @@ class CIDTree:
cid = CID.from_str(text)
if self.exists(cid):
return cid.to_str()
- except ValueError as e:
- if logger is not None:
- logger.debug("Direct CID parsing failed for '%s': %s", text, str(e))
+ except ValueError:
+ pass
segments = [segment.strip() for segment in text.split(".") if segment.strip()]
if not segments:
diff --git a/jiuwenswarm/symphony/orchestration/__init__.py b/jiuwenswarm/symphony/orchestration/__init__.py
deleted file mode 100644
index fed1bf8e67..0000000000
--- a/jiuwenswarm/symphony/orchestration/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""Skill orchestration from offline graph build artifacts."""
-
-from jiuwenswarm.symphony.orchestration.artifacts import (
- ScoreArtifacts,
- load_score_artifacts,
-)
-from jiuwenswarm.symphony.orchestration.planning.models import (
- ArtifactRef,
- OrchestrationPlan,
- PlanStep,
-)
-
-__all__ = [
- "ArtifactRef",
- "ScoreArtifacts",
- "OrchestrationPlan",
- "PlanStep",
- "load_score_artifacts",
-]
diff --git a/jiuwenswarm/symphony/orchestration/artifacts.py b/jiuwenswarm/symphony/orchestration/artifacts.py
deleted file mode 100644
index d624775115..0000000000
--- a/jiuwenswarm/symphony/orchestration/artifacts.py
+++ /dev/null
@@ -1,199 +0,0 @@
-"""Load Score artifacts for Skill orchestration."""
-
-from __future__ import annotations
-
-import json
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any, Sequence
-
-from jiuwenswarm.symphony.fingerprint.utils import normalize_slug
-from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dir
-
-
-@dataclass(frozen=True)
-class ScoreArtifacts:
- """Offline Score artifacts needed by orchestration."""
-
- score_dir: Path
- manifest: dict[str, Any]
- skills: list[dict[str, Any]]
- graph: dict[str, Any]
- lookup: dict[str, Any]
- io_name_vocab: dict[str, Any] | None = None
-
- @property
- def skill_by_id(self) -> dict[str, dict[str, Any]]:
- return {skill["id"]: skill for skill in self.skills if skill.get("id")}
-
-
-def load_score_artifacts(score_dir: str | Path) -> ScoreArtifacts:
- """Load Score artifacts through score_manifest.json."""
-
- root = resolve_score_artifact_dir(score_dir)
- manifest = _read_json(root / "score_manifest.json")
- artifacts = manifest.get("artifacts", {})
- skills_payload = _read_json(root / artifacts.get("skills", "skills.json"))
- graph = _read_json(root / artifacts.get("graph", "skill_graph.json"))
- lookup = _read_json(root / artifacts.get("score_lookup", "score_lookup.json"))
- io_name_vocab_path = root / artifacts.get("io_name_vocab", "io_name_vocab.json")
- return ScoreArtifacts(
- score_dir=root,
- manifest=manifest,
- skills=skills_payload.get("skills", []),
- graph=graph,
- lookup=lookup,
- io_name_vocab=_read_optional_json(io_name_vocab_path),
- )
-
-
-def filter_disabled_score_artifacts(
- artifacts: ScoreArtifacts,
- disabled_skill_names: Sequence[str] | None,
-) -> ScoreArtifacts:
- """Return Score artifacts with disabled skills removed from runtime views."""
-
- disabled_refs = _skill_ref_set(disabled_skill_names or [])
- if not disabled_refs:
- return artifacts
-
- disabled_skill_ids = {
- str(skill.get("id") or "")
- for skill in artifacts.skills
- if _skill_matches_refs(skill, disabled_refs)
- }
- disabled_skill_ids = {item for item in disabled_skill_ids if item}
- if not disabled_skill_ids:
- return artifacts
-
- all_disabled_refs = set(disabled_refs)
- all_disabled_refs.update(_skill_ref_set(disabled_skill_ids))
- skills = [
- skill
- for skill in artifacts.skills
- if not _skill_ref_is_disabled(skill.get("id"), all_disabled_refs)
- ]
- graph = _filter_graph(artifacts.graph, all_disabled_refs)
- lookup = _filter_lookup_payload(artifacts.lookup, all_disabled_refs)
- return ScoreArtifacts(
- score_dir=artifacts.score_dir,
- manifest=artifacts.manifest,
- skills=skills,
- graph=graph,
- lookup=lookup if isinstance(lookup, dict) else {},
- io_name_vocab=artifacts.io_name_vocab,
- )
-
-
-def _filter_graph(
- graph: dict[str, Any],
- disabled_refs: set[str],
-) -> dict[str, Any]:
- output = dict(graph)
- nodes = graph.get("nodes")
- if isinstance(nodes, list):
- output["nodes"] = [
- node
- for node in nodes
- if not _graph_node_is_disabled(node, disabled_refs)
- ]
- edges = graph.get("edges")
- if isinstance(edges, list):
- output["edges"] = [
- edge
- for edge in edges
- if not _graph_edge_is_disabled(edge, disabled_refs)
- ]
- return output
-
-
-def _filter_lookup_payload(value: Any, disabled_refs: set[str]) -> Any:
- if isinstance(value, dict):
- output = {}
- for key, item in value.items():
- if _skill_ref_is_disabled(key, disabled_refs):
- continue
- filtered = _filter_lookup_payload(item, disabled_refs)
- if filtered in ({}, []):
- continue
- output[key] = filtered
- return output
- if isinstance(value, list):
- output = []
- for item in value:
- if _skill_ref_is_disabled(item, disabled_refs):
- continue
- filtered = _filter_lookup_payload(item, disabled_refs)
- if filtered in ({}, []):
- continue
- output.append(filtered)
- return output
- if _skill_ref_is_disabled(value, disabled_refs):
- return []
- return value
-
-
-def _graph_edge_is_disabled(edge: Any, disabled_refs: set[str]) -> bool:
- if not isinstance(edge, dict):
- return False
- return (
- _skill_ref_is_disabled(edge.get("source") or edge.get("source_id"), disabled_refs)
- or _skill_ref_is_disabled(edge.get("target") or edge.get("target_id"), disabled_refs)
- )
-
-
-def _graph_node_is_disabled(node: Any, disabled_refs: set[str]) -> bool:
- if not isinstance(node, dict):
- return False
- properties = node.get("properties")
- properties = properties if isinstance(properties, dict) else {}
- values = (
- node.get("id"),
- node.get("node_id"),
- node.get("skill_id"),
- node.get("label"),
- node.get("name"),
- properties.get("skill_id"),
- properties.get("id"),
- properties.get("name"),
- )
- return any(_skill_ref_is_disabled(value, disabled_refs) for value in values)
-
-
-def _skill_matches_refs(skill: dict[str, Any], disabled_refs: set[str]) -> bool:
- return (
- _skill_ref_is_disabled(skill.get("id"), disabled_refs)
- or _skill_ref_is_disabled(skill.get("name"), disabled_refs)
- )
-
-
-def _skill_ref_is_disabled(value: Any, disabled_refs: set[str]) -> bool:
- return bool(_skill_ref_set([value]) & disabled_refs)
-
-
-def _skill_ref_set(values: Sequence[Any]) -> set[str]:
- refs: set[str] = set()
- for value in values:
- text = str(value or "").strip()
- if not text:
- continue
- unprefixed = text.removeprefix("skill:")
- for candidate in (text, unprefixed):
- if candidate:
- refs.add(candidate)
- slug = normalize_slug(candidate)
- if slug:
- refs.add(slug)
- return refs
-
-
-def _read_json(path: Path) -> dict[str, Any]:
- if not path.exists():
- raise FileNotFoundError(f"Missing score artifact: {path}")
- return json.loads(path.read_text(encoding="utf-8"))
-
-
-def _read_optional_json(path: Path) -> dict[str, Any] | None:
- if not path.exists():
- return None
- return json.loads(path.read_text(encoding="utf-8"))
diff --git a/jiuwenswarm/symphony/orchestration/execution_graph.py b/jiuwenswarm/symphony/orchestration/execution_graph.py
deleted file mode 100644
index 4f40759cf4..0000000000
--- a/jiuwenswarm/symphony/orchestration/execution_graph.py
+++ /dev/null
@@ -1,115 +0,0 @@
-"""Stable execution graph projection for Orchestration plan results."""
-
-from __future__ import annotations
-
-from typing import Any
-
-from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
-
-
-def build_execution_graph(
- planning_result: dict[str, Any],
- artifacts: ScoreArtifacts,
-) -> dict[str, Any]:
- """Project an orchestration result into stable nodes, edges, and gaps."""
-
- primary_plan = select_primary_plan(planning_result)
- steps = list(primary_plan.get("steps") or [])
- skill_ids = [
- str(step.get("skill_id") or "").strip()
- for step in steps
- if str(step.get("skill_id") or "").strip()
- ]
- skill_id_set = set(skill_ids)
-
- graph_edges = [
- _project_edge(edge)
- for edge in list(primary_plan.get("can_feed_edges") or [])
- if _edge_touches_selected_skills(edge, skill_id_set)
- ]
- if not graph_edges and skill_id_set:
- graph_edges = [
- _project_edge(edge)
- for edge in artifacts.graph.get("edges", [])
- if _edge_touches_selected_skills(edge, skill_id_set)
- ]
-
- missing_inputs = _collect_missing_inputs(planning_result, primary_plan)
- diagnostics = []
- 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
- if skill_id in artifacts.skill_by_id
- ],
- "edges": graph_edges,
- "recommended_plans": list(planning_result.get("recommended_plans") or []),
- "missing_inputs": missing_inputs,
- "diagnostics": diagnostics,
- }
-
-
-def select_primary_plan(planning_result: dict[str, Any]) -> dict[str, Any]:
- for key in ("recommended_plans", "plans"):
- plans = planning_result.get(key)
- if isinstance(plans, list):
- for plan in plans:
- if isinstance(plan, dict):
- return plan
- return {}
-
-
-def _project_skill(skill: dict[str, Any]) -> dict[str, Any]:
- return {
- "id": skill.get("id"),
- "name": skill.get("name"),
- "description": skill.get("description"),
- "inputs": list(skill.get("inputs") or []),
- "outputs": list(skill.get("outputs") or []),
- }
-
-
-def _project_edge(edge: dict[str, Any]) -> dict[str, Any]:
- source = edge.get("source") or edge.get("source_id")
- target = edge.get("target") or edge.get("target_id")
- return {
- "source": source,
- "target": target,
- "type": edge.get("type") or edge.get("relation_type") or "can_feed",
- "confidence": edge.get("confidence"),
- "method": edge.get("method"),
- "evidence": edge.get("evidence") or edge.get("supporting_fields") or {},
- }
-
-
-def _edge_touches_selected_skills(edge: dict[str, Any], skill_ids: set[str]) -> bool:
- source = str(edge.get("source") or edge.get("source_id") or "").strip()
- target = str(edge.get("target") or edge.get("target_id") or "").strip()
- return source in skill_ids and target in skill_ids
-
-
-def _collect_missing_inputs(
- planning_result: dict[str, Any],
- primary_plan: dict[str, Any],
-) -> list[dict[str, Any]]:
- missing: list[dict[str, Any]] = []
- for item in primary_plan.get("missing_inputs") or []:
- if isinstance(item, dict):
- missing.append(item)
- if not missing:
- for plan in planning_result.get("plans") or []:
- if not isinstance(plan, dict):
- continue
- for item in plan.get("missing_inputs") or []:
- if isinstance(item, dict):
- missing.append(item)
- return missing
diff --git a/jiuwenswarm/symphony/orchestration/language.py b/jiuwenswarm/symphony/orchestration/language.py
deleted file mode 100644
index 58d462de1a..0000000000
--- a/jiuwenswarm/symphony/orchestration/language.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""Language helpers for user-facing Symphony orchestration output."""
-
-from __future__ import annotations
-
-from typing import Any
-
-DEFAULT_ORCHESTRATION_LANGUAGE = "cn"
-SUPPORTED_ORCHESTRATION_LANGUAGES = frozenset({"cn", "en"})
-
-
-def resolve_orchestration_language(value: Any = None) -> str:
- """Normalize runtime language to the Symphony ``cn | en`` contract."""
-
- raw = str(value or "").strip().lower()
- if raw == "zh":
- raw = "cn"
- if raw not in SUPPORTED_ORCHESTRATION_LANGUAGES:
- return DEFAULT_ORCHESTRATION_LANGUAGE
- return raw
-
-
-def planner_language_instruction(language: str) -> str:
- """Build the shared LLM output-language instruction."""
-
- normalized = resolve_orchestration_language(language)
- target = "Simplified Chinese" if normalized == "cn" else "English"
- return (
- f"Write all user-visible natural-language fields in {target}. "
- "Keep Skill IDs, original Skill names, status values, enum values, and "
- "structured field names exactly as provided; do not translate them."
- )
-
-
-def default_plan_title(language: str) -> str:
- """Return the localized presentation fallback title."""
-
- if resolve_orchestration_language(language) == "en":
- return "Symphony plan"
- return "Symphony 编排计划"
-
-
-def default_fast_no_plan_title(language: str) -> str:
- """Return the localized fast-planner no-plan title."""
-
- if resolve_orchestration_language(language) == "en":
- return "No Symphony fast plan"
- return "未生成 Symphony 快速编排计划"
-
-
-def default_beam_plan_title(language: str) -> str:
- """Return the localized Beam planner fallback title."""
-
- if resolve_orchestration_language(language) == "en":
- return "Symphony beam plan"
- return "Symphony 束搜索编排计划"
diff --git a/jiuwenswarm/symphony/orchestration/planning/__init__.py b/jiuwenswarm/symphony/orchestration/planning/__init__.py
deleted file mode 100644
index 6b8a343c27..0000000000
--- a/jiuwenswarm/symphony/orchestration/planning/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""Planning internals for orchestration."""
-
-from jiuwenswarm.symphony.orchestration.planning.models import (
- ArtifactRef,
- OrchestrationPlan,
- PlanStep,
-)
-from jiuwenswarm.symphony.orchestration.planning.beam import BidirectionalBeamPlanner
-from jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlanner
-from jiuwenswarm.symphony.orchestration.planning.plan_builder import edge_plan_item
-
-__all__ = [
- "ArtifactRef",
- "OrchestrationPlan",
- "PlanStep",
- "BidirectionalBeamPlanner",
- "FastOneShotPlanner",
- "edge_plan_item",
-]
diff --git a/jiuwenswarm/symphony/orchestration/planning/beam.py b/jiuwenswarm/symphony/orchestration/planning/beam.py
deleted file mode 100644
index e4a01c1b4e..0000000000
--- a/jiuwenswarm/symphony/orchestration/planning/beam.py
+++ /dev/null
@@ -1,1615 +0,0 @@
-"""Bidirectional beam planner for Symphony score orchestration."""
-
-from __future__ import annotations
-
-import asyncio
-import hashlib
-import json
-import logging
-import mimetypes
-import re
-from collections import defaultdict
-from dataclasses import dataclass
-from typing import Any, Awaitable, Callable, Iterable, Sequence
-
-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 (
- default_beam_plan_title,
- planner_language_instruction,
-)
-from jiuwenswarm.symphony.orchestration.planning.models import (
- OrchestrationPlan,
- SearchState,
-)
-from jiuwenswarm.symphony.orchestration.planning.plan_builder import (
- build_incoming_edges,
- build_outgoing_edges,
- edge_plan_item,
- state_to_plan,
-)
-from jiuwenswarm.symphony.orchestration.planning.utils import (
- eligible_can_feed_edges,
- normalize_known_skill_ids,
- skill_id,
- skill_payload,
-)
-
-SEMANTIC_SCORE_THRESHOLD = 0.5
-SEED_BASELINE_SCORE = 0.5
-DEFAULT_MAX_CONCURRENT_JUDGES = 3
-BEAM_DEFAULT_MAX_SKILLS = 40
-BeamProgressCallback = Callable[[dict[str, Any]], Awaitable[None] | None]
-logger = logging.getLogger(__name__)
-_EXPLICIT_FILE_EXTENSION_RE = re.compile(
- r"(?<![A-Za-z0-9])[\w.-]+\.([A-Za-z0-9]{1,12})\b"
-)
-_MIME_TO_OUTPUT_TYPE = {
- "application/json": "json",
- "application/msword": "docx",
- "application/pdf": "pdf",
- "application/vnd.ms-excel": "xlsx",
- "application/vnd.ms-powerpoint": "pptx",
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": (
- "pptx"
- ),
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
- "text/csv": "csv",
- "text/html": "html",
-}
-for _extension, _mime_type in {
- ".doc": "application/msword",
- ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
- ".ppt": "application/vnd.ms-powerpoint",
- ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
- ".xls": "application/vnd.ms-excel",
- ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
-}.items():
- mimetypes.add_type(_mime_type, _extension)
-
-BEAM_JUDGE_SYSTEM_PROMPT = """You are Symphony's bidirectional beam expansion judge.
-Return strict JSON only.
-
-You receive:
-- The user's query.
-- The current Skill being expanded.
-- A search direction: forward or backward.
-- Candidate Skills already validated by existing can_feed edges.
-
-Task:
-- Score each candidate from 0.0 to 1.0 for usefulness to the user's query and
- the local Skill chain represented by the current Skill and search direction.
-- Treat data dependency as already validated; do not judge edge feasibility.
-- Do not invent Skills, inputs, outputs, or edge relationships.
-
-Schema:
-{
- "judgements": [
- {"candidate_id": "candidate-id", "score": 0.0, "reason": "short reason"}
- ]
-}
-"""
-
-BEAM_FINAL_RERANK_SYSTEM_PROMPT = """You are a final task orchestration reranker.
-Return strict JSON only.
-
-You receive the user's query, candidate plans produced by bidirectional beam
-search, a candidate Skill pool, and the existing can_feed edges available among
-those Skills.
-
-Task:
-- Select the best plan for completing the user's task.
-- Candidate plans are references, not hard constraints. You may combine Skills
- from different plans or remove duplicate-function Skills.
-- Use only Skill IDs from candidate_skill_pool.
-- Use only edges from candidate_can_feed_edges. Skills without a dependency edge
- may remain parallel steps in the same plan.
-- Preserve distinct Skills needed for multi-stage or multi-deliverable tasks.
-- Prefer the shortest plan that covers the user's intent.
-- Do not invent Skills, inputs, outputs, dependencies, or artifacts.
-- Keep each reason <= 50 Chinese characters or <= 12 English words.
-
-Schema:
-{
- "selected_plan_index": 1,
- "reason": "short reason",
- "steps": [
- {"skill_id": "skill-a", "reason": "short reason"}
- ],
- "can_feed_edges": [
- {"source_id": "skill-a", "target_id": "skill-b"}
- ]
-}
-"""
-
-
-@dataclass(frozen=True)
-class BeamState:
- """One bidirectional beam search state."""
-
- skill_ids: tuple[str, ...]
- edge_indices: tuple[int, ...]
- semantic_scores: tuple[float, ...]
- score_reasons: tuple[str, ...]
- seed_skill_ids: tuple[str, ...]
- last_direction: str
-
- @property
- def depth(self) -> int:
- return len(self.skill_ids)
-
- @property
- def head(self) -> str:
- return self.skill_ids[0]
-
- @property
- def tail(self) -> str:
- return self.skill_ids[-1]
-
- def to_search_state(self) -> SearchState:
- return SearchState(
- skill_ids=self.skill_ids,
- edges=self.edge_indices,
- score_reasons=self.score_reasons,
- )
-
-
-@dataclass(frozen=True)
-class NeighborExpansion:
- """A single adjacent Skill candidate to be judged."""
-
- candidate_id: str
- state: BeamState
- direction: str
- current_skill_id: str
- candidate_skill_id: str
- edge_index: int
-
-
-@dataclass(frozen=True)
-class SemanticJudgement:
- """LLM judgement for one neighbor expansion."""
-
- candidate_id: str
- score: float
- reason: str
-
-
-_GRAPH_STATUS_PRIORITY = {
- "pending": 0,
- "rejected": 1,
- "seed": 2,
- "selected": 3,
- "final": 4,
-}
-
-
-class BeamSearchGraph:
- """Lightweight search graph for user-facing beam progress."""
-
- def __init__(
- self,
- skill_by_id: dict[str, dict[str, Any]],
- ) -> None:
- self.skill_by_id = skill_by_id
- self.nodes: dict[str, dict[str, Any]] = {}
- self.graph_edges: dict[str, dict[str, Any]] = {}
-
- def add_seed(self, current_skill_id: str) -> None:
- self._ensure_node(current_skill_id, status="seed", seed=True)
-
- def add_candidate(self, expansion: NeighborExpansion) -> None:
- self._ensure_node(
- expansion.current_skill_id,
- status="seed" if self._is_seed(expansion.current_skill_id) else "selected",
- )
- self._ensure_node(
- expansion.candidate_skill_id,
- status="pending",
- )
- self._ensure_edge(expansion, status="pending")
-
- def apply_judgement(
- self,
- expansion: NeighborExpansion,
- judgement: SemanticJudgement,
- ) -> None:
- status = (
- "selected" if judgement.score >= SEMANTIC_SCORE_THRESHOLD else "rejected"
- )
- self._ensure_node(
- expansion.candidate_skill_id,
- status=status,
- )
- self._ensure_edge(expansion, status=status)
-
- def mark_final_plan(self, plan: dict[str, Any]) -> None:
- for step in plan.get("steps") or []:
- if not isinstance(step, dict):
- continue
- current_skill_id = str(step.get("skill_id") or "").strip()
- if not current_skill_id:
- continue
- self._ensure_node(current_skill_id, status="final")
- for edge in plan.get("can_feed_edges") or []:
- if not isinstance(edge, dict):
- continue
- source_id = str(edge.get("source_id") or edge.get("source") or "").strip()
- target_id = str(edge.get("target_id") or edge.get("target") or "").strip()
- edge_id = self._existing_edge_id(source_id, target_id)
- if not edge_id:
- continue
- self.graph_edges[edge_id]["status"] = _dominant_status(
- str(self.graph_edges[edge_id].get("status") or ""),
- "final",
- )
-
- def snapshot(self) -> dict[str, Any]:
- nodes = []
- for node in self.nodes.values():
- nodes.append(
- {
- "id": node["id"],
- "label": node["label"],
- "status": node["status"],
- "seed": bool(node.get("seed")),
- }
- )
- edges = [_copy_public_graph_edge(edge) for edge in self.graph_edges.values()]
- return {"nodes": nodes, "edges": edges}
-
- def _ensure_node(
- self,
- current_skill_id: str,
- *,
- status: str,
- seed: bool = False,
- ) -> None:
- node = self.nodes.get(current_skill_id)
- if node is None:
- node = {
- "id": current_skill_id,
- "label": _skill_label(self.skill_by_id.get(current_skill_id, {})),
- "status": status,
- "seed": seed,
- }
- self.nodes[current_skill_id] = node
- else:
- node["status"] = _dominant_status(str(node.get("status") or ""), status)
- node["seed"] = bool(node.get("seed")) or seed
- return node
-
- def _ensure_edge(
- self,
- expansion: NeighborExpansion,
- *,
- status: str,
- ) -> dict[str, Any]:
- source_id = expansion.current_skill_id
- target_id = expansion.candidate_skill_id
- edge_id = f"{source_id}->{target_id}"
- graph_edge = self.graph_edges.get(edge_id)
- if graph_edge is None:
- graph_edge = {
- "id": edge_id,
- "source": source_id,
- "target": target_id,
- "status": status,
- }
- self.graph_edges[edge_id] = graph_edge
- else:
- graph_edge["status"] = _dominant_status(
- str(graph_edge.get("status") or ""),
- status,
- )
-
- def _existing_edge_id(self, source_id: str, target_id: str) -> str:
- forward_id = f"{source_id}->{target_id}"
- if forward_id in self.graph_edges:
- return forward_id
- backward_id = f"{target_id}->{source_id}"
- if backward_id in self.graph_edges:
- return backward_id
- return ""
-
- def _is_seed(self, current_skill_id: str) -> bool:
- node = self.nodes.get(current_skill_id)
- return bool(node and node.get("seed"))
-
-
-class BidirectionalBeamPlanner:
- """Build candidate plans through semantic bidirectional beam search."""
-
- def __init__(
- self,
- artifacts: ScoreArtifacts,
- *,
- llm_config: LLMConfig | None,
- llm_client: Any | None,
- min_edge_confidence: float,
- top_k: int,
- max_depth: int,
- candidate_skill_ids: Sequence[str] | None = None,
- max_concurrent_judges: int = DEFAULT_MAX_CONCURRENT_JUDGES,
- progress_callback: BeamProgressCallback | None = None,
- language: str = "cn",
- ) -> None:
- self.artifacts = artifacts
- self.llm_config = llm_config
- self.llm_client = llm_client
- self.min_edge_confidence = min_edge_confidence
- self.top_k = max(1, int(top_k))
- self.max_depth = max(1, int(max_depth))
- self.max_concurrent_judges = max(1, int(max_concurrent_judges))
- self.skill_by_id = artifacts.skill_by_id
- self.candidate_skill_ids = normalize_known_skill_ids(
- candidate_skill_ids,
- known_skill_ids=set(self.skill_by_id),
- )
- self.progress_callback = progress_callback
- self.language = language
- self.eligible_edges = self._sorted_eligible_edges()
- self._beam_graph = BeamSearchGraph(self.skill_by_id)
- self.outgoing_edges = build_outgoing_edges(self.eligible_edges)
- self.incoming_edges = build_incoming_edges(self.eligible_edges)
- self._judgement_cache: dict[tuple[str, str, str, str], SemanticJudgement] = {}
- self._cache_hits = 0
- self._cache_misses = 0
- self._judge_semaphore = asyncio.Semaphore(self.max_concurrent_judges)
- self._llm_call_count = 0
- self._final_rerank_call_count = 0
- self._judge_failures: list[str] = []
- self.required_output_types: frozenset[str] = frozenset()
- self._current_expansions: dict[str, NeighborExpansion] = {}
- self._current_expansion_aliases: dict[str, list[str]] = {}
-
- async def plan(self, query: str) -> dict[str, Any]:
- self._reset_beam_progress()
- self._final_rerank_call_count = 0
- self.required_output_types = _required_output_types_from_query(query)
- query_signature = _query_signature(query)
- frontier = self._initial_states()
- all_states = list(frontier)
- seed_skill_ids = tuple(state.skill_ids[0] for state in frontier)
- for current_skill_id in seed_skill_ids:
- self._beam_graph.add_seed(current_skill_id)
- await self._emit_beam_event(
- "started",
- round_index=0,
- graph=self._beam_graph.snapshot(),
- )
- round_index = 0
-
- for _round in range(max(0, self.max_depth - 1)):
- groups, cached = self._expansion_groups(query_signature, frontier)
- found = self._record_candidates_found()
- if found:
- await self._emit_beam_event(
- "candidates_found",
- round_index=_round + 1,
- graph=self._beam_graph.snapshot(),
- )
- if not groups and not cached:
- break
- fresh = await self._judge_groups(query, groups)
- fresh = self._apply_judgement_aliases(fresh)
- for candidate_id, judgement in fresh.items():
- expansion = self._expansion_by_id(candidate_id)
- if expansion is not None:
- self._cache_set(query_signature, expansion, judgement)
- judgements = {**cached, **fresh}
- judged = self._record_candidates_judged(judgements)
- if judged:
- await self._emit_beam_event(
- "candidates_judged",
- round_index=_round + 1,
- graph=self._beam_graph.snapshot(),
- )
- next_states = self._apply_judgements(judgements)
- if not next_states:
- await self._emit_beam_event(
- "graph_merged",
- round_index=_round + 1,
- graph=self._beam_graph.snapshot(),
- )
- round_index = _round + 1
- break
- retained = self._rank_and_trim(next_states, limit=self.top_k)
- all_states = retained
- frontier = retained
- round_index = _round + 1
- await self._emit_beam_event(
- "graph_merged",
- round_index=_round + 1,
- graph=self._beam_graph.snapshot(),
- )
-
- final_states = self._merge_converged_states(all_states)
- plans = self._plans_from_states(final_states)[: self.top_k]
- recommended_plans = [self._plan_payload(plan, query=query) for plan in plans]
- final_rerank = await self._final_rerank_plans(
- query=query,
- recommended_plans=recommended_plans,
- seed_skill_ids=seed_skill_ids,
- )
- recommended_plans = final_rerank["recommended_plans"]
- final_plan = recommended_plans[0] if recommended_plans else {}
- self._beam_graph.mark_final_plan(final_plan)
- await self._emit_beam_event(
- "completed",
- round_index=round_index,
- graph=self._beam_graph.snapshot(),
- )
- status = recommended_plans[0]["status"] if recommended_plans else "no_plan"
- reason = recommended_plans[0].get("reason", "") if recommended_plans else ""
- unique_skill_ids = {
- current_skill_id
- for state in all_states
- for current_skill_id in state.skill_ids
- }
- return {
- "query": query,
- "language": self.language,
- "score_dir": str(self.artifacts.score_dir),
- "planning_mode": "bidirectional_beam",
- "llm_call_count": self._llm_call_count + self._final_rerank_call_count,
- "candidate_skill_count": len(unique_skill_ids),
- "candidate_edge_count": len(self.eligible_edges),
- "plans": recommended_plans,
- "recommended_plans": recommended_plans,
- "ranking_mode": "bidirectional_beam",
- "beam_search": {
- "mode": "bidirectional_beam",
- "language": self.language,
- "round_index": round_index,
- "graph": self._beam_graph.snapshot(),
- },
- "decision": {
- "mode": "bidirectional_beam",
- "strategy": "semantic_bidirectional_beam",
- "validated_count": len(recommended_plans),
- "candidate_count": len(unique_skill_ids),
- "judge_llm_call_count": self._llm_call_count,
- "judge_cache_hits": self._cache_hits,
- "judge_cache_misses": self._cache_misses,
- "final_rerank": {
- "applied": final_rerank["applied"],
- "llm_call_count": self._final_rerank_call_count,
- "cross_plan_skill_merge": final_rerank["cross_plan_skill_merge"],
- "error": final_rerank["error"],
- },
- },
- "validation": {
- "valid": True,
- "details": self._judge_failures[:10],
- },
- "status": status,
- "reason": reason,
- }
-
- async def judge_expansions(
- self,
- query: str,
- expansions: list[NeighborExpansion],
- ) -> dict[str, SemanticJudgement]:
- if not expansions:
- return {}
-
- first = expansions[0]
- current_skill = self.skill_by_id.get(first.current_skill_id, {})
- payload = {
- "query": query,
- "direction": first.direction,
- "current_skill": skill_payload(current_skill),
- "candidates": [
- self._candidate_payload(expansion) for expansion in expansions
- ],
- }
- with llm_usage_context("orchestration", "bidirectional_beam_judgement"):
- raw = await self._client().complete_json_async(
- system_prompt=(
- f"{BEAM_JUDGE_SYSTEM_PROMPT}\n"
- f"{planner_language_instruction(self.language)}"
- ),
- user_content=json.dumps(payload, ensure_ascii=False),
- error_context="Symphony bidirectional beam judgement",
- )
- data = json.loads(raw)
- items = data.get("judgements") if isinstance(data, dict) else data
- if not isinstance(items, list):
- return {}
-
- known_ids = {expansion.candidate_id for expansion in expansions}
- judgements: dict[str, SemanticJudgement] = {}
- for item in items:
- if not isinstance(item, dict):
- continue
- candidate_id = str(item.get("candidate_id") or "").strip()
- if candidate_id not in known_ids:
- continue
- score = _clamp_score(item.get("score"))
- judgements[candidate_id] = SemanticJudgement(
- candidate_id=candidate_id,
- score=score,
- reason=str(item.get("reason") or "").strip(),
- )
- return judgements
-
- async def _final_rerank_plans(
- self,
- *,
- query: str,
- recommended_plans: list[dict[str, Any]],
- seed_skill_ids: tuple[str, ...],
- ) -> dict[str, Any]:
- base = {
- "applied": False,
- "error": "",
- "cross_plan_skill_merge": False,
- "recommended_plans": recommended_plans[: self.top_k],
- }
- if not recommended_plans:
- return base
-
- payload = self._final_rerank_payload(
- query=query,
- recommended_plans=recommended_plans,
- seed_skill_ids=seed_skill_ids,
- )
- self._final_rerank_call_count += 1
- try:
- with llm_usage_context("orchestration", "beam_final_rerank"):
- raw = await self._client().complete_json_async(
- system_prompt=(
- f"{BEAM_FINAL_RERANK_SYSTEM_PROMPT}\n"
- f"{planner_language_instruction(self.language)}"
- ),
- user_content=json.dumps(payload, ensure_ascii=False),
- error_context="Symphony beam final rerank",
- request_overrides={
- "extra_body": {"thinking": {"type": "disabled"}}
- },
- )
- selection = json.loads(raw)
- except Exception as exc:
- return {**base, "error": f"{type(exc).__name__}: {exc}"}
- if not isinstance(selection, dict):
- return {**base, "error": "Final rerank returned non-object JSON."}
-
- materialized = self._materialize_final_rerank(
- selection,
- query=query,
- recommended_plans=recommended_plans,
- )
- if not materialized["valid"]:
- return {**base, "error": materialized["detail"]}
-
- primary_plan = materialized["plan"]
- output = [primary_plan]
- seen = {_dict_plan_signature(primary_plan)}
- for plan in recommended_plans:
- signature = _dict_plan_signature(plan)
- if signature in seen:
- continue
- output.append(plan)
- seen.add(signature)
- if len(output) >= self.top_k:
- break
- return {
- **base,
- "applied": True,
- "cross_plan_skill_merge": materialized["cross_plan_skill_merge"],
- "recommended_plans": output,
- }
-
- def _final_rerank_payload(
- self,
- *,
- query: str,
- recommended_plans: list[dict[str, Any]],
- seed_skill_ids: tuple[str, ...],
- ) -> dict[str, Any]:
- candidate_skill_ids = _candidate_plan_skill_ids(recommended_plans)
- return {
- "query": query,
- "required_output_types": sorted(self.required_output_types),
- "candidate_skill_pool": self._candidate_skill_pool_for_rerank(
- candidate_skill_ids,
- seed_skill_ids=seed_skill_ids,
- ),
- "candidate_can_feed_edges": self._candidate_edges_for_rerank(
- candidate_skill_ids
- ),
- "candidate_plans": [
- self._compact_plan_for_rerank(plan, plan_index=index)
- for index, plan in enumerate(recommended_plans, start=1)
- ],
- }
-
- def _candidate_skill_pool_for_rerank(
- self,
- candidate_skill_ids: set[str],
- *,
- seed_skill_ids: tuple[str, ...],
- ) -> list[dict[str, Any]]:
- seed_skill_id_set = set(seed_skill_ids)
- output = []
- for current_skill_id in sorted(candidate_skill_ids):
- skill = self.skill_by_id.get(current_skill_id)
- if not skill:
- continue
- output.append(
- {
- **skill_payload(skill),
- "is_seed": current_skill_id in seed_skill_id_set,
- "outputs": [
- {
- "name": str(item.get("name") or ""),
- "type": str(item.get("type") or "unknown"),
- }
- for item in skill.get("outputs") or []
- if isinstance(item, dict) and item.get("name")
- ],
- }
- )
- return output
-
- def _candidate_edges_for_rerank(
- self,
- candidate_skill_ids: set[str],
- ) -> list[dict[str, Any]]:
- output = []
- for edge in self.eligible_edges:
- source_id = skill_id(edge.get("source"))
- target_id = skill_id(edge.get("target"))
- if source_id not in candidate_skill_ids:
- continue
- if target_id not in candidate_skill_ids:
- continue
- output.append(
- {
- "source_id": source_id,
- "target_id": target_id,
- "confidence": edge.get("confidence"),
- }
- )
- return output
-
- @staticmethod
- def _compact_plan_for_rerank(
- plan: dict[str, Any],
- *,
- plan_index: int,
- ) -> dict[str, Any]:
- return {
- "plan_index": plan_index,
- "skills": list(_dict_plan_signature(plan)),
- "missing_input_count": len(plan.get("missing_inputs") or []),
- "status": plan.get("status"),
- }
-
- def _materialize_final_rerank(
- self,
- selection: dict[str, Any],
- *,
- query: str,
- recommended_plans: list[dict[str, Any]],
- ) -> dict[str, Any]:
- selected_index = _positive_int(selection.get("selected_plan_index")) or 1
- selected_index = min(selected_index, len(recommended_plans))
-
- selected_plan = recommended_plans[selected_index - 1]
- raw_steps = selection.get("steps")
- if raw_steps is None:
- return {
- "valid": True,
- "detail": "",
- "cross_plan_skill_merge": False,
- "plan": {
- **selected_plan,
- "reason": _short_text(str(selection.get("reason") or ""))
- or selected_plan.get("reason", ""),
- "source": "bidirectional_beam_final_rerank",
- },
- }
-
- allowed_skill_ids = _candidate_plan_skill_ids(recommended_plans)
- step_ids = []
- for current_skill_id in _normalize_rerank_step_ids(raw_steps):
- if current_skill_id not in allowed_skill_ids:
- continue
- if current_skill_id not in self.skill_by_id:
- continue
- step_ids.append(current_skill_id)
- if not step_ids:
- return {
- "valid": True,
- "detail": "",
- "cross_plan_skill_merge": False,
- "plan": selected_plan,
- }
-
- edge_result = _normalize_rerank_edges(selection.get("can_feed_edges"))
- selected_edges = edge_result["edges"]
- if selection.get("can_feed_edges") is None:
- selected_edges = self._default_rerank_edges(step_ids)
- step_set = set(step_ids)
- eligible_edge_keys = {
- (skill_id(edge.get("source")), skill_id(edge.get("target")))
- for edge in self.eligible_edges
- }
- order = {
- current_skill_id: index for index, current_skill_id in enumerate(step_ids)
- }
- filtered_edges = []
- for edge in selected_edges:
- if edge[0] not in step_set or edge[1] not in step_set:
- continue
- if edge not in eligible_edge_keys:
- continue
- if order[edge[0]] >= order[edge[1]]:
- continue
- filtered_edges.append(edge)
- selected_edges = filtered_edges
-
- return {
- "valid": True,
- "detail": "",
- "cross_plan_skill_merge": not set(step_ids)
- <= set(_dict_plan_signature(selected_plan)),
- "plan": self._final_rerank_plan_payload(
- selection,
- query=query,
- step_ids=step_ids,
- selected_edges=selected_edges,
- recommended_plans=recommended_plans,
- ),
- }
-
- def _default_rerank_edges(
- self,
- step_ids: list[str],
- ) -> list[tuple[str, str]]:
- order = {
- current_skill_id: index for index, current_skill_id in enumerate(step_ids)
- }
- output = []
- for item in self.eligible_edges:
- edge = (skill_id(item.get("source")), skill_id(item.get("target")))
- if (
- edge[0] in order
- and edge[1] in order
- and order[edge[0]] < order[edge[1]]
- ):
- output.append(edge)
- return output
-
- def _final_rerank_plan_payload(
- self,
- selection: dict[str, Any],
- *,
- query: str,
- step_ids: list[str],
- selected_edges: list[tuple[str, str]],
- recommended_plans: list[dict[str, Any]],
- ) -> dict[str, Any]:
- source_steps = _plan_steps_by_skill(recommended_plans)
- step_reasons = _step_reasons_by_skill(selection.get("steps"))
- steps = []
- produced_artifacts = []
- for index, current_skill_id in enumerate(step_ids, start=1):
- skill = self.skill_by_id[current_skill_id]
- source_step = source_steps.get(current_skill_id, {})
- outputs = list(skill.get("outputs") or [])
- produced_artifacts.extend(
- {
- "name": item.get("name"),
- "type": item.get("type") or "unknown",
- "source": "skill_output",
- }
- for item in outputs
- if isinstance(item, dict) and item.get("name")
- )
- steps.append(
- {
- "step": index,
- "skill_id": current_skill_id,
- "name": str(skill.get("name") or current_skill_id),
- "inputs": list(skill.get("inputs") or []),
- "outputs": outputs,
- "missing_inputs": list(source_step.get("missing_inputs") or []),
- "filled_inputs": list(source_step.get("filled_inputs") or []),
- "reason": step_reasons.get(current_skill_id, ""),
- }
- )
- raw_missing_inputs = []
- for step in steps:
- for item in step.get("missing_inputs") or []:
- if isinstance(item, dict):
- raw_missing_inputs.append(item)
- missing_inputs = _dedupe_dict_items(raw_missing_inputs)
- edge_by_key = {
- (skill_id(edge.get("source")), skill_id(edge.get("target"))): edge
- for edge in self.eligible_edges
- }
- edge_items = [edge_plan_item(edge_by_key[edge]) for edge in selected_edges]
- status = "needs_input" if missing_inputs else "ready"
- reason = _short_text(str(selection.get("reason") or ""))
- return {
- "title": _query_plan_title(query, language=self.language),
- "status": status,
- "steps": steps,
- "stages": _rerank_plan_stages(steps, edge_items),
- "produced_artifacts": _dedupe_dict_items(produced_artifacts),
- "missing_inputs": missing_inputs,
- "can_feed_edges": edge_items,
- "reason": reason,
- "reasons": [reason] if reason else [],
- "plan_classification": (
- "executable"
- if status == "ready"
- else "structurally_valid_but_incomplete"
- ),
- "connectivity_trace": ["can_feed"] if edge_items else [],
- "source": "bidirectional_beam_final_rerank",
- }
-
- def _client(self) -> Any:
- if self.llm_client is not None:
- return self.llm_client
- if self.llm_config is None:
- raise ValueError(
- "beam Symphony planning requires llm_config or llm_client."
- )
- self.llm_client = create_llm_client(self.llm_config)
- return self.llm_client
-
- async def _judge_groups(
- self,
- query: str,
- groups: list[list[NeighborExpansion]],
- ) -> dict[str, SemanticJudgement]:
- tasks = [self._judge_group(query, group) for group in groups if group]
- if not tasks:
- return {}
- output: dict[str, SemanticJudgement] = {}
- for result in await asyncio.gather(*tasks):
- output.update(result)
- return output
-
- async def _judge_group(
- self,
- query: str,
- group: list[NeighborExpansion],
- ) -> dict[str, SemanticJudgement]:
- async with self._judge_semaphore:
- self._llm_call_count += 1
- try:
- return await self.judge_expansions(query, group)
- except Exception as exc:
- candidates = ", ".join(item.candidate_id for item in group[:5])
- self._judge_failures.append(
- f"beam judge failed for candidates [{candidates}]: {exc}"
- )
- return {}
-
- @staticmethod
- def _cache_key(
- query_signature: str,
- expansion: NeighborExpansion,
- ) -> tuple[str, str, str, str]:
- return (
- query_signature,
- expansion.direction,
- expansion.current_skill_id,
- expansion.candidate_skill_id,
- )
-
- def _cache_get(
- self,
- query_signature: str,
- expansion: NeighborExpansion,
- ) -> SemanticJudgement | None:
- cached = self._judgement_cache.get(self._cache_key(query_signature, expansion))
- if cached is None:
- self._cache_misses += 1
- else:
- self._cache_hits += 1
- return cached
-
- def _cache_set(
- self,
- query_signature: str,
- expansion: NeighborExpansion,
- judgement: SemanticJudgement,
- ) -> None:
- self._judgement_cache[self._cache_key(query_signature, expansion)] = judgement
-
- def _initial_states(self) -> list[BeamState]:
- seeds = self.candidate_skill_ids or self._default_seed_skill_ids()
- states = [
- BeamState(
- skill_ids=(current_skill_id,),
- edge_indices=(),
- semantic_scores=(),
- score_reasons=(),
- seed_skill_ids=tuple(seeds),
- last_direction="seed",
- )
- for current_skill_id in seeds
- if current_skill_id in self.skill_by_id
- ]
- return self._rank_and_trim(states, limit=self.top_k)
-
- def _default_seed_skill_ids(self) -> tuple[str, ...]:
- output: list[str] = []
- seen: set[str] = set()
- for edge in self.eligible_edges:
- for key in ("source", "target"):
- current_skill_id = skill_id(edge.get(key))
- if (
- current_skill_id
- and current_skill_id in self.skill_by_id
- and current_skill_id not in seen
- ):
- seen.add(current_skill_id)
- output.append(current_skill_id)
- if len(output) >= BEAM_DEFAULT_MAX_SKILLS:
- return tuple(output)
- if output:
- return tuple(output)
- for skill in self.artifacts.skills[:BEAM_DEFAULT_MAX_SKILLS]:
- current_skill_id = str(skill.get("id") or "").strip()
- if current_skill_id:
- output.append(current_skill_id)
- return tuple(output)
-
- def _expansion_groups(
- self,
- query_signature: str,
- states: list[BeamState],
- ) -> tuple[list[list[NeighborExpansion]], dict[str, SemanticJudgement]]:
- groups: list[list[NeighborExpansion]] = []
- cached: dict[str, SemanticJudgement] = {}
- current_expansions: dict[str, NeighborExpansion] = {}
- pending_keys: dict[tuple[str, str, str], str] = {}
- aliases: dict[str, list[str]] = defaultdict(list)
- for state in states:
- for direction, current_skill_id in (
- ("forward", state.tail),
- ("backward", state.head),
- ):
- expansions = self._neighbor_expansions(
- state=state,
- direction=direction,
- current_skill_id=current_skill_id,
- )
- misses = []
- for expansion in expansions:
- current_expansions[expansion.candidate_id] = expansion
- judgement = self._cache_get(query_signature, expansion)
- if judgement is None:
- misses.append(expansion)
- else:
- cached[expansion.candidate_id] = judgement
- if misses:
- deduped_misses = []
- for expansion in misses:
- key = self._cache_key(query_signature, expansion)
- existing_candidate_id = pending_keys.get(key)
- if existing_candidate_id is not None:
- aliases[existing_candidate_id].append(
- expansion.candidate_id
- )
- continue
- pending_keys[key] = expansion.candidate_id
- deduped_misses.append(expansion)
- if deduped_misses:
- groups.append(deduped_misses)
- self._current_expansions = current_expansions
- self._current_expansion_aliases = aliases
- return groups, cached
-
- def _apply_judgement_aliases(
- self,
- judgements: dict[str, SemanticJudgement],
- ) -> dict[str, SemanticJudgement]:
- output = dict(judgements)
- for source_id, alias_ids in self._current_expansion_aliases.items():
- judgement = judgements.get(source_id)
- if judgement is None:
- continue
- for alias_id in alias_ids:
- output[alias_id] = SemanticJudgement(
- candidate_id=alias_id,
- score=judgement.score,
- reason=judgement.reason,
- )
- return output
-
- def _neighbor_expansions(
- self,
- *,
- state: BeamState,
- direction: str,
- current_skill_id: str,
- ) -> list[NeighborExpansion]:
- if state.depth >= self.max_depth:
- return []
- edge_indices = (
- self.outgoing_edges.get(current_skill_id, [])
- if direction == "forward"
- else self.incoming_edges.get(current_skill_id, [])
- )
- expansions = []
- for edge_index in edge_indices:
- edge = self.eligible_edges[edge_index]
- candidate_skill_id = (
- skill_id(edge.get("target"))
- if direction == "forward"
- else skill_id(edge.get("source"))
- )
- if (
- not candidate_skill_id
- or candidate_skill_id not in self.skill_by_id
- or candidate_skill_id in state.skill_ids
- ):
- continue
- expansions.append(
- NeighborExpansion(
- candidate_id=(
- f"{direction}:{edge_index}:"
- f"{_state_signature(state)}:{candidate_skill_id}"
- ),
- state=state,
- direction=direction,
- current_skill_id=current_skill_id,
- candidate_skill_id=candidate_skill_id,
- edge_index=edge_index,
- )
- )
- return expansions
-
- def _apply_judgements(
- self,
- judgements: dict[str, SemanticJudgement],
- ) -> list[BeamState]:
- output = []
- for candidate_id, judgement in judgements.items():
- if judgement.score < SEMANTIC_SCORE_THRESHOLD:
- continue
- expansion = self._expansion_by_id(candidate_id)
- if expansion is None:
- continue
- state = expansion.state
- if expansion.direction == "forward":
- skill_ids = (*state.skill_ids, expansion.candidate_skill_id)
- edge_indices = (*state.edge_indices, expansion.edge_index)
- else:
- skill_ids = (expansion.candidate_skill_id, *state.skill_ids)
- edge_indices = (expansion.edge_index, *state.edge_indices)
- output.append(
- BeamState(
- skill_ids=skill_ids,
- edge_indices=edge_indices,
- semantic_scores=(*state.semantic_scores, judgement.score),
- score_reasons=_append_unique(
- state.score_reasons,
- judgement.reason,
- ),
- seed_skill_ids=state.seed_skill_ids,
- last_direction=expansion.direction,
- )
- )
- return output
-
- def _expansion_by_id(self, candidate_id: str) -> NeighborExpansion | None:
- return self._current_expansions.get(candidate_id)
-
- def _reset_beam_progress(self) -> None:
- self._beam_graph = BeamSearchGraph(self.skill_by_id)
-
- async def _emit_beam_event(
- self,
- event: str,
- *,
- round_index: int,
- graph: dict[str, Any],
- ) -> None:
- item = {
- "event": event,
- "language": self.language,
- "round_index": round_index,
- "graph": graph,
- }
- if self.progress_callback is None:
- return
- try:
- result = self.progress_callback(item)
- if asyncio.iscoroutine(result):
- await result
- except Exception as exc:
- logger.debug("beam progress callback failed: %s", exc)
-
- def _record_candidates_found(self) -> bool:
- expansions = _sorted_expansions(self._current_expansions.values())
- for expansion in expansions:
- self._beam_graph.add_candidate(expansion)
- return bool(expansions)
-
- def _record_candidates_judged(
- self,
- judgements: dict[str, SemanticJudgement],
- ) -> bool:
- found = False
- for candidate_id in sorted(judgements):
- expansion = self._expansion_by_id(candidate_id)
- if expansion is None:
- continue
- self._beam_graph.apply_judgement(
- expansion,
- judgements[candidate_id],
- )
- found = True
- return found
-
- def _plans_from_states(self, states: list[BeamState]) -> list[OrchestrationPlan]:
- state_plans = [
- (
- state,
- state_to_plan(
- state=state.to_search_state(),
- seed_skill_ids=state.seed_skill_ids,
- skill_by_id=self.skill_by_id,
- can_feed_edges=self.eligible_edges,
- ),
- )
- for state in states
- if state.skill_ids
- ]
- state_plans.sort(
- key=lambda item: (
- -self._state_score(item[0], plan=item[1]),
- len(item[1].missing_inputs),
- len(item[1].steps),
- tuple(step.skill_id for step in item[1].steps),
- )
- )
- return [plan for _state, plan in state_plans]
-
- def _merge_converged_states(self, states: list[BeamState]) -> list[BeamState]:
- deduped = self._dedupe_states(states)
- merged = list(deduped)
- directional_groups = (
- _group_states(
- [state for state in deduped if state.last_direction == "forward"],
- lambda state: state.tail,
- ),
- _group_states(
- [state for state in deduped if state.last_direction == "backward"],
- lambda state: state.head,
- ),
- )
- for groups in directional_groups:
- for group in groups:
- if len(group) < 2:
- continue
- merged_state = self._merge_state_group(group)
- if merged_state is not None:
- merged.append(merged_state)
- return self._dedupe_states(merged)
-
- def _merge_state_group(self, states: list[BeamState]) -> BeamState | None:
- skill_ids = {current for state in states for current in state.skill_ids}
- edge_indices = tuple(
- sorted(
- {edge_index for state in states for edge_index in state.edge_indices}
- )
- )
- ordered = self._topological_order(skill_ids, edge_indices)
- if ordered is None:
- return None
- seed_skill_ids = tuple(
- dict.fromkeys(
- current for state in states for current in state.seed_skill_ids
- )
- )
- semantic_scores = tuple(
- score for state in states for score in state.semantic_scores
- )
- unique_reasons = []
- for state in states:
- for reason in state.score_reasons:
- if reason and reason not in unique_reasons:
- unique_reasons.append(reason)
- reasons = tuple(unique_reasons)
- return BeamState(
- skill_ids=tuple(ordered),
- edge_indices=edge_indices,
- semantic_scores=semantic_scores,
- score_reasons=reasons[:8],
- seed_skill_ids=seed_skill_ids,
- last_direction=states[0].last_direction,
- )
-
- def _topological_order(
- self,
- skill_ids: set[str],
- edge_indices: tuple[int, ...],
- ) -> list[str] | None:
- incoming = {current_skill_id: 0 for current_skill_id in skill_ids}
- outgoing: dict[str, list[str]] = defaultdict(list)
- for edge_index in edge_indices:
- edge = self.eligible_edges[edge_index]
- source_id = skill_id(edge.get("source"))
- target_id = skill_id(edge.get("target"))
- if source_id not in skill_ids or target_id not in skill_ids:
- continue
- outgoing[source_id].append(target_id)
- incoming[target_id] += 1
-
- ready = sorted(
- current_skill_id
- for current_skill_id, count in incoming.items()
- if count == 0
- )
- ordered = []
- while ready:
- current_skill_id = ready.pop(0)
- ordered.append(current_skill_id)
- for target_id in sorted(outgoing.get(current_skill_id, [])):
- incoming[target_id] -= 1
- if incoming[target_id] == 0:
- ready.append(target_id)
- ready.sort()
- if len(ordered) != len(skill_ids):
- return None
- return ordered
-
- def _dedupe_states(self, states: list[BeamState]) -> list[BeamState]:
- deduped: dict[tuple[tuple[str, ...], tuple[int, ...]], BeamState] = {}
- for state in states:
- key = (state.skill_ids, tuple(sorted(state.edge_indices)))
- existing = deduped.get(key)
- if existing is None or self._state_score(state) > self._state_score(
- existing
- ):
- deduped[key] = state
- return list(deduped.values())
-
- def _rank_and_trim(
- self,
- states: list[BeamState],
- *,
- limit: int,
- ) -> list[BeamState]:
- ranked = []
- for state in self._dedupe_states(states):
- plan = self._state_plan(state)
- ranked.append(
- (state, self._state_score(state, plan=plan), len(plan.missing_inputs))
- )
- ranked.sort(
- key=lambda item: (
- -item[1],
- item[2],
- len(item[0].skill_ids),
- item[0].skill_ids,
- item[0].edge_indices,
- )
- )
- return [state for state, _score, _missing in ranked[:limit]]
-
- def _state_score(
- self,
- state: BeamState,
- *,
- plan: OrchestrationPlan | None = None,
- ) -> float:
- plan = plan or self._state_plan(state)
- semantic_score = (
- sum(state.semantic_scores) / len(state.semantic_scores)
- if state.semantic_scores
- else SEED_BASELINE_SCORE
- )
- edge_confidence = self._state_edge_confidence(state)
- input_coverage = self._input_coverage(plan)
- depth_penalty = max(0, len(state.skill_ids) - 1)
- return (
- 0.45 * semantic_score
- + 0.25 * edge_confidence
- + 0.20 * input_coverage
- - 0.03 * depth_penalty
- )
-
- def _state_plan(self, state: BeamState) -> OrchestrationPlan:
- return state_to_plan(
- state=state.to_search_state(),
- seed_skill_ids=state.seed_skill_ids,
- skill_by_id=self.skill_by_id,
- can_feed_edges=self.eligible_edges,
- )
-
- def _state_edge_confidence(self, state: BeamState) -> float:
- if not state.edge_indices:
- return 1.0
- values = [
- float(self.eligible_edges[index].get("confidence") or 0.0)
- for index in state.edge_indices
- ]
- return sum(values) / len(values)
-
- @staticmethod
- def _input_coverage(plan: OrchestrationPlan) -> float:
- required = 0
- for step in plan.steps:
- required += sum(1 for item in step.inputs if item.get("required", True))
- if required <= 0:
- return 1.0
- missing = len(plan.missing_inputs)
- return max(0.0, min(1.0, (required - missing) / required))
-
- def _candidate_payload(self, expansion: NeighborExpansion) -> dict[str, Any]:
- return {
- "candidate_id": expansion.candidate_id,
- "skill": skill_payload(self.skill_by_id[expansion.candidate_skill_id]),
- }
-
- def _sorted_eligible_edges(self) -> list[dict[str, Any]]:
- return eligible_can_feed_edges(
- self.artifacts.graph.get("edges", []),
- known_skill_ids=set(self.skill_by_id),
- min_confidence=self.min_edge_confidence,
- )
-
- def _plan_payload(self, plan: OrchestrationPlan, *, query: str) -> dict[str, Any]:
- payload = plan.to_dict()
- title = _query_plan_title(query, language=self.language)
- reason = "; ".join(plan.reasons[:3])
- payload.update(
- {
- "title": title,
- "reason": reason,
- "plan_classification": (
- "executable"
- if plan.status == "ready"
- else "structurally_valid_but_incomplete"
- ),
- "connectivity_trace": (["can_feed"] if plan.can_feed_edges else []),
- "source": "bidirectional_beam",
- }
- )
- return payload
-
-
-def _query_signature(query: str) -> str:
- normalized = " ".join(str(query or "").strip().lower().split())
- return hashlib.sha1(normalized.encode("utf-8")).hexdigest()
-
-
-def _state_signature(state: BeamState) -> str:
- payload = {
- "skills": state.skill_ids,
- "edges": state.edge_indices,
- "last_direction": state.last_direction,
- }
- return hashlib.sha1(
- json.dumps(payload, sort_keys=True, default=str).encode("utf-8")
- ).hexdigest()[:10]
-
-
-def _dict_plan_signature(plan: dict[str, Any]) -> tuple[str, ...]:
- return tuple(
- str(step.get("skill_id") or "").strip()
- for step in plan.get("steps") or []
- if isinstance(step, dict) and str(step.get("skill_id") or "").strip()
- )
-
-
-def _candidate_plan_skill_ids(plans: list[dict[str, Any]]) -> set[str]:
- return {
- current_skill_id
- for plan in plans
- for current_skill_id in _dict_plan_signature(plan)
- }
-
-
-def _normalize_rerank_step_ids(raw_steps: Any) -> list[str]:
- if not isinstance(raw_steps, list):
- return []
- output = []
- for item in raw_steps:
- current_skill_id = skill_id(
- item.get("skill_id") if isinstance(item, dict) else item
- ).strip()
- if current_skill_id and current_skill_id not in output:
- output.append(current_skill_id)
- return output
-
-
-def _normalize_rerank_edges(raw_edges: Any) -> dict[str, Any]:
- edges: list[tuple[str, str]] = []
- if not isinstance(raw_edges, list):
- return {"edges": edges}
- seen = set()
- for item in raw_edges:
- if not isinstance(item, dict):
- continue
- source_id = skill_id(item.get("source_id") or item.get("source")).strip()
- target_id = skill_id(item.get("target_id") or item.get("target")).strip()
- edge = (source_id, target_id)
- if not source_id or not target_id:
- continue
- if source_id == target_id or edge in seen:
- continue
- seen.add(edge)
- edges.append(edge)
- return {"edges": edges}
-
-
-def _positive_int(value: Any) -> int | None:
- try:
- parsed = int(value)
- except (TypeError, ValueError):
- return None
- return parsed if parsed > 0 else None
-
-
-def _short_text(value: str, *, max_chars: int = 80) -> str:
- text = " ".join(str(value or "").split())
- if len(text) <= max_chars:
- return text
- return text[:max_chars].rstrip()
-
-
-def _plan_steps_by_skill(
- plans: list[dict[str, Any]],
-) -> dict[str, dict[str, Any]]:
- output = {}
- for plan in plans:
- for step in plan.get("steps") or []:
- if not isinstance(step, dict):
- continue
- current_skill_id = str(step.get("skill_id") or "").strip()
- if current_skill_id:
- output.setdefault(current_skill_id, step)
- return output
-
-
-def _step_reasons_by_skill(raw_steps: Any) -> dict[str, str]:
- if not isinstance(raw_steps, list):
- return {}
- output = {}
- for item in raw_steps:
- if not isinstance(item, dict):
- continue
- current_skill_id = skill_id(item.get("skill_id")).strip()
- if current_skill_id:
- output[current_skill_id] = _short_text(str(item.get("reason") or ""))
- return output
-
-
-def _dedupe_dict_items(items: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
- output = []
- seen = set()
- for item in items:
- key = json.dumps(item, ensure_ascii=False, sort_keys=True, default=str)
- if key in seen:
- continue
- seen.add(key)
- output.append(item)
- return output
-
-
-def _rerank_plan_stages(
- steps: list[dict[str, Any]],
- edges: list[dict[str, Any]],
-) -> list[dict[str, Any]]:
- step_by_id = {str(step.get("skill_id") or ""): step for step in steps}
- incoming = {current_skill_id: set() for current_skill_id in step_by_id}
- for edge in edges:
- source_id = str(edge.get("source_id") or "")
- target_id = str(edge.get("target_id") or "")
- if source_id in step_by_id and target_id in incoming:
- incoming[target_id].add(source_id)
- remaining = list(step_by_id)
- completed = set()
- stages = []
- while remaining:
- ready = [
- current_skill_id
- for current_skill_id in remaining
- if incoming[current_skill_id] <= completed
- ]
- if not ready:
- ready = [remaining[0]]
- stages.append(
- {
- "stage": len(stages) + 1,
- "skills": [step_by_id[current_skill_id] for current_skill_id in ready],
- }
- )
- completed.update(ready)
- remaining = [item for item in remaining if item not in completed]
- return stages
-
-
-def _required_output_types_from_query(query: str) -> frozenset[str]:
- output_types = set()
- for match in _EXPLICIT_FILE_EXTENSION_RE.finditer(str(query or "")):
- normalized = str(match.group(1) or "").strip().lower().lstrip(".")
- mime_type, _encoding = mimetypes.guess_type(f"file.{normalized}")
- if mime_type in _MIME_TO_OUTPUT_TYPE:
- output_types.add(_MIME_TO_OUTPUT_TYPE[mime_type])
- elif mime_type and mime_type.startswith("image/"):
- output_types.add("image")
- return frozenset(output_types)
-
-
-def _clamp_score(value: Any) -> float:
- try:
- parsed = float(value)
- except (TypeError, ValueError):
- return 0.0
- return max(0.0, min(1.0, parsed))
-
-
-def _query_plan_title(query: str, *, language: str) -> str:
- title = " ".join(str(query or "").split())
- if not title:
- return default_beam_plan_title(language)
- if len(title) <= 80:
- return title
- return f"{title[:77].rstrip()}..."
-
-
-def _append_unique(values: tuple[str, ...], value: str) -> tuple[str, ...]:
- text = str(value or "").strip()
- if not text or text in values:
- return values
- return (*values, text)
-
-
-def _group_states(
- states: list[BeamState],
- key_fn: Callable[[BeamState], str],
-) -> list[list[BeamState]]:
- grouped: dict[str, list[BeamState]] = defaultdict(list)
- for state in states:
- grouped[str(key_fn(state))].append(state)
- return list(grouped.values())
-
-
-def _dominant_status(current: str, incoming: str) -> str:
- current_priority = _GRAPH_STATUS_PRIORITY.get(current, -1)
- incoming_priority = _GRAPH_STATUS_PRIORITY.get(incoming, -1)
- return incoming if incoming_priority >= current_priority else current
-
-
-def _copy_public_graph_edge(edge: dict[str, Any]) -> dict[str, Any]:
- return {
- "source": edge.get("source"),
- "target": edge.get("target"),
- "status": edge.get("status"),
- }
-
-
-def _skill_label(skill: dict[str, Any]) -> str:
- current_skill_id = str(skill.get("id") or "").strip()
- return str(skill.get("name") or current_skill_id).strip() or current_skill_id
-
-
-def _sorted_expansions(
- expansions: Sequence[NeighborExpansion],
-) -> list[NeighborExpansion]:
- return sorted(
- expansions,
- key=lambda item: (
- item.direction,
- item.current_skill_id,
- item.candidate_skill_id,
- item.edge_index,
- item.candidate_id,
- ),
- )
diff --git a/jiuwenswarm/symphony/orchestration/planning/fast.py b/jiuwenswarm/symphony/orchestration/planning/fast.py
deleted file mode 100644
index 2f2fd73595..0000000000
--- a/jiuwenswarm/symphony/orchestration/planning/fast.py
+++ /dev/null
@@ -1,924 +0,0 @@
-"""One-shot fast Symphony score planner."""
-
-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 (
- default_fast_no_plan_title,
- planner_language_instruction,
-)
-from jiuwenswarm.symphony.orchestration.planning.plan_builder import edge_plan_item
-from jiuwenswarm.symphony.orchestration.planning.utils import (
- eligible_can_feed_edges,
- normalize_known_skill_ids,
- skill_id,
- skill_payload,
-)
-
-FAST_PLANNER_SYSTEM_PROMPT = """You are Symphony's fast Skill planner.
-Return strict JSON only.
-
-You receive:
-- The user's query.
-- Candidate Skills with id, name, and description only.
-- Candidate can_feed relationships between those Skills.
-
-Task:
-- Select the best Skill execution plan for the query.
-- Return the single best plan using the schema below.
-- Use only provided skill IDs.
-- Prefer provided can_feed edges. Infer a missing relationship only when needed to form
- the plan.
-- Give a short reason when explicitly including an inferred edge in can_feed_edges.
-- When can_feed_edges is omitted, Symphony infers adjacent step edges during validation.
-- Do not judge compatibility from Skill I/O because it is not provided; Symphony handles
- Skill I/O after validating the plan.
-- missing_inputs does not describe a Skill I/O schema. Use it only for information the
- user must provide when that need can be determined from the query and Skill
- descriptions.
-- Do not invent Skills, inputs, or outputs.
-- Prefer the shortest path that satisfies the user's intent.
-- 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".
-
-Schema:
-{
- "title": "short plan title",
- "status": "ready | needs_input | no_plan",
- "reason": "why this plan is best",
- "steps": [
- {"skill_id": "skill-a", "reason": "why this step is used"}
- ],
- "can_feed_edges": [
- {"source_id": "skill-a", "target_id": "skill-b", "reason": "why the relationship is needed"}
- ],
- "missing_inputs": [
- {"skill_id": "skill-a", "name": "input name", "type": "unknown", "reason": "why it is needed"}
- ]
-}
-"""
-
-
-class FastOneShotPlanner:
- """Ask the LLM for one validated plan from a compact score subgraph."""
-
- def __init__(
- self,
- artifacts: ScoreArtifacts,
- *,
- llm_config: LLMConfig | None,
- llm_client: Any | None,
- min_edge_confidence: float,
- 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
- self.llm_client = llm_client
- 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),
- )
-
- async def plan(self, query: str) -> dict[str, Any]:
- client = self._client()
- subgraph = self._candidate_subgraph(query)
- prompt_payload = {
- "query": query,
- "skills": subgraph["skills"],
- "can_feed_edges": subgraph["edges"],
- }
- with llm_usage_context("orchestration", "one_shot_fast_planning"):
- raw = await client.complete_json_async(
- system_prompt=(
- f"{FAST_PLANNER_SYSTEM_PROMPT}\n"
- f"{planner_language_instruction(self.language)}"
- ),
- user_content=json.dumps(prompt_payload, ensure_ascii=False),
- error_context="Symphony one-shot fast planning",
- request_overrides={
- "extra_body": {"thinking": {"type": "disabled"}},
- },
- )
-
- base = {
- "query": query,
- "language": self.language,
- "score_dir": str(self.artifacts.score_dir),
- "planning_mode": "one_shot_fast",
- "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)
- except json.JSONDecodeError as exc:
- return self._failure(base, f"Invalid fast planner JSON: {raw[:500]}", exc)
- if not isinstance(selection, dict):
- return self._failure(base, "Fast planner returned a non-object JSON payload.")
-
- materialized = self._materialize_selection(
- selection,
- candidate_skill_ids=set(subgraph["skill_ids"]),
- candidate_edges=subgraph["edge_by_key"],
- )
- if not materialized["valid"]:
- return self._failure(base, materialized["detail"], validation=materialized)
-
- plan = materialized["plan"]
- return {
- **base,
- "plans": [plan] if plan.get("steps") else [],
- "recommended_plans": [plan] if plan.get("steps") else [],
- "ranking_mode": "one_shot_fast",
- "decision": {
- "mode": "one_shot_fast",
- "strategy": "single_llm_selection",
- "validated_count": 1 if plan.get("steps") else 0,
- "candidate_count": len(subgraph["skills"]),
- },
- "validation": materialized,
- "status": plan.get("status", "no_plan") if plan else "no_plan",
- "reason": plan.get("reason", "") if plan else "",
- }
-
- def _client(self) -> Any:
- if self.llm_client is not None:
- return self.llm_client
- if self.llm_config is None:
- raise ValueError("fast Symphony planning requires llm_config or llm_client.")
- return create_llm_client(self.llm_config)
-
- def _candidate_subgraph(self, query: str) -> dict[str, Any]:
- if self.candidate_skill_ids:
- return self._retrieval_candidate_subgraph(query)
- return self._default_candidate_subgraph(query)
-
- 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:
- self._append_skill(selected, selected_set, skill_id(edge.get("source")))
- self._append_skill(selected, selected_set, skill_id(edge.get("target")))
- if not selected:
- for skill in self.artifacts.skills:
- current_skill_id = str(skill.get("id") or "")
- self._append_skill(selected, selected_set, current_skill_id)
- return self._subgraph_payload(selected, candidate_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
- }
- seeds = list(self.candidate_skill_ids)
- adjacency: dict[str, list[str]] = defaultdict(list)
- for source_id, target_id in edge_by_key:
- adjacency[source_id].append(target_id)
- for source_id in adjacency:
- adjacency[source_id].sort()
-
- selected = list(seeds)
- selected_set = set(seeds)
- candidate_edges = []
- candidate_edge_keys = set()
- parent = {seed_id: seed_id for seed_id in seeds}
-
- def find(current_skill_id: str) -> str:
- while parent[current_skill_id] != current_skill_id:
- parent[current_skill_id] = parent[parent[current_skill_id]]
- current_skill_id = parent[current_skill_id]
- return current_skill_id
-
- def union(left: str, right: str) -> None:
- left_root = find(left)
- right_root = find(right)
- if left_root != right_root:
- parent[right_root] = left_root
-
- connections = []
- for left_index, left_seed in enumerate(seeds):
- for right_index in range(left_index + 1, len(seeds)):
- right_seed = seeds[right_index]
- paths = [
- self._best_directed_path(
- left_seed,
- right_seed,
- adjacency=adjacency,
- edge_by_key=edge_by_key,
- ),
- self._best_directed_path(
- right_seed,
- left_seed,
- adjacency=adjacency,
- edge_by_key=edge_by_key,
- ),
- ]
- ranked_paths = [
- (self._path_rank(path), path) for path in paths if path
- ]
- if ranked_paths:
- path_rank, path = min(ranked_paths, key=lambda item: item[0])
- connections.append((path_rank, left_index, right_index, path))
-
- seed_set = set(seeds)
- for _, left_index, right_index, path in sorted(connections):
- left_seed = seeds[left_index]
- right_seed = seeds[right_index]
- if find(left_seed) == find(right_seed):
- continue
- for edge in path:
- self._append_candidate_edge(
- candidate_edges,
- candidate_edge_keys,
- edge,
- )
- self._append_skill(
- selected,
- selected_set,
- skill_id(edge.get("source")),
- )
- self._append_skill(
- selected,
- selected_set,
- skill_id(edge.get("target")),
- )
- path_seeds = [skill for skill in self._path_skill_ids(path) if skill in seed_set]
- for path_seed in path_seeds[1:]:
- union(path_seeds[0], path_seed)
-
- components: dict[str, list[str]] = defaultdict(list)
- for seed_id in seeds:
- components[find(seed_id)].append(seed_id)
- neighbor_owners: dict[str, str] = {}
- for component_seeds in components.values():
- if len(component_seeds) != 1:
- continue
- seed_id = component_seeds[0]
- incoming = next(
- (edge for edge in sorted_edges if skill_id(edge.get("target")) == seed_id),
- None,
- )
- outgoing = next(
- (edge for edge in sorted_edges if skill_id(edge.get("source")) == seed_id),
- None,
- )
- for edge in (incoming, outgoing):
- if edge is None:
- continue
- source_id = skill_id(edge.get("source"))
- target_id = skill_id(edge.get("target"))
- neighbor_id = source_id if target_id == seed_id else target_id
- owner = neighbor_owners.get(neighbor_id)
- if neighbor_id in seed_set or (owner is not None and owner != seed_id):
- continue
- neighbor_owners[neighbor_id] = seed_id
- self._append_candidate_edge(candidate_edges, candidate_edge_keys, edge)
- self._append_skill(selected, selected_set, source_id)
- self._append_skill(selected, selected_set, target_id)
- return self._subgraph_payload(selected, candidate_edges)
-
- def _best_directed_path(
- self,
- source_id: str,
- target_id: str,
- *,
- adjacency: dict[str, list[str]],
- edge_by_key: dict[tuple[str, str], dict[str, Any]],
- ) -> list[dict[str, Any]]:
- queue = [(0, -1.0, 0.0, (source_id,))]
- while queue:
- hops, negative_minimum, negative_total, nodes = heapq.heappop(queue)
- current_id = nodes[-1]
- if current_id == target_id and hops:
- return [
- edge_by_key[(nodes[index], nodes[index + 1])]
- for index in range(len(nodes) - 1)
- ]
- if hops >= self.max_depth:
- continue
- minimum_confidence = -negative_minimum
- total_confidence = -negative_total
- for next_id in adjacency.get(current_id, []):
- if next_id in nodes:
- continue
- edge = edge_by_key[(current_id, next_id)]
- confidence = self._edge_rank_score(edge)
- heapq.heappush(
- queue,
- (
- hops + 1,
- -min(minimum_confidence, confidence),
- -(total_confidence + confidence),
- (*nodes, next_id),
- ),
- )
- return []
-
- 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,
- selected: Sequence[str],
- candidate_edges: list[dict[str, Any]],
- ) -> dict[str, Any]:
- skill_by_id = self.artifacts.skill_by_id
- skill_payloads = [
- skill_payload(skill_by_id[current_skill_id])
- for current_skill_id in selected
- if current_skill_id in skill_by_id
- ]
- edge_payloads = [self._edge_payload(edge) for edge in candidate_edges]
- runtime_edges = [edge for edge in candidate_edges if edge.get("runtime_evidence")]
- return {
- "skills": skill_payloads,
- "edges": edge_payloads,
- "skill_ids": [item["id"] for item in skill_payloads],
- "edge_by_key": {
- (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]]:
- known_skill_ids = set(self.artifacts.skill_by_id)
- output = []
- seen = set()
- for edge in edges:
- key = (skill_id(edge.get("source")), skill_id(edge.get("target")))
- if key in seen or key[0] not in known_skill_ids or key[1] not in known_skill_ids:
- continue
- seen.add(key)
- output.append(edge)
- return output
-
- @staticmethod
- def _append_skill(output: list[str], seen: set[str], current_skill_id: str) -> None:
- current_skill_id = str(current_skill_id or "").strip()
- if current_skill_id and current_skill_id not in seen:
- seen.add(current_skill_id)
- output.append(current_skill_id)
-
- @staticmethod
- def _append_candidate_edge(
- output: list[dict[str, Any]],
- seen: set[tuple[str, str]],
- edge: dict[str, Any],
- ) -> None:
- key = (skill_id(edge.get("source")), skill_id(edge.get("target")))
- if key not in seen:
- seen.add(key)
- output.append(edge)
-
- @staticmethod
- def _path_skill_ids(path: Sequence[dict[str, Any]]) -> list[str]:
- if not path:
- return []
- return [
- skill_id(path[0].get("source")),
- *(skill_id(edge.get("target")) for edge in path),
- ]
-
- @classmethod
- def _path_rank(cls, path: Sequence[dict[str, Any]]) -> tuple[Any, ...]:
- confidences = [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
- )
- return (
- len(path),
- -min(confidences),
- -sum(confidences),
- edge_ids,
- )
-
- def _materialize_selection(
- self,
- selection: dict[str, Any],
- *,
- candidate_skill_ids: set[str],
- candidate_edges: dict[tuple[str, str], dict[str, Any]],
- ) -> dict[str, Any]:
- status = str(selection.get("status") or "ready").strip().lower()
- if status not in {"ready", "needs_input", "no_plan"}:
- status = "ready"
- raw_steps = selection.get("steps") or selection.get("skill_order") or []
- step_ids = self._normalize_step_ids(raw_steps)
- if status == "no_plan" or not step_ids:
- return {
- "valid": True,
- "detail": "",
- "plan": {
- "title": str(
- selection.get("title")
- or default_fast_no_plan_title(self.language)
- ).strip(),
- "status": "no_plan",
- "steps": [],
- "stages": [],
- "produced_artifacts": [],
- "missing_inputs": [],
- "can_feed_edges": [],
- "reason": str(selection.get("reason") or "").strip(),
- "plan_classification": "invalid",
- "connectivity_trace": [],
- },
- }
-
- unknown_ids = [
- current_skill_id
- for current_skill_id in step_ids
- if current_skill_id not in candidate_skill_ids
- ]
- if unknown_ids:
- return {
- "valid": False,
- "detail": f"Fast planner selected unknown skill IDs: {unknown_ids}",
- }
- skill_by_id = self.artifacts.skill_by_id
-
- selected_edges_result = self._normalize_selected_edges(
- selection.get("can_feed_edges") or []
- )
- selected_edges = selected_edges_result["edges"]
- if selected_edges_result["invalid"]:
- return {
- "valid": False,
- "detail": (
- "Fast planner returned malformed can_feed edges: "
- f"{selected_edges_result['invalid']}"
- ),
- }
- if selected_edges_result["duplicates"]:
- return {
- "valid": False,
- "detail": (
- "Fast planner returned duplicate can_feed edges: "
- f"{selected_edges_result['duplicates']}"
- ),
- }
- if len(step_ids) > 1 and not selected_edges:
- selected_edges = [
- (step_ids[index], step_ids[index + 1])
- for index in range(len(step_ids) - 1)
- ]
-
- step_id_set = set(step_ids)
- unknown_edge_endpoints = [
- edge
- for edge in selected_edges
- if edge[0] not in step_id_set or edge[1] not in step_id_set
- ]
- if unknown_edge_endpoints:
- return {
- "valid": False,
- "detail": (
- "Fast planner selected edges outside plan steps: "
- f"{unknown_edge_endpoints}"
- ),
- }
- order = {current_skill_id: index for index, current_skill_id in enumerate(step_ids)}
- backward_edges = [
- (source, target)
- for source, target in selected_edges
- if order.get(source, -1) >= order.get(target, -1)
- ]
- if backward_edges:
- return {
- "valid": False,
- "detail": (
- "Fast planner selected edges that violate step order: "
- f"{backward_edges}"
- ),
- }
-
- missing_inputs = self._normalize_missing_inputs(
- selection.get("missing_inputs") or [],
- set(step_ids),
- )
- missing_by_skill: dict[str, list[dict[str, Any]]] = {}
- for item in missing_inputs:
- missing_by_skill.setdefault(str(item.get("skill_id") or ""), []).append(item)
-
- steps = []
- produced_artifacts = []
- for index, current_skill_id in enumerate(step_ids, start=1):
- skill = skill_by_id[current_skill_id]
- outputs = list(skill.get("outputs") or [])
- produced_artifacts.extend(
- {
- "name": item.get("name"),
- "type": item.get("type") or "unknown",
- "source": "skill_output",
- }
- for item in outputs
- if item.get("name")
- )
- steps.append(
- {
- "step": index,
- "skill_id": current_skill_id,
- "name": str(skill.get("name") or current_skill_id),
- "inputs": list(skill.get("inputs") or []),
- "outputs": outputs,
- "missing_inputs": missing_by_skill.get(current_skill_id, []),
- "filled_inputs": [],
- "reason": self._step_reason(
- selection.get("steps") or [],
- current_skill_id,
- ),
- }
- )
-
- edge_items = []
- has_inferred_edges = False
- for edge in selected_edges:
- if edge in candidate_edges:
- edge_items.append(edge_plan_item(candidate_edges[edge]))
- continue
- has_inferred_edges = True
- edge_items.append(
- self._inferred_edge_plan_item(
- edge,
- selected_edges_result["reasons"].get(edge, ""),
- )
- )
- if missing_inputs:
- status = "needs_input"
- return {
- "valid": True,
- "detail": "",
- "plan": {
- "title": str(selection.get("title") or "Symphony fast plan").strip(),
- "status": status,
- "steps": steps,
- "stages": [
- {"stage": index, "skills": [step]}
- for index, step in enumerate(steps, start=1)
- ],
- "produced_artifacts": produced_artifacts,
- "missing_inputs": missing_inputs,
- "can_feed_edges": edge_items,
- "reason": str(selection.get("reason") or "").strip(),
- "plan_classification": (
- "executable"
- if status == "ready"
- else "structurally_valid_but_incomplete"
- ),
- "connectivity_trace": (
- ["can_feed", "fast_llm_inferred"]
- if has_inferred_edges
- else (["can_feed"] if edge_items else [])
- ),
- "source": "one_shot_fast",
- },
- }
-
- @staticmethod
- def _failure(
- base: dict[str, Any],
- detail: str,
- exc: Exception | None = None,
- *,
- validation: dict[str, Any] | None = None,
- ) -> dict[str, Any]:
- payload = {
- **base,
- "success": False,
- "detail": detail,
- "plans": [],
- "recommended_plans": [],
- "ranking_mode": "one_shot_fast_failed",
- "validation": validation or {"valid": False, "detail": detail},
- }
- if exc is not None:
- payload["error"] = str(exc)
- return payload
-
- @staticmethod
- def _edge_payload(edge: dict[str, Any]) -> dict[str, Any]:
- 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(
- edge: tuple[str, str],
- reason: str,
- ) -> dict[str, Any]:
- return {
- "source_id": edge[0],
- "target_id": edge[1],
- "confidence": None,
- "method": "fast_llm_inferred",
- "port_mappings": [],
- "source_outputs": [],
- "target_inputs": [],
- "reasons": [reason] if reason else [],
- "reason": reason,
- }
-
- @staticmethod
- def _normalize_step_ids(raw_steps: Any) -> list[str]:
- if not isinstance(raw_steps, list):
- return []
- output = []
- for item in raw_steps:
- current_skill_id = skill_id(
- item.get("skill_id") if isinstance(item, dict) else item
- ).strip()
- if current_skill_id and current_skill_id not in output:
- output.append(current_skill_id)
- return output
-
- @staticmethod
- def _normalize_selected_edges(raw_edges: Any) -> dict[str, Any]:
- if not isinstance(raw_edges, list):
- return {
- "edges": [],
- "invalid": [raw_edges],
- "duplicates": [],
- "reasons": {},
- }
- edges = []
- invalid = []
- duplicates = []
- reasons = {}
- for item in raw_edges:
- if not isinstance(item, dict):
- invalid.append(item)
- continue
- 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:
- invalid.append(item)
- continue
- if source == target:
- continue
- edge = (source, target)
- if edge in edges:
- duplicates.append(edge)
- continue
- edges.append(edge)
- reasons[edge] = str(item.get("reason") or "").strip()
- return {
- "edges": edges,
- "invalid": invalid,
- "duplicates": duplicates,
- "reasons": reasons,
- }
-
- @staticmethod
- def _normalize_missing_inputs(
- raw_items: Any,
- step_ids: set[str],
- ) -> list[dict[str, Any]]:
- if not isinstance(raw_items, list):
- return []
- output = []
- for item in raw_items:
- if not isinstance(item, dict):
- continue
- current_skill_id = skill_id(item.get("skill_id")).strip()
- if current_skill_id and current_skill_id not in step_ids:
- continue
- normalized = {
- "skill_id": current_skill_id,
- "name": str(item.get("name") or "unknown"),
- "type": str(item.get("type") or "unknown"),
- }
- reason = str(item.get("reason") or "").strip()
- if reason:
- normalized["reason"] = reason
- output.append(normalized)
- return output
-
- @staticmethod
- def _step_reason(raw_steps: Any, target_skill_id: str) -> str:
- if not isinstance(raw_steps, list):
- return ""
- for item in raw_steps:
- if (
- isinstance(item, dict)
- and skill_id(item.get("skill_id")) == target_skill_id
- ):
- return str(item.get("reason") or "").strip()
- return ""
diff --git a/jiuwenswarm/symphony/orchestration/planning/input_matching.py b/jiuwenswarm/symphony/orchestration/planning/input_matching.py
deleted file mode 100644
index ea7b062c38..0000000000
--- a/jiuwenswarm/symphony/orchestration/planning/input_matching.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""Input and output matching helpers for Beam plans."""
-
-from __future__ import annotations
-
-from typing import Any, Iterable
-
-
-def missing_inputs(
- skill: dict[str, Any],
- available: Iterable[tuple[str, str]],
-) -> list[dict[str, Any]]:
- available_set = set(available)
- missing = []
- for item in skill.get("inputs", []):
- if not item.get("required", True):
- continue
- expected = (str(item.get("name")), str(item.get("type") or "unknown"))
- if not artifact_matches(expected, available_set):
- missing.append({"name": expected[0], "type": expected[1]})
- return missing
-
-
-def artifact_matches(
- expected: tuple[str, str],
- available: set[tuple[str, str]],
-) -> bool:
- name, type_ = expected
- if expected in available:
- return True
- return any(
- candidate_name == name and (candidate_type == "unknown" or type_ == "unknown")
- for candidate_name, candidate_type in available
- )
-
-
-def output_keys(skill: dict[str, Any]) -> frozenset[tuple[str, str]]:
- return frozenset(
- (str(item.get("name")), str(item.get("type") or "unknown"))
- for item in skill.get("outputs", [])
- if item.get("name")
- )
diff --git a/jiuwenswarm/symphony/orchestration/planning/models.py b/jiuwenswarm/symphony/orchestration/planning/models.py
deleted file mode 100644
index 83db03a143..0000000000
--- a/jiuwenswarm/symphony/orchestration/planning/models.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""Data models for orchestration planning."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-from typing import Any
-
-
-@dataclass(frozen=True)
-class ArtifactRef:
- """A normalized runtime artifact available to the orchestrator."""
-
- name: str
- type: str = "unknown"
- source: str = "user_query"
-
- @property
- def key(self) -> tuple[str, str]:
- return (self.name, self.type)
-
- def to_dict(self) -> dict[str, Any]:
- return {"name": self.name, "type": self.type, "source": self.source}
-
-
-@dataclass(frozen=True)
-class PlanStep:
- """One Skill call in a candidate orchestration plan."""
-
- skill_id: str
- name: str
- inputs: list[dict[str, Any]]
- outputs: list[dict[str, Any]]
- missing_inputs: list[dict[str, Any]] = field(default_factory=list)
- filled_inputs: list[dict[str, Any]] = field(default_factory=list)
-
- def to_dict(self) -> dict[str, Any]:
- return {
- "skill_id": self.skill_id,
- "name": self.name,
- "inputs": self.inputs,
- "outputs": self.outputs,
- "missing_inputs": self.missing_inputs,
- "filled_inputs": self.filled_inputs,
- }
-
-
-@dataclass(frozen=True)
-class OrchestrationPlan:
- """A candidate Skill orchestration plan."""
-
- steps: list[PlanStep]
- produced_artifacts: list[ArtifactRef]
- missing_inputs: list[dict[str, Any]]
- can_feed_edges: list[dict[str, Any]]
- goal_score: float
- edge_confidence: float
- consumed_user_artifacts: int
- status: str
- reasons: list[str]
-
- def to_dict(self) -> dict[str, Any]:
- from jiuwenswarm.symphony.orchestration.planning.plan_builder import (
- plan_stages,
- )
-
- return {
- "status": self.status,
- "goal_score": round(self.goal_score, 3),
- "edge_confidence": round(self.edge_confidence, 3),
- "consumed_user_artifacts": self.consumed_user_artifacts,
- "stages": plan_stages(self.steps, self.can_feed_edges),
- "steps": [
- {"step": index + 1, **step.to_dict()}
- for index, step in enumerate(self.steps)
- ],
- "produced_artifacts": [
- artifact.to_dict() for artifact in self.produced_artifacts
- ],
- "missing_inputs": self.missing_inputs,
- "can_feed_edges": self.can_feed_edges,
- "reasons": self.reasons,
- }
-
-
-@dataclass(frozen=True)
-class SearchState:
- """Internal forward-search state."""
-
- skill_ids: tuple[str, ...]
- edges: tuple[int, ...]
- score_reasons: tuple[str, ...] = ()
diff --git a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py b/jiuwenswarm/symphony/orchestration/planning/plan_builder.py
deleted file mode 100644
index 8ca57d3f1d..0000000000
--- a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py
+++ /dev/null
@@ -1,153 +0,0 @@
-"""Build concrete orchestration plans from Beam search state."""
-
-from __future__ import annotations
-
-from collections import defaultdict
-from typing import Any
-
-from jiuwenswarm.symphony.orchestration.planning.input_matching import (
- missing_inputs,
- output_keys,
-)
-from jiuwenswarm.symphony.orchestration.planning.models import (
- ArtifactRef,
- OrchestrationPlan,
- PlanStep,
- SearchState,
-)
-from jiuwenswarm.symphony.orchestration.planning.utils import skill_id
-
-
-def state_to_plan(
- *,
- state: SearchState,
- seed_skill_ids: tuple[str, ...],
- skill_by_id: dict[str, dict[str, Any]],
- can_feed_edges: list[dict[str, Any]],
-) -> OrchestrationPlan:
- available: set[tuple[str, str]] = set()
- steps: list[PlanStep] = []
- all_missing: list[dict[str, Any]] = []
- produced: set[tuple[str, str]] = set()
-
- for current_skill_id in state.skill_ids:
- skill = skill_by_id[current_skill_id]
- missing = missing_inputs(skill, available)
- all_missing.extend({**item, "skill_id": current_skill_id} for item in missing)
- outputs = output_keys(skill)
- produced.update(outputs)
- available.update(outputs)
- steps.append(
- PlanStep(
- skill_id=current_skill_id,
- name=skill.get("name", current_skill_id),
- inputs=[
- {"name": item.get("name"), "type": item.get("type")}
- for item in skill.get("inputs", [])
- ],
- outputs=[
- {"name": item.get("name"), "type": item.get("type")}
- for item in skill.get("outputs", [])
- ],
- missing_inputs=missing,
- )
- )
-
- edges = [can_feed_edges[index] for index in state.edges]
- edge_confidence = (
- sum(float(edge.get("confidence") or 0.0) for edge in edges) / len(edges)
- if edges
- else 1.0
- )
- status = "ready" if not all_missing else "needs_input"
- return OrchestrationPlan(
- steps=steps,
- produced_artifacts=[
- ArtifactRef(name=name, type=type_, source="skill_output")
- for name, type_ in sorted(produced)
- ],
- missing_inputs=all_missing,
- can_feed_edges=[edge_plan_item(edge) for edge in edges],
- goal_score=sum(10.0 for item in state.skill_ids if item in seed_skill_ids),
- edge_confidence=edge_confidence,
- consumed_user_artifacts=0,
- status=status,
- reasons=list(state.score_reasons[:8]),
- )
-
-
-def build_outgoing_edges(edges: list[dict[str, Any]]) -> dict[str, list[int]]:
- outgoing: dict[str, list[int]] = defaultdict(list)
- for index, edge in enumerate(edges):
- outgoing[skill_id(edge.get("source"))].append(index)
- return outgoing
-
-
-def build_incoming_edges(edges: list[dict[str, Any]]) -> dict[str, list[int]]:
- incoming: dict[str, list[int]] = defaultdict(list)
- for index, edge in enumerate(edges):
- incoming[skill_id(edge.get("target"))].append(index)
- return incoming
-
-
-def plan_stages(
- steps: list[PlanStep],
- edges: list[dict[str, Any]],
-) -> list[dict[str, Any]]:
- step_by_id = {step.skill_id: step for step in steps}
- remaining = set(step_by_id)
- incoming: dict[str, set[str]] = {
- current_skill_id: set() for current_skill_id in remaining
- }
- for edge in edges:
- source_id = str(edge.get("source_id") or "")
- target_id = str(edge.get("target_id") or "")
- if source_id in remaining and target_id in remaining:
- incoming[target_id].add(source_id)
-
- stages = []
- completed: set[str] = set()
- while remaining:
- ready = sorted(
- current_skill_id
- for current_skill_id in remaining
- if incoming[current_skill_id] <= completed
- )
- if not ready:
- ready = sorted(remaining)
- stages.append(
- {
- "stage": len(stages) + 1,
- "skills": [
- step_by_id[current_skill_id].to_dict() for current_skill_id in ready
- ],
- }
- )
- completed.update(ready)
- remaining.difference_update(ready)
- return stages
-
-
-def edge_plan_item(edge: dict[str, Any]) -> dict[str, Any]:
- evidence = edge.get("evidence") or {}
- supporting_fields = evidence.get("supporting_fields") or {}
- item = {
- "source_id": skill_id(edge.get("source")),
- "target_id": skill_id(edge.get("target")),
- "confidence": edge.get("confidence"),
- "method": edge.get("method"),
- "port_mappings": supporting_fields.get("port_mappings", [])[:5],
- "source_outputs": supporting_fields.get("source_outputs", [])[:3],
- "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/planning/utils.py b/jiuwenswarm/symphony/orchestration/planning/utils.py
deleted file mode 100644
index 166893d578..0000000000
--- a/jiuwenswarm/symphony/orchestration/planning/utils.py
+++ /dev/null
@@ -1,72 +0,0 @@
-# -*- coding: utf-8 -*-
-"""Utility helpers for orchestration planning."""
-
-from __future__ import annotations
-
-from typing import Any, Sequence
-
-
-def skill_id(node_id: Any) -> str:
- text = str(node_id or "")
- return text.removeprefix("skill:")
-
-
-def clamp(value: float) -> float:
- return max(0.0, min(1.0, float(value)))
-
-
-def skill_payload(skill: dict[str, Any]) -> dict[str, Any]:
- current_skill_id = str(skill.get("id") or "")
- return {
- "id": current_skill_id,
- "name": str(skill.get("name") or current_skill_id),
- "description": str(skill.get("description") or "")[:800],
- }
-
-
-def eligible_can_feed_edges(
- edges: Sequence[dict[str, Any]],
- *,
- known_skill_ids: set[str],
- min_confidence: float,
-) -> list[dict[str, Any]]:
- eligible = []
- for edge in edges:
- source_id = skill_id(edge.get("source"))
- target_id = skill_id(edge.get("target"))
- if edge.get("type") != "can_feed":
- continue
- if float(edge.get("confidence") or 0.0) < min_confidence:
- continue
- if source_id not in known_skill_ids or target_id not in known_skill_ids:
- continue
- eligible.append(edge)
- return sorted(
- eligible,
- key=lambda item: (
- -float(item.get("confidence") or 0.0),
- skill_id(item.get("source")),
- skill_id(item.get("target")),
- ),
- )
-
-
-def normalize_known_skill_ids(
- values: Sequence[str] | None,
- *,
- known_skill_ids: set[str],
-) -> tuple[str, ...] | None:
- if values is None:
- return None
- output = []
- seen = set()
- for value in values:
- current_skill_id = str(value or "").strip()
- if (
- current_skill_id
- and current_skill_id not in seen
- and current_skill_id in known_skill_ids
- ):
- seen.add(current_skill_id)
- output.append(current_skill_id)
- return tuple(output) if output else None
diff --git a/jiuwenswarm/symphony/orchestration/service.py b/jiuwenswarm/symphony/orchestration/service.py
deleted file mode 100644
index 0e2fcbc2e9..0000000000
--- a/jiuwenswarm/symphony/orchestration/service.py
+++ /dev/null
@@ -1,162 +0,0 @@
-"""Online orchestration planning service APIs."""
-
-from __future__ import annotations
-
-from pathlib import Path
-from typing import Any, Sequence
-from uuid import uuid4
-
-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,
- load_score_artifacts,
-)
-from jiuwenswarm.symphony.orchestration.execution_graph import build_execution_graph
-from jiuwenswarm.symphony.orchestration.planning.beam import BidirectionalBeamPlanner
-from jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlanner
-from jiuwenswarm.symphony.orchestration.planning.utils import clamp
-
-
-async def plan_from_score(
- score_dir: str | Path,
- query: str,
- llm_config: LLMConfig | None = None,
- *,
- top_k: int = 3,
- max_depth: int = 4,
- 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,
- language: str = "cn",
-) -> dict[str, Any]:
- """Run online planning from an existing Symphony score."""
-
- if orchestration_config is not None:
- top_k = orchestration_config.top_k
- max_depth = orchestration_config.max_depth
- min_edge_confidence = orchestration_config.min_edge_confidence
- mode = orchestration_config.mode if orchestration_config is not None else "fast"
-
- artifacts = filter_disabled_score_artifacts(
- load_score_artifacts(score_dir),
- disabled_skill_names,
- )
- 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,
- )
- if mode == "beam":
- result = await BidirectionalBeamPlanner(
- artifacts,
- llm_config=llm_config,
- llm_client=llm_client,
- min_edge_confidence=clamp(min_edge_confidence),
- top_k=max(1, int(top_k)),
- max_depth=max(1, int(max_depth)),
- candidate_skill_ids=selected_candidate_skill_ids,
- progress_callback=progress_callback,
- language=language,
- ).plan(query)
- else:
- result = await FastOneShotPlanner(
- artifacts,
- llm_config=llm_config,
- llm_client=llm_client,
- min_edge_confidence=clamp(min_edge_confidence),
- 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
-
-
-def _input_candidate_summary(
- values: Sequence[str] | None,
- *,
- skills: Sequence[dict[str, Any]],
-) -> tuple[tuple[str, ...] | None, dict[str, Any]]:
- normalized = _normalize_candidate_skill_ids(values)
- selected = _resolve_candidate_skill_ids(normalized, skills)
- fallback_reason = ""
- if values is None:
- fallback_reason = "candidate_skill_ids not provided"
- elif not normalized:
- fallback_reason = "candidate_skill_ids is empty"
- elif not selected:
- fallback_reason = "candidate_skill_ids did not match current score"
-
- return selected or None, {
- "source": "input",
- "used": bool(selected),
- "candidate_skill_ids": list(selected),
- "candidate_count": len(selected),
- "fallback_reason": fallback_reason,
- }
-
-
-def _resolve_candidate_skill_ids(
- values: Sequence[str],
- skills: Sequence[dict[str, Any]],
-) -> tuple[str, ...]:
- known_skill_ids = {
- str(skill.get("id") or "").strip()
- for skill in skills
- if str(skill.get("id") or "").strip()
- }
- skill_ids_by_name: dict[str, set[str]] = {}
- for skill in skills:
- current_skill_id = str(skill.get("id") or "").strip()
- name = str(skill.get("name") or "").strip()
- if current_skill_id and name:
- skill_ids_by_name.setdefault(name, set()).add(current_skill_id)
-
- selected: list[str] = []
- seen: set[str] = set()
- for value in values:
- current_skill_id = value if value in known_skill_ids else ""
- if not current_skill_id:
- matching_ids = skill_ids_by_name.get(value, set())
- if len(matching_ids) == 1:
- current_skill_id = next(iter(matching_ids))
- if not current_skill_id or current_skill_id in seen:
- continue
- seen.add(current_skill_id)
- selected.append(current_skill_id)
- return tuple(selected)
-
-
-def _normalize_candidate_skill_ids(values: Sequence[str] | None) -> tuple[str, ...]:
- if values is None:
- return ()
- output: list[str] = []
- seen: set[str] = set()
- for value in values:
- current_skill_id = str(value or "").strip()
- if not current_skill_id or current_skill_id in seen:
- continue
- seen.add(current_skill_id)
- output.append(current_skill_id)
- return tuple(output)
diff --git a/jiuwenswarm/symphony/orchestration/utils/__init__.py b/jiuwenswarm/symphony/orchestration/utils/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/jiuwenswarm/symphony/retrieval/service/retriever.py b/jiuwenswarm/symphony/retrieval/service/retriever.py
index 1282326827..75b9adf5c9 100644
--- a/jiuwenswarm/symphony/retrieval/service/retriever.py
+++ b/jiuwenswarm/symphony/retrieval/service/retriever.py
@@ -297,7 +297,7 @@ class Retriever:
return self._progressive_unavailable_reason(runtime_config) is None
@staticmethod
- def _build_scored_candidate_records(*, hits: Sequence[object], source: str) -> List[Dict[str, object]]:
+ def _build_graphd_candidate_records(*, hits: Sequence[object], source: str) -> List[Dict[str, object]]:
return [
{
"rank": int(getattr(hit, "rank", 0) or 0),
diff --git a/jiuwenswarm/symphony/score_storage.py b/jiuwenswarm/symphony/score_storage.py
deleted file mode 100644
index 90fe68c094..0000000000
--- a/jiuwenswarm/symphony/score_storage.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""Versioned storage helpers for Symphony Score artifacts."""
-
-from __future__ import annotations
-
-import json
-import os
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any
-
-CURRENT_POINTER_FILENAME = "current.json"
-VERSIONS_DIRNAME = "versions"
-BUILD_RUNS_DIRNAME = ".build_runs"
-
-
-@dataclass(frozen=True)
-class ScorePointer:
- """Pointer to the currently published Score version."""
-
- version: str
- path: str
-
- def to_dict(self) -> dict[str, Any]:
- return {
- "schema_version": "Symphony-score-pointer-v1",
- "version": self.version,
- "path": self.path,
- }
-
- @classmethod
- def from_dict(cls, payload: dict[str, Any]) -> "ScorePointer":
- version = str(payload.get("version") or "").strip()
- path = str(payload.get("path") or "").strip()
- if not version or not path:
- raise ValueError("Invalid Symphony score pointer.")
- return cls(version=version, path=path)
-
-
-def resolve_score_artifact_dir(score_dir: str | Path) -> Path:
- """Return the directory containing the currently readable artifacts.
-
- New builds publish versioned artifacts behind ``current.json``. Older
- layouts stored artifacts directly in ``score_dir``; this helper keeps that
- legacy layout readable.
- """
-
- root = Path(score_dir).resolve()
- pointer_path = root / CURRENT_POINTER_FILENAME
- if not pointer_path.is_file():
- return root
-
- pointer = ScorePointer.from_dict(
- json.loads(pointer_path.read_text(encoding="utf-8"))
- )
- candidate = (root / pointer.path).resolve()
- if not _is_relative_to(candidate, root):
- raise ValueError(f"Symphony score pointer escapes score_dir: {candidate}")
- return candidate
-
-
-def score_manifest_path(score_dir: str | Path) -> Path:
- return resolve_score_artifact_dir(score_dir) / "score_manifest.json"
-
-
-def score_exists(score_dir: str | Path) -> bool:
- return score_manifest_path(score_dir).is_file()
-
-
-def build_runs_dir(score_dir: str | Path) -> Path:
- return Path(score_dir).resolve() / BUILD_RUNS_DIRNAME
-
-
-def build_run_dir(score_dir: str | Path, run_id: str) -> Path:
- return build_runs_dir(score_dir) / run_id
-
-
-def build_artifact_dir(score_dir: str | Path, run_id: str) -> Path:
- return build_run_dir(score_dir, run_id) / "artifacts"
-
-
-def publish_artifact_dir(
- score_dir: str | Path,
- artifact_dir: str | Path,
- *,
- version: str,
-) -> Path:
- """Publish a fully built artifact directory as the current Score version."""
-
- root = Path(score_dir).resolve()
- source = Path(artifact_dir).resolve()
- versions_dir = root / VERSIONS_DIRNAME
- versions_dir.mkdir(parents=True, exist_ok=True)
- target = versions_dir / version
- if target.exists():
- raise FileExistsError(f"Symphony score version already exists: {target}")
- os.replace(source, target)
-
- pointer = ScorePointer(
- version=version,
- path=f"{VERSIONS_DIRNAME}/{version}",
- )
- tmp_pointer = root / f".{CURRENT_POINTER_FILENAME}.{version}.tmp"
- tmp_pointer.write_text(
- json.dumps(pointer.to_dict(), ensure_ascii=False, indent=2),
- encoding="utf-8",
- )
- os.replace(tmp_pointer, root / CURRENT_POINTER_FILENAME)
- return target
-
-
-def latest_incomplete_build(score_dir: str | Path) -> Path | None:
- runs_root = build_runs_dir(score_dir)
- if not runs_root.is_dir():
- return None
- candidates = []
- for child in runs_root.iterdir():
- checkpoint = child / "checkpoint.json"
- if not checkpoint.is_file():
- continue
- try:
- payload = json.loads(checkpoint.read_text(encoding="utf-8"))
- except json.JSONDecodeError:
- continue
- candidates.append(
- (
- str(payload.get("updated_at") or ""),
- str(payload.get("status") or ""),
- child,
- )
- )
- if not candidates:
- return None
- _updated_at, status, path = sorted(candidates, key=lambda item: item[0])[-1]
- if status in {"running", "failed"}:
- return path
- return None
-
-
-def _is_relative_to(path: Path, root: Path) -> bool:
- try:
- path.relative_to(root)
- except ValueError:
- return False
- return True
diff --git a/jiuwenswarm/symphony/service.py b/jiuwenswarm/symphony/service.py
new file mode 100644
index 0000000000..751692d82e
--- /dev/null
+++ b/jiuwenswarm/symphony/service.py
@@ -0,0 +1,1101 @@
+"""Process-local JiuwenSwarm integration for public Symphony orchestration."""
+
+from __future__ import annotations
+
+import asyncio
+from concurrent.futures import Future as ConcurrentFuture
+import inspect
+import json
+import logging
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+from threading import Lock
+from typing import Any, Callable
+
+from openjiuwen.symphony import SymphonyRuntime
+
+from jiuwenswarm.common.config import get_config
+from jiuwenswarm.server.runtime.skill import load_execution_disabled_skills
+from jiuwenswarm.symphony.adapter import (
+ candidate_ids_from_skill_ids,
+ graph_config_from_swarm,
+ llm_config_signature,
+ model_from_config,
+ model_response_observer_from_config,
+ orchestration_config_from_swarm,
+ swarm_plan_from_public,
+)
+from jiuwenswarm.symphony.llm import LLMConfig
+from jiuwenswarm.symphony.config import load_symphony_config
+from jiuwenswarm.symphony.build import build_graph as service_build_graph
+from jiuwenswarm.symphony.build import graph_status
+from jiuwenswarm.symphony.evolution.service import load_dynamic_overlay
+from jiuwenswarm.symphony.graph_storage import resolve_graph_artifact_dir
+
+logger = logging.getLogger(__name__)
+
+
+ProgressCallback = Callable[[dict[str, Any]], Any]
+
+
+class SwarmSymphonyService:
+ """Own the process-local Symphony runtime used by all Agent tools."""
+
+ def __init__(self) -> None:
+ self._build_guard = asyncio.Lock()
+ self._active_build_task: asyncio.Task | None = None
+ self._runtime: SymphonyRuntime | None = None
+ self._runtime_key: tuple[Any, ...] | None = None
+
+ async def graph_status(
+ self,
+ ) -> dict[str, Any]:
+ config = load_symphony_config()
+ skills_root = config.paths.skills_root
+ graph_dir = config.paths.graph_dir
+ await self._repair_interrupted_build_state(graph_dir)
+ try:
+ llm_config = LLMConfig.from_default_model()
+ except (RuntimeError, ValueError):
+ llm_config = None
+
+ def status() -> dict[str, Any]:
+ payload = graph_status(
+ skills_root,
+ graph_dir,
+ llm_config=llm_config,
+ symphony_config=config,
+ ).to_dict()
+ payload.update(_build_log_payload(graph_dir))
+ return payload
+
+ return await asyncio.to_thread(status)
+
+ async def refresh_graph(
+ self,
+ *,
+ force: bool = False,
+ progress: ProgressCallback | None = None,
+ ) -> dict[str, Any]:
+ return await self._build_graph(force=force, progress=progress)
+
+ async def start_refresh_graph(
+ self,
+ *,
+ force: bool = False,
+ ) -> dict[str, Any]:
+ """Start or reuse a process-local background graph build."""
+
+ config = load_symphony_config()
+ graph_dir = config.paths.graph_dir
+ async with self._build_guard:
+ task = self._active_build_task
+ if task is not None and not task.done():
+ payload = {
+ "success": True,
+ "background": True,
+ "build_status": "running",
+ "graph_dir": str(graph_dir),
+ "detail": "技能总谱已在后台构建中。",
+ }
+ payload.update(_build_log_payload(graph_dir))
+ build_progress = payload.get("build_progress")
+ if (
+ not isinstance(build_progress, dict)
+ or build_progress.get("status") != "running"
+ ):
+ payload.update({"build_progress": _starting_build_progress()})
+ return payload
+ if task is not None:
+ self._active_build_task = None
+ task = asyncio.create_task(
+ self._build_graph(force=force, progress=None),
+ name="symphony-graph-build",
+ )
+ self._active_build_task = task
+ task.add_done_callback(self._consume_background_build_result)
+
+ return {
+ "success": True,
+ "background": True,
+ "build_status": "running",
+ "graph_dir": str(graph_dir),
+ "detail": "技能总谱后台构建已启动。",
+ "build_progress": _starting_build_progress(),
+ "build_log": [],
+ }
+
+ async def cancel_build(
+ self,
+ ) -> dict[str, Any]:
+ config = load_symphony_config()
+ graph_dir = config.paths.graph_dir
+ build_logger = _BuildProcessLogger(graph_dir / "build_log.jsonl")
+ async with self._build_guard:
+ task = self._active_build_task
+ if task is None or task.done():
+ if task is not None:
+ self._active_build_task = None
+ _repair_interrupted_build_log(graph_dir)
+ payload = {
+ "success": False,
+ "graph_dir": str(graph_dir),
+ "cancelled": False,
+ "build_status": "idle",
+ "detail": "当前没有正在运行的技能总谱构建。",
+ }
+ payload.update(_build_log_payload(graph_dir))
+ payload["build_status"] = "idle"
+ return payload
+ build_logger.record("update.cancel_requested")
+ task.cancel("skills.graph.cancel")
+ build_logger.record("update.cancelled")
+ # 构建可能正处于不可即时中断的区段(to_thread/LLM 调用),
+ # 最多等 5 秒即返回,收尾状态由 skills.graph.status 轮询。
+ await asyncio.wait({task}, timeout=5)
+ payload = {
+ "success": True,
+ "graph_dir": str(graph_dir),
+ "cancelled": True,
+ "build_status": "cancelled",
+ "detail": "已取消技能总谱构建,已完成的缓存和 checkpoint 会保留。",
+ }
+ payload.update(_build_log_payload(graph_dir))
+ return payload
+
+ async def graph(self) -> dict[str, Any]:
+ """Return the public graph artifact in the shape consumed by the Web UI."""
+
+ config = load_symphony_config()
+ graph_dir = config.paths.graph_dir
+ await self._repair_interrupted_build_state(graph_dir)
+ try:
+ artifact = self._read_graph_artifact(graph_dir)
+ except (FileNotFoundError, ValueError) as exc:
+ payload = {
+ "success": False,
+ "graph_dir": str(graph_dir),
+ "detail": "技能总谱不存在或不完整,请先构建总谱。",
+ "error": str(exc),
+ }
+ else:
+ payload = _web_graph_payload(
+ artifact,
+ graph_dir=graph_dir,
+ min_edge_confidence=config.orchestration.min_edge_confidence,
+ disabled_skill_names=load_execution_disabled_skills(),
+ dynamic_overlay=(
+ load_dynamic_overlay(graph_dir)
+ if config.evolution.enabled
+ else None
+ ),
+ )
+ payload.update(_build_log_payload(graph_dir))
+ return payload
+
+ async def plan(
+ self,
+ query: str,
+ mode: str | None = None,
+ candidate_skill_ids: list[str] | None = None,
+ *,
+ progress: ProgressCallback | None = None,
+ ) -> dict[str, Any]:
+ query = str(query or "").strip()
+ if not query:
+ return {"success": False, "detail": "query is required"}
+ candidate_ids = candidate_ids_from_skill_ids(candidate_skill_ids)
+ language = _resolve_orchestration_language(
+ get_config().get("preferred_language", "zh")
+ )
+ config = load_symphony_config()
+ graph_dir = config.paths.graph_dir
+ requested_mode = str(mode or config.orchestration.mode).strip()
+ try:
+ orchestration_config_from_swarm(config, mode=requested_mode)
+ except ValueError as exc:
+ return {
+ "success": False,
+ "graph_dir": str(graph_dir),
+ "query": query,
+ "mode": config.orchestration.mode,
+ "detail": str(exc),
+ }
+
+ status = await self.graph_status()
+ if not status.get("success"):
+ return {
+ "success": False,
+ "detail": "规划前技能总谱状态检查失败",
+ "graph_status": status,
+ }
+ if _graph_needs_build(status):
+ graph_build = await self.refresh_graph(progress=progress)
+ graph_build["rebuilt"] = True
+ if not graph_build.get("success"):
+ return {
+ "success": False,
+ "detail": "规划前技能总谱构建失败",
+ "graph_status": status,
+ "graph_build": graph_build,
+ }
+ else:
+ graph_build = {
+ "success": True,
+ "rebuilt": False,
+ "reason": "not_required",
+ }
+ try:
+ public_payload = await self._runtime_for(config).orchestration.plan(
+ query,
+ candidate_ids=candidate_ids,
+ language=language,
+ progress=progress,
+ disabled_capability_ids=load_execution_disabled_skills(),
+ dynamic_overlay=(
+ load_dynamic_overlay(graph_dir)
+ if config.evolution.enabled
+ else None
+ ),
+ mode=requested_mode,
+ )
+ payload = swarm_plan_from_public(public_payload.to_dict())
+ except Exception as exc: # noqa: BLE001
+ logger.exception("Symphony planning failed")
+ payload = {"success": False, "detail": str(exc)}
+ if payload.get("success") is False:
+ return {
+ "success": False,
+ "graph_dir": str(graph_dir),
+ "query": query,
+ "mode": requested_mode,
+ "language": language,
+ "graph_status": status,
+ "graph_build": graph_build,
+ **payload,
+ }
+ presentation = _build_presentation(payload, language=language)
+ return {
+ "success": True,
+ "graph_dir": str(graph_dir),
+ "query": query,
+ "mode": requested_mode,
+ "language": language,
+ "content": presentation["markdown"],
+ "direct_display": True,
+ "graph_status": status,
+ "graph_build": graph_build,
+ "result": payload,
+ }
+
+ async def _build_graph(
+ self,
+ *,
+ force: bool,
+ progress: ProgressCallback | None,
+ ) -> dict[str, Any]:
+ config = load_symphony_config()
+ skills_root = config.paths.skills_root
+ graph_dir = config.paths.graph_dir
+ current_task = asyncio.current_task()
+ async with self._build_guard:
+ active_task = self._active_build_task
+ if (
+ active_task is not None
+ and active_task is not current_task
+ and not active_task.done()
+ ):
+ payload = {
+ "success": False,
+ "graph_dir": str(graph_dir),
+ "detail": "已有技能总谱构建正在运行,请等待完成或先取消当前构建。",
+ }
+ payload.update(_build_log_payload(graph_dir))
+ return payload
+ self._active_build_task = current_task
+ progress_dispatcher = _OrderedProgressDispatcher(progress)
+ progress_dispatcher.start()
+ build_logger = _BuildProcessLogger(
+ graph_dir / "build_log.jsonl",
+ progress=progress_dispatcher,
+ )
+ abort_progress = False
+ try:
+ build_logger.reset()
+ build_logger.record(
+ "update.start",
+ skills_root=str(skills_root),
+ out_dir=str(graph_dir),
+ force=force,
+ )
+ try:
+ result = (
+ await service_build_graph(
+ skills_root,
+ graph_dir,
+ LLMConfig.from_default_model(),
+ force=force,
+ symphony_config=config,
+ build_log=build_logger.record,
+ )
+ ).to_dict()
+ except asyncio.CancelledError:
+ abort_progress = True
+ if (
+ _build_progress(_read_build_log(graph_dir)).get("status")
+ != "cancelled"
+ ):
+ build_logger.record("update.cancelled")
+ payload = {
+ "success": False,
+ "graph_dir": str(graph_dir),
+ "cancelled": True,
+ "build_status": "cancelled",
+ "detail": "技能总谱构建已取消,可再次执行增量构建继续。",
+ }
+ payload.update(_build_log_payload(graph_dir))
+ return payload
+ except Exception as exc: # noqa: BLE001
+ build_logger.record("update.failed", error=str(exc))
+ payload = {
+ "success": False,
+ "graph_dir": str(graph_dir),
+ "detail": f"Symphony 总谱构建失败: {exc}",
+ }
+ payload.update(_build_log_payload(graph_dir))
+ return payload
+ build_logger.record("update.done", **result)
+ result["success"] = True
+ result.update(_build_log_payload(graph_dir))
+ return result
+ finally:
+ try:
+ if abort_progress:
+ await progress_dispatcher.abort()
+ else:
+ await progress_dispatcher.close()
+ finally:
+ await self._clear_active_build_task(current_task)
+
+ def _runtime_for(self, config) -> SymphonyRuntime:
+ llm_config = LLMConfig.from_default_model()
+ llm_signature = llm_config_signature(llm_config)
+ key = (
+ str(config.paths.graph_dir),
+ config.orchestration.mode,
+ config.orchestration.top_k,
+ config.orchestration.max_depth,
+ config.orchestration.min_edge_confidence,
+ config.evolution.enabled,
+ llm_signature,
+ )
+ if self._runtime is None or self._runtime_key != key:
+ self._runtime = SymphonyRuntime(
+ graph_artifact_root=config.paths.graph_dir,
+ capability_provider=(),
+ model=model_from_config(llm_config),
+ model_response_observer=model_response_observer_from_config(llm_config),
+ orchestration_config=orchestration_config_from_swarm(config),
+ graph_config=graph_config_from_swarm(config),
+ )
+ self._runtime_key = key
+ return self._runtime
+
+ @staticmethod
+ def _read_graph_artifact(graph_dir: Path) -> dict[str, Any]:
+ """Read an existing graph without requiring an LLM client configuration."""
+
+ return (
+ SymphonyRuntime(
+ graph_artifact_root=graph_dir,
+ capability_provider=(),
+ model=None,
+ )
+ .orchestration.read()
+ .to_dict()
+ )
+
+ async def _clear_active_build_task(self, task: asyncio.Task | None) -> None:
+ async with self._build_guard:
+ if self._active_build_task is task:
+ self._active_build_task = None
+
+ @staticmethod
+ def _consume_background_build_result(task: asyncio.Task) -> None:
+ """Consume unexpected task failures so background builds never leak them."""
+
+ try:
+ task.result()
+ except asyncio.CancelledError:
+ return
+ except Exception: # noqa: BLE001
+ logger.exception("Background Skill Graph build failed")
+
+ async def _repair_interrupted_build_state(self, graph_dir: Path) -> bool:
+ async with self._build_guard:
+ task = self._active_build_task
+ if task is not None and not task.done():
+ return False
+ if task is not None:
+ self._active_build_task = None
+ return await asyncio.to_thread(_repair_interrupted_build_log, graph_dir)
+
+
+_SHARED_SERVICE: SwarmSymphonyService | None = None
+
+
+def get_swarm_symphony_service() -> SwarmSymphonyService:
+ global _SHARED_SERVICE
+ if _SHARED_SERVICE is None:
+ _SHARED_SERVICE = SwarmSymphonyService()
+ return _SHARED_SERVICE
+
+
+def set_swarm_symphony_service(service: SwarmSymphonyService | None) -> None:
+ """Override/reset the process service for tests and controlled embedding."""
+
+ global _SHARED_SERVICE
+ _SHARED_SERVICE = service
+
+
+def _graph_needs_build(status: dict[str, Any]) -> bool:
+ if not bool(status.get("exists", False)) or bool(status.get("stale", False)):
+ return True
+ for key in ("added_count", "changed_count", "removed_count"):
+ try:
+ if int(status.get(key) or 0) > 0:
+ return True
+ except (TypeError, ValueError):
+ continue
+ return False
+
+
+def _web_graph_payload(
+ artifact: dict[str, Any],
+ *,
+ graph_dir: Path,
+ min_edge_confidence: float,
+ disabled_skill_names: set[str] | list[str] | tuple[str, ...],
+ dynamic_overlay: dict[str, Any] | None,
+) -> dict[str, Any]:
+ """Adapt the public capability graph for the existing Skill Graph panel."""
+
+ skills = []
+ disabled_refs = {
+ _normalize_capability_ref(value)
+ for value in disabled_skill_names
+ if _normalize_capability_ref(value)
+ }
+ disabled_ids: set[str] = set()
+ for raw_capability in artifact.get("capabilities") or []:
+ if not isinstance(raw_capability, dict):
+ continue
+ capability = dict(raw_capability)
+ capability_id = _capability_id(
+ capability.get("capability_id") or capability.get("id")
+ )
+ if not capability_id:
+ continue
+ capability["id"] = capability_id
+ capability["type"] = str(
+ capability.get("capability_type") or capability.get("type") or "skill"
+ )
+ if (
+ _normalize_capability_ref(capability_id) in disabled_refs
+ or _normalize_capability_ref(capability.get("name")) in disabled_refs
+ ):
+ disabled_ids.add(capability_id)
+ continue
+ skills.append(capability)
+
+ nodes: list[dict[str, Any]] = []
+ for node in artifact.get("nodes") or []:
+ if not isinstance(node, dict):
+ continue
+ if _capability_id(node.get("id")) in disabled_ids:
+ continue
+ nodes.append(dict(node))
+
+ edges: list[dict[str, Any]] = []
+ for edge in artifact.get("edges") or []:
+ if not isinstance(edge, dict):
+ continue
+ if _capability_id(edge.get("source")) in disabled_ids:
+ continue
+ if _capability_id(edge.get("target")) in disabled_ids:
+ continue
+ edges.append(dict(edge))
+
+ graph = {"nodes": nodes, "edges": edges}
+ return {
+ "success": True,
+ "graph_dir": str(graph_dir),
+ "graph_manifest": dict(artifact.get("config") or {}),
+ "orchestration_min_edge_confidence": min_edge_confidence,
+ "skills": skills,
+ "graph": _graph_with_runtime_weights(graph, dynamic_overlay),
+ "diagnostics": {"diagnostics": list(artifact.get("diagnostics") or [])},
+ }
+
+
+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
+ edges = []
+ for raw_edge in graph.get("edges") or []:
+ edge = dict(raw_edge)
+ key = (
+ f"{_capability_id(edge.get('source'))}->"
+ f"{_capability_id(edge.get('target'))}:"
+ f"{str(edge.get('type') or 'can_feed')}"
+ )
+ stats = runtime_edges.get(key)
+ if isinstance(stats, dict):
+ edge["runtime_weight"] = float(stats.get("runtime_weight") or 1.0)
+ edges.append(edge)
+ return {**graph, "edges": edges}
+
+
+def _capability_id(value: Any) -> str:
+ return str(value or "").removeprefix("skill:").removeprefix("capability:")
+
+
+def _normalize_capability_ref(value: Any) -> str:
+ return re.sub(r"[^a-z0-9]+", "-", _capability_id(value).strip().lower()).strip("-")
+
+
+def _resolve_orchestration_language(value: Any = None) -> str:
+ language = str(value or "").strip().lower()
+ if language == "zh":
+ language = "cn"
+ return language if language in {"cn", "en"} else "cn"
+
+
+def _select_primary_plan(payload: dict[str, Any]) -> dict[str, Any]:
+ for key in ("recommended_plans", "plans"):
+ plans = payload.get(key)
+ if not isinstance(plans, list):
+ continue
+ for plan in plans:
+ if isinstance(plan, dict):
+ return plan
+ return {}
+
+
+def _default_plan_title(language: str) -> str:
+ if _resolve_orchestration_language(language) == "en":
+ return "Symphony plan"
+ return "Symphony 编排计划"
+
+
+_BUILD_STAGE_LABELS = {
+ "update.start": "开始构建技能总谱",
+ "update.cancel_requested": "正在取消技能总谱构建",
+ "update.cancelled": "技能总谱构建已取消",
+ "scan.start": "扫描技能目录",
+ "scan.done": "技能目录扫描完成",
+ "diff.done": "计算技能变更",
+ "fingerprint.reuse": "复用技能指纹",
+ "fingerprint.parse.start": "解析技能指纹",
+ "fingerprint.extract.start": "提取技能指纹",
+ "fingerprint.normalize.start": "规范化技能指纹",
+ "fingerprint.done": "技能指纹处理完成",
+ "artifact.fingerprints.write.start": "写入技能指纹文件",
+ "artifact.fingerprints.write.done": "技能指纹文件写入完成",
+ "graph.build.start": "构建技能关系图",
+ "graph.registry.start": "注册技能节点",
+ "graph.registry.done": "技能节点注册完成",
+ "graph.candidates.start": "生成候选关系",
+ "graph.candidates.done": "候选关系生成完成",
+ "graph.resolve.start": "解析候选关系",
+ "graph.resolve.progress": "解析候选关系",
+ "graph.resolve.done": "候选关系解析完成",
+ "graph.materialize.start": "生成总谱结构",
+ "graph.materialize.done": "总谱结构生成完成",
+ "graph.lookup.start": "构建总谱检索结构",
+ "graph.lookup.done": "总谱检索结构构建完成",
+ "graph.build.done": "技能关系图构建完成",
+ "artifact.graph.write.start": "写入总谱文件",
+ "artifact.graph.write.done": "总谱文件写入完成",
+ "state.write.start": "写入总谱状态",
+ "state.write.done": "总谱状态写入完成",
+ "update.failed": "总谱构建失败",
+ "update.done": "总谱构建完成",
+}
+
+
+def _starting_build_progress() -> dict[str, Any]:
+ return {
+ "stage": "update.start",
+ "label": _BUILD_STAGE_LABELS["update.start"],
+ "percent": _BUILD_STAGE_PROGRESS["update.start"],
+ "status": "running",
+ }
+
+
+_BUILD_STAGE_PROGRESS = {
+ "update.start": 3,
+ "update.cancel_requested": 100,
+ "update.cancelled": 100,
+ "scan.start": 8,
+ "scan.done": 14,
+ "diff.done": 20,
+ "artifact.fingerprints.write.start": 52,
+ "artifact.fingerprints.write.done": 55,
+ "graph.build.start": 58,
+ "graph.registry.start": 63,
+ "graph.registry.done": 65,
+ "graph.candidates.start": 66,
+ "graph.candidates.done": 70,
+ "graph.resolve.start": 72,
+ "graph.resolve.done": 84,
+ "graph.materialize.start": 86,
+ "graph.materialize.done": 88,
+ "graph.lookup.start": 90,
+ "graph.lookup.done": 92,
+ "graph.build.done": 94,
+ "artifact.graph.write.start": 95,
+ "artifact.graph.write.done": 96,
+ "state.write.start": 98,
+ "state.write.done": 99,
+ "update.failed": 100,
+ "update.done": 100,
+}
+
+
+def _build_log_payload(graph_dir: Path | str, *, limit: int = 80) -> dict[str, Any]:
+ resolved_graph_dir = Path(graph_dir)
+ entries = _read_build_log(resolved_graph_dir, limit=limit)
+ token_usage = _build_token_usage_payload(resolved_graph_dir, entries)
+ build_progress = _build_progress(entries)
+ if token_usage:
+ build_progress["llm_token_usage"] = token_usage
+ return {
+ "build_log": entries,
+ "build_progress": build_progress,
+ "llm_token_usage": token_usage,
+ }
+
+
+def _read_build_log(graph_dir: Path, *, limit: int = 80) -> list[dict[str, Any]]:
+ log_path = graph_dir / "build_log.jsonl"
+ if not log_path.is_file():
+ return []
+ try:
+ lines = log_path.read_text(encoding="utf-8").splitlines()
+ except OSError:
+ return []
+ entries: list[dict[str, Any]] = []
+ line_limit = max(1, limit)
+ for line in lines[-line_limit:]:
+ try:
+ payload = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(payload, dict) and payload.get("stage"):
+ entries.append(_normalize_build_log_entry(payload))
+ return entries
+
+
+def _repair_interrupted_build_log(graph_dir: Path) -> bool:
+ """Close an orphaned running log after its owning process has disappeared.
+
+ Callers must hold the extension build guard and first rule out a live task.
+ """
+ if _build_progress(_read_build_log(graph_dir)).get("status") != "running":
+ return False
+ _BuildProcessLogger(graph_dir / "build_log.jsonl").record(
+ "update.cancelled",
+ reason="process_interrupted",
+ )
+ return True
+
+
+def _normalize_build_log_entry(payload: dict[str, Any]) -> dict[str, Any]:
+ stage = str(payload.get("stage") or "")
+ entry = dict(payload)
+ entry["stage"] = stage
+ entry["label"] = _BUILD_STAGE_LABELS.get(stage, stage)
+ _clamp_build_log_count(entry)
+ return entry
+
+
+def _clamp_build_log_count(entry: dict[str, Any]) -> None:
+ if "current" not in entry or "total" not in entry:
+ return
+ try:
+ total = int(entry.get("total") or 0)
+ current = int(entry.get("current") or 0)
+ except (TypeError, ValueError):
+ return
+ if total <= 0:
+ return
+ entry["total"] = total
+ entry["current"] = max(0, min(current, total))
+
+
+def _build_progress(entries: list[dict[str, Any]]) -> dict[str, Any]:
+ if not entries:
+ return {
+ "stage": "idle",
+ "label": "暂无构建日志",
+ "percent": 0,
+ "status": "idle",
+ }
+ latest = _latest_effective_build_log_entry(entries)
+ stage = str(latest.get("stage") or "")
+ status = "running"
+ if stage == "update.done":
+ status = "success"
+ elif stage == "update.failed":
+ status = "error"
+ elif stage == "update.cancelled":
+ status = "cancelled"
+ return {
+ "stage": stage,
+ "label": str(latest.get("label") or _BUILD_STAGE_LABELS.get(stage, stage)),
+ "percent": _build_stage_percent(stage, latest),
+ "status": status,
+ "current": latest.get("current"),
+ "total": latest.get("total"),
+ "ts": latest.get("ts"),
+ }
+
+
+def _latest_effective_build_log_entry(entries: list[dict[str, Any]]) -> dict[str, Any]:
+ if not entries:
+ return {}
+ for entry in reversed(entries):
+ if str(entry.get("stage") or "") in {
+ "update.done",
+ "update.failed",
+ "update.cancelled",
+ }:
+ return entry
+ return entries[-1]
+
+
+def _build_token_usage_payload(
+ graph_dir: Path, entries: list[dict[str, Any]]
+) -> dict[str, Any]:
+ status = _build_progress(entries).get("status")
+ if status == "running":
+ current = _current_token_usage_summary()
+ if _has_token_usage(current):
+ return current
+ return {}
+
+ for usage in (
+ _read_json_token_usage(
+ resolve_graph_artifact_dir(graph_dir) / "llm_token_usage.json"
+ ),
+ _read_json_token_usage(graph_dir / "llm_token_usage.json"),
+ ):
+ if _has_token_usage(usage):
+ return usage
+
+ return {}
+
+
+def _current_token_usage_summary() -> dict[str, Any]:
+ try:
+ from jiuwenswarm.symphony.llm import get_llm_token_usage_summary
+
+ usage = get_llm_token_usage_summary()
+ except Exception: # noqa: BLE001
+ return {}
+ return usage if isinstance(usage, dict) else {}
+
+
+def _read_json_token_usage(path: Path) -> dict[str, Any]:
+ try:
+ usage = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ return usage if isinstance(usage, dict) else {}
+
+
+def _has_token_usage(usage: dict[str, Any]) -> bool:
+ total = usage.get("total")
+ if not isinstance(total, dict):
+ return False
+ try:
+ return int(total.get("total_tokens") or 0) > 0
+ except (TypeError, ValueError):
+ return False
+
+
+def _build_stage_percent(stage: str, entry: dict[str, Any]) -> int:
+ if stage == "graph.resolve.progress":
+ return _progress_between(entry, start=72, end=84)
+ if stage.startswith("fingerprint."):
+ return _progress_between(entry, start=24, end=48)
+ return int(_BUILD_STAGE_PROGRESS.get(stage, 0))
+
+
+def _progress_between(entry: dict[str, Any], *, start: int, end: int) -> int:
+ try:
+ current = int(entry.get("current") or 0)
+ total = int(entry.get("total") or 0)
+ except (TypeError, ValueError):
+ return start
+ if total <= 0:
+ return start
+ ratio = max(0.0, min(1.0, current / total))
+ return int(round(start + (end - start) * ratio))
+
+
+class _OrderedProgressDispatcher:
+ """Serialize progress delivery and drain it before the tool returns."""
+
+ def __init__(self, callback: ProgressCallback | None) -> None:
+ self.callback = callback
+ self.loop: asyncio.AbstractEventLoop | None = None
+ self.queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue()
+ self.worker: asyncio.Task[None] | None = None
+ self._close_lock = asyncio.Lock()
+ self._state_lock = Lock()
+ self._accepting = False
+ self._threadsafe_puts: set[ConcurrentFuture[None]] = set()
+
+ def start(self) -> None:
+ with self._state_lock:
+ if self.callback is None or self.worker is not None:
+ return
+ self.loop = asyncio.get_running_loop()
+ self.worker = self.loop.create_task(
+ self._run(),
+ name="symphony-build-progress",
+ )
+ self._accepting = True
+
+ def enqueue(self, event: dict[str, Any]) -> None:
+ try:
+ running_loop = asyncio.get_running_loop()
+ except RuntimeError:
+ running_loop = None
+ with self._state_lock:
+ loop = self.loop
+ if not self._accepting or self.worker is None or loop is None:
+ return
+ if running_loop is loop:
+ self.queue.put_nowait(event)
+ return
+ put = self.queue.put(event)
+ try:
+ future = asyncio.run_coroutine_threadsafe(put, loop)
+ except RuntimeError:
+ put.close()
+ logger.warning("Symphony progress event arrived after loop shutdown")
+ return
+ self._threadsafe_puts.add(future)
+ future.add_done_callback(self._forget_threadsafe_put)
+
+ async def close(self) -> None:
+ async with self._close_lock:
+ try:
+ await self._close_locked()
+ except BaseException:
+ await self._abort_locked()
+ raise
+
+ async def abort(self) -> None:
+ """Stop progress delivery immediately and reclaim all owned work."""
+
+ async with self._close_lock:
+ await self._abort_locked()
+
+ async def shutdown_now(self) -> None:
+ """Alias for callers that prefer explicit shutdown terminology."""
+
+ await self.abort()
+
+ async def _close_locked(self) -> None:
+ with self._state_lock:
+ worker = self.worker
+ self._accepting = False
+ pending_puts = tuple(self._threadsafe_puts)
+ if worker is None:
+ return
+ for future in pending_puts:
+ try:
+ await asyncio.wrap_future(future)
+ except asyncio.CancelledError:
+ current = asyncio.current_task()
+ if current is not None and current.cancelling():
+ raise
+ logger.warning("Symphony threaded progress delivery cancelled")
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "Symphony threaded progress delivery failed",
+ exc_info=True,
+ )
+ await self.queue.join()
+ self.queue.put_nowait(None)
+ await worker
+ with self._state_lock:
+ self.worker = None
+ self._threadsafe_puts.clear()
+
+ async def _abort_locked(self) -> None:
+ with self._state_lock:
+ worker = self.worker
+ self._accepting = False
+ pending_puts = tuple(self._threadsafe_puts)
+ for future in pending_puts:
+ future.cancel()
+ if worker is not None and not worker.done():
+ worker.cancel("symphony.progress.abort")
+ for future in pending_puts:
+ try:
+ await asyncio.wrap_future(future)
+ except BaseException:
+ pass
+ if worker is not None:
+ try:
+ await worker
+ except BaseException:
+ pass
+ while True:
+ try:
+ self.queue.get_nowait()
+ except asyncio.QueueEmpty:
+ break
+ else:
+ self.queue.task_done()
+ with self._state_lock:
+ self.worker = None
+ self._threadsafe_puts.clear()
+
+ def _forget_threadsafe_put(self, future: ConcurrentFuture[None]) -> None:
+ with self._state_lock:
+ self._threadsafe_puts.discard(future)
+
+ async def _run(self) -> None:
+ while True:
+ event = await self.queue.get()
+ try:
+ if event is None:
+ return
+ result = self.callback(event) if self.callback is not None else None
+ if inspect.isawaitable(result):
+ await result
+ except asyncio.CancelledError:
+ current = asyncio.current_task()
+ if current is not None and current.cancelling():
+ raise
+ logger.warning("Symphony progress callback cancelled")
+ except Exception: # noqa: BLE001
+ logger.warning("Symphony progress callback failed", exc_info=True)
+ finally:
+ self.queue.task_done()
+
+
+class _BuildProcessLogger:
+ def __init__(
+ self,
+ path: Path,
+ *,
+ progress: _OrderedProgressDispatcher | None = None,
+ ) -> None:
+ self.path = path
+ self.progress = progress
+
+ def reset(self) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ self.path.write_text("", encoding="utf-8")
+
+ def record(self, stage: str, **details: Any) -> None:
+ payload = {
+ "ts": datetime.now(timezone.utc).isoformat(),
+ "stage": stage,
+ **details,
+ }
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ with self.path.open("a", encoding="utf-8") as handle:
+ handle.write(json.dumps(payload, ensure_ascii=False, default=str) + "\n")
+ logger.info("[SymphonyBuild] %s: %s", stage, _compact_details(details))
+ if self.progress is not None:
+ self.progress.enqueue({"event": stage, **details})
+
+
+def _compact_details(details: dict[str, Any]) -> str:
+ if not details:
+ return "{}"
+ rendered = json.dumps(details, ensure_ascii=False, default=str)
+ return rendered if len(rendered) <= 500 else rendered[:497] + "..."
+
+
+def _build_presentation(
+ payload: dict[str, Any],
+ *,
+ language: str = "cn",
+) -> dict[str, str]:
+ plan = _select_primary_plan(payload)
+ title = str(plan.get("title") or _default_plan_title(language)).strip()
+ mermaid = _plan_to_mermaid(plan, payload.get("execution_graph") or {})
+ lines = [
+ f"## {title}",
+ "",
+ "```mermaid",
+ mermaid,
+ "```",
+ ]
+ reason = str(plan.get("reason") or payload.get("reason") or "").strip()
+ if reason:
+ lines.extend(["", reason])
+ steps = plan.get("steps") if isinstance(plan, dict) else []
+ if isinstance(steps, list) and steps:
+ confirmation = (
+ "Would you like to proceed with the orchestration plan above?"
+ if language == "en"
+ else "是否按照上述编排结果执行?"
+ )
+ lines.extend(["", confirmation])
+ return {"markdown": "\n".join(lines), "mermaid": mermaid}
+
+
+def _plan_to_mermaid(plan: dict[str, Any], graph: dict[str, Any]) -> str:
+ steps = plan.get("steps") if isinstance(plan, dict) else []
+ edges = graph.get("edges") if isinstance(graph, dict) else []
+ labels = {
+ str(step.get("skill_id") or ""): str(
+ step.get("skill_name") or step.get("name") or step.get("skill_id") or ""
+ )
+ for step in steps or []
+ if isinstance(step, dict)
+ }
+ node_ids = [skill_id for skill_id in labels if skill_id]
+ for edge in edges or []:
+ source = str(edge.get("source") or "")
+ target = str(edge.get("target") or "")
+ if source and source not in node_ids:
+ node_ids.append(source)
+ if target and target not in node_ids:
+ node_ids.append(target)
+ if not node_ids:
+ return 'flowchart LR\n none["No Symphony plan"]'
+
+ node_keys = {
+ node_id: f"N{index}" for index, node_id in enumerate(node_ids, start=1)
+ }
+ lines = ["flowchart LR"]
+ for node_id in node_ids:
+ lines.append(
+ f' {node_keys[node_id]}["{_mermaid_escape(labels.get(node_id) or node_id)}"]'
+ )
+ for edge in edges or []:
+ source = str(edge.get("source") or "")
+ target = str(edge.get("target") or "")
+ if source in node_keys and target in node_keys:
+ lines.append(f" {node_keys[source]} --> {node_keys[target]}")
+ return "\n".join(lines)
+
+
+def _mermaid_escape(value: str) -> str:
+ return str(value or "").replace("\\", "\\\\").replace('"', '\\"')[:80]
diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.py
index 5885c21123..30960cfa23 100644
--- a/tests/agents/swarm/test_swarm_assembly.py
+++ b/tests/agents/swarm/test_swarm_assembly.py
@@ -1447,7 +1447,7 @@ def test_symphony_toolkit_is_leader_only(monkeypatch: pytest.MonkeyPatch) -> Non
"""Symphony tools are built only for the team leader."""
seen_configs: list[dict] = []
fake_tool = types.SimpleNamespace(
- card=types.SimpleNamespace(name="symphony_compose_score")
+ card=types.SimpleNamespace(name="symphony_compose_graph")
)
class FakeSymphonyToolkit:
@@ -1468,7 +1468,7 @@ def test_symphony_toolkit_is_leader_only(monkeypatch: pytest.MonkeyPatch) -> Non
built = tools.build_symphony_toolkit({}, leader)
- assert [tool.card.name for tool in built] == ["symphony_compose_score"]
+ assert [tool.card.name for tool in built] == ["symphony_compose_graph"]
assert tools.build_symphony_toolkit({}, teammate) == []
assert seen_configs == [{"symphony": {"enabled": True}}]
diff --git a/tests/symphony/test_experience_base.py b/tests/symphony/test_experience_base.py
index eb9be8890f..5fcc68287f 100644
--- a/tests/symphony/test_experience_base.py
+++ b/tests/symphony/test_experience_base.py
@@ -13,11 +13,11 @@ from typing import Any
import numpy as np
import pytest
-from jiuwenswarm.symphony.experience.bank import ExperienceBank
-from jiuwenswarm.symphony.experience.cluster import ClusteredQuery, cluster_traces
-from jiuwenswarm.symphony.experience.collector import ExperienceBaseBuilder
-from jiuwenswarm.symphony.experience.retriever import ExperienceRetriever
-from jiuwenswarm.symphony.experience.models import (
+from openjiuwen.symphony.experience.bank import ExperienceBank
+from openjiuwen.symphony.experience.cluster import ClusteredQuery, cluster_traces
+from openjiuwen.symphony.experience.collector import ExperienceBaseBuilder
+from openjiuwen.symphony.experience.retriever import ExperienceRetriever
+from openjiuwen.symphony.experience.models import (
DistilledPattern,
ExperienceBankBuildConfig,
ExperienceItem,
@@ -182,7 +182,7 @@ def test_build_drops_traces_with_success_false(monkeypatch) -> None:
captured.append(list(traces))
return [ClusteredQuery(0, "ok", [], [], [])]
- import jiuwenswarm.symphony.experience.collector as collector_mod
+ import openjiuwen.symphony.experience.collector as collector_mod
monkeypatch.setattr(collector_mod, "cluster_traces", fake_cluster_traces)
monkeypatch.setattr(
collector_mod, "TraceDistiller",
@@ -219,7 +219,7 @@ def test_build_drops_traces_with_empty_skills(monkeypatch) -> None:
captured.append(list(traces))
return [ClusteredQuery(0, "ok", [], [], [])]
- import jiuwenswarm.symphony.experience.collector as collector_mod
+ import openjiuwen.symphony.experience.collector as collector_mod
monkeypatch.setattr(collector_mod, "cluster_traces", fake_cluster_traces)
monkeypatch.setattr(
collector_mod, "TraceDistiller",
@@ -256,7 +256,7 @@ def test_build_returns_zero_when_all_traces_invalid(monkeypatch) -> None:
called["cluster"] = True
return []
- import jiuwenswarm.symphony.experience.collector as collector_mod
+ import openjiuwen.symphony.experience.collector as collector_mod
monkeypatch.setattr(collector_mod, "cluster_traces", fake_cluster_traces)
builder = ExperienceBaseBuilder(
@@ -289,7 +289,7 @@ def test_build_logs_dropped_count(monkeypatch) -> None:
captured.append(list(traces))
return [ClusteredQuery(0, "ok", [], [], [])]
- import jiuwenswarm.symphony.experience.collector as collector_mod
+ import openjiuwen.symphony.experience.collector as collector_mod
monkeypatch.setattr(collector_mod, "cluster_traces", fake_cluster_traces)
monkeypatch.setattr(
collector_mod, "TraceDistiller",
@@ -313,7 +313,7 @@ def test_build_logs_dropped_count(monkeypatch) -> None:
records: list[logging.LogRecord] = []
handler = logging.Handler()
handler.emit = records.append
- logger = logging.getLogger("jiuwenswarm.symphony.experience.collector")
+ logger = logging.getLogger("openjiuwen.symphony.experience.collector")
prev_level = logger.level
logger.setLevel(logging.WARNING)
logger.addHandler(handler)
@@ -427,7 +427,7 @@ def test_add_propagates_flush_exception_instead_of_dropping_pending(monkeypatch)
builder._pattern_merge_threshold = 1.0
builder._query_examples_count = 0
- import jiuwenswarm.symphony.experience.collector as collector_mod
+ import openjiuwen.symphony.experience.collector as collector_mod
monkeypatch.setattr(
collector_mod, "TraceDistiller",
lambda *a, **kw: _BoomDistiller(),
diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.py
index c6b5d5e253..7e7671eb09 100644
--- a/tests/unit_tests/agentserver/test_agentserver_acp.py
+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py
@@ -302,8 +302,8 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_result_status():
"direct_display": True,
"display_format": "markdown",
"mermaid": "flowchart LR\n A --> B",
- "score_status": {"success": True, "exists": False},
- "score_build": {"success": False, "detail": "failed"},
+ "graph_status": {"success": True, "exists": False},
+ "graph_build": {"success": False, "detail": "failed"},
}
parsed = parse_stream_chunk(
types.SimpleNamespace(
@@ -311,7 +311,7 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_result_status():
payload={
"tool_result": {
"tool_call_id": "call-1",
- "tool_name": "symphony_compose_score",
+ "tool_name": "symphony_compose_graph",
"result": "failed",
"status": "error",
"success": False,
@@ -320,8 +320,8 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_result_status():
"direct_display": True,
"display_format": "markdown",
"mermaid": raw_output["mermaid"],
- "score_status": raw_output["score_status"],
- "score_build": raw_output["score_build"],
+ "graph_status": raw_output["graph_status"],
+ "graph_build": raw_output["graph_build"],
}
},
)
@@ -330,7 +330,7 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_result_status():
assert parsed == {
"event_type": "chat.tool_result",
"result": "failed",
- "tool_name": "symphony_compose_score",
+ "tool_name": "symphony_compose_graph",
"tool_call_id": "call-1",
"status": "error",
"success": False,
@@ -339,8 +339,8 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_result_status():
"direct_display": True,
"display_format": "markdown",
"mermaid": raw_output["mermaid"],
- "score_status": raw_output["score_status"],
- "score_build": raw_output["score_build"],
+ "graph_status": raw_output["graph_status"],
+ "graph_build": raw_output["graph_build"],
}
@@ -492,7 +492,7 @@ def test_parse_stream_chunk_preserves_symphony_status_payload():
types.SimpleNamespace(
type="chat.symphony_status",
payload={
- "source": "symphony_compose_score",
+ "source": "symphony_compose_graph",
"operation_id": "call-1",
"phase": "checking_score",
"content": "Symphony status",
@@ -503,7 +503,7 @@ def test_parse_stream_chunk_preserves_symphony_status_payload():
assert parsed == {
"event_type": "chat.symphony_status",
- "source": "symphony_compose_score",
+ "source": "symphony_compose_graph",
"operation_id": "call-1",
"phase": "checking_score",
"content": "Symphony status",
@@ -517,7 +517,7 @@ def test_interface_deep_parse_stream_chunk_preserves_symphony_status_payload():
types.SimpleNamespace(
type="chat.symphony_status",
payload={
- "source": "symphony_compose_score",
+ "source": "symphony_compose_graph",
"operation_id": "call-1",
"phase": "planning",
"content": "Symphony planning status",
@@ -528,7 +528,7 @@ def test_interface_deep_parse_stream_chunk_preserves_symphony_status_payload():
assert parsed == {
"event_type": "chat.symphony_status",
- "source": "symphony_compose_score",
+ "source": "symphony_compose_graph",
"operation_id": "call-1",
"phase": "planning",
"content": "Symphony planning status",
diff --git a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
index 94e32f9260..c3b995bc93 100644
--- a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
+++ b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
@@ -44,7 +44,7 @@ class _ModelContext:
def test_symphony_tool_stream_handler_matches_only_compose_tool():
handler = SymphonyToolStreamHandler()
- assert handler.matches(SimpleNamespace(name="symphony_compose_score"))
+ assert handler.matches(SimpleNamespace(name="symphony_compose_graph"))
assert not handler.matches(SimpleNamespace(name="todo_list"))
@@ -136,7 +136,7 @@ async def test_stream_event_rail_keeps_image_blocks_when_read_image_multimodal_e
async def test_stream_event_rail_does_not_enable_symphony_status_events_for_plan_tool():
rail = JiuSwarmStreamEventRail()
session = _StreamSession()
- ctx = _ctx(session, "symphony_compose_score", tool_call_id="parent-call")
+ ctx = _ctx(session, "symphony_compose_graph", tool_call_id="parent-call")
await rail.before_tool_call(ctx)
@@ -155,7 +155,7 @@ async def test_stream_event_rail_does_not_enable_symphony_status_events_for_plan
async def test_stream_event_rail_emits_beam_progress_as_tool_update():
rail = JiuSwarmStreamEventRail()
session = _StreamSession()
- ctx = _ctx(session, "symphony_compose_score", tool_call_id="beam-call")
+ ctx = _ctx(session, "symphony_compose_graph", tool_call_id="beam-call")
await rail.before_tool_call(ctx)
callback = current_tool_progress()
@@ -179,15 +179,15 @@ async def test_stream_event_rail_emits_beam_progress_as_tool_update():
@pytest.mark.asyncio
-async def test_stream_event_rail_force_finishes_symphony_compose_score_result():
+async def test_stream_event_rail_force_finishes_symphony_compose_graph_result():
rail = JiuSwarmStreamEventRail()
session = _StreamSession()
result = {
"success": True,
"direct_display": True,
"content": "## Symphony plan\n\n```mermaid\nflowchart LR\n A --> B\n```",
- "score_status": {"success": True, "exists": True, "stale": False},
- "score_build": {"rebuilt": False, "reason": "not_required"},
+ "graph_status": {"success": True, "exists": True, "stale": False},
+ "graph_build": {"rebuilt": False, "reason": "not_required"},
"beam_search": {
"round_index": 2,
"graph": {
@@ -196,7 +196,7 @@ async def test_stream_event_rail_force_finishes_symphony_compose_score_result():
},
},
}
- ctx = _ctx(session, "symphony_compose_score", tool_result=result)
+ ctx = _ctx(session, "symphony_compose_graph", tool_result=result)
await rail.before_tool_call(ctx)
await rail.after_tool_call(ctx)
@@ -207,12 +207,12 @@ async def test_stream_event_rail_force_finishes_symphony_compose_score_result():
if (
chunk.type == "tool_result"
and tool_result is not None
- and tool_result.get("tool_name") == "symphony_compose_score"
+ and tool_result.get("tool_name") == "symphony_compose_graph"
):
tool_results.append(tool_result)
assert tool_results[0]["raw_output"] == result
- assert tool_results[0]["score_status"] == result["score_status"]
- assert tool_results[0]["score_build"] == result["score_build"]
+ assert tool_results[0]["graph_status"] == result["graph_status"]
+ assert tool_results[0]["graph_build"] == result["graph_build"]
assert "beam_search" not in tool_results[0]
assert tool_results[0]["raw_output"]["beam_search"] == result["beam_search"]
assert tool_results[0]["direct_display"] is True
@@ -235,7 +235,7 @@ async def test_stream_event_rail_continues_after_symphony_skill_gap_result():
"continue_after_display": True,
"followup_action": "external_skill_discovery",
}
- ctx = _ctx(session, "symphony_compose_score", tool_result=result)
+ ctx = _ctx(session, "symphony_compose_graph", tool_result=result)
await rail.before_tool_call(ctx)
await rail.after_tool_call(ctx)
@@ -322,7 +322,7 @@ async def test_stream_event_rail_inserts_missing_tool_result_after_cancelled_cal
"type": "function",
"id": "compose-call",
"function": {
- "name": "symphony_compose_score",
+ "name": "symphony_compose_graph",
"arguments": "{\"query\":\"compose\"}",
},
}],
@@ -336,5 +336,5 @@ async def test_stream_event_rail_inserts_missing_tool_result_after_cancelled_cal
assert isinstance(messages[1], AssistantMessage)
assert isinstance(messages[2], ToolMessage)
assert messages[2].tool_call_id == "compose-call"
- assert "symphony_compose_score" in messages[2].content
+ assert "symphony_compose_graph" in messages[2].content
assert isinstance(messages[3], UserMessage)
diff --git a/tests/unit_tests/agentserver/test_symphony_web_panel.py b/tests/unit_tests/agentserver/test_symphony_web_panel.py
new file mode 100644
index 0000000000..edb88ed801
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_symphony_web_panel.py
@@ -0,0 +1,84 @@
+"""Skill Graph Web transport is routed through the shared SkillManager facade."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+import pytest
+
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.server.runtime.agent_adapter.interface import _SKILL_ROUTES
+from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+
+
+@dataclass
+class _FakeSymphonyService:
+ calls: list[tuple[str, object]] = field(default_factory=list)
+
+ async def start_refresh_graph(self, *, force: bool = False) -> dict[str, object]:
+ self.calls.append(("build", force))
+ return {"success": True, "background": True, "build_status": "running"}
+
+ async def cancel_build(self) -> dict[str, object]:
+ self.calls.append(("cancel", None))
+ return {"success": True, "cancelled": True, "build_status": "cancelled"}
+
+ async def graph_status(self) -> dict[str, object]:
+ self.calls.append(("status", None))
+ return {"success": True, "build_status": "running"}
+
+ async def graph(self) -> dict[str, object]:
+ self.calls.append(("get", None))
+ return {"success": True, "graph": {"nodes": [], "edges": []}}
+
+
+ ("method", "handler_name"),
+ [
+ (ReqMethod.SKILLS_GRAPH_BUILD, "handle_skills_graph_build"),
+ (ReqMethod.SKILLS_GRAPH_STATUS, "handle_skills_graph_status"),
+ (ReqMethod.SKILLS_GRAPH_GET, "handle_skills_graph_get"),
+ (ReqMethod.SKILLS_GRAPH_CANCEL, "handle_skills_graph_cancel"),
+ ],
+)
+def test_skill_graph_methods_use_shared_skill_routes(method, handler_name):
+ assert _SKILL_ROUTES[method] == handler_name
+
+
+ ("handler_name", "params", "expected_call"),
+ [
+ ("handle_skills_graph_build", {"force": "true"}, ("build", True)),
+ ("handle_skills_graph_cancel", {}, ("cancel", None)),
+ ("handle_skills_graph_status", {}, ("status", None)),
+ ("handle_skills_graph_get", {}, ("get", None)),
+ ],
+)
+async def test_skill_graph_handlers_delegate_to_process_service(
+ monkeypatch,
+ handler_name,
+ params,
+ expected_call,
+):
+ service = _FakeSymphonyService()
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.get_swarm_symphony_service",
+ lambda: service,
+ )
+ manager = object.__new__(SkillManager)
+
+ result = await getattr(manager, handler_name)(params)
+
+ assert result["success"] is True
+ assert service.calls == [expected_call]
+
+
+def test_legacy_symphony_web_methods_are_not_request_methods():
+ values = {method.value for method in ReqMethod}
+ assert {
+ "symphony.build_score",
+ "symphony.pause_build",
+ "symphony.score_status",
+ "symphony.graph",
+ }.isdisjoint(values)
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index 011e12eb1b..11cc7d8e9f 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -166,7 +166,7 @@ def test_build_agent_identity_prompt_contains_identity_section_only():
assert "# JiuwenSwarm 内部数据" in prompt
assert "## Symphony Orchestration" not in prompt
- assert "`symphony_compose_score`" not in prompt
+ assert "`symphony_compose_graph`" not in prompt
assert "# 消息说明" not in prompt
# Agent-internal dirs must stay logical; absolute tenant paths belong in runtime context.
assert "Agent 内部数据目录/skills" in prompt
@@ -191,7 +191,7 @@ async def test_symphony_orchestration_rail_respects_config_snapshot():
enabled_ctx = AgentCallbackContext(
agent=enabled_agent,
inputs=SimpleNamespace(
- tools=[SimpleNamespace(name="symphony_compose_score")],
+ tools=[SimpleNamespace(name="symphony_compose_graph")],
),
session=_FakeSession(),
extra={},
@@ -207,7 +207,7 @@ async def test_symphony_orchestration_rail_respects_config_snapshot():
disabled_ctx = AgentCallbackContext(
agent=disabled_agent,
inputs=SimpleNamespace(
- tools=[SimpleNamespace(name="symphony_compose_score")],
+ tools=[SimpleNamespace(name="symphony_compose_graph")],
),
session=_FakeSession(),
extra={},
@@ -221,9 +221,9 @@ async def test_symphony_orchestration_rail_respects_config_snapshot():
enabled_prompt = enabled_builder.build()
disabled_prompt = disabled_builder.build()
assert "## Symphony Orchestration" in enabled_prompt
- assert "`symphony_compose_score`" in enabled_prompt
+ assert "`symphony_compose_graph`" in enabled_prompt
assert "## Symphony Orchestration" not in disabled_prompt
- assert "`symphony_compose_score`" not in disabled_prompt
+ assert "`symphony_compose_graph`" not in disabled_prompt
@pytest.mark.asyncio
@@ -239,7 +239,7 @@ async def test_symphony_orchestration_rail_injects_when_tool_visible(
ctx = AgentCallbackContext(
agent=agent,
inputs=SimpleNamespace(
- tools=[SimpleNamespace(name="symphony_compose_score")],
+ tools=[SimpleNamespace(name="symphony_compose_graph")],
),
session=_FakeSession(),
extra={},
@@ -251,7 +251,7 @@ async def test_symphony_orchestration_rail_injects_when_tool_visible(
prompt = builder.build()
assert "## Symphony Orchestration" in prompt
- assert "`symphony_compose_score`" in prompt
+ assert "`symphony_compose_graph`" in prompt
assert "exact identifiers or names" in prompt
assert "Do not omit this field" in prompt
assert "skill_branch_explore" not in prompt
@@ -276,7 +276,7 @@ async def test_symphony_orchestration_rail_backfills_viewed_skills():
)
compose_ctx = _tool_call_ctx(
- "symphony_compose_score",
+ "symphony_compose_graph",
{"query": "build a financial model"},
extra=invocation_extra,
)
@@ -299,7 +299,7 @@ async def test_symphony_orchestration_rail_preserves_explicit_candidates():
)
)
compose_ctx = _tool_call_ctx(
- "symphony_compose_score",
+ "symphony_compose_graph",
{"query": "task", "candidate_skill_ids": ["explicit-skill"]},
extra=invocation_extra,
)
@@ -322,7 +322,7 @@ async def test_symphony_orchestration_rail_does_not_reuse_other_invocation():
)
)
compose_ctx = _tool_call_ctx(
- "symphony_compose_score",
+ "symphony_compose_graph",
{"query": "new task"},
extra={},
)
@@ -352,7 +352,7 @@ async def test_symphony_orchestration_rail_ignores_disclosure_and_failed_views()
)
)
compose_ctx = _tool_call_ctx(
- "symphony_compose_score",
+ "symphony_compose_graph",
{"query": "task"},
extra=invocation_extra,
)
@@ -406,7 +406,7 @@ async def test_symphony_orchestration_rail_clears_when_disabled(
ctx = AgentCallbackContext(
agent=agent,
inputs=SimpleNamespace(
- tools=[SimpleNamespace(name="symphony_compose_score")],
+ tools=[SimpleNamespace(name="symphony_compose_graph")],
),
session=_FakeSession(),
extra={},
@@ -433,9 +433,9 @@ def test_deep_adapter_syncs_symphony_tools_from_config_snapshot(monkeypatch):
tools = [
SimpleNamespace(card=SimpleNamespace(id=name, name=name))
for name in (
- "symphony_read_score",
- "symphony_refresh_score",
- "symphony_compose_score",
+ "symphony_read_graph",
+ "symphony_refresh_graph",
+ "symphony_compose_graph",
)
]
@@ -452,14 +452,14 @@ def test_deep_adapter_syncs_symphony_tools_from_config_snapshot(monkeypatch):
assert seen_configs == [{"symphony": {"enabled": True}}]
assert adapter._symphony_tools_registered is True
assert [card.name for card in adapter._tool_cards] == [
- "symphony_read_score",
- "symphony_refresh_score",
- "symphony_compose_score",
+ "symphony_read_graph",
+ "symphony_refresh_graph",
+ "symphony_compose_graph",
]
assert fake_resource.added == [
- "symphony_read_score",
- "symphony_refresh_score",
- "symphony_compose_score",
+ "symphony_read_graph",
+ "symphony_refresh_graph",
+ "symphony_compose_graph",
]
assert fake_instance.ability_manager.added == fake_resource.added
@@ -473,9 +473,9 @@ def test_deep_adapter_syncs_symphony_tools_from_config_snapshot(monkeypatch):
# sibling adapter still running on it.
assert fake_resource.removed == []
assert fake_instance.ability_manager.removed == [
- "symphony_read_score",
- "symphony_refresh_score",
- "symphony_compose_score",
+ "symphony_read_graph",
+ "symphony_refresh_graph",
+ "symphony_compose_graph",
]
diff --git a/tests/unit_tests/channel/test_web_channel_symphony_status.py b/tests/unit_tests/channel/test_web_channel_symphony_status.py
index ea729fbf3a..ee1a473a14 100644
--- a/tests/unit_tests/channel/test_web_channel_symphony_status.py
+++ b/tests/unit_tests/channel/test_web_channel_symphony_status.py
@@ -163,7 +163,7 @@ async def test_web_channel_preserves_symphony_status_payload():
timestamp=0.0,
ok=True,
payload={
- "source": "symphony_compose_score",
+ "source": "symphony_compose_graph",
"operation_id": "call-1",
"phase": "checking_score",
"content": "Symphony status",
@@ -193,7 +193,7 @@ async def test_web_channel_preserves_symphony_status_payload():
"type": "event",
"event": "chat.symphony_status",
"payload": {
- "source": "symphony_compose_score",
+ "source": "symphony_compose_graph",
"operation_id": "call-1",
"phase": "checking_score",
"content": "Symphony status",
diff --git a/tests/unit_tests/e2a/test_acp_session_updates.py b/tests/unit_tests/e2a/test_acp_session_updates.py
index fb8596ab8e..2498c2cd10 100644
--- a/tests/unit_tests/e2a/test_acp_session_updates.py
+++ b/tests/unit_tests/e2a/test_acp_session_updates.py
@@ -84,7 +84,7 @@ def test_build_acp_session_update_ignores_symphony_status():
update = build_acp_session_update(
_build_message(EventType.CHAT_SYMPHONY_STATUS),
{
- "source": "symphony_compose_score",
+ "source": "symphony_compose_graph",
"operation_id": "call-1",
"phase": "checking_score",
"content": "Symphony status",
diff --git a/tests/unit_tests/symphony/test_beam_planner.py b/tests/unit_tests/symphony/test_beam_planner.py
deleted file mode 100644
index df5473febb..0000000000
--- a/tests/unit_tests/symphony/test_beam_planner.py
+++ /dev/null
@@ -1,604 +0,0 @@
-import asyncio
-import json
-
-from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
-from jiuwenswarm.symphony.orchestration.planning.beam import (
- BidirectionalBeamPlanner,
-)
-
-
-class _FakeBeamLLM:
- def __init__(
- self,
- scores: dict[str, float],
- *,
- delay: float = 0.0,
- rerank_selection: dict | list | None = None,
- ) -> None:
- self.scores = scores
- self.delay = delay
- self.rerank_selection = rerank_selection or {"selected_plan_index": 1}
- self.calls = []
- self.active = 0
- self.max_active = 0
-
- async def complete_json_async(self, **kwargs):
- self.calls.append(kwargs)
- self.active += 1
- self.max_active = max(self.max_active, self.active)
- try:
- if self.delay:
- await asyncio.sleep(self.delay)
- payload = json.loads(kwargs["user_content"])
- if "candidate_plans" in payload:
- return json.dumps(self.rerank_selection)
- return json.dumps(
- {
- "judgements": [
- {
- "candidate_id": candidate["candidate_id"],
- "score": self.scores.get(candidate["skill"]["id"], 0.9),
- "reason": f"{candidate['skill']['id']} is useful",
- }
- for candidate in payload["candidates"]
- ]
- }
- )
- finally:
- self.active -= 1
-
- @property
- def judge_calls(self):
- return [
- call
- for call in self.calls
- if "candidates" in json.loads(call["user_content"])
- ]
-
- @property
- def rerank_calls(self):
- return [
- call
- for call in self.calls
- if "candidate_plans" in json.loads(call["user_content"])
- ]
-
-
-async def test_beam_batches_outgoing_neighbors_and_filters_low_scores(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-b", confidence=0.91),
- _edge("skill-a", "skill-c", confidence=0.88),
- _edge("skill-a", "skill-d", confidence=0.2),
- ],
- )
- llm = _FakeBeamLLM({"skill-b": 0.9, "skill-c": 0.4})
-
- result = await _planner(
- artifacts,
- llm,
- top_k=2,
- max_depth=2,
- candidate_skill_ids=["skill-a"],
- ).plan("compose an alpha plan")
-
- assert result["planning_mode"] == "bidirectional_beam"
- assert result["llm_call_count"] == 2
- assert result["decision"]["judge_llm_call_count"] == 1
- assert result["recommended_plans"][0]["title"] == "compose an alpha plan"
- assert result["beam_search"]["round_index"] == 1
- graph_nodes = {item["id"]: item for item in result["beam_search"]["graph"]["nodes"]}
- assert graph_nodes["skill-a"]["status"] == "final"
- assert graph_nodes["skill-a"]["seed"] is True
- assert graph_nodes["skill-b"]["status"] == "final"
- assert graph_nodes["skill-c"]["status"] == "rejected"
- payload = json.loads(llm.judge_calls[0]["user_content"])
- assert set(payload) == {
- "query",
- "direction",
- "current_skill",
- "candidates",
- }
- assert payload["direction"] == "forward"
- assert [item["skill"]["id"] for item in payload["candidates"]] == [
- "skill-b",
- "skill-c",
- ]
- assert all(set(item) == {"candidate_id", "skill"} for item in payload["candidates"])
- assert (
- "Write all user-visible natural-language fields in Simplified Chinese"
- in (llm.judge_calls[0]["system_prompt"])
- )
- assert _plan_signatures(result) == {("skill-a", "skill-b")}
-
-
-async def test_beam_scores_incoming_neighbors_for_backward_expansion(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-c", confidence=0.91),
- _edge("skill-b", "skill-c", confidence=0.89),
- ],
- )
- llm = _FakeBeamLLM({"skill-a": 0.8, "skill-b": 0.9})
-
- result = await _planner(
- artifacts,
- llm,
- top_k=2,
- max_depth=2,
- candidate_skill_ids=["skill-c"],
- ).plan("prepare the final output")
-
- payload = json.loads(llm.judge_calls[0]["user_content"])
- assert payload["direction"] == "backward"
- assert {item["skill"]["id"] for item in payload["candidates"]} == {
- "skill-a",
- "skill-b",
- }
- assert _plan_signatures(result) == {
- ("skill-a", "skill-c"),
- ("skill-b", "skill-c"),
- }
-
-
-async def test_beam_reuses_same_round_judgement_for_duplicate_skill_edge(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-shared", confidence=0.91),
- _edge("skill-c", "skill-shared", confidence=0.9),
- _edge("skill-shared", "skill-d", confidence=0.89),
- ],
- )
- llm = _FakeBeamLLM({"skill-shared": 0.9, "skill-d": 0.95})
-
- result = await _planner(
- artifacts,
- llm,
- top_k=2,
- max_depth=3,
- candidate_skill_ids=["skill-a", "skill-c"],
- ).plan("finish through the shared skill")
-
- assert result["llm_call_count"] == 4
- assert len(llm.judge_calls) == 3
- assert len(llm.rerank_calls) == 1
- first_round_current_skills = {
- json.loads(call["user_content"])["current_skill"]["id"]
- for call in llm.judge_calls[:2]
- }
- assert first_round_current_skills == {"skill-a", "skill-c"}
- final_payload = json.loads(llm.judge_calls[-1]["user_content"])
- assert [item["skill"]["id"] for item in final_payload["candidates"]] == ["skill-d"]
- assert result["decision"]["judge_cache_misses"] >= 3
- assert any("skill-d" in signature for signature in _plan_signatures(result))
-
-
-async def test_beam_judges_same_candidate_separately_by_direction(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-shared", confidence=0.91),
- _edge("skill-shared", "skill-b", confidence=0.9),
- ],
- )
- llm = _FakeBeamLLM({"skill-shared": 0.9})
-
- result = await _planner(
- artifacts,
- llm,
- top_k=2,
- max_depth=2,
- candidate_skill_ids=["skill-a", "skill-b"],
- ).plan("use the shared skill")
-
- shared_calls = [
- json.loads(call["user_content"])
- for call in llm.judge_calls
- if any(
- candidate["skill"]["id"] == "skill-shared"
- for candidate in json.loads(call["user_content"])["candidates"]
- )
- ]
- assert result["llm_call_count"] == 3
- assert {payload["direction"] for payload in shared_calls} == {
- "forward",
- "backward",
- }
-
-
-async def test_beam_limits_concurrent_judge_requests(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-b", confidence=0.91),
- _edge("skill-c", "skill-d", confidence=0.9),
- _edge("skill-e", "skill-f", confidence=0.89),
- ],
- )
- llm = _FakeBeamLLM(
- {"skill-b": 0.9, "skill-d": 0.9, "skill-f": 0.9},
- delay=0.02,
- )
-
- result = await _planner(
- artifacts,
- llm,
- top_k=3,
- max_depth=2,
- candidate_skill_ids=["skill-a", "skill-c", "skill-e"],
- ).plan("run several independent branches")
-
- assert result["llm_call_count"] == 4
- assert llm.max_active == 3
-
-
-async def test_beam_merges_converging_paths_into_dag_plan(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-c", confidence=0.91),
- _edge("skill-b", "skill-c", confidence=0.9),
- ],
- )
- llm = _FakeBeamLLM({"skill-c": 0.9})
-
- result = await _planner(
- artifacts,
- llm,
- top_k=3,
- max_depth=2,
- candidate_skill_ids=["skill-a", "skill-b"],
- ).plan("merge two preparation skills")
-
- assert ("skill-a", "skill-b", "skill-c") in _plan_signatures(result)
- merged = next(
- plan
- for plan in result["recommended_plans"]
- if tuple(step["skill_id"] for step in plan["steps"])
- == ("skill-a", "skill-b", "skill-c")
- )
- assert {
- (edge["source_id"], edge["target_id"]) for edge in merged["can_feed_edges"]
- } == {("skill-a", "skill-c"), ("skill-b", "skill-c")}
- graph = result["beam_search"]["graph"]
- assert sorted(node["id"] for node in graph["nodes"]) == [
- "skill-a",
- "skill-b",
- "skill-c",
- ]
- assert {(edge["source"], edge["target"]) for edge in graph["edges"]} == {
- ("skill-a", "skill-c"),
- ("skill-b", "skill-c"),
- }
- assert {edge["status"] for edge in graph["edges"]} == {"final", "selected"}
-
-
-async def test_beam_keeps_diverging_paths_as_separate_plans(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-b", confidence=0.91),
- _edge("skill-a", "skill-c", confidence=0.9),
- ],
- )
- llm = _FakeBeamLLM({"skill-b": 0.9, "skill-c": 0.9})
-
- result = await _planner(
- artifacts,
- llm,
- top_k=3,
- max_depth=2,
- candidate_skill_ids=["skill-a"],
- ).plan("choose one downstream path")
-
- assert _plan_signatures(result) == {
- ("skill-a", "skill-b"),
- ("skill-a", "skill-c"),
- }
-
-
-async def test_beam_final_rerank_selects_second_plan(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-b", confidence=0.91),
- _edge("skill-a", "skill-c", confidence=0.9),
- ],
- )
- llm = _FakeBeamLLM(
- {"skill-b": 0.9, "skill-c": 0.9},
- rerank_selection={
- "selected_plan_index": 2,
- "reason": "skill c better matches the task",
- },
- )
-
- result = await _planner(
- artifacts,
- llm,
- top_k=2,
- max_depth=2,
- candidate_skill_ids=["skill-a"],
- ).plan("choose the best downstream skill")
-
- assert tuple(
- step["skill_id"] for step in result["recommended_plans"][0]["steps"]
- ) == ("skill-a", "skill-c")
- assert result["decision"]["final_rerank"] == {
- "applied": True,
- "llm_call_count": 1,
- "cross_plan_skill_merge": False,
- "error": "",
- }
- rerank_payload = json.loads(llm.rerank_calls[0]["user_content"])
- assert set(rerank_payload) == {
- "query",
- "required_output_types",
- "candidate_skill_pool",
- "candidate_can_feed_edges",
- "candidate_plans",
- }
- assert {item["id"] for item in rerank_payload["candidate_skill_pool"]} == {
- "skill-a",
- "skill-b",
- "skill-c",
- }
- assert {
- (edge["source_id"], edge["target_id"])
- for edge in rerank_payload["candidate_can_feed_edges"]
- } == {("skill-a", "skill-b"), ("skill-a", "skill-c")}
-
-
-async def test_beam_final_rerank_merges_paths_without_seed_guard(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-b", confidence=0.91),
- _edge("skill-a", "skill-c", confidence=0.9),
- ],
- )
- llm = _FakeBeamLLM(
- {"skill-b": 0.9, "skill-c": 0.9},
- rerank_selection={
- "selected_plan_index": 1,
- "reason": "both delivery skills are required",
- "steps": [
- {"skill_id": "skill-b", "reason": "first deliverable"},
- {"skill_id": "skill-c", "reason": "second deliverable"},
- ],
- "can_feed_edges": [],
- },
- )
-
- result = await _planner(
- artifacts,
- llm,
- top_k=2,
- max_depth=2,
- candidate_skill_ids=["skill-a"],
- ).plan("produce two independent deliverables")
-
- primary = result["recommended_plans"][0]
- assert tuple(step["skill_id"] for step in primary["steps"]) == (
- "skill-b",
- "skill-c",
- )
- assert primary["can_feed_edges"] == []
- assert [step["skill_id"] for step in primary["stages"][0]["skills"]] == [
- "skill-b",
- "skill-c",
- ]
- assert primary["source"] == "bidirectional_beam_final_rerank"
- assert result["decision"]["final_rerank"]["cross_plan_skill_merge"] is True
-
-
-async def test_beam_final_rerank_drops_unknown_items_without_rejecting(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[_edge("skill-a", "skill-b", confidence=0.91)],
- )
- llm = _FakeBeamLLM(
- {"skill-b": 0.9},
- rerank_selection={
- "steps": ["unknown-skill", "skill-a", "skill-b"],
- "can_feed_edges": [
- {"source_id": "skill-b", "target_id": "skill-a"},
- {"source_id": "skill-a", "target_id": "skill-b"},
- ],
- },
- )
-
- result = await _planner(
- artifacts,
- llm,
- top_k=1,
- max_depth=2,
- candidate_skill_ids=["skill-a"],
- ).plan("compose a plan")
-
- primary = result["recommended_plans"][0]
- assert tuple(step["skill_id"] for step in primary["steps"]) == (
- "skill-a",
- "skill-b",
- )
- assert [
- (edge["source_id"], edge["target_id"]) for edge in primary["can_feed_edges"]
- ] == [("skill-a", "skill-b")]
- assert result["decision"]["final_rerank"]["applied"] is True
- assert result["decision"]["final_rerank"]["error"] == ""
-
-
-async def test_beam_final_rerank_malformed_response_falls_back(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[_edge("skill-a", "skill-b", confidence=0.91)],
- )
- llm = _FakeBeamLLM(
- {"skill-b": 0.9},
- rerank_selection=["not", "an", "object"],
- )
-
- result = await _planner(
- artifacts,
- llm,
- top_k=1,
- max_depth=2,
- candidate_skill_ids=["skill-a"],
- ).plan("compose a plan")
-
- assert _plan_signatures(result) == {("skill-a", "skill-b")}
- assert result["decision"]["final_rerank"]["applied"] is False
- assert (
- result["decision"]["final_rerank"]["error"]
- == "Final rerank returned non-object JSON."
- )
-
-
-async def test_beam_progress_callback_receives_lightweight_graph_events(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[
- _edge("skill-a", "skill-b", confidence=0.91),
- _edge("skill-a", "skill-c", confidence=0.88),
- ],
- )
- llm = _FakeBeamLLM({"skill-b": 0.9, "skill-c": 0.4})
- events = []
-
- async def progress_callback(event):
- events.append(event)
-
- result = await _planner(
- artifacts,
- llm,
- top_k=2,
- max_depth=2,
- candidate_skill_ids=["skill-a"],
- progress_callback=progress_callback,
- ).plan("compose an alpha plan")
-
- assert [event["event"] for event in events] == [
- "started",
- "candidates_found",
- "candidates_judged",
- "graph_merged",
- "completed",
- ]
- assert result["language"] == "cn"
- assert result["beam_search"]["language"] == "cn"
- assert all(event["language"] == "cn" for event in events)
- assert all(
- set(event) == {"event", "language", "round_index", "graph"} for event in events
- )
- judged_nodes = {node["id"]: node for node in events[2]["graph"]["nodes"]}
- assert judged_nodes["skill-b"]["status"] == "selected"
- assert judged_nodes["skill-c"]["status"] == "rejected"
-
-
-async def test_beam_judge_reason_uses_english_without_seed_copy(tmp_path):
- artifacts = _artifacts(
- tmp_path,
- edges=[_edge("skill-a", "skill-b", confidence=0.91)],
- )
- llm = _FakeBeamLLM({"skill-b": 0.9})
-
- result = await _planner(
- artifacts,
- llm,
- top_k=1,
- max_depth=2,
- candidate_skill_ids=["skill-a"],
- language="en",
- ).plan("compose a plan")
-
- prompt = llm.calls[0]
- payload = json.loads(prompt["user_content"])
- assert "language" not in payload
- assert "language_instruction" not in payload
- assert "state" not in payload
- assert (
- "Write all user-visible natural-language fields in English"
- in (prompt["system_prompt"])
- )
- assert result["reason"] == "skill-b is useful"
-
-
-def _planner(
- artifacts: ScoreArtifacts,
- llm: _FakeBeamLLM,
- *,
- top_k: int,
- max_depth: int,
- candidate_skill_ids: list[str],
- progress_callback=None,
- language="cn",
-) -> BidirectionalBeamPlanner:
- return BidirectionalBeamPlanner(
- artifacts,
- llm_config=None,
- llm_client=llm,
- min_edge_confidence=0.7,
- top_k=top_k,
- max_depth=max_depth,
- candidate_skill_ids=candidate_skill_ids,
- progress_callback=progress_callback,
- language=language,
- )
-
-
-def _artifacts(
- tmp_path,
- *,
- edges: list[dict[str, object]],
-) -> ScoreArtifacts:
- skill_ids = sorted(
- {endpoint for edge in edges for endpoint in (edge["source"], edge["target"])}
- )
- return ScoreArtifacts(
- score_dir=tmp_path,
- manifest={},
- skills=[
- {
- "id": current_skill_id,
- "name": current_skill_id.replace("-", " ").title(),
- "description": f"{current_skill_id} description",
- "inputs": [{"name": "input", "type": "text", "required": True}],
- "outputs": [{"name": current_skill_id, "type": "text"}],
- }
- for current_skill_id in skill_ids
- ],
- graph={"edges": edges},
- lookup={},
- )
-
-
-def _edge(
- source: str,
- target: str,
- *,
- confidence: float,
-) -> dict[str, object]:
- return {
- "type": "can_feed",
- "source": source,
- "target": target,
- "confidence": confidence,
- "method": "llm",
- "evidence": {
- "reasons": [f"{source} feeds {target}"],
- "supporting_fields": {
- "source_outputs": [source],
- "target_inputs": ["input"],
- },
- },
- }
-
-
-def _plan_signatures(result: dict[str, object]) -> set[tuple[str, ...]]:
- return {
- tuple(step["skill_id"] for step in plan["steps"])
- for plan in result["recommended_plans"]
- }
diff --git a/tests/unit_tests/symphony/test_config.py b/tests/unit_tests/symphony/test_config.py
index 93a26e6180..ae339df56c 100644
--- a/tests/unit_tests/symphony/test_config.py
+++ b/tests/unit_tests/symphony/test_config.py
@@ -1,3 +1,5 @@
+import logging
+
import pytest
from jiuwenswarm.symphony import config as symphony_config
@@ -13,8 +15,8 @@ def test_symphony_config_defaults_paths(monkeypatch, tmp_path):
cfg = symphony_config.symphony_config_from_dict({})
assert cfg.paths.skills_root == (tmp_path / "agent" / "jiuwenclaw_workspace" / "skills").resolve()
- assert cfg.paths.score_dir == (
- tmp_path / "agent" / "jiuwenclaw_workspace" / "symphony" / "score"
+ assert cfg.paths.graph_dir == (
+ tmp_path / "agent" / "jiuwenclaw_workspace" / "symphony" / "graph"
).resolve()
assert cfg.fingerprint.scan.max_depth is None
assert cfg.fingerprint.extraction.body_limit is None
@@ -27,6 +29,57 @@ def test_symphony_config_defaults_paths(monkeypatch, tmp_path):
assert cfg.enabled is False
+def test_symphony_config_does_not_accept_legacy_score_dir(monkeypatch, tmp_path):
+ monkeypatch.setattr(
+ symphony_config,
+ "get_agent_workspace_dir",
+ lambda: tmp_path / "agent" / "workspace",
+ )
+
+ cfg = symphony_config.symphony_config_from_dict(
+ {"paths": {"score_dir": str(tmp_path / "legacy-score")}}
+ )
+
+ assert cfg.paths.graph_dir == (
+ tmp_path / "agent" / "workspace" / "symphony" / "graph"
+ ).resolve()
+
+
+def test_symphony_config_warns_once_on_legacy_score_dir(monkeypatch, tmp_path, caplog):
+ monkeypatch.setattr(
+ symphony_config,
+ "get_agent_workspace_dir",
+ lambda: tmp_path / "agent" / "workspace",
+ )
+ monkeypatch.setattr(symphony_config, "_legacy_score_dir_warned", False)
+
+ with caplog.at_level(logging.WARNING, logger="jiuwenswarm.symphony.config"):
+ symphony_config.symphony_config_from_dict(
+ {"paths": {"score_dir": str(tmp_path / "legacy-score")}}
+ )
+ symphony_config.symphony_config_from_dict(
+ {"paths": {"score_dir": str(tmp_path / "legacy-score")}}
+ )
+
+ assert caplog.text.count("score_dir") == 1
+
+
+def test_symphony_config_no_warning_without_legacy_score_dir(
+ monkeypatch, tmp_path, caplog
+):
+ monkeypatch.setattr(
+ symphony_config,
+ "get_agent_workspace_dir",
+ lambda: tmp_path / "agent" / "workspace",
+ )
+ monkeypatch.setattr(symphony_config, "_legacy_score_dir_warned", False)
+
+ with caplog.at_level(logging.WARNING, logger="jiuwenswarm.symphony.config"):
+ symphony_config.symphony_config_from_dict({})
+
+ assert "score_dir" not in caplog.text
+
+
def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
monkeypatch.setattr(
symphony_config,
@@ -38,7 +91,7 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
{
"paths": {
"skills_root": str(tmp_path / "skills-custom"),
- "score_dir": str(tmp_path / "score-custom"),
+ "graph_dir": str(tmp_path / "graph-custom"),
},
"fingerprint": {
"scan": {
@@ -74,7 +127,7 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
)
assert cfg.paths.skills_root == (tmp_path / "skills-custom").resolve()
- assert cfg.paths.score_dir == (tmp_path / "score-custom").resolve()
+ assert cfg.paths.graph_dir == (tmp_path / "graph-custom").resolve()
assert cfg.fingerprint.scan.max_depth == 6
assert cfg.fingerprint.extraction.workers == 1
assert cfg.fingerprint.extraction.batch_size == 4
diff --git a/tests/unit_tests/symphony/test_direct_service.py b/tests/unit_tests/symphony/test_direct_service.py
new file mode 100644
index 0000000000..916fcce647
--- /dev/null
+++ b/tests/unit_tests/symphony/test_direct_service.py
@@ -0,0 +1,1880 @@
+import asyncio
+import ast
+import json
+from pathlib import Path
+from threading import Event, Thread
+from types import SimpleNamespace
+
+import pytest
+
+from openjiuwen.symphony import OrchestrationPlan, SymphonyRuntime
+
+from jiuwenswarm.symphony.adapter import (
+ candidate_ids_from_skill_ids,
+ capability_from_skill,
+ graph_build_orchestration_config_from_swarm,
+ llm_config_signature,
+ orchestration_config_from_swarm,
+)
+from jiuwenswarm.symphony.build import (
+ _relation_cache_counts,
+ build_graph,
+ graph_status,
+)
+from jiuwenswarm.symphony.config import symphony_config_from_dict
+from jiuwenswarm.symphony.fingerprint import (
+ ArtifactSpec,
+ Fingerprint,
+ ParameterSpec,
+ SkillFolderScanner,
+)
+from jiuwenswarm.symphony.graph_state import GraphStateBuilder, load_graph_state
+from jiuwenswarm.symphony.fingerprint.artifacts import (
+ write_extraction_result as real_write_extraction_result,
+)
+from jiuwenswarm.symphony.llm import LLMConfig
+from jiuwenswarm.symphony.service import (
+ SwarmSymphonyService,
+ _BuildProcessLogger,
+ _OrderedProgressDispatcher,
+ _build_progress,
+)
+from jiuwenswarm.symphony.graph_storage import (
+ graph_exists,
+ latest_incomplete_build,
+ resolve_graph_artifact_dir,
+)
+
+
+class _FakeGraphModel:
+ def __init__(self, model="fake-model", confidences=()):
+ self.model = model
+ self.confidences = list(confidences)
+ self.call_count = 0
+ self.model_config = SimpleNamespace(
+ model_name=model,
+ temperature=0.0,
+ top_p=1.0,
+ max_tokens=None,
+ stop=None,
+ )
+ self.model_client_config = SimpleNamespace(
+ client_provider="fake",
+ api_base="https://fake.example/v1",
+ api_key="fake-secret",
+ )
+
+ async def invoke(self, messages, **kwargs):
+ del kwargs
+ self.call_count += 1
+ payload = json.loads(messages[-1]["content"])
+ matches = []
+ for candidate, confidence in zip(
+ payload.get("candidates", []),
+ self.confidences,
+ ):
+ directions = candidate.get("directions") or {}
+ direction = "forward" if "forward" in directions else next(iter(directions))
+ matches.append(
+ {
+ "id": candidate["id"],
+ "direction": direction,
+ "confidence": confidence,
+ }
+ )
+ return SimpleNamespace(content=json.dumps({"matches": matches}))
+
+
+class _CountingGraphModel(_FakeGraphModel):
+ """Use the production identity contract while keeping tests offline."""
+
+ def __init__(self, config):
+ super().__init__(config.model, confidences=[0.95] * 100)
+ self.config = config
+ request_config = config.model_request_kwargs()
+ self.model_config = SimpleNamespace(
+ model_name=config.model,
+ **{key: value for key, value in request_config.items() if key != "model"},
+ )
+ self.model_client_config = SimpleNamespace(**config.model_client_kwargs())
+
+
+def _forbidden_symphony_import(
+ node,
+ *,
+ allowed_symbols,
+):
+ if isinstance(node, ast.Import):
+ imported_modules = {
+ alias.name
+ for alias in node.names
+ if alias.name.startswith("openjiuwen.symphony")
+ }
+ forbidden = imported_modules - {"openjiuwen.symphony"}
+ return ",".join(sorted(forbidden))
+ if not isinstance(node, ast.ImportFrom):
+ return ""
+ imported = {alias.name for alias in node.names}
+ if node.module == "openjiuwen":
+ return "openjiuwen:symphony" if "symphony" in imported else ""
+ if not (node.module or "").startswith("openjiuwen.symphony"):
+ return ""
+ if node.module == "openjiuwen.symphony" and imported <= allowed_symbols:
+ return ""
+ return f"{node.module}:{','.join(sorted(imported))}"
+
+
+def fake_graph_llm(monkeypatch):
+ client = _FakeGraphModel()
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.model_from_config",
+ lambda _config: client,
+ )
+ return client
+
+
+def _config(tmp_path, *, evolution=True):
+ return SimpleNamespace(
+ paths=SimpleNamespace(
+ skills_root=tmp_path / "skills",
+ graph_dir=tmp_path / "graph",
+ ),
+ build=SimpleNamespace(
+ workers=1,
+ batch_size=4,
+ max_candidates_per_skill_relation=8,
+ require_consensus=False,
+ min_edge_confidence=0.5,
+ ),
+ orchestration=SimpleNamespace(
+ mode="fast",
+ top_k=3,
+ max_depth=4,
+ min_edge_confidence=0.5,
+ ),
+ evolution=SimpleNamespace(enabled=evolution),
+ )
+
+
+def test_adapter_maps_skill_contract_to_public_capability():
+ capability = capability_from_skill(
+ Fingerprint(
+ type="skill",
+ id="writer",
+ name="Writer",
+ description="Write markdown.",
+ version="1.0.0",
+ inputs=[ParameterSpec(name="topic", type="text")],
+ outputs=[ArtifactSpec(name="document", type="markdown")],
+ )
+ )
+
+ assert capability.capability_id == "writer"
+ assert capability.capability_type == "skill"
+ assert capability.inputs[0].name == "topic"
+ assert capability.outputs[0].type == "markdown"
+ assert candidate_ids_from_skill_ids(["writer", "writer", "reviewer"]) == [
+ "writer",
+ "reviewer",
+ ]
+
+
+def test_adapter_maps_dynamic_graph_config(tmp_path):
+ public = orchestration_config_from_swarm(_config(tmp_path), mode="beam")
+
+ assert public.mode == "beam"
+ assert public.dynamic_graph_enabled is True
+
+
+def test_build_and_planning_configs_use_distinct_relation_thresholds(tmp_path):
+ config = symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(tmp_path / "skills"),
+ "graph_dir": str(tmp_path / "graph"),
+ },
+ "build": {"min_edge_confidence": 0.9},
+ "orchestration": {"min_edge_confidence": 0.1},
+ }
+ )
+
+ assert (
+ graph_build_orchestration_config_from_swarm(config).min_edge_confidence == 0.9
+ )
+ assert orchestration_config_from_swarm(config).min_edge_confidence == 0.1
+
+
+async def test_service_graph_adapts_public_artifact_for_skill_graph_panel(
+ monkeypatch,
+ tmp_path,
+):
+ config = _config(tmp_path)
+
+ artifact = {
+ "config": {"thresholds": {"can_feed": 0.5}},
+ "capabilities": [
+ {"capability_id": "writer", "capability_type": "skill", "name": "Writer"},
+ {
+ "capability_id": "reviewer",
+ "capability_type": "skill",
+ "name": "Reviewer",
+ },
+ {
+ "capability_id": "disabled",
+ "capability_type": "skill",
+ "name": "Disabled",
+ },
+ ],
+ "nodes": [
+ {
+ "id": "capability:writer",
+ "type": "skill",
+ "label": "Writer",
+ "properties": {},
+ },
+ {
+ "id": "capability:reviewer",
+ "type": "skill",
+ "label": "Reviewer",
+ "properties": {},
+ },
+ {
+ "id": "capability:disabled",
+ "type": "skill",
+ "label": "Disabled",
+ "properties": {},
+ },
+ ],
+ "edges": [
+ {
+ "source": "capability:writer",
+ "target": "capability:reviewer",
+ "type": "can_feed",
+ },
+ {
+ "source": "capability:writer",
+ "target": "capability:disabled",
+ "type": "can_feed",
+ },
+ ],
+ "diagnostics": [{"code": "sample"}],
+ }
+
+ service = SwarmSymphonyService()
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(service, "_read_graph_artifact", lambda _graph_dir: artifact)
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_execution_disabled_skills",
+ lambda: {"disabled"},
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_dynamic_overlay",
+ lambda _graph_dir: {
+ "edges": {"writer->reviewer:can_feed": {"runtime_weight": 0.7}}
+ },
+ )
+
+ result = await service.graph()
+
+ assert result["success"] is True
+ assert [item["id"] for item in result["skills"]] == ["writer", "reviewer"]
+ assert [item["id"] for item in result["graph"]["nodes"]] == [
+ "capability:writer",
+ "capability:reviewer",
+ ]
+ assert result["graph"]["edges"] == [
+ {
+ "source": "capability:writer",
+ "target": "capability:reviewer",
+ "type": "can_feed",
+ "runtime_weight": 0.7,
+ }
+ ]
+
+
+async def test_service_plans_through_public_runtime_and_restores_skill_fields(
+ monkeypatch,
+ tmp_path,
+):
+ config = _config(tmp_path)
+ captured = {}
+
+ class FakeOrchestration:
+ async def plan(self, query, candidate_ids=None, **kwargs):
+ captured.update(query=query, candidate_ids=candidate_ids, **kwargs)
+ return OrchestrationPlan(
+ {
+ "plan_id": "plan-1",
+ "dynamic_graph_enabled": True,
+ "recommended_plans": [
+ {
+ "title": "Plan",
+ "status": "ready",
+ "steps": [
+ {
+ "step": 1,
+ "capability_id": "writer",
+ "name": "Writer",
+ }
+ ],
+ "can_feed_edges": [],
+ "missing_inputs": [],
+ }
+ ],
+ "execution_graph": {
+ "nodes": [{"id": "writer"}],
+ "edges": [],
+ },
+ }
+ )
+
+ service = SwarmSymphonyService()
+
+ async def fresh_status():
+ return {"success": True, "exists": True, "stale": False}
+
+ service.graph_status = fresh_status
+ service._runtime_for = lambda _config: SimpleNamespace(
+ orchestration=FakeOrchestration()
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config", lambda: config
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.get_config",
+ lambda: {"preferred_language": "zh"},
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_execution_disabled_skills",
+ lambda: {"disabled"},
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_dynamic_overlay",
+ lambda _graph_dir: {"edges": {"writer->reviewer": {}}},
+ )
+
+ progress = object()
+ result = await service.plan(
+ "write",
+ mode="beam",
+ candidate_skill_ids=["writer", "writer"],
+ progress=progress,
+ )
+
+ assert result["success"] is True
+ assert result["direct_display"] is True
+ assert result["result"]["recommended_plans"][0]["steps"][0]["skill_id"] == "writer"
+ assert captured["candidate_ids"] == ["writer"]
+ assert captured["disabled_capability_ids"] == {"disabled"}
+ assert captured["dynamic_overlay"]["edges"]
+ assert captured["language"] == "cn"
+ assert captured["mode"] == "beam"
+ assert captured["progress"] is progress
+
+
+async def test_service_rebuilds_stale_graph_before_planning(monkeypatch, tmp_path):
+ config = _config(tmp_path, evolution=False)
+ calls = []
+ plan_kwargs = {}
+
+ class FakeOrchestration:
+ async def plan(self, *args, **kwargs):
+ del args
+ plan_kwargs.update(kwargs)
+ return OrchestrationPlan(
+ {"recommended_plans": [], "execution_graph": {"nodes": [], "edges": []}}
+ )
+
+ service = SwarmSymphonyService()
+
+ async def stale_status():
+ return {"success": True, "exists": True, "stale": True}
+
+ async def refresh_graph(*, force=False, progress=None):
+ calls.append((force, progress))
+ return {"success": True}
+
+ service.graph_status = stale_status
+ service.refresh_graph = refresh_graph
+ service._runtime_for = lambda _config: SimpleNamespace(
+ orchestration=FakeOrchestration()
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config", lambda: config
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.get_config",
+ lambda: {"preferred_language": "en"},
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_execution_disabled_skills", set
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_dynamic_overlay",
+ lambda _graph_dir: pytest.fail("overlay must stay disabled"),
+ )
+
+ progress = object()
+ result = await service.plan("write", progress=progress)
+
+ assert calls == [(False, progress)]
+ assert result["graph_build"]["rebuilt"] is True
+ assert result["language"] == "en"
+ assert plan_kwargs["dynamic_overlay"] is None
+ assert "No Symphony plan" in result["content"]
+ assert "Would you like to proceed" not in result["content"]
+
+
+async def test_swarm_build_publishes_public_graph_artifact(
+ monkeypatch,
+ tmp_path,
+ fake_graph_llm,
+):
+ fake_graph_llm.confidences = [0.95, 0.1]
+ fingerprint = Fingerprint(
+ type="skill",
+ id="writer",
+ name="Writer",
+ description="Write markdown.",
+ version="1.0.0",
+ outputs=[ArtifactSpec(name="document", type="markdown")],
+ )
+ reviewer = Fingerprint(
+ type="skill",
+ id="reviewer",
+ name="Reviewer",
+ description="Review markdown.",
+ version="1.0.0",
+ inputs=[ParameterSpec(name="document", type="markdown")],
+ )
+ archiver = Fingerprint(
+ type="skill",
+ id="archiver",
+ name="Archiver",
+ description="Archive markdown.",
+ version="1.0.0",
+ inputs=[ParameterSpec(name="document", type="markdown")],
+ )
+ extraction_result = SimpleNamespace(
+ fingerprints=[fingerprint, reviewer, archiver],
+ diagnostics=[],
+ reused_count=0,
+ extracted_count=3,
+ folders=[],
+ current_hashes={},
+ fingerprints_by_path={},
+ removed_paths=set(),
+ io_name_vocab={},
+ )
+
+ class FakeExtractor:
+ async def extract_from_root(self, *args, **kwargs):
+ del args, kwargs
+ return extraction_result
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.FingerprintExtractor",
+ lambda **kwargs: FakeExtractor(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.write_extraction_result",
+ lambda *args, **kwargs: None,
+ )
+ (tmp_path / "skills").mkdir()
+ graph_dir = tmp_path / "graph"
+ config = symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(tmp_path / "skills"),
+ "graph_dir": str(graph_dir),
+ },
+ "build": {"min_edge_confidence": 0.9},
+ "orchestration": {"min_edge_confidence": 0.1},
+ }
+ )
+ build_events = []
+
+ result = await build_graph(
+ tmp_path / "skills",
+ graph_dir,
+ force=True,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ build_log=lambda stage, **details: build_events.append((stage, details)),
+ symphony_config=config,
+ )
+
+ current = json.loads((graph_dir / "current.json").read_text(encoding="utf-8"))
+ graph_path = graph_dir / current["artifact"]
+ graph = json.loads(graph_path.read_text(encoding="utf-8"))
+ assert result.success is True
+ assert result.edge_count == 1
+ assert result.relation_reused_count == 0
+ assert result.relation_resolved_count == 2
+ assert graph["config"]["llm"]["relation_cache"]["resolved_count"] == 2
+ assert graph["config"]["thresholds"]["can_feed"] == 0.9
+ assert graph["config"]["orchestration"]["min_edge_confidence"] == 0.9
+ assert (
+ graph["source_snapshot"]["symphony_graph_build"]["matcher"]["thresholds"][
+ "can_feed"
+ ]
+ == 0.9
+ )
+ assert orchestration_config_from_swarm(config).min_edge_confidence == 0.1
+ assert current["schema_version"] == "1.0"
+ assert {item["capability_id"] for item in graph["capabilities"]} == {
+ "archiver",
+ "reviewer",
+ "writer",
+ }
+ resolve_events = [
+ details for stage, details in build_events if stage == "graph.resolve.done"
+ ]
+ assert resolve_events == [
+ {
+ "candidate_count": 2,
+ "match_count": 2,
+ "accepted_match_count": 1,
+ "diagnostics_count": 1,
+ }
+ ]
+ build_done = next(
+ details for stage, details in build_events if stage == "graph.build.done"
+ )
+ assert build_done["candidate_count"] == 2
+ assert build_done["match_count"] == 2
+ assert build_done["accepted_match_count"] == 1
+ assert build_done["match_count"] > build_done["edge_count"] == 1
+ stages = [stage for stage, _details in build_events]
+ assert "build_started" not in stages
+ assert "build_published" not in stages
+ assert stages.count("graph.resolve.done") == 1
+ progress_entries = []
+ percents = []
+ for stage, details in build_events:
+ progress_entries.append({"stage": stage, **details})
+ percents.append(_build_progress(progress_entries)["percent"])
+ assert percents == sorted(percents)
+ assert (
+ graph_status(
+ tmp_path / "skills",
+ graph_dir,
+ symphony_config=config,
+ ).stale
+ is False
+ )
+ assert (graph_path.parent / "graph_state.json").is_file()
+ assert graph_exists(graph_dir) is True
+ assert not list((graph_dir / ".build_runs").glob("*/artifacts"))
+
+
+async def test_swarm_build_relation_cache_reuses_unchanged_candidates(
+ monkeypatch,
+ tmp_path,
+ fake_graph_llm,
+):
+ writer = Fingerprint(
+ type="skill",
+ id="writer",
+ name="Writer",
+ description="Write markdown.",
+ version="1.0.0",
+ outputs=[ArtifactSpec(name="document", type="markdown")],
+ )
+ reviewer = Fingerprint(
+ type="skill",
+ id="reviewer",
+ name="Reviewer",
+ description="Review markdown.",
+ version="1.0.0",
+ inputs=[ParameterSpec(name="document", type="markdown")],
+ )
+ unrelated = Fingerprint(
+ type="skill",
+ id="unrelated",
+ name="Unrelated",
+ description="Unrelated capability.",
+ version="1.0.0",
+ )
+ results = [
+ _extraction_result([writer, reviewer]),
+ _extraction_result([writer, reviewer, unrelated]),
+ ]
+
+ class FakeExtractor:
+ async def extract_from_root(self, *args, **kwargs):
+ del args, kwargs
+ return results.pop(0)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.FingerprintExtractor",
+ lambda **kwargs: FakeExtractor(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.write_extraction_result",
+ lambda *args, **kwargs: None,
+ )
+ graph_dir = tmp_path / "graph"
+ config = symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(tmp_path / "skills"),
+ "graph_dir": str(graph_dir),
+ }
+ }
+ )
+ first = await build_graph(
+ tmp_path / "skills",
+ graph_dir,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+ first_call_count = fake_graph_llm.call_count
+ second = await build_graph(
+ tmp_path / "skills",
+ graph_dir,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+
+ assert first.relation_resolved_count > 0
+ assert second.relation_reused_count == first.relation_resolved_count
+ assert fake_graph_llm.call_count == first_call_count
+ assert (graph_dir / "cache" / "relation_matches.json").is_file()
+
+
+async def test_real_core_relation_cache_invalidates_for_complete_llm_identity(
+ monkeypatch,
+ tmp_path,
+):
+ writer = Fingerprint(
+ type="skill",
+ id="writer",
+ name="Writer",
+ description="Write markdown.",
+ version="1.0.0",
+ outputs=[ArtifactSpec(name="document", type="markdown")],
+ )
+ reviewer = Fingerprint(
+ type="skill",
+ id="reviewer",
+ name="Reviewer",
+ description="Review markdown.",
+ version="1.0.0",
+ inputs=[ParameterSpec(name="document", type="markdown")],
+ )
+ extraction_result = _extraction_result([writer, reviewer])
+
+ class FakeExtractor:
+ async def extract_from_root(self, *args, **kwargs):
+ del args, kwargs
+ return extraction_result
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.FingerprintExtractor",
+ lambda **kwargs: FakeExtractor(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.write_extraction_result",
+ lambda *args, **kwargs: None,
+ )
+ clients = []
+
+ def create_counting_model(config):
+ client = _CountingGraphModel(config)
+ clients.append(client)
+ return client
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.model_from_config",
+ create_counting_model,
+ )
+ skills_root = tmp_path / "skills"
+ graph_dir = tmp_path / "graph"
+ skills_root.mkdir()
+ config = symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(skills_root),
+ "graph_dir": str(graph_dir),
+ }
+ }
+ )
+ raw_endpoint = "https://private-endpoint.example/v1"
+ sensitive_values = (
+ "secret-api-key",
+ raw_endpoint,
+ "private-credential",
+ "private-token",
+ )
+
+ def llm_config(*, top_p, routing, request_route):
+ return LLMConfig(
+ model="model-a",
+ temperature=0.0,
+ top_p=top_p,
+ model_client_config={
+ "api_key": sensitive_values[0],
+ "api_base": raw_endpoint,
+ "client_provider": "openai",
+ "routing": {
+ "region": routing,
+ "credential": sensitive_values[2],
+ },
+ },
+ model_config_obj={
+ "max_tokens": 99,
+ "extra_body": {
+ "request_route": request_route,
+ "token": sensitive_values[3],
+ },
+ },
+ )
+
+ configs = [
+ llm_config(top_p=0.2, routing="route-a", request_route="request-a"),
+ llm_config(top_p=0.9, routing="route-a", request_route="request-a"),
+ llm_config(top_p=0.9, routing="route-b", request_route="request-a"),
+ llm_config(top_p=0.9, routing="route-b", request_route="request-b"),
+ ]
+ results = []
+ artifacts = []
+ for llm_config_value in configs:
+ result = await build_graph(
+ skills_root,
+ graph_dir,
+ llm_config=llm_config_value,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+ results.append(result)
+ artifacts.append(
+ json.loads(
+ (graph_dir / "versions" / result.version / "graph.json").read_text(
+ encoding="utf-8"
+ )
+ )
+ )
+
+ assert len(clients) == 4
+ assert all(client.call_count > 0 for client in clients)
+ assert all(result.relation_resolved_count > 0 for result in results)
+ assert all(result.relation_reused_count == 0 for result in results[1:])
+ assert [artifact["source_snapshot"]["llm_sha256"] for artifact in artifacts] == [
+ client.config.identity_digest() for client in clients
+ ]
+ cache_path = graph_dir / "cache" / "relation_matches.json"
+ assert cache_path.is_file()
+ serialized_outputs = "\n".join(
+ path.read_text(encoding="utf-8") for path in graph_dir.rglob("*.json")
+ )
+ for sensitive_value in sensitive_values:
+ assert sensitive_value not in serialized_outputs
+
+
+async def test_swarm_refresh_publishes_state_when_file_changes_but_fingerprint_does_not(
+ monkeypatch,
+ tmp_path,
+ fake_graph_llm,
+):
+ del fake_graph_llm
+ skills_root = tmp_path / "skills"
+ skill_md = skills_root / "writer" / "SKILL.md"
+ skill_md.parent.mkdir(parents=True)
+ skill_md.write_text("---\nname: writer\n---\nWrite markdown.\n", encoding="utf-8")
+ fingerprint = Fingerprint(
+ type="skill",
+ id="writer",
+ name="Writer",
+ description="Write markdown.",
+ version="1.0.0",
+ outputs=[ArtifactSpec(name="document", type="markdown")],
+ )
+
+ class FakeExtractor:
+ async def extract_from_root(self, root, *args, **kwargs):
+ del args, kwargs
+ folders = SkillFolderScanner().scan(root)
+ current_hashes = GraphStateBuilder().folder_hashes(folders)
+ return SimpleNamespace(
+ fingerprints=[fingerprint],
+ diagnostics=[],
+ reused_count=1,
+ extracted_count=0,
+ folders=folders,
+ current_hashes=current_hashes,
+ fingerprints_by_path={"writer": fingerprint},
+ removed_paths=set(),
+ io_name_vocab={},
+ )
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.FingerprintExtractor",
+ lambda **kwargs: FakeExtractor(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.write_extraction_result",
+ lambda *args, **kwargs: None,
+ )
+ graph_dir = tmp_path / "graph"
+ config = symphony_config_from_dict(
+ {"paths": {"skills_root": str(skills_root), "graph_dir": str(graph_dir)}}
+ )
+ first = await build_graph(
+ skills_root,
+ graph_dir,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+ old_hash = load_graph_state(graph_dir).active_entries()["writer"].skill_md_sha256
+ skill_md.write_text(
+ "---\nname: writer\n---\nWrite markdown with revised guidance.\n",
+ encoding="utf-8",
+ )
+
+ assert (
+ graph_status(
+ skills_root,
+ graph_dir,
+ symphony_config=config,
+ ).stale
+ is True
+ )
+ second = await build_graph(
+ skills_root,
+ graph_dir,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+
+ new_hash = load_graph_state(graph_dir).active_entries()["writer"].skill_md_sha256
+ assert second.version != first.version
+ assert new_hash != old_hash
+ assert new_hash == GraphStateBuilder.file_sha256(skill_md)
+ current = json.loads((graph_dir / "current.json").read_text(encoding="utf-8"))
+ artifact = json.loads((graph_dir / current["artifact"]).read_text(encoding="utf-8"))
+ captured_status_snapshots = []
+ real_runtime = SymphonyRuntime
+
+ def capture_status_runtime(**kwargs):
+ if kwargs.get("model") is None and "source_snapshot" in kwargs:
+ captured_status_snapshots.append(dict(kwargs["source_snapshot"]))
+ return real_runtime(**kwargs)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.SymphonyRuntime",
+ capture_status_runtime,
+ )
+ assert (
+ graph_status(
+ skills_root,
+ graph_dir,
+ symphony_config=config,
+ ).stale
+ is False
+ )
+ assert len(captured_status_snapshots) == 1
+ expected_snapshot = captured_status_snapshots[0]
+ assert set(expected_snapshot) == {
+ "schema_version",
+ "capabilities_sha256",
+ "current_hashes",
+ "fingerprint_sha256",
+ "fingerprint_config_sha256",
+ "graph_config",
+ "llm_sha256",
+ }
+ assert "symphony_graph_build" not in expected_snapshot
+ assert (
+ expected_snapshot["fingerprint_sha256"]
+ == artifact["source_snapshot"]["fingerprint_sha256"]
+ )
+ assert expected_snapshot["llm_sha256"] == artifact["source_snapshot"]["llm_sha256"]
+
+
[email protected]("change", ["build_config", "llm_config"])
+async def test_swarm_graph_identity_rebuilds_for_build_or_llm_config_change(
+ monkeypatch,
+ tmp_path,
+ change,
+):
+ fingerprint = Fingerprint(
+ type="skill",
+ id="writer",
+ name="Writer",
+ description="Write markdown.",
+ version="1.0.0",
+ )
+ extraction_result = _extraction_result([fingerprint])
+
+ class FakeExtractor:
+ async def extract_from_root(self, *args, **kwargs):
+ del args, kwargs
+ return extraction_result
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.FingerprintExtractor",
+ lambda **kwargs: FakeExtractor(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.write_extraction_result",
+ lambda *args, **kwargs: None,
+ )
+ graph_dir = tmp_path / "graph"
+ skills_root = tmp_path / "skills"
+ skills_root.mkdir()
+
+ def config(max_candidates):
+ return symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(skills_root),
+ "graph_dir": str(graph_dir),
+ },
+ "build": {
+ "max_candidates_per_skill_relation": max_candidates,
+ },
+ }
+ )
+
+ first_config = config(8)
+ second_config = config(9 if change == "build_config" else 8)
+ first_llm_config = LLMConfig(model="model-v1")
+ second_llm_config = LLMConfig(
+ model="model-v2" if change == "llm_config" else "model-v1"
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.model_from_config",
+ lambda llm_config: _FakeGraphModel(llm_config.model),
+ )
+ captured_status_snapshots = []
+ real_runtime = SymphonyRuntime
+
+ def capture_status_runtime(**kwargs):
+ if kwargs.get("model") is None and "source_snapshot" in kwargs:
+ captured_status_snapshots.append(dict(kwargs["source_snapshot"]))
+ return real_runtime(**kwargs)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.SymphonyRuntime",
+ capture_status_runtime,
+ )
+ first = await build_graph(
+ skills_root,
+ graph_dir,
+ llm_config=first_llm_config,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=first_config,
+ )
+ first_graph = json.loads(
+ (graph_dir / "versions" / first.version / "graph.json").read_text()
+ )
+
+ assert (
+ graph_status(
+ skills_root,
+ graph_dir,
+ llm_config=second_llm_config,
+ symphony_config=second_config,
+ ).stale
+ is True
+ )
+ assert "symphony_graph_build" not in captured_status_snapshots[-1]
+
+ second = await build_graph(
+ skills_root,
+ graph_dir,
+ llm_config=second_llm_config,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=second_config,
+ )
+ second_graph = json.loads(
+ (graph_dir / "versions" / second.version / "graph.json").read_text()
+ )
+
+ assert second.version != first.version
+ assert second_graph["source_snapshot"] != first_graph["source_snapshot"]
+ assert (
+ graph_status(
+ skills_root,
+ graph_dir,
+ llm_config=second_llm_config,
+ symphony_config=second_config,
+ ).stale
+ is False
+ )
+ assert "symphony_graph_build" not in captured_status_snapshots[-1]
+ if change == "build_config":
+ assert second_graph["config"]["graph"]["max_candidates_per_skill_relation"] == 9
+ else:
+ assert (
+ second_graph["source_snapshot"]["llm_sha256"]
+ != first_graph["source_snapshot"]["llm_sha256"]
+ )
+
+
+ "failure", [RuntimeError("prepare failed"), asyncio.CancelledError()]
+)
+async def test_swarm_auxiliary_prepare_failure_preserves_current(
+ monkeypatch,
+ tmp_path,
+ failure,
+ fake_graph_llm,
+):
+ del fake_graph_llm
+ writer = Fingerprint(
+ type="skill",
+ id="writer",
+ name="Writer",
+ description="Write markdown.",
+ version="1.0.0",
+ outputs=[ArtifactSpec(name="document", type="markdown")],
+ )
+ results = [
+ _extraction_result([writer]),
+ _extraction_result(
+ [
+ writer,
+ Fingerprint(
+ type="skill",
+ id="reviewer",
+ name="Reviewer",
+ description="Review markdown.",
+ version="1.0.0",
+ inputs=[ParameterSpec(name="document", type="markdown")],
+ ),
+ ]
+ ),
+ ]
+
+ class FakeExtractor:
+ async def extract_from_root(self, *args, **kwargs):
+ del args, kwargs
+ return results.pop(0)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.FingerprintExtractor",
+ lambda **kwargs: FakeExtractor(),
+ )
+ graph_dir = tmp_path / "graph"
+ config = symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(tmp_path / "skills"),
+ "graph_dir": str(graph_dir),
+ }
+ }
+ )
+
+ await build_graph(
+ tmp_path / "skills",
+ graph_dir,
+ force=True,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+ current_before = (graph_dir / "current.json").read_bytes()
+
+ def fail_staged_write(result, path):
+ path = Path(path)
+ if path.parent.name == "versions":
+ raise failure
+ real_write_extraction_result(result, path)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.build.write_extraction_result",
+ fail_staged_write,
+ )
+ with pytest.raises(type(failure), match="prepare failed" if str(failure) else None):
+ await build_graph(
+ tmp_path / "skills",
+ graph_dir,
+ force=True,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+
+ assert (graph_dir / "current.json").read_bytes() == current_before
+ resume_from = latest_incomplete_build(graph_dir)
+ assert resume_from is not None
+ assert (resume_from / "artifacts").is_dir()
+
+
+def test_incompatible_graph_pointer_forces_first_public_rebuild(tmp_path):
+ graph_dir = tmp_path / "graph"
+ version_dir = graph_dir / "versions" / "old"
+ version_dir.mkdir(parents=True)
+ (version_dir / "graph.json").write_text("{}", encoding="utf-8")
+ (graph_dir / "current.json").write_text(
+ json.dumps(
+ {
+ "schema_version": "Symphony-graph-pointer-v0",
+ "version": "old",
+ "path": "versions/old",
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ assert graph_exists(graph_dir) is False
+
+
+def _write_legacy_score_layout(graph_dir: Path) -> None:
+ """Real pre-rename layout: score pointer v1 + score_state.json artifacts."""
+
+ version_dir = graph_dir / "versions" / "20260101"
+ version_dir.mkdir(parents=True)
+ (version_dir / "skill_graph.json").write_text("{}", encoding="utf-8")
+ (version_dir / "score_state.json").write_text(
+ json.dumps({"schema_version": 1, "active_entries": {}}),
+ encoding="utf-8",
+ )
+ (graph_dir / "current.json").write_text(
+ json.dumps(
+ {
+ "schema_version": "Symphony-score-pointer-v1",
+ "version": "20260101",
+ "path": "versions/20260101",
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+def test_legacy_score_pointer_layout_is_not_graph_exists(tmp_path):
+ graph_dir = tmp_path / "graph"
+ _write_legacy_score_layout(graph_dir)
+
+ assert graph_exists(graph_dir) is False
+
+
+async def test_legacy_score_layout_rebuild_publishes_graph_pointer(
+ monkeypatch,
+ tmp_path,
+ fake_graph_llm,
+):
+ graph_dir = tmp_path / "graph"
+ _write_legacy_score_layout(graph_dir)
+ (tmp_path / "skills").mkdir()
+ config = symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(tmp_path / "skills"),
+ "graph_dir": str(graph_dir),
+ }
+ }
+ )
+
+ result = await build_graph(
+ tmp_path / "skills",
+ graph_dir,
+ force=True,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+
+ current = json.loads((graph_dir / "current.json").read_text(encoding="utf-8"))
+ assert result.success is True
+ assert current["schema_version"] == "1.0"
+ assert graph_exists(graph_dir) is True
+
+
+ "pointer_payload",
+ [
+ '{"schema_version": "1.0", "vers',
+ '{"schema_version": "1.0"}',
+ "123",
+ "null",
+ '"abc"',
+ "[1, 2]",
+ ],
+ ids=[
+ "truncated-json",
+ "missing-version",
+ "int-json",
+ "null-json",
+ "string-json",
+ "list-json",
+ ],
+)
+async def test_corrupt_current_json_self_heals_via_rebuild(
+ monkeypatch,
+ tmp_path,
+ fake_graph_llm,
+ pointer_payload,
+):
+ graph_dir = tmp_path / "graph"
+ graph_dir.mkdir(parents=True)
+ (graph_dir / "current.json").write_text(pointer_payload, encoding="utf-8")
+ (tmp_path / "skills").mkdir()
+ config = symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(tmp_path / "skills"),
+ "graph_dir": str(graph_dir),
+ }
+ }
+ )
+
+ assert graph_exists(graph_dir) is False
+ assert resolve_graph_artifact_dir(graph_dir) == graph_dir.resolve()
+
+ result = await build_graph(
+ tmp_path / "skills",
+ graph_dir,
+ force=True,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+
+ current = json.loads((graph_dir / "current.json").read_text(encoding="utf-8"))
+ assert result.success is True
+ assert current["schema_version"] == "1.0"
+ assert graph_exists(graph_dir) is True
+
+
+async def test_empty_skills_root_builds_empty_graph(tmp_path, fake_graph_llm):
+ (tmp_path / "skills").mkdir()
+ graph_dir = tmp_path / "graph"
+ config = symphony_config_from_dict(
+ {
+ "paths": {
+ "skills_root": str(tmp_path / "skills"),
+ "graph_dir": str(graph_dir),
+ }
+ }
+ )
+
+ result = await build_graph(
+ tmp_path / "skills",
+ graph_dir,
+ force=True,
+ schema_extractor=object(),
+ io_name_resolver=object(),
+ symphony_config=config,
+ )
+
+ current = json.loads((graph_dir / "current.json").read_text(encoding="utf-8"))
+ graph = json.loads((graph_dir / current["artifact"]).read_text(encoding="utf-8"))
+ assert result.success is True
+ assert graph["capabilities"] == []
+ assert graph_exists(graph_dir) is True
+ assert (
+ graph_status(
+ tmp_path / "skills",
+ graph_dir,
+ symphony_config=config,
+ ).stale
+ is False
+ )
+
+
+ "resolved_count",
+ [float("nan"), float("inf"), float("-inf"), "not-a-number"],
+)
+def test_force_relation_cache_counts_fall_back_for_invalid_metadata(resolved_count):
+ graph_payload = {
+ "edges": [{"source": "writer", "target": "reviewer"}],
+ "config": {
+ "llm": {
+ "relation_cache": {
+ "reused_count": float("inf"),
+ "resolved_count": resolved_count,
+ }
+ }
+ },
+ }
+
+ assert _relation_cache_counts(graph_payload, force=True) == (0, 1)
+
+
+def test_runtime_cache_rebuilds_when_default_llm_changes(monkeypatch, tmp_path):
+ config = _config(tmp_path)
+ current = {
+ "value": LLMConfig(
+ model="model-a",
+ model_client_config={
+ "api_key": "secret-a",
+ "api_base": "https://a.example/v1",
+ "client_provider": "openai",
+ },
+ )
+ }
+ created = []
+
+ class FakeRuntime:
+ def __init__(self, **kwargs):
+ created.append(kwargs)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.LLMConfig.from_default_model",
+ lambda: current["value"],
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.model_from_config",
+ lambda value: ("model", value.model),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.SymphonyRuntime",
+ FakeRuntime,
+ )
+ service = SwarmSymphonyService()
+
+ first = service._runtime_for(config)
+ assert service._runtime_for(config) is first
+ current["value"] = LLMConfig(
+ model="model-b",
+ model_client_config={
+ "api_key": "secret-b",
+ "api_base": "https://b.example/v1",
+ "client_provider": "openai",
+ },
+ )
+ second = service._runtime_for(config)
+
+ assert second is not first
+ assert len(created) == 2
+ current["value"] = LLMConfig(
+ model="model-b",
+ model_client_config={
+ "api_key": "secret-c",
+ "api_base": "https://b.example/v1",
+ "client_provider": "openai",
+ },
+ )
+ third = service._runtime_for(config)
+
+ assert third is not second
+ assert len(created) == 3
+ signature_text = repr(llm_config_signature(current["value"]))
+ assert "secret-c" not in signature_text
+ assert "https://b.example" not in signature_text
+
+
+def test_production_uses_only_stable_openjiuwen_symphony_imports():
+ package_root = Path(__file__).parents[3] / "jiuwenswarm"
+ allowed_symbols = {
+ "ArtifactSpec",
+ "CapabilityFingerprint",
+ "OrchestrationConfig",
+ "ParameterSpec",
+ "SymphonyRuntime",
+ }
+ offenders = []
+ for path in package_root.rglob("*.py"):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ violation = _forbidden_symphony_import(
+ node,
+ allowed_symbols=allowed_symbols,
+ )
+ if violation:
+ offenders.append(
+ f"{path.relative_to(package_root)}:{node.lineno}:{violation}"
+ )
+
+ assert offenders == []
+
+
+def test_static_import_guard_detects_openjiuwen_symphony_alias_bypass():
+ bypass = ast.parse("from openjiuwen import symphony as hidden").body[0]
+ dotted = ast.parse("import openjiuwen.symphony.orchestration.graph as hidden").body[
+ 0
+ ]
+ legal = ast.parse("from openjiuwen import core as public_core").body[0]
+ stable_module = ast.parse("import openjiuwen.symphony as stable").body[0]
+
+ assert _forbidden_symphony_import(bypass, allowed_symbols=set())
+ assert _forbidden_symphony_import(dotted, allowed_symbols=set())
+ assert not _forbidden_symphony_import(legal, allowed_symbols=set())
+ assert not _forbidden_symphony_import(stable_module, allowed_symbols=set())
+
+
+async def test_build_progress_is_ordered_and_drained_before_close(tmp_path):
+ events = []
+
+ async def progress(event):
+ await asyncio.sleep(0)
+ events.append(event["event"])
+
+ dispatcher = _OrderedProgressDispatcher(progress)
+ dispatcher.start()
+ build_logger = _BuildProcessLogger(
+ tmp_path / "build_log.jsonl",
+ progress=dispatcher,
+ )
+ build_logger.record("scan.start")
+ build_logger.record("scan.done")
+ await dispatcher.close()
+
+ assert events == ["scan.start", "scan.done"]
+ assert dispatcher.worker is None
+
+
+async def test_build_progress_callback_failure_does_not_drop_later_events(tmp_path):
+ attempted = []
+
+ async def progress(event):
+ attempted.append(event["event"])
+ if event["event"] == "scan.start":
+ raise RuntimeError("progress transport failed")
+
+ dispatcher = _OrderedProgressDispatcher(progress)
+ dispatcher.start()
+ build_logger = _BuildProcessLogger(
+ tmp_path / "build_log.jsonl",
+ progress=dispatcher,
+ )
+ build_logger.record("scan.start")
+ build_logger.record("scan.done")
+
+ await dispatcher.close()
+
+ assert attempted == ["scan.start", "scan.done"]
+ assert dispatcher.worker is None
+
+
+async def test_threaded_progress_enqueue_is_acknowledged_before_worker_shutdown():
+ events = []
+
+ async def progress(event):
+ events.append(event["event"])
+
+ dispatcher = _OrderedProgressDispatcher(progress)
+ dispatcher.start()
+ enqueued = Event()
+
+ def send_from_thread():
+ dispatcher.enqueue({"event": "thread.event"})
+ enqueued.set()
+
+ thread = Thread(target=send_from_thread)
+ thread.start()
+ assert enqueued.wait(timeout=1.0)
+
+ await dispatcher.close()
+ thread.join(timeout=1.0)
+
+ assert not thread.is_alive()
+ assert events == ["thread.event"]
+ assert dispatcher.queue.empty()
+ assert dispatcher.worker is None
+
+ late_thread = Thread(target=lambda: dispatcher.enqueue({"event": "late.event"}))
+ late_thread.start()
+ late_thread.join(timeout=1.0)
+ await asyncio.sleep(0)
+
+ assert events == ["thread.event"]
+ assert dispatcher.queue.empty()
+
+
+async def test_abort_cancels_pending_thread_delivery_and_clears_queue():
+ async def blocking_progress(_event):
+ await asyncio.Event().wait()
+
+ dispatcher = _OrderedProgressDispatcher(blocking_progress)
+ dispatcher.start()
+ enqueued = Event()
+
+ def send_from_thread():
+ dispatcher.enqueue({"event": "thread.event"})
+ enqueued.set()
+
+ thread = Thread(target=send_from_thread)
+ thread.start()
+ assert enqueued.wait(timeout=1.0)
+
+ await asyncio.wait_for(dispatcher.abort(), timeout=0.5)
+ thread.join(timeout=1.0)
+
+ assert not thread.is_alive()
+ assert dispatcher.worker is None
+ assert dispatcher.queue.empty()
+ assert not _named_progress_tasks()
+
+
+async def test_refresh_keeps_build_guard_until_slow_progress_is_drained(
+ monkeypatch,
+ tmp_path,
+):
+ config = _config(tmp_path)
+ callback_entered = asyncio.Event()
+ release_callback = asyncio.Event()
+ first_events = []
+ second_events = []
+
+ async def first_progress(event):
+ first_events.append(event["event"])
+ if event["event"] == "update.start":
+ callback_entered.set()
+ await release_callback.wait()
+
+ async def second_progress(event):
+ second_events.append(event["event"])
+
+ async def fake_build_graph(*args, **kwargs):
+ del args, kwargs
+ return SimpleNamespace(to_dict=lambda: {"success": True, "version": "v1"})
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.LLMConfig.from_default_model",
+ lambda: object(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.service_build_graph",
+ fake_build_graph,
+ )
+ service = SwarmSymphonyService()
+
+ first = asyncio.create_task(service.refresh_graph(progress=first_progress))
+ await callback_entered.wait()
+ await asyncio.sleep(0)
+
+ second = await service.refresh_graph(progress=second_progress)
+
+ assert second["success"] is False
+ assert "正在运行" in second["detail"]
+ assert second_events == []
+ assert not first.done()
+
+ release_callback.set()
+ first_result = await first
+
+ assert first_result["success"] is True
+ assert first_events == ["update.start", "update.done"]
+
+
+async def test_start_refresh_graph_runs_in_background_and_reuses_active_task(
+ monkeypatch,
+ tmp_path,
+):
+ config = _config(tmp_path)
+ build_entered = asyncio.Event()
+ release_build = asyncio.Event()
+
+ async def fake_build_graph(*args, **kwargs):
+ del args, kwargs
+ build_entered.set()
+ await release_build.wait()
+ return SimpleNamespace(to_dict=lambda: {"success": True, "version": "v1"})
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.LLMConfig.from_default_model",
+ lambda: object(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.service_build_graph",
+ fake_build_graph,
+ )
+ service = SwarmSymphonyService()
+
+ started = await service.start_refresh_graph(force=True)
+ first_task = service._active_build_task
+
+ assert started["success"] is True
+ assert started["background"] is True
+ assert started["build_status"] == "running"
+ assert started["build_progress"]["status"] == "running"
+ assert first_task is not None
+ assert build_entered.is_set() is False
+
+ await build_entered.wait()
+ reused = await service.start_refresh_graph(force=False)
+
+ assert reused["success"] is True
+ assert reused["background"] is True
+ assert reused["build_status"] == "running"
+ assert service._active_build_task is first_task
+
+ release_build.set()
+ result = await asyncio.wait_for(first_task, timeout=0.5)
+
+ assert result["success"] is True
+ assert service._active_build_task is None
+
+
+async def test_cancel_build_without_active_task_returns_idle(monkeypatch, tmp_path):
+ config = _config(tmp_path)
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+
+ result = await SwarmSymphonyService().cancel_build()
+
+ assert result["success"] is False
+ assert result["cancelled"] is False
+ assert result["build_status"] == "idle"
+
+
+async def test_direct_cancel_aborts_blocked_progress_and_releases_guard(
+ monkeypatch,
+ tmp_path,
+):
+ config = _config(tmp_path)
+ callback_entered = asyncio.Event()
+ callback_cancelled = asyncio.Event()
+ build_entered = asyncio.Event()
+
+ async def blocking_progress(_event):
+ callback_entered.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ callback_cancelled.set()
+
+ async def fake_build_graph(*args, **kwargs):
+ del args, kwargs
+ build_entered.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.LLMConfig.from_default_model",
+ lambda: object(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.service_build_graph",
+ fake_build_graph,
+ )
+ service = SwarmSymphonyService()
+ task = asyncio.create_task(service.refresh_graph(progress=blocking_progress))
+ await callback_entered.wait()
+ await build_entered.wait()
+
+ task.cancel("test.direct_cancel")
+ result = await asyncio.wait_for(task, timeout=0.5)
+
+ assert result["success"] is False
+ assert result["cancelled"] is True
+ assert result["build_status"] == "cancelled"
+ assert callback_cancelled.is_set()
+ assert service._active_build_task is None
+ assert not _named_progress_tasks()
+
+
+async def test_cancel_build_aborts_blocked_progress_and_releases_guard(
+ monkeypatch,
+ tmp_path,
+):
+ config = _config(tmp_path)
+ callback_entered = asyncio.Event()
+ build_entered = asyncio.Event()
+
+ async def blocking_progress(_event):
+ callback_entered.set()
+ await asyncio.Event().wait()
+
+ async def fake_build_graph(*args, **kwargs):
+ del args, kwargs
+ build_entered.set()
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.LLMConfig.from_default_model",
+ lambda: object(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.service_build_graph",
+ fake_build_graph,
+ )
+ service = SwarmSymphonyService()
+ task = asyncio.create_task(service.refresh_graph(progress=blocking_progress))
+ await callback_entered.wait()
+ await build_entered.wait()
+
+ cancelled = await asyncio.wait_for(service.cancel_build(), timeout=0.5)
+ build_result = await asyncio.wait_for(task, timeout=0.5)
+
+ assert cancelled["success"] is True
+ assert cancelled["cancelled"] is True
+ assert cancelled["build_status"] == "cancelled"
+ assert build_result["success"] is False
+ assert build_result["cancelled"] is True
+ assert build_result["build_status"] == "cancelled"
+ assert service._active_build_task is None
+ assert not _named_progress_tasks()
+
+
+async def test_cancel_build_returns_before_uninterruptible_section_exits(
+ monkeypatch,
+ tmp_path,
+):
+ config = _config(tmp_path)
+ build_entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def slow_to_cancel_build(*args, **kwargs):
+ del args, kwargs
+ build_entered.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ # 模拟 to_thread/LLM 区段:收到取消后仍需一段时间才能退出
+ await asyncio.wait_for(release.wait(), timeout=30)
+ raise
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.LLMConfig.from_default_model",
+ lambda: object(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.service_build_graph",
+ slow_to_cancel_build,
+ )
+ service = SwarmSymphonyService()
+ task = asyncio.create_task(service.refresh_graph())
+ await build_entered.wait()
+
+ loop = asyncio.get_running_loop()
+ started = loop.time()
+ cancelled = await asyncio.wait_for(service.cancel_build(), timeout=6.5)
+ elapsed = loop.time() - started
+
+ assert cancelled["success"] is True
+ assert cancelled["cancelled"] is True
+ assert cancelled["build_status"] == "cancelled"
+ assert elapsed < 6.5
+ assert not task.done()
+
+ release.set()
+ build_result = await asyncio.wait_for(task, timeout=5)
+
+ assert build_result["success"] is False
+ assert build_result["build_status"] == "cancelled"
+
+
+async def test_graph_status_repairs_interrupted_build_log(monkeypatch, tmp_path):
+ config = _config(tmp_path)
+ graph_dir = config.paths.graph_dir
+ _BuildProcessLogger(graph_dir / "build_log.jsonl").record("update.start")
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.graph_status",
+ lambda *args, **kwargs: SimpleNamespace(
+ to_dict=lambda: {"success": True, "exists": False, "stale": True}
+ ),
+ )
+
+ result = await SwarmSymphonyService().graph_status()
+
+ assert result["build_progress"]["status"] == "cancelled"
+ assert result["build_log"][-1]["stage"] == "update.cancelled"
+ assert result["build_log"][-1]["reason"] == "process_interrupted"
+
+
+async def test_refresh_build_failure_returns_business_payload(monkeypatch, tmp_path):
+ config = _config(tmp_path)
+
+ async def fail_build(*args, **kwargs):
+ del args, kwargs
+ raise RuntimeError("LLM unavailable")
+
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.LLMConfig.from_default_model",
+ lambda: object(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.service_build_graph",
+ fail_build,
+ )
+
+ result = await SwarmSymphonyService().refresh_graph()
+
+ assert result["success"] is False
+ assert "LLM unavailable" in result["detail"]
+ assert result["build_progress"]["status"] == "error"
+
+
+def _named_progress_tasks():
+ return [
+ task
+ for task in asyncio.all_tasks()
+ if task.get_name() == "symphony-build-progress"
+ ]
+
+
+def _extraction_result(fingerprints):
+ return SimpleNamespace(
+ fingerprints=fingerprints,
+ diagnostics=[],
+ normalization_decisions=[],
+ llm_token_usage={},
+ reused_count=0,
+ extracted_count=len(fingerprints),
+ folders=[],
+ current_hashes={},
+ fingerprints_by_path={},
+ removed_paths=set(),
+ io_name_vocab={},
+ )
diff --git a/tests/unit_tests/symphony/test_extension.py b/tests/unit_tests/symphony/test_extension.py
deleted file mode 100644
index 37f70a3bfe..0000000000
--- a/tests/unit_tests/symphony/test_extension.py
+++ /dev/null
@@ -1,1299 +0,0 @@
-import asyncio
-import json
-from pathlib import Path
-from types import SimpleNamespace
-
-import pytest
-
-from jiuwenswarm.extensions.symphony.extension import (
- SYMPHONY_BUILD_SCORE,
- SYMPHONY_GRAPH,
- SYMPHONY_PAUSE_BUILD,
- SYMPHONY_PLAN,
- SYMPHONY_SCORE_STATUS,
- SymphonyExtension,
- _BuildProcessLogger,
- _build_log_payload,
- _build_presentation,
- _latest_effective_build_log_entry,
-)
-from jiuwenswarm.common.schema.agent import AgentRequest
-from jiuwenswarm.common.schema.message import ReqMethod
-from jiuwenswarm.extensions.registry import ExtensionRegistry
-from jiuwenswarm.symphony.config import symphony_config_from_dict
-from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
-
-_REAL_SCORE_STATUS = SymphonyExtension.score_status
-
-
[email protected](autouse=True)
-def _use_chinese_preferred_language(monkeypatch):
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.get_config",
- lambda: {"preferred_language": "zh"},
- )
-
- async def fresh_score(self, params=None, request=None):
- del self, params, request
- return {"success": True, "exists": True, "stale": False}
-
- monkeypatch.setattr(SymphonyExtension, "score_status", fresh_score)
-
-
-class _Registry:
- def __init__(self):
- self.handlers = {}
-
- def register_rpc_handler(self, method, handler):
- self.handlers[method] = handler
-
-
-def test_extension_registers_rpc_handlers():
- registry = _Registry()
-
- SymphonyExtension().register(registry)
-
- assert set(registry.handlers) == {
- SYMPHONY_SCORE_STATUS,
- SYMPHONY_BUILD_SCORE,
- SYMPHONY_PAUSE_BUILD,
- SYMPHONY_GRAPH,
- SYMPHONY_PLAN,
- }
-
-
-def test_symphony_skill_metadata():
- skill_md = Path(
- "jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md"
- )
- content = skill_md.read_text(encoding="utf-8")
-
- assert "name: symphony-assistant" in content
- assert "source of truth" in content
- assert "allowed_tools:" in content
- assert "- symphony_compose_score" in content
- assert "- symphony_read_score" in content
- assert "- symphony_refresh_score" in content
- assert "skill capabilities, skill chaining, skill ordering" in content
- assert "use `search_skill` to discover external skills" in content
- assert "call `symphony_refresh_score`" in content
- assert "currently installed skills" not in content
- assert "instead of inventing them" in content
-
-
-def test_extension_requires_query():
- result = asyncio.run(SymphonyExtension().plan({"query": ""}))
-
- assert result["success"] is False
- assert "query is required" in result["detail"]
-
-
-def test_plan_refreshes_stale_score_in_extension(monkeypatch, tmp_path):
- extension = SymphonyExtension()
- calls = []
-
- async def stale_status(params=None, request=None):
- del params, request
- calls.append("status")
- return {"success": True, "exists": True, "stale": True}
-
- async def build_score(params=None, request=None):
- del params, request
- calls.append("build")
- return {"success": True}
-
- async def plan_from_score(*args, **kwargs):
- del args, kwargs
- calls.append("plan")
- return {"status": "ready", "recommended_plans": []}
-
- monkeypatch.setattr(extension, "score_status", stale_status)
- monkeypatch.setattr(extension, "build_score", build_score)
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.plan_from_score",
- plan_from_score,
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {"paths": {"score_dir": str(tmp_path / "score")}}
- ),
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",
- lambda: object(),
- )
-
- result = asyncio.run(extension.plan({"query": "compose"}))
-
- assert calls == ["status", "build", "plan"]
- assert result["score_build"] == {"success": True, "rebuilt": True}
-
-
-def test_plan_uses_llm_plan_from_score(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- llm_config = object()
- seen = {}
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.get_config",
- lambda: {"preferred_language": "zh"},
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {"paths": {"score_dir": str(configured_score_dir)}}
- ),
- )
- 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: llm_config,
- )
-
- async def fake_plan_from_score(score_dir, query, received_llm_config, **kwargs):
- seen["score_dir"] = score_dir
- seen["query"] = query
- seen["llm_config"] = received_llm_config
- seen["kwargs"] = kwargs
- return {
- "status": "ready",
- "recommended_plans": [
- {
- "title": "Plan",
- "status": "ready",
- "steps": [{"skill_id": "skill-1", "skill_name": "Skill 1"}],
- }
- ],
- "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 result["mode"] == "fast"
- assert result["direct_display"] is True
- assert "display_format" not in result
- assert seen["score_dir"] == configured_score_dir.resolve()
- assert seen["query"] == "do work"
- 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):
- 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)}}
- ),
- )
- 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(*args, **kwargs):
- del args
- 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", "language": "en"})
- )
-
- assert result["language"] == "cn"
- assert result["content"].startswith("## Symphony 编排计划")
- assert seen["language"] == "cn"
-
-
-def test_plan_resolves_language_from_runtime_config(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- seen = {}
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.get_config",
- lambda: {"preferred_language": "en"},
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {"paths": {"score_dir": str(configured_score_dir)}}
- ),
- )
- 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(*args, **kwargs):
- del args
- 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["language"] == "en"
- 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 = {}
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {"paths": {"score_dir": str(configured_score_dir)}}
- ),
- )
- 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["orchestration_config"] = kwargs["orchestration_config"]
- 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", "mode": "fast"}))
-
- assert result["success"] is True
- assert result["mode"] == "fast"
- assert seen["orchestration_config"].mode == "fast"
-
-
-def test_plan_passes_candidate_skill_ids(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)}}
- ),
- )
- 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(),
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_execution_disabled_skills",
- lambda: ["skill-b"],
- )
-
- async def fake_plan_from_score(score_dir, query, received_llm_config, **kwargs):
- del score_dir, query, received_llm_config
- seen["candidate_skill_ids"] = kwargs["candidate_skill_ids"]
- seen["disabled_skill_names"] = kwargs["disabled_skill_names"]
- 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",
- "candidate_skill_ids": [" skill-a ", "", "skill-a", "skill-b"],
- }
- )
- )
-
- assert result["success"] is True
- assert seen["candidate_skill_ids"] == ["skill-a", "skill-b"]
- assert seen["disabled_skill_names"] == ["skill-b"]
-
-
-def test_graph_filters_disabled_skills_from_visual_payload(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- artifacts = ScoreArtifacts(
- score_dir=configured_score_dir,
- manifest={},
- skills=[
- {"id": "skill-a", "name": "Alpha Skill"},
- {"id": "skill-b", "name": "Beta Skill"},
- {"id": "skill-c", "name": "Gamma Skill"},
- ],
- graph={
- "nodes": [
- {"id": "skill:skill-a", "type": "skill"},
- {"id": "skill:skill-b", "type": "skill"},
- {"id": "skill:skill-c", "type": "skill"},
- ],
- "edges": [
- {"source": "skill:skill-a", "target": "skill:skill-b"},
- {"source": "skill:skill-a", "target": "skill:skill-c"},
- {"source": "skill:skill-b", "target": "skill:skill-c"},
- ],
- },
- lookup={
- "by_output": {
- "draft": ["skill-a"],
- "review": ["skill-b"],
- },
- "neighbors": {
- "skill-a": ["skill-b", "skill-c"],
- "skill-b": ["skill-c"],
- },
- "by_text_term": {
- "alpha": ["skill-a", "skill-b"],
- "beta": ["skill-b"],
- },
- },
- )
- 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: artifacts,
- )
- monkeypatch.setattr(
- "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({}))
-
- assert result["success"] is True
- assert [skill["id"] for skill in result["skills"]] == ["skill-a", "skill-c"]
- assert [node["id"] for node in result["graph"]["nodes"]] == [
- "skill:skill-a",
- "skill:skill-c",
- ]
- assert result["graph"]["edges"] == [
- {
- "source": "skill:skill-a",
- "target": "skill:skill-c",
- "runtime_weight": 1.15,
- }
- ]
- assert result["score_lookup"] == {
- "by_output": {"draft": ["skill-a"]},
- "neighbors": {"skill-a": ["skill-c"]},
- "by_text_term": {"alpha": ["skill-a"]},
- }
-
-
-def test_plan_uses_requested_beam_mode(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)}}
- ),
- )
- 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["orchestration_config"] = kwargs["orchestration_config"]
- 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", "mode": "beam"}))
-
- assert result["success"] is True
- assert result["mode"] == "beam"
- assert seen["orchestration_config"].mode == "beam"
-
-
-def test_plan_streams_beam_progress_events(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- events = []
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {"score_dir": str(configured_score_dir)},
- "orchestration": {"mode": "beam"},
- }
- ),
- )
- 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
- await kwargs["progress_callback"](
- {
- "event": "started",
- "language": "en",
- "round_index": 0,
- "graph": {"nodes": [], "edges": []},
- }
- )
- return {
- "status": "ready",
- "recommended_plans": [],
- "execution_graph": {"edges": []},
- "beam_search": {"graph": {"nodes": [], "edges": []}},
- }
-
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.plan_from_score",
- fake_plan_from_score,
- )
- request = SimpleNamespace(
- metadata={
- "symphony_progress_callback": lambda event: events.append(event),
- }
- )
-
- result = asyncio.run(
- SymphonyExtension().plan({"query": "do work", "mode": "beam"}, request)
- )
-
- assert result["success"] is True
- assert events == [
- {
- "event": "started",
- "language": "en",
- "round_index": 0,
- "graph": {"nodes": [], "edges": []},
- }
- ]
-
-
-def test_plan_presentation_uses_recommended_plan(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {"paths": {"score_dir": str(configured_score_dir)}}
- ),
- )
- 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, kwargs
- return {
- "recommended_plans": [
- {
- "title": "Recommended Plan",
- "status": "ready",
- "reason": "Best match.",
- "steps": [
- {"skill_id": "skill-1", "name": "Skill 1"},
- {"skill_id": "skill-2", "name": "Skill 2"},
- ],
- "can_feed_edges": [
- {
- "source_id": "skill-1",
- "target_id": "skill-2",
- "confidence": 0.91,
- }
- ],
- "missing_inputs": [
- {
- "skill_id": "imap-smtp-email",
- "name": "收件邮箱地址",
- "type": "unknown",
- "reason": "需要用户提供收件邮箱地址才能发送邮件",
- }
- ],
- }
- ],
- "execution_graph": {
- "edges": [
- {
- "source": "skill-1",
- "target": "skill-2",
- "confidence": 0.91,
- }
- ]
- },
- "beam_search": {
- "language": "cn",
- "round_index": 1,
- "graph": {
- "nodes": [
- {
- "id": "skill-1",
- "label": "Skill 1",
- "status": "final",
- "seed": True,
- },
- {
- "id": "skill-2",
- "label": "Skill 2",
- "status": "final",
- "seed": False,
- },
- {
- "id": "skill-3",
- "label": "Skill 3",
- "status": "rejected",
- "seed": False,
- },
- ],
- "edges": [
- {
- "source": "skill-1",
- "target": "skill-2",
- "status": "final",
- },
- {
- "source": "skill-1",
- "target": "skill-3",
- "status": "rejected",
- },
- ],
- },
- },
- }
-
- 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 "## Recommended Plan" in result["content"]
- assert "markdown" not in result
- assert result["direct_display"] is True
- assert "display_format" not in result
- assert "Status:" not in result["content"]
- assert result["result"]["recommended_plans"][0]["status"] == "ready"
- assert "Best match." in result["content"]
- assert result["content"].endswith("是否按照上述编排结果执行?")
- assert "## Beam search" not in result["content"]
- assert "classDef rejected" not in result["content"]
- assert "score `0.91`" not in result["content"]
- assert "strong can_feed match" not in result["content"]
- assert "Missing inputs:" not in result["content"]
- assert "收件邮箱地址" not in result["content"]
- assert "imap-smtp-email" not in result["content"]
- assert result["result"]["recommended_plans"][0]["missing_inputs"] == [
- {
- "skill_id": "imap-smtp-email",
- "name": "收件邮箱地址",
- "type": "unknown",
- "reason": "需要用户提供收件邮箱地址才能发送邮件",
- }
- ]
- assert (
- result["result"]["recommended_plans"][0]["can_feed_edges"][0]["confidence"]
- == 0.91
- )
- assert 'N1["Skill 1"]' in result["content"]
- assert "N1 --> N2" in result["content"]
-
-
-def test_plan_presentation_does_not_ask_to_execute_empty_plan():
- presentation = _build_presentation(
- {"recommended_plans": [{"title": "Empty Plan", "status": "ready", "steps": []}]}
- )
-
- assert "是否按照上述编排结果执行?" not in presentation["markdown"]
-
-
-def test_plan_presentation_asks_to_execute_in_english():
- presentation = _build_presentation(
- {
- "recommended_plans": [
- {
- "title": "Recommended Plan",
- "status": "ready",
- "steps": [{"skill_id": "skill-1"}],
- }
- ]
- },
- language="en",
- )
-
- assert presentation["markdown"].endswith(
- "Would you like to proceed with the orchestration plan above?"
- )
-
-
-def test_plan_presentation_does_not_ask_to_execute_no_plan():
- presentation = _build_presentation(
- {"recommended_plans": [{"title": "No Plan", "status": "no_plan", "steps": []}]}
- )
-
- assert "是否按照上述编排结果执行?" not in presentation["markdown"]
-
-
-def test_build_score_awaits_service_and_records_build_log(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- skills_root = tmp_path / "skills"
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(skills_root),
- "score_dir": str(configured_score_dir),
- }
- }
- ),
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",
- lambda: object(),
- )
- seen = {}
-
- class _Result:
- @staticmethod
- def to_dict():
- return {
- "success": True,
- "score_dir": str(configured_score_dir.resolve()),
- "skill_count": 1,
- "reused_count": 0,
- "extracted_count": 1,
- "removed_count": 0,
- "edge_count": 0,
- "diagnostics_count": 0,
- }
-
- async def fake_build_score(*args, **kwargs):
- seen["args"] = args
- seen["kwargs"] = kwargs
- kwargs["build_log"](
- "fingerprint.extract.start", current=1, total=1, path="skill-1"
- )
- return _Result()
-
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.service_build_score",
- fake_build_score,
- )
-
- result = asyncio.run(SymphonyExtension().build_score({}))
-
- assert result["success"] is True
- assert result["score_dir"] == str(configured_score_dir.resolve())
- assert seen["args"][0] == skills_root.resolve()
- assert seen["args"][1] == configured_score_dir.resolve()
- assert seen["kwargs"]["force"] is False
- assert result["build_log"][-1]["stage"] == "update.done"
-
-
-def test_build_score_accepts_force_rebuild_param(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- skills_root = tmp_path / "skills"
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(skills_root),
- "score_dir": str(configured_score_dir),
- }
- }
- ),
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",
- lambda: object(),
- )
- seen = {}
-
- class _Result:
- @staticmethod
- def to_dict():
- return {
- "success": True,
- "score_dir": str(configured_score_dir.resolve()),
- "skill_count": 1,
- "reused_count": 0,
- "extracted_count": 1,
- "removed_count": 0,
- "edge_count": 0,
- "diagnostics_count": 0,
- }
-
- async def fake_build_score(*args, **kwargs):
- seen["args"] = args
- seen["kwargs"] = kwargs
- return _Result()
-
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.service_build_score",
- fake_build_score,
- )
-
- result = asyncio.run(SymphonyExtension().build_score({"force": True}))
-
- assert result["success"] is True
- assert seen["args"][0] == skills_root.resolve()
- assert seen["kwargs"]["force"] is True
-
-
-def test_pause_build_cancels_active_build(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(tmp_path / "skills"),
- "score_dir": str(configured_score_dir),
- }
- }
- ),
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",
- lambda: object(),
- )
-
- async def run_case():
- started = asyncio.Event()
-
- async def fake_build_score(*args, **kwargs):
- del args
- kwargs["build_log"]("graph.resolve.start")
- started.set()
- await asyncio.sleep(30)
-
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.service_build_score",
- fake_build_score,
- )
- extension = SymphonyExtension()
- build_task = asyncio.create_task(extension.build_score({}))
- await started.wait()
- pause_result = await extension.pause_build({})
- build_result = await build_task
- return pause_result, build_result
-
- pause_result, build_result = asyncio.run(run_case())
-
- assert pause_result["success"] is True
- assert pause_result["paused"] is True
- assert pause_result["build_progress"]["status"] == "paused"
- assert pause_result["build_log"][-1]["stage"] == "update.paused"
- assert build_result["success"] is False
- assert build_result["paused"] is True
- assert build_result["build_progress"]["status"] == "paused"
- assert build_result["build_log"][-1]["stage"] == "update.paused"
-
-
-def test_score_status_repairs_interrupted_build_after_restart(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- skills_root = tmp_path / "skills"
- logger = _BuildProcessLogger(configured_score_dir / "build_log.jsonl")
- logger.reset()
- logger.record("update.start")
- logger.record("graph.resolve.start")
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(skills_root),
- "score_dir": str(configured_score_dir),
- }
- }
- ),
- )
-
- class _Status:
- @staticmethod
- def to_dict():
- return {
- "success": True,
- "score_dir": str(configured_score_dir),
- "exists": False,
- "stale": True,
- }
-
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.score_status",
- lambda *args, **kwargs: _Status(),
- )
-
- async def run_case():
- extension = SymphonyExtension()
- first = await _REAL_SCORE_STATUS(extension, {})
- second = await _REAL_SCORE_STATUS(extension, {})
- return first, second
-
- first, second = asyncio.run(run_case())
-
- assert first["build_progress"]["status"] == "paused"
- assert first["build_log"][-1]["stage"] == "update.paused"
- assert first["build_log"][-1]["reason"] == "process_interrupted"
- assert second["build_progress"]["status"] == "paused"
- assert [
- entry["stage"] for entry in second["build_log"]
- ].count("update.paused") == 1
-
-
-def test_score_status_keeps_active_build_running(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- skills_root = tmp_path / "skills"
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(skills_root),
- "score_dir": str(configured_score_dir),
- }
- }
- ),
- )
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",
- lambda: object(),
- )
-
- class _Status:
- @staticmethod
- def to_dict():
- return {
- "success": True,
- "score_dir": str(configured_score_dir),
- "exists": False,
- "stale": True,
- }
-
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.score_status",
- lambda *args, **kwargs: _Status(),
- )
-
- async def run_case():
- started = asyncio.Event()
-
- async def fake_build_score(*args, **kwargs):
- del args
- kwargs["build_log"]("graph.resolve.start")
- started.set()
- await asyncio.sleep(30)
-
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.service_build_score",
- fake_build_score,
- )
- extension = SymphonyExtension()
- build_task = asyncio.create_task(extension.build_score({}))
- await started.wait()
- status = await _REAL_SCORE_STATUS(extension, {})
- await extension.pause_build({})
- await build_task
- return status
-
- result = asyncio.run(run_case())
-
- assert result["build_progress"]["status"] == "running"
- assert all(
- entry.get("reason") != "process_interrupted"
- for entry in result["build_log"]
- )
-
-
-def test_pause_build_repairs_interrupted_build_without_active_task(
- monkeypatch, tmp_path
-):
- configured_score_dir = tmp_path / "configured"
- logger = _BuildProcessLogger(configured_score_dir / "build_log.jsonl")
- logger.reset()
- logger.record("update.start")
- logger.record("graph.resolve.start")
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(tmp_path / "skills"),
- "score_dir": str(configured_score_dir),
- }
- }
- ),
- )
-
- async def run_case():
- extension = SymphonyExtension()
- first = await extension.pause_build({})
- second = await extension.pause_build({})
- return first, second
-
- result, repeated = asyncio.run(run_case())
-
- assert result["success"] is True
- assert result["paused"] is True
- assert result["build_progress"]["status"] == "paused"
- assert result["build_log"][-1]["stage"] == "update.paused"
- assert result["build_log"][-1]["reason"] == "process_interrupted"
- assert repeated["paused"] is True
- assert repeated["build_progress"]["status"] == "paused"
- assert [
- entry["stage"] for entry in repeated["build_log"]
- ].count("update.paused") == 1
-
-
-def test_graph_repairs_interrupted_build_without_status_request(
- monkeypatch, tmp_path
-):
- configured_score_dir = tmp_path / "configured"
- logger = _BuildProcessLogger(configured_score_dir / "build_log.jsonl")
- logger.reset()
- logger.record("update.start")
- logger.record("graph.resolve.start")
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(tmp_path / "skills"),
- "score_dir": str(configured_score_dir),
- }
- }
- ),
- )
-
- result = asyncio.run(SymphonyExtension().graph({}))
-
- assert result["success"] is False
- assert result["build_progress"]["status"] == "paused"
- assert result["build_log"][-1]["stage"] == "update.paused"
- assert result["build_log"][-1]["reason"] == "process_interrupted"
-
-
-def test_graph_returns_business_error_when_artifacts_missing(monkeypatch, tmp_path):
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(tmp_path / "skills"),
- "score_dir": str(tmp_path),
- }
- }
- ),
- )
-
- result = asyncio.run(SymphonyExtension().graph({"score_dir": str(tmp_path)}))
-
- assert result["success"] is False
- assert result["score_dir"] == str(tmp_path.resolve())
- assert "技能总谱不存在" in result["detail"]
- assert "Missing score artifact" in result["error"]
- assert result["build_progress"]["status"] == "idle"
-
-
-def test_graph_ignores_request_score_dir_param(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- legacy_score_dir = tmp_path / "legacy"
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(tmp_path / "skills"),
- "score_dir": str(configured_score_dir),
- }
- }
- ),
- )
-
- result = asyncio.run(
- SymphonyExtension().graph({"score_dir": str(legacy_score_dir)})
- )
-
- assert result["success"] is False
- assert result["score_dir"] == str(configured_score_dir.resolve())
-
-
-def test_graph_includes_orchestration_min_edge_confidence(monkeypatch, tmp_path):
- configured_score_dir = tmp_path / "configured"
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_symphony_config",
- lambda: symphony_config_from_dict(
- {
- "paths": {
- "skills_root": str(tmp_path / "skills"),
- "score_dir": str(configured_score_dir),
- },
- "orchestration": {"min_edge_confidence": 0.33},
- }
- ),
- )
-
- class _Artifacts:
- score_dir = configured_score_dir.resolve()
- manifest = {"created_at": "2026-06-14T00:00:00+00:00"}
- skills = {"skills": []}
- graph = {"nodes": [], "edges": []}
- lookup = {}
-
- monkeypatch.setattr(
- "jiuwenswarm.extensions.symphony.extension.load_score_artifacts",
- lambda score_dir: _Artifacts(),
- )
-
- result = asyncio.run(SymphonyExtension().graph({}))
-
- assert result["success"] is True
- assert result["orchestration_min_edge_confidence"] == 0.33
-
-
-def test_build_log_payload_reports_running_progress(tmp_path):
- logger = _BuildProcessLogger(tmp_path / "build_log.jsonl")
- logger.reset()
- logger.record("scan.start", skills_root=str(tmp_path / "skills"))
- logger.record("fingerprint.extract.start", current=2, total=4, path="demo")
-
- result = _build_log_payload(tmp_path)
-
- assert len(result["build_log"]) == 2
- assert result["build_log"][-1]["label"] == "提取技能指纹"
- assert result["build_progress"]["status"] == "running"
- assert result["build_progress"]["percent"] == 36
-
-
-def test_build_log_payload_clamps_progress_count_to_total(tmp_path):
- logger = _BuildProcessLogger(tmp_path / "build_log.jsonl")
- logger.reset()
- logger.record("fingerprint.extract.start", current=19, total=14, path="demo")
-
- result = _build_log_payload(tmp_path)
-
- assert result["build_log"][-1]["current"] == 14
- assert result["build_log"][-1]["total"] == 14
- assert result["build_progress"]["current"] == 14
- assert result["build_progress"]["total"] == 14
- assert result["build_progress"]["percent"] == 48
-
-
-def test_build_log_payload_terminal_stage_wins_over_late_progress(tmp_path):
- logger = _BuildProcessLogger(tmp_path / "build_log.jsonl")
- logger.reset()
- logger.record("fingerprint.extract.start", current=14, total=15, path="demo")
- logger.record("update.failed", error="bad model")
- logger.record("fingerprint.extract.start", current=15, total=15, path="late-demo")
-
- result = _build_log_payload(tmp_path)
-
- assert result["build_progress"]["status"] == "error"
- assert result["build_progress"]["stage"] == "update.failed"
- assert result["build_progress"]["label"] == "总谱构建失败"
- assert result["build_progress"]["percent"] == 100
-
-
-def test_latest_effective_build_log_entry_handles_empty_entries():
- assert _latest_effective_build_log_entry([]) == {}
-
-
-def test_build_log_payload_includes_manifest_token_usage(tmp_path):
- usage = {
- "total": {
- "request_count": 2,
- "prompt_tokens": 106436,
- "completion_tokens": 496,
- "total_tokens": 106932,
- },
- "by_stage": {},
- "by_operation": {},
- "records": [],
- }
- (tmp_path / "score_manifest.json").write_text(
- json.dumps({"llm": {"token_usage": usage}}),
- encoding="utf-8",
- )
-
- result = _build_log_payload(tmp_path)
-
- assert result["llm_token_usage"] == usage
- assert result["build_progress"]["llm_token_usage"] == usage
-
-
-def test_running_build_log_payload_does_not_reuse_persisted_token_usage(tmp_path):
- logger = _BuildProcessLogger(tmp_path / "build_log.jsonl")
- logger.reset()
- logger.record("fingerprint.extract.start", current=1, total=3, path="demo")
- stale_usage = {
- "total": {
- "request_count": 2,
- "prompt_tokens": 106436,
- "completion_tokens": 496,
- "total_tokens": 106932,
- },
- }
- (tmp_path / "score_manifest.json").write_text(
- json.dumps({"llm": {"token_usage": stale_usage}}),
- encoding="utf-8",
- )
-
- result = _build_log_payload(tmp_path)
-
- assert result["build_progress"]["status"] == "running"
- assert result["llm_token_usage"] == {}
- assert "llm_token_usage" not in result["build_progress"]
-
-
-def test_agent_adapter_keeps_symphony_business_error_as_successful_rpc():
- from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenSwarm
-
- ExtensionRegistry.reset_instance()
- registry = ExtensionRegistry.create_instance(None, {}, None)
- registry.register_rpc_handler(
- SYMPHONY_GRAPH,
- lambda _params, request=None: {"success": False, "detail": "总谱不存在"},
- )
- request = AgentRequest(
- request_id="request-1",
- channel_id="web",
- req_method=ReqMethod.SYMPHONY_GRAPH,
- params={},
- )
-
- try:
- adapter = JiuWenSwarm.__new__(JiuWenSwarm)
- response = asyncio.run(getattr(adapter, "_handle_symphony_request")(request))
- finally:
- ExtensionRegistry.reset_instance()
-
- assert response is not None
- assert response.ok is True
- assert response.payload == {"success": False, "detail": "总谱不存在"}
diff --git a/tests/unit_tests/symphony/test_fingerprint_models.py b/tests/unit_tests/symphony/test_fingerprint_models.py
index c2ddd685c9..5efae20a6f 100644
--- a/tests/unit_tests/symphony/test_fingerprint_models.py
+++ b/tests/unit_tests/symphony/test_fingerprint_models.py
@@ -7,10 +7,7 @@ from jiuwenswarm.symphony.fingerprint import (
Fingerprint,
ParameterSpec,
)
-from jiuwenswarm.symphony.graph.matcher.cache import RelationMatchCache
-from jiuwenswarm.symphony.graph.models import LLMMatch, RelationCandidate
-from jiuwenswarm.symphony.graph.registry import SkillRegistryBuilder
-from jiuwenswarm.symphony.score_state import ScoreStateBuilder
+from jiuwenswarm.symphony.graph_state import GraphStateBuilder
def _fingerprint(**overrides):
@@ -111,60 +108,6 @@ def test_graph_identity_excludes_static_data_and_hash_is_stable():
assert "static_data" not in first.graph_identity_dict()
assert first.graph_identity_dict() == second.graph_identity_dict()
- assert ScoreStateBuilder.fingerprint_hash(
+ assert GraphStateBuilder.fingerprint_hash(
first
- ) == ScoreStateBuilder.fingerprint_hash(second)
-
-
-def test_skill_registry_rejects_agent_fingerprint():
- registry = SkillRegistryBuilder.register([_fingerprint(type="agent")])
-
- assert registry.skills == {}
- assert [item.code for item in registry.diagnostics] == [
- "unsupported_fingerprint_type"
- ]
-
-
-def test_relation_cache_ignores_static_data_changes(tmp_path):
- candidate = RelationCandidate(
- source_id="weather",
- target_id="summary",
- relation_hints=["exact_io"],
- candidate_methods=["exact_io"],
- priority="high",
- )
- match = LLMMatch(
- source_id="weather",
- target_id="summary",
- relation_type="can_feed",
- confidence=1.0,
- method="test",
- candidate_id=candidate.key,
- accepted=True,
- )
- target = _fingerprint(
- id="summary",
- name="Summary",
- static_data={"documentation": "first"},
- )
- cache_path = tmp_path / "relations.json"
- first_cache = RelationMatchCache(
- cache_path,
- matcher_signature={"matcher": "test"},
- fingerprints=[_fingerprint(), target],
- )
- first_cache.store(candidate, [match])
- first_cache.flush()
-
- changed_target = _fingerprint(
- id="summary",
- name="Summary",
- static_data={"documentation": "second"},
- )
- second_cache = RelationMatchCache(
- cache_path,
- matcher_signature={"matcher": "test"},
- fingerprints=[_fingerprint(), changed_target],
- )
-
- assert second_cache.load(candidate) == [match]
+ ) == GraphStateBuilder.fingerprint_hash(second)
diff --git a/tests/unit_tests/symphony/test_graph_exact_io.py b/tests/unit_tests/symphony/test_graph_exact_io.py
deleted file mode 100644
index d3250cc458..0000000000
--- a/tests/unit_tests/symphony/test_graph_exact_io.py
+++ /dev/null
@@ -1,696 +0,0 @@
-import pytest
-
-from jiuwenswarm.symphony.fingerprint.models import (
- ArtifactSpec,
- ParameterSpec,
- Fingerprint,
-)
-from jiuwenswarm.symphony.graph.builders import ScoreLookupBuilder
-from jiuwenswarm.symphony.graph.candidates import CandidateGenerator
-from jiuwenswarm.symphony.graph.pipeline import GraphBuilder
-from jiuwenswarm.symphony.graph.models import (
- GraphEdge,
- LLMMatch,
- SkillGraph,
- SkillRegistry,
-)
-
-
-def test_candidate_generator_emits_exact_io_match():
- candidates = _candidates(
- _skill("source", outputs=[ArtifactSpec(name="summary", type="text")]),
- _skill("target", inputs=[ParameterSpec(name="summary", type="text")]),
- )
-
- assert len(candidates) == 1
- candidate = candidates[0]
- assert candidate.source_id == "source"
- assert candidate.target_id == "target"
- assert "exact_io_match" in candidate.candidate_methods
- evidence = candidate.evidence["directions"]["source->target"]
- assert evidence["port_mappings"] == [
- {
- "source_output": "summary",
- "source_type": "text",
- "target_input": "summary",
- "target_type": "text",
- "match_reason": (
- "source output and target input share the same normalized name and type"
- ),
- "match_method": "exact_io_match",
- }
- ]
-
-
-def test_candidate_generator_default_candidate_limit_is_thirty_two():
- assert CandidateGenerator().max_candidates_per_skill_relation == 32
-
-
-def test_candidate_generator_keeps_stronger_candidates_before_target_name():
- candidates = CandidateGenerator(max_candidates_per_skill_relation=1).generate(
- SkillRegistry(
- skills={
- "source": _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="outline",
- type="markdown",
- description="shared research slides evidence",
- )
- ],
- ),
- "aaa-weak": _skill(
- "aaa-weak",
- inputs=[
- ParameterSpec(
- name="report",
- type="text",
- description="shared research slides evidence",
- )
- ],
- ),
- "zzz-content": _skill(
- "zzz-content",
- inputs=[
- ParameterSpec(
- name="content",
- type="markdown",
- description="shared research slides evidence",
- )
- ],
- ),
- }
- )
- )
-
- assert [candidate.key for candidate in candidates] == ["source->zzz-content"]
- assert candidates[0].candidate_methods == [
- "semantic_overlap_match",
- "textual_coercion_match",
- ]
-
-
-def test_candidate_generator_keeps_more_port_mapping_evidence_before_target_name():
- candidates = CandidateGenerator(max_candidates_per_skill_relation=1).generate(
- SkillRegistry(
- skills={
- "source": _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="brief",
- type="text",
- description="shared planning evidence",
- ),
- ArtifactSpec(
- name="outline",
- type="text",
- description="shared planning evidence",
- ),
- ],
- ),
- "aaa-weak": _skill(
- "aaa-weak",
- inputs=[
- ParameterSpec(
- name="request",
- type="text",
- description="shared planning evidence",
- )
- ],
- ),
- "zzz-rich": _skill(
- "zzz-rich",
- inputs=[
- ParameterSpec(
- name="content",
- type="text",
- description="shared planning evidence",
- ),
- ParameterSpec(
- name="text",
- type="text",
- description="shared planning evidence",
- ),
- ],
- ),
- }
- )
- )
-
- assert [candidate.key for candidate in candidates] == ["source->zzz-rich"]
- evidence = candidates[0].evidence["directions"]["source->zzz-rich"]
- assert len(evidence["port_mappings"]) > 1
-
-
-def test_candidate_generator_candidate_limit_sorting_is_stable():
- skills = [
- _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="outline",
- type="markdown",
- description="shared research slides evidence",
- )
- ],
- ),
- _skill(
- "aaa-weak",
- inputs=[
- ParameterSpec(
- name="report",
- type="text",
- description="shared research slides evidence",
- )
- ],
- ),
- _skill(
- "zzz-content",
- inputs=[
- ParameterSpec(
- name="content",
- type="markdown",
- description="shared research slides evidence",
- )
- ],
- ),
- ]
-
- first = CandidateGenerator(max_candidates_per_skill_relation=1).generate(
- SkillRegistry(skills={skill.id: skill for skill in skills})
- )
- second = CandidateGenerator(max_candidates_per_skill_relation=1).generate(
- SkillRegistry(skills={skill.id: skill for skill in reversed(skills)})
- )
-
- assert [candidate.key for candidate in first] == [
- candidate.key for candidate in second
- ]
-
-
-def test_candidate_generator_keeps_reverse_direction_candidates_distinct():
- candidates = _candidates(
- _skill(
- "alpha",
- inputs=[ParameterSpec(name="beta_payload", type="text")],
- outputs=[ArtifactSpec(name="alpha_payload", type="text")],
- ),
- _skill(
- "beta",
- inputs=[ParameterSpec(name="alpha_payload", type="text")],
- outputs=[ArtifactSpec(name="beta_payload", type="text")],
- ),
- )
-
- assert [(item.source_id, item.target_id) for item in candidates] == [
- ("alpha", "beta"),
- ("beta", "alpha"),
- ]
- assert [item.key for item in candidates] == [
- "alpha->beta",
- "beta->alpha",
- ]
- assert "alpha->beta" in candidates[0].evidence["directions"]
- assert "beta->alpha" in candidates[1].evidence["directions"]
-
-
-def test_candidate_generator_suppresses_ambiguous_exact_io_candidate_name():
- candidates = _candidates(
- _skill("source", outputs=[ArtifactSpec(name="dependencies", type="text")]),
- _skill("target", inputs=[ParameterSpec(name="dependencies", type="text")]),
- )
-
- assert candidates == []
-
-
-def test_candidate_generator_treats_code_as_regular_exact_io_name():
- candidates = _candidates(
- _skill("source", outputs=[ArtifactSpec(name="code", type="text")]),
- _skill("target", inputs=[ParameterSpec(name="code", type="text")]),
- )
-
- assert len(candidates) == 1
- candidate = candidates[0]
- assert candidate.source_id == "source"
- assert candidate.target_id == "target"
- assert "exact_io_match" in candidate.candidate_methods
-
-
-def test_candidate_generator_emits_semantic_overlap_match():
- candidates = _candidates(
- _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="summary",
- type="text",
- description="document findings and action items",
- )
- ],
- ),
- _skill(
- "target",
- inputs=[
- ParameterSpec(
- name="report",
- type="text",
- description="document findings and action items",
- )
- ],
- ),
- )
-
- assert len(candidates) == 1
- candidate = candidates[0]
- assert candidate.source_id == "source"
- assert candidate.target_id == "target"
- assert "semantic_overlap_match" in candidate.candidate_methods
- evidence = candidate.evidence["directions"]["source->target"]
- assert evidence["port_mappings"] == [
- {
- "source_output": "summary",
- "source_type": "text",
- "target_input": "report",
- "target_type": "text",
- "match_reason": "source output and target input share semantic terms",
- "match_method": "semantic_overlap_match",
- }
- ]
-
-
-def test_candidate_generator_merges_multiple_matched_types_without_stale_scalar():
- candidates = _candidates(
- _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="summary",
- type="text",
- description="shared topic evidence",
- ),
- ArtifactSpec(
- name="asset_url",
- type="url",
- description="remote URL",
- ),
- ],
- ),
- _skill(
- "target",
- inputs=[
- ParameterSpec(
- name="brief",
- type="text",
- description="shared topic evidence",
- ),
- ParameterSpec(
- name="asset_file",
- type="file",
- description="accepts HTTP or HTTPS URL",
- ),
- ],
- ),
- )
-
- assert len(candidates) == 1
- evidence = candidates[0].evidence["directions"]["source->target"]
- assert evidence["matched_types"] == [
- "text->text",
- "url->file",
- ]
- assert "matched_type" not in evidence
-
-
-def test_candidate_generator_emits_textual_coercion_match():
- candidates = _candidates(
- _skill("source", outputs=[ArtifactSpec(name="article", type="text")]),
- _skill("target", inputs=[ParameterSpec(name="content", type="text")]),
- )
-
- assert len(candidates) == 1
- candidate = candidates[0]
- assert candidate.source_id == "source"
- assert candidate.target_id == "target"
- assert candidate.priority == "low"
- assert candidate.candidate_methods == ["textual_coercion_match"]
- evidence = candidate.evidence["directions"]["source->target"]
- assert evidence["port_mappings"] == [
- {
- "source_output": "article",
- "source_type": "text",
- "target_input": "content",
- "target_type": "text",
- "match_reason": "textual output can be coerced to generic content input",
- "match_method": "textual_coercion_match",
- }
- ]
-
-
-def test_candidate_generator_skips_textual_coercion_for_control_destination_inputs():
- for input_name in ("to", "cc", "bcc", "limit", "command"):
- assert (
- _candidates(
- _skill("source", outputs=[ArtifactSpec(name="article", type="text")]),
- _skill("target", inputs=[ParameterSpec(name=input_name, type="text")]),
- )
- == []
- )
-
-
-def test_candidate_generator_emits_remote_reference_candidate_for_url_file_like_input():
- candidates = _candidates(
- _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="asset_reference",
- type="url",
- description="remote URL",
- )
- ],
- ),
- _skill(
- "target",
- inputs=[
- ParameterSpec(
- name="file",
- type="file",
- description="accepts HTTP or HTTPS URL",
- )
- ],
- ),
- )
-
- assert len(candidates) == 1
- candidate = candidates[0]
- assert candidate.source_id == "source"
- assert candidate.target_id == "target"
- assert "semantic_overlap_match" in candidate.candidate_methods
- evidence = candidate.evidence["directions"]["source->target"]
- assert evidence["port_mappings"] == [
- {
- "source_output": "asset_reference",
- "source_type": "url",
- "target_input": "file",
- "target_type": "file",
- "match_reason": (
- "source output URL can satisfy target file-like input that accepts "
- "remote references"
- ),
- "match_method": "semantic_overlap_match",
- }
- ]
-
-
-def test_candidate_generator_emits_remote_reference_candidate_for_url_text_input():
- candidates = _candidates(
- _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="translated_image_url",
- type="url",
- description="URL of the translated image.",
- )
- ],
- ),
- _skill(
- "target",
- inputs=[
- ParameterSpec(
- name="image_url",
- type="text",
- description="Public image URL to process.",
- )
- ],
- ),
- )
-
- assert len(candidates) == 1
- candidate = candidates[0]
- assert candidate.source_id == "source"
- assert candidate.target_id == "target"
- assert "semantic_overlap_match" in candidate.candidate_methods
- evidence = candidate.evidence["directions"]["source->target"]
- assert evidence["port_mappings"][0]["source_output"] == "translated_image_url"
- assert evidence["port_mappings"][0]["target_input"] == "image_url"
-
-
-def test_candidate_generator_emits_image_artifact_candidate():
- candidates = _candidates(
- _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="translated_image_url",
- type="image",
- description="URL of the translated image.",
- )
- ],
- ),
- _skill(
- "target",
- inputs=[
- ParameterSpec(
- name="image",
- type="image",
- description="Image input to process.",
- )
- ],
- ),
- )
-
- assert len(candidates) == 1
- candidate = candidates[0]
- assert candidate.source_id == "source"
- assert candidate.target_id == "target"
- assert "semantic_overlap_match" in candidate.candidate_methods
- evidence = candidate.evidence["directions"]["source->target"]
- assert evidence["port_mappings"][0]["source_output"] == "translated_image_url"
- assert evidence["port_mappings"][0]["target_input"] == "image"
-
-
-def test_candidate_generator_emits_remote_reference_for_explicit_url_descriptions():
- for description in ("accepts remote URL", "download URL"):
- candidates = _candidates(
- _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="asset_reference",
- type="url",
- description="remote URL",
- )
- ],
- ),
- _skill(
- "target",
- inputs=[
- ParameterSpec(
- name="file",
- type="file",
- description=description,
- )
- ],
- ),
- )
-
- assert len(candidates) == 1
- evidence = candidates[0].evidence["directions"]["source->target"]
- assert evidence["port_mappings"][0]["source_type"] == "url"
- assert evidence["port_mappings"][0]["target_type"] == "file"
-
-
-def test_candidate_generator_skips_remote_reference_for_broad_web_descriptions():
- for description in ("web asset", "website content"):
- assert (
- _candidates(
- _skill(
- "source",
- outputs=[
- ArtifactSpec(
- name="asset_reference",
- type="url",
- description="remote URL",
- )
- ],
- ),
- _skill(
- "target",
- inputs=[
- ParameterSpec(
- name="file",
- type="file",
- description=description,
- )
- ],
- ),
- )
- == []
- )
-
-
-async def test_graph_builder_does_not_materialize_rejected_exact_io_match():
- result = await GraphBuilder(matcher=_RejectedExactMatcher()).build(
- [
- _skill("source", outputs=[ArtifactSpec(name="summary", type="text")]),
- _skill("target", inputs=[ParameterSpec(name="summary", type="text")]),
- ]
- )
-
- assert result.candidates
- assert "exact_io_match" in result.candidates[0].candidate_methods
- assert result.llm_matches == [
- LLMMatch(
- source_id="source",
- target_id="target",
- relation_type="can_feed",
- confidence=0.2,
- accepted=False,
- candidate_id=result.candidates[0].key,
- )
- ]
- assert result.graph.edges == []
-
-
-async def test_graph_builder_materializes_accepted_exact_io_match():
- result = await GraphBuilder(matcher=_AcceptedExactMatcher()).build(
- [
- _skill("source", outputs=[ArtifactSpec(name="summary", type="text")]),
- _skill("target", inputs=[ParameterSpec(name="summary", type="text")]),
- ]
- )
-
- assert len(result.graph.edges) == 1
- edge = result.graph.edges[0]
- assert edge.source == "skill:source"
- assert edge.target == "skill:target"
- assert edge.type == "can_feed"
- assert edge.confidence == 0.9
-
-
-def test_score_lookup_emits_text_term_lookup():
- registry = SkillRegistry(
- skills={
- "source": _skill(
- "source",
- outputs=[
- ArtifactSpec(name="code", type="text"),
- ArtifactSpec(name="summary", type="text"),
- ArtifactSpec(name="dependencies", type="text"),
- ],
- ),
- "target": _skill(
- "target",
- inputs=[
- ParameterSpec(name="code", type="text"),
- ParameterSpec(name="summary", type="text"),
- ParameterSpec(name="dependencies", type="text"),
- ],
- ),
- }
- )
- graph = SkillGraph(
- nodes=[],
- edges=[
- GraphEdge(
- source="skill:source",
- target="skill:target",
- type="can_feed",
- )
- ],
- )
-
- lookup = ScoreLookupBuilder().build(registry, graph).to_dict()
-
- assert "by_text_term" in lookup
- assert lookup["by_output"] == {
- "code": ["source"],
- "summary": ["source"],
- }
- assert lookup["by_input"] == {
- "code": ["target"],
- "summary": ["target"],
- }
- assert lookup["by_text_term"]["code"] == ["source", "target"]
- assert lookup["by_text_term"]["dependencies"] == ["source", "target"]
- assert lookup["by_text_term"]["summary"] == ["source", "target"]
- assert lookup["upstream_by_input"] == {
- "code": ["source"],
- "summary": ["source"],
- }
- assert lookup["downstream_by_output"] == {
- "code": ["target"],
- "summary": ["target"],
- }
-
-
-def _candidates(*skills: Fingerprint):
- return CandidateGenerator().generate(
- SkillRegistry(skills={skill.id: skill for skill in skills})
- )
-
-
-def _skill(
- skill_id: str,
- *,
- inputs: list[ParameterSpec] | None = None,
- outputs: list[ArtifactSpec] | None = None,
-) -> Fingerprint:
- return Fingerprint(
- type="skill",
- id=skill_id,
- name=skill_id,
- description="",
- version="1.0.0",
- inputs=inputs or [],
- outputs=outputs or [],
- )
-
-
-class _RejectedExactMatcher:
- thresholds = {"can_feed": 0.7}
-
- async def match(self, registry, candidates):
- del registry
- assert len(candidates) == 1
- return [
- LLMMatch(
- source_id=candidates[0].source_id,
- target_id=candidates[0].target_id,
- relation_type="can_feed",
- confidence=0.2,
- accepted=False,
- candidate_id=candidates[0].key,
- )
- ]
-
- @staticmethod
- def manifest_metadata():
- return {"matcher": "rejected-exact"}
-
-
-class _AcceptedExactMatcher:
- thresholds = {"can_feed": 0.7}
-
- async def match(self, registry, candidates):
- del registry
- assert len(candidates) == 1
- return [
- LLMMatch(
- source_id=candidates[0].source_id,
- target_id=candidates[0].target_id,
- relation_type="can_feed",
- confidence=0.9,
- accepted=True,
- candidate_id=candidates[0].key,
- )
- ]
-
- @staticmethod
- def manifest_metadata():
- return {"matcher": "accepted-exact"}
diff --git a/tests/unit_tests/symphony/test_graph_service.py b/tests/unit_tests/symphony/test_graph_service.py
deleted file mode 100644
index c8cc114909..0000000000
--- a/tests/unit_tests/symphony/test_graph_service.py
+++ /dev/null
@@ -1,1893 +0,0 @@
-import asyncio
-import json
-
-import pytest
-
-from jiuwenswarm.symphony.fingerprint.models import (
- ArtifactSpec,
- ExtractedSkillSchema,
- ParameterSpec,
- RawSkillManifest,
- Fingerprint,
- SkillFolder,
-)
-from jiuwenswarm.symphony.fingerprint.normalize import (
- IONameCandidate,
- IONameResolution,
- IONameVocabulary,
- LLMIONameResolver,
- SkillFingerprintNormalizer,
-)
-from jiuwenswarm.symphony.fingerprint.extract.extractor import LLMSchemaExtractor
-from jiuwenswarm.symphony.fingerprint.manifest import SkillManifestParser
-from jiuwenswarm.symphony.fingerprint.pipeline import FingerprintExtractor
-from jiuwenswarm.symphony.fingerprint.scan import SkillFolderScanner
-from jiuwenswarm.symphony.fingerprint.artifacts import write_extraction_result
-from jiuwenswarm.symphony.graph import (
- GraphBuilder,
- GraphDiagnostic,
- LLMMatch,
- OpenAICompatibleOntologyMatcher,
- RelationCandidate,
- SkillRegistry,
-)
-from jiuwenswarm.symphony.graph.candidates.generator import CandidateGenerator
-from jiuwenswarm.symphony.score_state import (
- ScoreState,
- ScoreStateEntry,
- write_score_state,
-)
-from jiuwenswarm.symphony.build import (
- ScoreBuildRuntimeFactory,
- build_score,
- score_status,
- _fingerprint_signature,
-)
-from jiuwenswarm.symphony.llm import LLMConfig
-from jiuwenswarm.symphony.config import symphony_config_from_dict
-from jiuwenswarm.symphony.graph.matcher.cache import CachedOntologyMatcher
-from jiuwenswarm.symphony.orchestration.artifacts import load_score_artifacts
-
-
-class _SchemaExtractor:
- def __init__(self):
- self.extract_count = 0
-
- async def extract(self, manifest):
- self.extract_count += 1
- return ExtractedSkillSchema(
- description=f"{manifest.folder.id_hint} schema",
- inputs=[ParameterSpec(name="input", type="text")],
- outputs=[ArtifactSpec(name="result", type="text")],
- )
-
-
-class _LinkedSchemaExtractor:
- def __init__(self):
- self.extract_count = 0
-
- async def extract(self, manifest):
- self.extract_count += 1
- if manifest.folder.id_hint == "skill-1":
- return ExtractedSkillSchema(
- description="Create a draft.",
- inputs=[ParameterSpec(name="brief", type="text")],
- outputs=[ArtifactSpec(name="draft", type="markdown")],
- )
- return ExtractedSkillSchema(
- description="Review a draft.",
- inputs=[ParameterSpec(name="draft", type="markdown")],
- outputs=[ArtifactSpec(name="review", type="markdown")],
- )
-
-
-class _NoopMatcher:
- thresholds = {"can_feed": 0.7}
-
- async def match(self, registry, candidates):
- return []
-
- @staticmethod
- def manifest_metadata():
- return {"matcher": "noop"}
-
-
-class _CountingAcceptedMatcher:
- thresholds = {"can_feed": 0.7}
-
- def __init__(self):
- self.calls = []
-
- async def match(self, registry, candidates):
- del registry
- candidates = list(candidates)
- self.calls.append([candidate.key for candidate in candidates])
- return [
- LLMMatch(
- source_id=candidate.source_id,
- target_id=candidate.target_id,
- relation_type="can_feed",
- confidence=0.9,
- accepted=True,
- candidate_id=candidate.key,
- )
- for candidate in candidates
- ]
-
- @staticmethod
- def manifest_metadata():
- return {"matcher": "counting-accepted"}
-
-
-class _MismatchedBatchSchemaExtractor(_SchemaExtractor):
- use_batch = True
- batch_size = 2
-
- async def extract_many(self, manifests):
- return [await self.extract(manifests[0])]
-
-
-class _NonBatchSchemaExtractor(_SchemaExtractor):
- use_batch = False
- batch_size = 99
-
- async def extract_many(self, manifests):
- raise AssertionError("Non-batch extractor should not use extract_many.")
-
-
-class _BatchSchemaExtractor:
- use_batch = True
-
- def __init__(self, batch_size=2):
- self.batch_size = batch_size
- self.batches = []
-
- async def extract(self, manifest):
- raise AssertionError("Batch extractor should use extract_many.")
-
- async def extract_many(self, manifests):
- self.batches.append([manifest.folder.id_hint for manifest in manifests])
- return [
- ExtractedSkillSchema(
- description=f"{manifest.folder.id_hint} schema",
- inputs=[ParameterSpec(name="input", type="text")],
- outputs=[ArtifactSpec(name="result", type="text")],
- )
- for manifest in manifests
- ]
-
-
-class _PromptBatchIONameResolver:
- batch_size = 2
-
- def __init__(self):
- self.calls = []
-
- async def resolve_async(self, candidates_by_skill, vocabulary):
- del vocabulary
- self.calls.append([[candidate.token for candidate in batch] for batch in candidates_by_skill])
- candidates = [
- candidate
- for batch in reversed(candidates_by_skill)
- for candidate in reversed(batch)
- ]
- return {
- candidate.token: IONameResolution(
- action="create_new",
- normalized_value=candidate.token,
- confidence=0.9,
- reason="test",
- )
- for candidate in candidates
- }
-
-
-class _CreateNewIONameResolver:
- batch_size = 1
-
- def __init__(self):
- self.calls = []
-
- async def resolve_async(self, candidates_by_skill, vocabulary):
- del vocabulary
- self.calls.append([[candidate.token for candidate in batch] for batch in candidates_by_skill])
- return {
- candidate.token: IONameResolution(
- action="create_new",
- normalized_value=candidate.token,
- confidence=0.9,
- reason="test",
- )
- for batch in candidates_by_skill
- for candidate in batch
- }
-
-
-class _ExcludeFromVocabIONameResolver:
- batch_size = 1
-
- async def resolve_async(self, candidates_by_skill, vocabulary):
- del vocabulary
- return {
- candidate.token: IONameResolution(
- action="exclude_from_vocab",
- normalized_value=None,
- confidence=0.9,
- reason="not a vocabulary term",
- )
- for batch in candidates_by_skill
- for candidate in batch
- }
-
-
-class _MappingIONameResolver:
- def __init__(self, resolutions, batch_size=1):
- self.resolutions = resolutions
- self.batch_size = batch_size
- self.calls = []
-
- async def resolve_async(self, candidates_by_skill, vocabulary):
- del vocabulary
- self.calls.append(
- [[candidate.token for candidate in batch] for batch in candidates_by_skill]
- )
- return {
- candidate.token: self.resolutions[candidate.token]
- for batch in candidates_by_skill
- for candidate in batch
- }
-
-
-class _CaptureJSONClient:
- def __init__(self):
- self.calls = []
-
- async def complete_json_async(self, **kwargs):
- self.calls.append(kwargs)
- return """
- {
- "resolutions": [
- {
- "id": "i1",
- "action": "alias_existing",
- "target": "content",
- "confidence": 0.9,
- "reason": "same content role",
- "definition": "Text content alias"
- }
- ]
- }
- """
-
-
-class _CaptureSchemaClient:
- def __init__(self):
- self.calls = []
-
- async def complete_json_async(self, **kwargs):
- self.calls.append({"method": "one", **kwargs})
- payload = json.loads(kwargs["user_content"])
- if isinstance(payload.get("skills"), list):
- return json.dumps(
- {
- "schemas": [
- {
- "skill_ref": item["skill_ref"],
- "description": "Schema",
- "inputs": [{"name": "input", "type": "text"}],
- "outputs": [{"name": "result", "type": "text"}],
- "confidence": 0.9,
- "warnings": [],
- }
- for item in payload["skills"]
- ]
- }
- )
- return json.dumps(
- {
- "description": "Schema",
- "inputs": [{"name": "input", "type": "text"}],
- "outputs": [{"name": "result", "type": "text"}],
- "confidence": 0.9,
- "warnings": [],
- }
- )
-
- async def complete_json_many_async(self, requests, **kwargs):
- self.calls.append({"method": "many", "requests": requests, **kwargs})
- return [
- json.dumps(
- {
- "description": "Schema",
- "inputs": [{"name": "input", "type": "text"}],
- "outputs": [{"name": "result", "type": "text"}],
- "confidence": 0.9,
- "warnings": [],
- }
- )
- for _ in requests
- ]
-
-
-class _CaptureMatchClient:
- def __init__(self):
- self.calls = []
-
- async def complete_json_async(self, **kwargs):
- self.calls.append(kwargs)
- return json.dumps(
- {
- "matches": [
- {
- "id": "c1",
- "direction": "forward",
- "confidence": 0.95,
- "reason": "result satisfies input",
- }
- ]
- }
- )
-
-
-class _OutOfOrderBatchMatcher:
- def __init__(self):
- self.batch_size = 1
- self.max_workers = 3
- self.require_consensus = False
- self.thresholds = {"can_feed": 0.7}
- self.diagnostics = []
- self.progress = None
-
- async def match(self, registry, candidates):
- del registry
- candidate_list = list(candidates)
- batches = [
- (batch_index, [candidate])
- for batch_index, candidate in enumerate(candidate_list, start=1)
- ]
- results = await asyncio.gather(
- *(
- self._match_batch(None, batch, batch_index, len(batches))
- for batch_index, batch in batches
- )
- )
- matches = []
- for _, batch_matches, batch_diagnostics in sorted(
- results,
- key=lambda item: item[0],
- ):
- matches.extend(batch_matches)
- self.diagnostics.extend(batch_diagnostics)
- return matches
-
- async def _match_batch(self, registry, batch, batch_index, total_batches):
- del registry, batch, total_batches
- await asyncio.sleep(0.03 if batch_index == 1 else 0)
- return (
- batch_index,
- [
- LLMMatch(
- source_id=f"source-{batch_index}",
- target_id=f"target-{batch_index}",
- relation_type="can_feed",
- confidence=0.9,
- accepted=True,
- candidate_id=f"candidate-{batch_index}",
- )
- ],
- [
- GraphDiagnostic(
- stage="matching",
- severity="info",
- code="batch_done",
- message=f"batch {batch_index}",
- )
- ],
- )
-
-
-def _raw_manifest(tmp_path, folder_name):
- folder_path = tmp_path / folder_name
- folder_path.mkdir()
- skill_file = folder_path / "SKILL.md"
- skill_file.write_text(f"---\nname: {folder_name}\n---\n\nTest.", encoding="utf-8")
- return RawSkillManifest(
- folder=SkillFolder(
- id_hint=folder_name,
- path=folder_path,
- entry=skill_file,
- relative_path=folder_name,
- ),
- frontmatter={"name": folder_name},
- body="Test.",
- body_sha256=folder_name,
- )
-
-
-def _expected_thinking_disabled_overrides():
- return {
- "extra_body": {
- "thinking": {"type": "disabled"},
- "enable_thinking": False,
- "chat_template_kwargs": {"enable_thinking": False},
- },
- }
-
-
-async def test_schema_extractor_disables_thinking_for_single_extract(monkeypatch, tmp_path):
- client = _CaptureSchemaClient()
- monkeypatch.setattr(
- "jiuwenswarm.symphony.fingerprint.extract.extractor.create_llm_client",
- lambda config: client,
- )
- extractor = LLMSchemaExtractor(
- LLMConfig(
- model="model-a",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- )
- )
-
- result = await extractor.extract(_raw_manifest(tmp_path, "schema-single"))
-
- assert result.outputs[0].name == "result"
- assert client.calls[0]["request_overrides"] == _expected_thinking_disabled_overrides()
- assert "Return JSON only" in client.calls[0]["system_prompt"]
-
-
-async def test_schema_extractor_disables_thinking_for_many_paths(monkeypatch, tmp_path):
- client = _CaptureSchemaClient()
- monkeypatch.setattr(
- "jiuwenswarm.symphony.fingerprint.extract.extractor.create_llm_client",
- lambda config: client,
- )
- config = LLMConfig(
- model="model-a",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- )
-
- await LLMSchemaExtractor(config, batch_size=1).extract_many(
- [_raw_manifest(tmp_path, "schema-many-one")]
- )
- await LLMSchemaExtractor(config, batch_size=2).extract_many(
- [
- _raw_manifest(tmp_path, "schema-prompt-a"),
- _raw_manifest(tmp_path, "schema-prompt-b"),
- ]
- )
-
- assert client.calls[0]["method"] == "many"
- assert client.calls[0]["request_overrides"] == _expected_thinking_disabled_overrides()
- assert client.calls[1]["method"] == "one"
- assert client.calls[1]["request_overrides"] == _expected_thinking_disabled_overrides()
- assert "Return JSON only" in client.calls[1]["system_prompt"]
-
-
-async def test_graph_matcher_disables_thinking_for_forward_and_reverse(monkeypatch):
- client = _CaptureMatchClient()
- monkeypatch.setattr(
- "jiuwenswarm.symphony.graph.matcher.openai.create_llm_client",
- lambda config: client,
- )
- matcher = OpenAICompatibleOntologyMatcher(
- LLMConfig(
- model="model-a",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- ),
- batch_size=1,
- require_consensus=True,
- )
- registry = SkillRegistry(
- skills={
- "source": Fingerprint(
- type="skill",
- id="source",
- name="Source",
- description="Produces result",
- version="1.0.0",
- inputs=[],
- outputs=[ArtifactSpec(name="result", type="text")],
- ),
- "target": Fingerprint(
- type="skill",
- id="target",
- name="Target",
- description="Consumes input",
- version="1.0.0",
- inputs=[ParameterSpec(name="input", type="text")],
- outputs=[],
- ),
- }
- )
- candidate = RelationCandidate(
- source_id="source",
- target_id="target",
- relation_hints=["can_feed"],
- candidate_methods=["test"],
- priority="high",
- evidence={
- "directions": {
- "source->target": {
- "port_mappings": [
- {
- "source_output": "result",
- "target_input": "input",
- }
- ],
- "source_outputs": [{"name": "result"}],
- "target_inputs": [{"name": "input"}],
- }
- }
- },
- )
-
- matches = await matcher.match(registry, [candidate])
-
- assert len(matches) == 1
- assert len(client.calls) == 2
- assert [
- call["request_overrides"]
- for call in client.calls
- ] == [
- _expected_thinking_disabled_overrides(),
- _expected_thinking_disabled_overrides(),
- ]
- assert all("Return JSON only" in call["system_prompt"] for call in client.calls)
-
-
-async def test_build_score_fingerprint_progress_does_not_exceed_total(tmp_path):
- skills_root = tmp_path / "skills"
- for index in range(3):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
-
- build_log = []
-
- await build_score(
- skills_root,
- tmp_path / "score",
- schema_extractor=_SchemaExtractor(),
- matcher=_NoopMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- build_log=lambda stage, **details: build_log.append({"stage": stage, **details}),
- )
-
- for stage in (
- "fingerprint.parse.start",
- "fingerprint.extract.start",
- "fingerprint.normalize.start",
- ):
- entries = [entry for entry in build_log if entry["stage"] == stage]
- assert [entry["current"] for entry in entries] == [1, 2, 3]
- assert all(entry["total"] == 3 for entry in entries)
-
-
-async def test_build_score_passes_separate_symphony_stage_configs(tmp_path):
- skills_root = tmp_path / "skills"
- skill_dir = skills_root / "skill-1"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- "---\nname: Skill 1\n---\n\nTest skill 1.",
- encoding="utf-8",
- )
- runtime_config = symphony_config_from_dict(
- {
- "fingerprint": {
- "extraction": {
- "workers": 2,
- "batch_size": 3,
- "body_limit": 5000,
- },
- "normalization": {
- "workers": 5,
- "batch_size": 6,
- "duplicate_name_similarity_threshold": 0.42,
- "max_vocab_size": 7,
- },
- },
- "build": {
- "workers": 8,
- "batch_size": 9,
- "max_candidates_per_skill_relation": 17,
- "require_consensus": False,
- "min_edge_confidence": 0.33,
- },
- }
- )
- seen = {}
-
- class _RuntimeFactory:
- @staticmethod
- def schema_extractor(llm_config, extraction_config):
- seen["extraction"] = extraction_config
- return _SchemaExtractor()
-
- @staticmethod
- def io_name_resolver(llm_config, normalization_config):
- seen["normalization"] = normalization_config
- return _CreateNewIONameResolver()
-
- @staticmethod
- def matcher(llm_config, *, build_config, build_log=None):
- seen["build"] = build_config
- return _NoopMatcher()
-
- await build_score(
- skills_root,
- tmp_path / "score",
- llm_config=LLMConfig(
- model="model",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- ),
- symphony_config=runtime_config,
- runtime_factory=_RuntimeFactory(),
- )
-
- assert seen["extraction"].workers == 2
- assert seen["extraction"].batch_size == 3
- assert seen["extraction"].body_limit == 5000
- assert seen["normalization"].workers == 5
- assert seen["normalization"].batch_size == 6
- assert seen["normalization"].duplicate_name_similarity_threshold == 0.42
- 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
-
-
-def test_default_matcher_uses_configured_min_edge_confidence():
- runtime_config = symphony_config_from_dict(
- {"build": {"min_edge_confidence": 0.42}}
- )
- matcher = ScoreBuildRuntimeFactory().matcher(
- LLMConfig(
- model="model",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- ),
- build_config=runtime_config.build,
- )
-
- assert matcher.thresholds == {"can_feed": 0.42}
-
-
-def test_llm_endpoint_does_not_change_fingerprint_cache_signature():
- runtime_config = symphony_config_from_dict({})
- first_signature = _fingerprint_signature(
- runtime_config,
- LLMConfig(
- model="model",
- model_client_config={
- "api_key": "key-a",
- "api_base": "https://a.example.test/v1",
- "client_provider": "openai",
- },
- ),
- )
- second_signature = _fingerprint_signature(
- runtime_config,
- LLMConfig(
- model="model",
- model_client_config={
- "api_key": "key-b",
- "api_base": "https://b.example.test/v1",
- "client_provider": "openai",
- },
- ),
- )
-
- assert first_signature == second_signature
-
-
-def test_llm_endpoint_is_not_recorded_in_relation_cache_signature(tmp_path):
- matcher = ScoreBuildRuntimeFactory().matcher(
- LLMConfig(
- model="model",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- ),
- build_config=symphony_config_from_dict({}).build,
- )
-
- metadata = matcher.manifest_metadata()
- cached_matcher = CachedOntologyMatcher(
- matcher,
- tmp_path / "relation_matches.json",
- fingerprints=[],
- )
-
- assert "base_url" not in metadata
- assert "api_key" not in metadata
- assert "base_url" not in cached_matcher.cache.matcher_signature
- assert "api_key" not in cached_matcher.cache.matcher_signature
-
-
-async def test_build_score_uses_configured_scan_max_depth(tmp_path):
- skills_root = tmp_path / "skills"
- shallow_skill = skills_root / "skill-1"
- nested_skill = skills_root / "nested" / "skill-2"
- shallow_skill.mkdir(parents=True)
- nested_skill.mkdir(parents=True)
- (shallow_skill / "SKILL.md").write_text(
- "---\nname: Skill 1\n---\n\nShallow skill.",
- encoding="utf-8",
- )
- (nested_skill / "SKILL.md").write_text(
- "---\nname: Skill 2\n---\n\nNested skill.",
- encoding="utf-8",
- )
- runtime_config = symphony_config_from_dict(
- {"fingerprint": {"scan": {"max_depth": 1}}}
- )
-
- status = score_status(
- skills_root,
- tmp_path / "score",
- symphony_config=runtime_config,
- )
- result = await build_score(
- skills_root,
- tmp_path / "score",
- schema_extractor=_SchemaExtractor(),
- matcher=_NoopMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- symphony_config=runtime_config,
- )
-
- assert status.skill_count == 1
- assert result.skill_count == 1
- assert result.extracted_count == 1
-
-
-async def test_build_score_reuses_unchanged_and_reextracts_changed_skills(tmp_path):
- skills_root = tmp_path / "skills"
- score_dir = tmp_path / "score"
- for index in range(2):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
-
- first = await build_score(
- skills_root,
- score_dir,
- schema_extractor=_SchemaExtractor(),
- matcher=_NoopMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- )
- second = await build_score(
- skills_root,
- score_dir,
- schema_extractor=_SchemaExtractor(),
- matcher=_NoopMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- )
- (skills_root / "skill-2" / "SKILL.md").write_text(
- "---\nname: Skill 2\n---\n\nChanged skill 2.",
- encoding="utf-8",
- )
- third = await build_score(
- skills_root,
- score_dir,
- schema_extractor=_SchemaExtractor(),
- matcher=_NoopMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- )
- fourth = await build_score(
- skills_root,
- score_dir,
- schema_extractor=_SchemaExtractor(),
- matcher=_NoopMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- force=True,
- )
-
- assert first.extracted_count == 2
- assert first.reused_count == 0
- assert second.extracted_count == 0
- assert second.reused_count == 2
- assert third.extracted_count == 1
- assert third.reused_count == 1
- assert fourth.extracted_count == 2
- assert fourth.reused_count == 0
-
-
-async def test_build_score_publishes_versioned_artifacts_and_loads_current(tmp_path):
- skills_root = tmp_path / "skills"
- score_dir = tmp_path / "score"
- for index in range(2):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
-
- result = await build_score(
- skills_root,
- score_dir,
- schema_extractor=_LinkedSchemaExtractor(),
- matcher=_CountingAcceptedMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- )
- artifacts = load_score_artifacts(score_dir)
-
- assert result.version
- assert (score_dir / "current.json").is_file()
- assert (score_dir / "versions" / result.version / "score_manifest.json").is_file()
- assert artifacts.score_dir == (score_dir / "versions" / result.version).resolve()
- assert [skill["id"] for skill in artifacts.skills] == ["skill-1", "skill-2"]
-
-
-async def test_build_score_reuses_unchanged_relation_matches(tmp_path):
- skills_root = tmp_path / "skills"
- score_dir = tmp_path / "score"
- for index in range(2):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
-
- first_matcher = _CountingAcceptedMatcher()
- first = await build_score(
- skills_root,
- score_dir,
- schema_extractor=_LinkedSchemaExtractor(),
- matcher=first_matcher,
- io_name_resolver=_CreateNewIONameResolver(),
- )
- second_matcher = _CountingAcceptedMatcher()
- second = await build_score(
- skills_root,
- score_dir,
- schema_extractor=_LinkedSchemaExtractor(),
- matcher=second_matcher,
- io_name_resolver=_CreateNewIONameResolver(),
- )
-
- assert first.relation_resolved_count >= 1
- assert first.relation_reused_count == 0
- assert first_matcher.calls
- assert second.relation_resolved_count == 0
- assert second.relation_reused_count == first.relation_resolved_count
- 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,
- }
-
-
-async def test_build_score_reports_removed_skills(tmp_path):
- skills_root = tmp_path / "skills"
- score_dir = tmp_path / "score"
- for index in range(2):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
- await build_score(
- skills_root,
- score_dir,
- schema_extractor=_SchemaExtractor(),
- matcher=_NoopMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- )
- (skills_root / "skill-2" / "SKILL.md").unlink()
- (skills_root / "skill-2").rmdir()
-
- result = await build_score(
- skills_root,
- score_dir,
- schema_extractor=_SchemaExtractor(),
- matcher=_NoopMatcher(),
- io_name_resolver=_CreateNewIONameResolver(),
- )
-
- assert result.skill_count == 1
- assert result.removed_count == 1
- assert result.reused_count == 1
- assert result.extracted_count == 0
-
-
-def _write_state_from_extraction_result(result, output_dir):
- entries = {}
- for folder in result.folders:
- fingerprint = result.fingerprints_by_path[folder.relative_path]
- entries[folder.relative_path] = ScoreStateEntry(
- skill_id=fingerprint.id,
- relative_path=folder.relative_path,
- skill_md_sha256=result.current_hashes[folder.relative_path],
- fingerprint_hash="test-fingerprint-hash",
- status="active",
- updated_at="2026-06-06T00:00:00+00:00",
- )
- write_score_state(ScoreState(skills=entries), output_dir)
-
-
-async def test_fingerprint_extractor_extract_from_root_preserves_changed_folder_progress_index(tmp_path):
- skills_root = tmp_path / "skills"
- output_dir = tmp_path / "score"
- for index in range(2):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
- first = await FingerprintExtractor(
- schema_extractor=_SchemaExtractor(),
- parser=SkillManifestParser(),
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- ).extract_from_root(skills_root, output_dir=output_dir)
- write_extraction_result(first, output_dir)
- _write_state_from_extraction_result(first, output_dir)
- (skills_root / "skill-2" / "SKILL.md").write_text(
- "---\nname: Skill 2\n---\n\nChanged skill 2.",
- encoding="utf-8",
- )
-
- progress = []
- schema_extractor = _SchemaExtractor()
- extractor = FingerprintExtractor(
- schema_extractor=schema_extractor,
- parser=SkillManifestParser(),
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- progress=lambda stage, current, total, item: progress.append(
- {
- "stage": stage,
- "current": current,
- "total": total,
- "item": item,
- }
- ),
- )
-
- result = await extractor.extract_from_root(skills_root, output_dir=output_dir)
-
- assert result.extracted_count == 1
- assert result.reused_count == 1
- assert result.fingerprints_by_path["skill-2"].id == "skill-2"
- assert schema_extractor.extract_count == 1
- assert [
- (entry["stage"], entry["current"], entry["total"])
- for entry in progress
- ] == [
- ("parse", 2, 2),
- ("extract", 2, 2),
- ("normalize", 2, 2),
- ]
-
-
-async def test_fingerprint_extractor_reuses_per_skill_cache_without_published_state(tmp_path):
- skills_root = tmp_path / "skills"
- output_dir = tmp_path / "score"
- skill_dir = skills_root / "skill-1"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- "---\nname: Skill 1\n---\n\nTest skill 1.",
- encoding="utf-8",
- )
-
- first_schema_extractor = _SchemaExtractor()
- first = await FingerprintExtractor(
- schema_extractor=first_schema_extractor,
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- ).extract_from_root(
- skills_root,
- output_dir=output_dir,
- fingerprint_signature="test-signature",
- )
- second_schema_extractor = _SchemaExtractor()
- second = await FingerprintExtractor(
- schema_extractor=second_schema_extractor,
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- ).extract_from_root(
- skills_root,
- output_dir=output_dir,
- fingerprint_signature="test-signature",
- )
-
- assert first.extracted_count == 1
- assert first.reused_count == 0
- assert second.extracted_count == 0
- assert second.reused_count == 1
- assert second_schema_extractor.extract_count == 0
-
-
-async def test_fingerprint_extractor_batch_schema_count_mismatch_raises(tmp_path):
- skills_root = tmp_path / "skills"
- for index in range(2):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
- extractor = FingerprintExtractor(
- schema_extractor=_MismatchedBatchSchemaExtractor(),
- parser=SkillManifestParser(),
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- )
-
- with pytest.raises(RuntimeError, match="Batch schema extractor returned"):
- await extractor.extract_from_root(skills_root, output_dir=tmp_path / "score")
-
-
-async def test_fingerprint_extractor_uses_schema_extractor_batches(tmp_path):
- skills_root = tmp_path / "skills"
- for index in range(3):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
- progress = []
- schema_extractor = _BatchSchemaExtractor(batch_size=2)
-
- result = await FingerprintExtractor(
- schema_extractor=schema_extractor,
- parser=SkillManifestParser(),
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- progress=lambda stage, current, total, item: progress.append(
- {
- "stage": stage,
- "current": current,
- "total": total,
- "item": item,
- }
- ),
- ).extract_from_root(skills_root, output_dir=tmp_path / "score")
-
- assert schema_extractor.batches == [["skill-1", "skill-2"], ["skill-3"]]
- assert result.extracted_count == 3
- assert [
- (entry["current"], entry["total"])
- for entry in progress
- if entry["stage"] == "extract"
- ] == [(1, 3), (2, 3), (3, 3)]
-
-
-async def test_fingerprint_extractor_non_batch_extractor_uses_single_item_batches(tmp_path):
- skills_root = tmp_path / "skills"
- for index in range(3):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
- schema_extractor = _NonBatchSchemaExtractor()
-
- result = await FingerprintExtractor(
- schema_extractor=schema_extractor,
- parser=SkillManifestParser(),
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- max_workers=2,
- ).extract_from_root(skills_root, output_dir=tmp_path / "score")
-
- assert result.extracted_count == 3
- assert schema_extractor.extract_count == 3
-
-
-async def test_normalizer_async_prefetch_keeps_result_order_stable(tmp_path):
- resolver = _PromptBatchIONameResolver()
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
- items = [
- (
- _raw_manifest(tmp_path, "skill-1"),
- ExtractedSkillSchema(
- outputs=[ArtifactSpec(name="first_result", type="text")],
- ),
- ),
- (
- _raw_manifest(tmp_path, "skill-2"),
- ExtractedSkillSchema(
- outputs=[ArtifactSpec(name="second_result", type="text")],
- ),
- ),
- ]
-
- results = await normalizer.normalize(items)
-
- assert [result.fingerprint.id for result in results] == ["skill-1", "skill-2"]
- assert [result.fingerprint.outputs[0].name for result in results] == [
- "first_result",
- "second_result",
- ]
- assert resolver.calls == [[["first_result"], ["second_result"]]]
-
-
-async def test_normalizer_batch_size_one_uses_single_skill_batches(tmp_path):
- resolver = _CreateNewIONameResolver()
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
- items = [
- (
- _raw_manifest(tmp_path, "skill-1"),
- ExtractedSkillSchema(outputs=[ArtifactSpec(name="first_result", type="text")]),
- ),
- (
- _raw_manifest(tmp_path, "skill-2"),
- ExtractedSkillSchema(outputs=[ArtifactSpec(name="second_result", type="text")]),
- ),
- ]
-
- await normalizer.normalize(items)
-
- assert resolver.calls == [[["first_result"]], [["second_result"]]]
-
-
-async def test_normalizer_overrides_single_image_reference_types(tmp_path):
- normalizer = SkillFingerprintNormalizer(io_name_resolver=_CreateNewIONameResolver())
-
- result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "image-skill"),
- ExtractedSkillSchema(
- inputs=[
- ParameterSpec(
- name="imageUrl",
- type="url",
- description="Public image URL to process.",
- ),
- ParameterSpec(
- name="image",
- type="text",
- description="图片输入,可以是图片 URL、本地文件路径或图片 BASE64 编码数据。",
- ),
- ParameterSpec(
- name="source_language",
- type="text",
- required=False,
- description="Source language of the text in the image.",
- ),
- ParameterSpec(
- name="homepage_url",
- type="url",
- description="Public product homepage URL.",
- ),
- ParameterSpec(
- name="download_url",
- type="url",
- description="Download URL for a file artifact.",
- ),
- ],
- outputs=[
- ArtifactSpec(
- name="translated_image_url",
- type="url",
- description="URL of the translated image.",
- )
- ],
- ),
- )
-
- input_types = {item.name: item.type for item in result.fingerprint.inputs}
- output_types = {item.name: item.type for item in result.fingerprint.outputs}
- assert input_types["imageurl"] == "image"
- assert input_types["image"] == "image"
- assert input_types["source_language"] == "text"
- assert input_types["homepage_url"] == "url"
- assert input_types["download_url"] == "url"
- assert output_types["translated_image_url"] == "image"
- override_decisions = [
- decision
- for decision in result.decisions
- if decision.field == "type" and decision.method == "semantic_media_override"
- ]
- assert {decision.normalized_value for decision in override_decisions} == {"image"}
- assert {decision.raw_value for decision in override_decisions} == {"url", "text"}
-
-
-async def test_normalizer_resolves_single_skill_candidates_together(tmp_path):
- resolver = _CreateNewIONameResolver()
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
-
- await normalizer.normalize_single(
- _raw_manifest(tmp_path, "skill"),
- ExtractedSkillSchema(
- inputs=[ParameterSpec(name="source_text", type="text")],
- outputs=[ArtifactSpec(name="summary_text", type="text")],
- ),
- )
-
- assert resolver.calls == [[["source_text", "summary_text"]]]
-
-
-async def test_normalizer_aliases_natural_language_command_input_to_text(tmp_path):
- resolver = _CreateNewIONameResolver()
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
-
- result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "calendar-memo"),
- ExtractedSkillSchema(
- inputs=[
- ParameterSpec(
- name="command",
- type="text",
- description="用户指令,如 '添加 明天下午3点 团队周会'",
- )
- ],
- outputs=[ArtifactSpec(name="result", type="markdown")],
- ),
- )
-
- assert resolver.calls == [[["result"]]]
- assert result.fingerprint.inputs[0].name == "text"
- assert normalizer.io_name_vocabulary.lookup("command") == "text"
- name_decisions = [
- decision
- for decision in result.decisions
- if decision.field == "name" and decision.token == "command"
- ]
- assert len(name_decisions) == 1
- assert name_decisions[0].method == "semantic_alias"
- assert name_decisions[0].normalized_value == "text"
-
-
-async def test_normalizer_keeps_control_command_input_as_command(tmp_path):
- resolver = _CreateNewIONameResolver()
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
-
- result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "cli-skill"),
- ExtractedSkillSchema(
- inputs=[
- ParameterSpec(
- name="command",
- type="text",
- description="CLI subcommand to run. Allowed values: start, stop",
- )
- ],
- ),
- )
-
- assert resolver.calls == [[["command"]]]
- assert result.fingerprint.inputs[0].name == "command"
- assert normalizer.io_name_vocabulary.lookup("command") == "command"
-
-
-async def test_normalized_calendar_memo_input_enables_expected_candidates(tmp_path):
- resolver = _CreateNewIONameResolver()
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
- calendar_result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "calendar-memo"),
- ExtractedSkillSchema(
- inputs=[
- ParameterSpec(
- name="command",
- type="text",
- description="用户指令,如 '添加 明天下午3点 团队周会'",
- )
- ],
- outputs=[ArtifactSpec(name="result", type="markdown")],
- ),
- )
- registry = SkillRegistry(
- skills={
- calendar_result.fingerprint.id: calendar_result.fingerprint,
- "speech-to-text": Fingerprint(
- type="skill",
- id="speech-to-text",
- name="speech-to-text",
- description="Transcribe audio to text.",
- version="1.0.0",
- inputs=[ParameterSpec(name="audio", type="audio")],
- outputs=[ArtifactSpec(name="text", type="text")],
- ),
- "general-writing": Fingerprint(
- type="skill",
- id="general-writing",
- name="general-writing",
- description="Write markdown content.",
- version="1.0.0",
- inputs=[ParameterSpec(name="text", type="text")],
- outputs=[ArtifactSpec(name="writing_output", type="markdown")],
- ),
- }
- )
-
- candidate_keys = {
- candidate.key
- for candidate in CandidateGenerator().generate(registry)
- }
-
- assert "speech-to-text->calendar-memo" in candidate_keys
- assert "general-writing->calendar-memo" in candidate_keys
-
-
-async def test_normalizer_aliases_same_skill_candidate_to_batch_created_term(tmp_path):
- resolver = _MappingIONameResolver(
- {
- "content": IONameResolution(
- action="create_new",
- normalized_value="content",
- confidence=0.9,
- reason="canonical",
- ),
- "text": IONameResolution(
- action="alias_existing",
- normalized_value="content",
- confidence=0.9,
- reason="same content role",
- ),
- }
- )
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
-
- result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "skill"),
- ExtractedSkillSchema(
- inputs=[
- ParameterSpec(name="text", type="text"),
- ParameterSpec(name="content", type="text"),
- ],
- ),
- )
-
- assert resolver.calls == [[["text", "content"]]]
- assert [item.name for item in result.fingerprint.inputs] == ["content"]
- assert normalizer.io_name_vocabulary.term_names() == ["content"]
- assert normalizer.io_name_vocabulary.lookup("text") == "content"
- name_methods = {
- decision.token: decision.method
- for decision in result.decisions
- if decision.field == "name" and decision.token in {"text", "content"}
- }
- assert name_methods == {
- "text": "alias_existing",
- "content": "create_new",
- }
-
-
-async def test_normalizer_aliases_cross_skill_candidate_to_batch_created_term(tmp_path):
- resolver = _MappingIONameResolver(
- {
- "content": IONameResolution(
- action="create_new",
- normalized_value="content",
- confidence=0.9,
- reason="canonical",
- ),
- "body": IONameResolution(
- action="merge_existing",
- normalized_value="content",
- confidence=0.9,
- reason="same content role",
- ),
- },
- batch_size=2,
- )
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
- items = [
- (
- _raw_manifest(tmp_path, "skill-1"),
- ExtractedSkillSchema(outputs=[ArtifactSpec(name="content", type="text")]),
- ),
- (
- _raw_manifest(tmp_path, "skill-2"),
- ExtractedSkillSchema(outputs=[ArtifactSpec(name="body", type="text")]),
- ),
- ]
-
- results = await normalizer.normalize(items)
-
- assert resolver.calls == [[["content"], ["body"]]]
- assert [result.fingerprint.outputs[0].name for result in results] == [
- "content",
- "content",
- ]
- assert normalizer.io_name_vocabulary.term_names() == ["content"]
- assert normalizer.io_name_vocabulary.lookup("body") == "content"
-
-
-async def test_normalizer_aliases_candidate_to_existing_vocab_term(tmp_path):
- resolver = _MappingIONameResolver(
- {
- "text": IONameResolution(
- action="alias_existing",
- normalized_value="content",
- confidence=0.9,
- reason="existing synonym",
- ),
- }
- )
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
- normalizer.io_name_vocabulary.create_term("content")
-
- result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "skill"),
- ExtractedSkillSchema(inputs=[ParameterSpec(name="text", type="text")]),
- )
-
- assert resolver.calls == [[["text"]]]
- assert result.fingerprint.inputs[0].name == "content"
- assert normalizer.io_name_vocabulary.lookup("text") == "content"
-
-
-async def test_normalizer_alias_to_unknown_non_batch_target_falls_back_to_token(tmp_path):
- resolver = _MappingIONameResolver(
- {
- "text": IONameResolution(
- action="alias_existing",
- normalized_value="missing_content",
- confidence=0.9,
- reason="bad target",
- ),
- }
- )
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
-
- result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "skill"),
- ExtractedSkillSchema(inputs=[ParameterSpec(name="text", type="text")]),
- )
-
- assert resolver.calls == [[["text"]]]
- assert result.fingerprint.inputs[0].name == "text"
- assert normalizer.io_name_vocabulary.term_names() == ["text"]
- assert normalizer.io_name_vocabulary.lookup("missing_content") is None
-
-
-async def test_normalizer_normalize_single_wraps_single_candidate_batch(tmp_path):
- resolver = _CreateNewIONameResolver()
- normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)
-
- result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "skill"),
- ExtractedSkillSchema(outputs=[ArtifactSpec(name="late_result", type="text")]),
- )
-
- assert result.fingerprint.outputs[0].name == "late_result"
- assert resolver.calls == [[["late_result"]]]
-
-
-async def test_normalizer_can_exclude_candidate_from_io_name_vocab(tmp_path):
- normalizer = SkillFingerprintNormalizer(
- io_name_resolver=_ExcludeFromVocabIONameResolver(),
- )
-
- result = await normalizer.normalize_single(
- _raw_manifest(tmp_path, "skill"),
- ExtractedSkillSchema(
- outputs=[ArtifactSpec(name="tracking_original_copy", type="text")]
- ),
- )
-
- assert result.fingerprint.outputs == []
- assert normalizer.io_name_vocabulary.lookup("tracking_original_copy") is None
- assert result.decisions[-1].method == "exclude_from_vocab"
-
-
-async def test_llm_io_name_resolver_disables_thinking_and_uses_compact_vocab(monkeypatch):
- client = _CaptureJSONClient()
- monkeypatch.setattr(
- "jiuwenswarm.symphony.fingerprint.normalize.io_name_resolver.create_llm_client",
- lambda config: client,
- )
- vocabulary = IONameVocabulary(
- version="test-vocab",
- max_vocab_size=None,
- )
- vocabulary.create_term(
- "content",
- alias="body",
- example="Long example text that should not be sent to the resolver.",
- definition="Generated written content",
- )
- resolver = LLMIONameResolver(
- LLMConfig(
- model="model-a",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- )
- )
-
- result = await resolver.resolve_async(
- [
- [
- IONameCandidate(
- raw_value="text",
- token="text",
- description="Text to process",
- direction="input",
- data_type="text",
- skill_id="skill-a",
- )
- ]
- ],
- vocabulary,
- )
-
- assert result["text"].normalized_value == "content"
- call = client.calls[0]
- assert call["request_overrides"] == _expected_thinking_disabled_overrides()
- payload = json.loads(call["user_content"])
- assert "rules" not in payload
- assert payload["vocabulary"] == [
- {
- "name": "content",
- "definition": "Generated written content",
- "aliases": ["body"],
- }
- ]
- assert "examples" not in payload["vocabulary"][0]
- assert "count" not in payload["vocabulary"][0]
-
-
-async def test_fingerprint_extractor_extract_from_root_reuses_unchanged_fingerprints(tmp_path):
- skills_root = tmp_path / "skills"
- output_dir = tmp_path / "score"
- for index in range(2):
- skill_dir = skills_root / f"skill-{index + 1}"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",
- encoding="utf-8",
- )
- first_schema_extractor = _SchemaExtractor()
- first = await FingerprintExtractor(
- schema_extractor=first_schema_extractor,
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- ).extract_from_root(skills_root, output_dir=output_dir)
- write_extraction_result(first, output_dir)
- _write_state_from_extraction_result(first, output_dir)
-
- second_schema_extractor = _SchemaExtractor()
- second = await FingerprintExtractor(
- schema_extractor=second_schema_extractor,
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- ).extract_from_root(skills_root, output_dir=output_dir)
- forced_schema_extractor = _SchemaExtractor()
- forced = await FingerprintExtractor(
- schema_extractor=forced_schema_extractor,
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- ).extract_from_root(skills_root, output_dir=output_dir, force=True)
-
- assert first.extracted_count == 2
- assert first.reused_count == 0
- assert second.extracted_count == 0
- assert second.reused_count == 2
- assert second_schema_extractor.extract_count == 0
- assert forced.extracted_count == 2
- assert forced.reused_count == 0
- assert forced_schema_extractor.extract_count == 2
-
-
-async def test_fingerprint_extractor_extract_from_root_reextracts_missing_old_fingerprint(tmp_path):
- skills_root = tmp_path / "skills"
- output_dir = tmp_path / "score"
- skill_dir = skills_root / "skill-1"
- skill_dir.mkdir(parents=True)
- (skill_dir / "SKILL.md").write_text(
- "---\nname: Skill 1\n---\n\nTest skill 1.",
- encoding="utf-8",
- )
- folders, current_hashes = SkillFolderScanner().snapshot(skills_root)
- write_score_state(
- ScoreState(
- skills={
- folders[0].relative_path: ScoreStateEntry(
- skill_id="missing-skill",
- relative_path=folders[0].relative_path,
- skill_md_sha256=current_hashes[folders[0].relative_path],
- fingerprint_hash="missing",
- status="active",
- updated_at="2026-06-06T00:00:00+00:00",
- )
- }
- ),
- output_dir,
- )
- schema_extractor = _SchemaExtractor()
-
- result = await FingerprintExtractor(
- schema_extractor=schema_extractor,
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- ).extract_from_root(skills_root, output_dir=output_dir)
-
- assert result.extracted_count == 1
- assert result.reused_count == 0
- assert schema_extractor.extract_count == 1
-
-
-async def test_fingerprint_extractor_extract_from_root_reports_removed_paths_and_max_depth(tmp_path):
- skills_root = tmp_path / "skills"
- output_dir = tmp_path / "score"
- shallow_skill = skills_root / "skill-1"
- nested_skill = skills_root / "nested" / "skill-2"
- shallow_skill.mkdir(parents=True)
- nested_skill.mkdir(parents=True)
- (shallow_skill / "SKILL.md").write_text(
- "---\nname: Skill 1\n---\n\nShallow skill.",
- encoding="utf-8",
- )
- (nested_skill / "SKILL.md").write_text(
- "---\nname: Skill 2\n---\n\nNested skill.",
- encoding="utf-8",
- )
- write_score_state(
- ScoreState(
- skills={
- "removed-skill": ScoreStateEntry(
- skill_id="removed-skill",
- relative_path="removed-skill",
- skill_md_sha256="old-hash",
- fingerprint_hash="old-fingerprint-hash",
- status="active",
- updated_at="2026-06-06T00:00:00+00:00",
- )
- }
- ),
- output_dir,
- )
-
- result = await FingerprintExtractor(
- schema_extractor=_SchemaExtractor(),
- normalizer=SkillFingerprintNormalizer(
- io_name_resolver=_CreateNewIONameResolver(),
- ),
- ).extract_from_root(skills_root, output_dir=output_dir, max_depth=1)
-
- assert [folder.relative_path for folder in result.folders] == ["skill-1"]
- assert result.extracted_count == 1
- assert result.removed_paths == {"removed-skill"}
-
-
-async def test_graph_builder_call_emits_progress_and_supports_no_progress():
- fingerprints = [
- Fingerprint(
- type="skill",
- id="skill-1",
- name="Skill 1",
- description="Test skill",
- version="1.0.0",
- inputs=[ParameterSpec(name="input", type="text")],
- outputs=[ArtifactSpec(name="result", type="text")],
- )
- ]
- progress = []
- builder = GraphBuilder(matcher=_NoopMatcher())
-
- result = await builder.build(
- fingerprints,
- progress=lambda stage, **details: progress.append(
- {"stage": stage, **details}
- ),
- )
- result_without_progress = await GraphBuilder(matcher=_NoopMatcher()).build(fingerprints)
-
- assert result.graph.nodes
- assert result_without_progress.graph.nodes
- assert [entry["stage"] for entry in progress] == [
- "graph.registry.start",
- "graph.registry.done",
- "graph.candidates.start",
- "graph.candidates.done",
- "graph.resolve.start",
- "graph.resolve.done",
- "graph.materialize.start",
- "graph.materialize.done",
- "graph.score.start",
- "graph.score.done",
- ]
-
-
-async def test_graph_matcher_merges_concurrent_batches_by_batch_index():
- matcher = _OutOfOrderBatchMatcher()
- 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(1, 4)
- ]
-
- matches = await matcher.match(SkillRegistry(skills={}), candidates)
-
- assert [match.candidate_id for match in matches] == [
- "candidate-1",
- "candidate-2",
- "candidate-3",
- ]
- assert [diagnostic.message for diagnostic in matcher.diagnostics] == [
- "batch 1",
- "batch 2",
- "batch 3",
- ]
-
-
-def test_default_llm_factories_keep_batch_settings_out_of_llm_config():
- runtime_config = symphony_config_from_dict(
- {
- "fingerprint": {
- "extraction": {
- "batch_size": 3,
- "body_limit": 5000,
- },
- "normalization": {"batch_size": 6},
- },
- }
- )
- llm_config = LLMConfig(
- model="model",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- )
-
- factory = ScoreBuildRuntimeFactory()
- extractor = factory.schema_extractor(
- llm_config,
- runtime_config.fingerprint.extraction,
- )
- resolver = factory.io_name_resolver(
- llm_config,
- runtime_config.fingerprint.normalization,
- )
-
- assert not hasattr(llm_config, "batch_size")
- assert extractor.batch_size == 3
- assert extractor.body_limit == 5000
- assert resolver.batch_size == 6
-
-
-def test_default_io_name_resolver_requires_llm_config():
- runtime_config = symphony_config_from_dict({})
-
- with pytest.raises(ValueError, match="llm_config is required"):
- ScoreBuildRuntimeFactory().io_name_resolver(
- None,
- runtime_config.fingerprint.normalization,
- )
-
-
-def test_skill_fingerprint_normalizer_requires_io_name_resolver():
- with pytest.raises(ValueError, match="requires io_name_resolver"):
- SkillFingerprintNormalizer()
-
-
-def test_fingerprint_extractor_requires_normalizer():
- with pytest.raises(ValueError, match="requires normalizer"):
- FingerprintExtractor(schema_extractor=_SchemaExtractor())
diff --git a/tests/unit_tests/symphony/test_language.py b/tests/unit_tests/symphony/test_language.py
deleted file mode 100644
index 1fa7ee3f6c..0000000000
--- a/tests/unit_tests/symphony/test_language.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from jiuwenswarm.symphony.orchestration.language import (
- default_plan_title,
- resolve_orchestration_language,
-)
-
-
-def test_resolve_orchestration_language_maps_config_values() -> None:
- assert resolve_orchestration_language("zh") == "cn"
- assert resolve_orchestration_language("cn") == "cn"
- assert resolve_orchestration_language("en") == "en"
-
-
-def test_resolve_orchestration_language_falls_back_to_chinese() -> None:
- assert resolve_orchestration_language("fr") == "cn"
- assert resolve_orchestration_language(None) == "cn"
-
-
-def test_deterministic_copy_uses_selected_language() -> None:
- assert default_plan_title("cn") == "Symphony 编排计划"
- assert default_plan_title("en") == "Symphony plan"
diff --git a/tests/unit_tests/symphony/test_llm.py b/tests/unit_tests/symphony/test_llm.py
index a8a4ebbc29..ae907a1a7c 100644
--- a/tests/unit_tests/symphony/test_llm.py
+++ b/tests/unit_tests/symphony/test_llm.py
@@ -3,9 +3,11 @@ from types import SimpleNamespace
import pytest
+from jiuwenswarm.symphony.adapter import llm_config_signature
from jiuwenswarm.symphony.llm import (
LLMConfig,
create_llm_client,
+ create_model_response_observer,
extract_message_content,
get_llm_token_usage_summary,
reset_llm_token_usage,
@@ -66,7 +68,7 @@ def test_thinking_disabled_request_overrides_returns_isolated_compatibility_fiel
def test_extract_message_content_supports_openjiuwen_response_shape():
- response = SimpleNamespace(content=[{"text": "{\"ok\": true}"}])
+ response = SimpleNamespace(content=[{"text": '{"ok": true}'}])
assert extract_message_content(response) == '{"ok": true}'
@@ -96,7 +98,11 @@ def test_llm_config_from_default_models(monkeypatch):
"timeout": 12,
"verify_ssl": False,
},
- "model_config_obj": {"temperature": 0.2, "top_p": 0.8, "max_tokens": 99},
+ "model_config_obj": {
+ "temperature": 0.2,
+ "top_p": 0.8,
+ "max_tokens": 99,
+ },
}
],
)
@@ -131,7 +137,10 @@ def test_llm_config_removes_internal_reasoning_level():
assert "reasoning_level" not in request_kwargs
assert request_kwargs["max_tokens"] == 99
- assert request_kwargs["extra_body"] == thinking_disabled_request_overrides()["extra_body"]
+ assert (
+ request_kwargs["extra_body"]
+ == thinking_disabled_request_overrides()["extra_body"]
+ )
def test_llm_config_forces_high_reasoning_config_to_disabled():
@@ -183,7 +192,9 @@ def test_llm_config_owns_nested_model_entry_data():
assert entry == original
assert config.model_client_kwargs()["custom_headers"] == {"X-Test": "original"}
assert config.model_request_kwargs()["response_format"] == {"type": "json_object"}
- assert config.model_request_kwargs()["extra_body"]["custom_option"] == {"enabled": True}
+ assert config.model_request_kwargs()["extra_body"]["custom_option"] == {
+ "enabled": True
+ }
def test_llm_config_prefers_resolved_default_model(monkeypatch):
@@ -244,6 +255,155 @@ def test_create_llm_client_uses_jiuwenswarm_client():
assert type(client).__name__ == "JiuwenSwarmChatClient"
+def test_llm_config_creates_native_openjiuwen_model(monkeypatch):
+ captured = {}
+
+ class FakeModel:
+ def __init__(self, *, model_client_config, model_config):
+ captured["client"] = model_client_config
+ captured["request"] = model_config
+
+ monkeypatch.setattr("openjiuwen.core.foundation.llm.Model", FakeModel)
+
+ model = _llm_config().create_model()
+
+ assert isinstance(model, FakeModel)
+ assert captured["request"].model_name == "model-a"
+ assert captured["client"].api_base == "https://example.test/v1"
+
+
+def test_model_response_observer_preserves_orchestration_usage_context():
+ reset_llm_token_usage()
+ config = _llm_config()
+ observer = create_model_response_observer(config)
+
+ observer(
+ SimpleNamespace(
+ usage_metadata=SimpleNamespace(
+ input_tokens=7,
+ output_tokens=3,
+ total_tokens=10,
+ )
+ ),
+ "orchestration",
+ "beam_final_rerank",
+ )
+
+ summary = get_llm_token_usage_summary()
+ assert summary["by_stage"]["orchestration"]["total_tokens"] == 10
+ assert (
+ summary["by_operation"]["orchestration.beam_final_rerank"]["request_count"] == 1
+ )
+ reset_llm_token_usage()
+
+
+def test_llm_identity_digest_is_complete_stable_and_redacted():
+ config = LLMConfig(
+ model="model-a",
+ temperature=0.2,
+ top_p=0.8,
+ model_client_config={
+ "api_key": "super-secret-api-key",
+ "api_base": "https://private-endpoint.example/v1/",
+ "client_provider": "openai",
+ "routing": {"region": "region-a", "credential": "route-secret"},
+ },
+ model_config_obj={
+ "max_tokens": 99,
+ "extra_body": {
+ "request_route": "route-a",
+ "token": "request-secret",
+ },
+ },
+ )
+
+ reordered_config = LLMConfig(
+ model="model-a",
+ temperature=0.2,
+ top_p=0.8,
+ model_client_config={
+ "routing": {"credential": "route-secret", "region": "region-a"},
+ "client_provider": "openai",
+ "api_base": "https://private-endpoint.example/v1/",
+ "api_key": "super-secret-api-key",
+ },
+ model_config_obj={
+ "extra_body": {
+ "token": "request-secret",
+ "request_route": "route-a",
+ },
+ "max_tokens": 99,
+ },
+ )
+ digest = config.identity_digest()
+
+ assert digest == reordered_config.identity_digest()
+ assert digest == llm_config_signature(config)
+ assert len(digest) == 64
+ for sensitive_value in (
+ "super-secret-api-key",
+ "https://private-endpoint.example/v1",
+ "route-secret",
+ "request-secret",
+ ):
+ assert sensitive_value not in digest
+
+
+ ("field", "updated_client", "updated_request", "updated_top_p"),
+ [
+ (
+ "endpoint",
+ {"api_base": "https://endpoint-b.example/v1"},
+ {},
+ 0.2,
+ ),
+ ("provider", {"client_provider": "azure"}, {}, 0.2),
+ ("routing", {"routing_region": "region-b"}, {}, 0.2),
+ (
+ "request",
+ {},
+ {"extra_body": {"request_route": "request-b"}},
+ 0.2,
+ ),
+ ("top_p", {}, {}, 0.9),
+ ],
+)
+def test_llm_identity_digest_changes_for_every_client_affecting_setting(
+ field,
+ updated_client,
+ updated_request,
+ updated_top_p,
+):
+ del field
+ client_config = {
+ "api_key": "secret",
+ "api_base": "https://endpoint-a.example/v1",
+ "client_provider": "openai",
+ "routing_region": "region-a",
+ }
+ request_config = {
+ "max_tokens": 99,
+ "extra_body": {"request_route": "request-a"},
+ }
+ baseline = LLMConfig(
+ model="model-a",
+ temperature=0.0,
+ top_p=0.2,
+ model_client_config=client_config,
+ model_config_obj=request_config,
+ )
+ changed = LLMConfig(
+ model="model-a",
+ temperature=0.0,
+ top_p=updated_top_p,
+ model_client_config={**client_config, **updated_client},
+ model_config_obj={**request_config, **updated_request},
+ )
+
+ assert baseline.identity_digest() != changed.identity_digest()
+
+
@pytest.mark.asyncio
async def test_complete_json_async_passes_request_overrides_to_invoke():
client = create_llm_client(_llm_config())
@@ -260,9 +420,7 @@ async def test_complete_json_async_passes_request_overrides_to_invoke():
assert result == '{"ok": true}'
assert "reasoning_effort" not in fake_model.calls[0]
- assert fake_model.calls[0]["extra_body"] == {
- "thinking": {"type": "disabled"}
- }
+ assert fake_model.calls[0]["extra_body"] == {"thinking": {"type": "disabled"}}
@pytest.mark.asyncio
@@ -295,10 +453,7 @@ async def test_complete_json_many_async_passes_request_overrides_to_each_invoke(
assert results == ['{"ok": true}', '{"ok": true}']
assert all("reasoning_effort" not in call for call in fake_model.calls)
- assert [
- call["extra_body"]
- for call in fake_model.calls
- ] == [
+ assert [call["extra_body"] for call in fake_model.calls] == [
{"thinking": {"type": "disabled"}},
{"thinking": {"type": "disabled"}},
]
diff --git a/tests/unit_tests/symphony/test_llm_concurrency.py b/tests/unit_tests/symphony/test_llm_concurrency.py
index 420d0e6108..8452355232 100644
--- a/tests/unit_tests/symphony/test_llm_concurrency.py
+++ b/tests/unit_tests/symphony/test_llm_concurrency.py
@@ -1,13 +1,10 @@
import asyncio
-import json
import pytest
from jiuwenswarm.symphony.fingerprint.batching import gather_limited
from jiuwenswarm.symphony.fingerprint.models import (
- ArtifactSpec,
ExtractedSkillSchema,
- Fingerprint,
ParameterSpec,
RawSkillManifest,
SkillFolder,
@@ -17,60 +14,6 @@ from jiuwenswarm.symphony.fingerprint.normalize import (
SkillFingerprintNormalizer,
)
from jiuwenswarm.symphony.fingerprint.pipeline import FingerprintExtractor
-from jiuwenswarm.symphony.graph import (
- OpenAICompatibleOntologyMatcher,
- RelationCandidate,
- SkillRegistry,
-)
-from jiuwenswarm.symphony.llm import LLMConfig
-
-
-class _DelayedMatchClient:
- def __init__(self, delay=0.02):
- self.delay = delay
- self.active = 0
- self.max_active = 0
- self.call_count = 0
-
- async def complete_json_async(self, **kwargs):
- del kwargs
- self.call_count += 1
- self.active += 1
- self.max_active = max(self.max_active, self.active)
- try:
- await asyncio.sleep(self.delay)
- finally:
- self.active -= 1
- return json.dumps(
- {
- "matches": [
- {
- "id": "c1",
- "direction": "forward",
- "confidence": 0.95,
- }
- ]
- }
- )
-
-
-class _FailingMatchClient:
- def __init__(self):
- self.call_count = 0
- self.cancelled_count = 0
-
- async def complete_json_async(self, **kwargs):
- del kwargs
- self.call_count += 1
- if self.call_count == 1:
- await asyncio.sleep(0)
- raise RuntimeError("forward failed")
- try:
- await asyncio.sleep(10)
- except asyncio.CancelledError:
- self.cancelled_count += 1
- raise
- return '{"matches":[]}'
class _VocabularyObservingResolver:
@@ -92,120 +35,6 @@ class _VocabularyObservingResolver:
}
-def _llm_config():
- return LLMConfig(
- model="model-a",
- model_client_config={
- "api_key": "key",
- "api_base": "https://example.test/v1",
- "client_provider": "openai",
- },
- )
-
-
-def _fingerprint(skill_id, *, consumes):
- return Fingerprint(
- type="skill",
- id=skill_id,
- name=skill_id,
- description="Consumes input" if consumes else "Produces result",
- version="1.0.0",
- inputs=[ParameterSpec(name="input", type="text")] if consumes else [],
- outputs=[] if consumes else [ArtifactSpec(name="result", type="text")],
- )
-
-
-def _registry_and_candidates(count):
- skills = {}
- candidates = []
- for index in range(count):
- source_id = f"source-{index}"
- target_id = f"target-{index}"
- skills[source_id] = _fingerprint(source_id, consumes=False)
- skills[target_id] = _fingerprint(target_id, consumes=True)
- candidates.append(
- RelationCandidate(
- source_id=source_id,
- target_id=target_id,
- relation_hints=["can_feed"],
- candidate_methods=["test"],
- priority="high",
- evidence={
- "directions": {
- f"{source_id}->{target_id}": {
- "port_mappings": [
- {
- "source_output": "result",
- "target_input": "input",
- }
- ],
- "source_outputs": [{"name": "result"}],
- "target_inputs": [{"name": "input"}],
- }
- }
- },
- )
- )
- return SkillRegistry(skills=skills), candidates
-
-
-def _matcher(monkeypatch, client, *, workers):
- monkeypatch.setattr(
- "jiuwenswarm.symphony.graph.matcher.openai.create_llm_client",
- lambda config: client,
- )
- return OpenAICompatibleOntologyMatcher(
- _llm_config(),
- batch_size=1,
- max_workers=workers,
- require_consensus=True,
- )
-
-
- ("workers", "candidate_count", "expected_max_active"),
- [(1, 1, 1), (2, 1, 2), (3, 3, 3)],
-)
-async def test_graph_consensus_respects_request_worker_limit(
- monkeypatch,
- workers,
- candidate_count,
- expected_max_active,
-):
- client = _DelayedMatchClient(delay=0.01)
- matcher = _matcher(monkeypatch, client, workers=workers)
- registry, candidates = _registry_and_candidates(candidate_count)
-
- await matcher.match(registry, candidates)
-
- assert client.call_count == candidate_count * 2
- assert client.max_active == expected_max_active
-
-
- ("candidate_count", "workers", "expected_calls", "expected_cancelled"),
- [(1, 2, 2, 1), (2, 4, 4, 3)],
-)
-async def test_graph_failure_cancels_remaining_requests(
- monkeypatch,
- candidate_count,
- workers,
- expected_calls,
- expected_cancelled,
-):
- client = _FailingMatchClient()
- matcher = _matcher(monkeypatch, client, workers=workers)
- registry, candidates = _registry_and_candidates(candidate_count)
-
- with pytest.raises(RuntimeError, match="forward failed"):
- await matcher.match(registry, candidates)
-
- assert client.call_count == expected_calls
- assert client.cancelled_count == expected_cancelled
-
-
@pytest.mark.asyncio
async def test_extraction_batches_preserve_order_and_worker_limit():
active = 0
diff --git a/tests/unit_tests/symphony/test_llm_payload_compaction.py b/tests/unit_tests/symphony/test_llm_payload_compaction.py
deleted file mode 100644
index e6055d3487..0000000000
--- a/tests/unit_tests/symphony/test_llm_payload_compaction.py
+++ /dev/null
@@ -1,420 +0,0 @@
-import json
-from pathlib import Path
-
-import pytest
-
-from jiuwenswarm.symphony.fingerprint.extract.extractor import (
- _SCHEMA_EXTRACTION_PROMPT,
- _build_llm_context,
- schema_from_llm_payload,
-)
-from jiuwenswarm.symphony.fingerprint.models import (
- ArtifactSpec,
- Fingerprint,
- ParameterSpec,
- RawSkillManifest,
- SkillFolder,
-)
-from jiuwenswarm.symphony.fingerprint.normalize import (
- IONameCandidate,
- IONameVocabTerm,
- IONameVocabulary,
- LLMIONameResolver,
-)
-from jiuwenswarm.symphony.fingerprint.normalize.io_name_resolver import (
- _resolution_from_payload,
-)
-from jiuwenswarm.symphony.llm import LLMConfig
-from jiuwenswarm.symphony import build as build_module
-from jiuwenswarm.symphony.config import symphony_config_from_dict
-from jiuwenswarm.symphony.graph.matcher.openai import (
- OpenAICompatibleOntologyMatcher,
-)
-from jiuwenswarm.symphony.graph.matcher import prompt as graph_prompt
-from jiuwenswarm.symphony.graph.models import RelationCandidate, SkillRegistry
-
-
-def _manifest(
- body: str,
- *,
- frontmatter: dict | None = None,
- relative_path: str = "example",
-) -> RawSkillManifest:
- return RawSkillManifest(
- folder=SkillFolder(
- id_hint="example",
- path=Path("skills/example"),
- entry=Path("skills/example/SKILL.md"),
- relative_path=relative_path,
- ),
- frontmatter=frontmatter or {},
- body=body,
- body_sha256="digest",
- )
-
-
-def test_schema_prompt_is_at_least_45_percent_shorter():
- assert len(_SCHEMA_EXTRACTION_PROMPT) <= 2498
-
-
-def test_schema_context_preserves_non_empty_frontmatter_without_source_metadata():
- context = _build_llm_context(
- _manifest(
- "Full body.",
- frontmatter={
- "name": "example",
- "description": "Example skill.",
- "metadata": {"owner": "team", "empty": ""},
- "license": None,
- "tags": [],
- },
- )
- )
-
- assert context == {
- "frontmatter": {
- "name": "example",
- "description": "Example skill.",
- "metadata": {"owner": "team"},
- },
- "body": "Full body.",
- }
-
-
-def test_schema_context_uses_short_ref_only_for_batch_correlation():
- context = _build_llm_context(
- _manifest("Full body.", relative_path="long/path/to/example"),
- skill_ref="s1",
- )
-
- assert context == {"skill_ref": "s1", "body": "Full body."}
-
-
-def test_schema_context_only_marks_actual_truncation():
- full = _build_llm_context(_manifest("short"), body_limit=20)
- truncated = _build_llm_context(_manifest("long body"), body_limit=4)
-
- assert "body_truncated" not in full
- assert truncated == {"body": "long", "body_truncated": True}
-
-
-def test_schema_warnings_are_limited_and_truncated():
- schema = schema_from_llm_payload(
- {
- "warnings": ["a" * 200, "second", "", "fourth"],
- "raw_output_notes": ["third", "ignored"],
- }
- )
-
- assert schema.warnings == ["a" * 160, "second", "fourth"]
-
-
-def test_compact_schema_context_is_smaller_than_pretty_json():
- context = _build_llm_context(_manifest("body", frontmatter={"name": "example"}))
- compact = json.dumps(context, ensure_ascii=False, separators=(",", ":"))
- pretty = json.dumps(context, ensure_ascii=False, indent=2)
-
- assert len(compact) < len(pretty)
-
-
-class _IOCaptureClient:
- def __init__(self) -> None:
- self.call = None
-
- async def complete_json_async(self, **kwargs):
- self.call = kwargs
- return json.dumps(
- {
- "resolutions": [
- {
- "id": "i1",
- "action": "alias_existing",
- "target": "content",
- "confidence": 0.9,
- }
- ]
- }
- )
-
-
-async def test_io_resolution_uses_compact_ids_and_full_clean_vocabulary():
- resolver = LLMIONameResolver(LLMConfig(model="test"))
- client = _IOCaptureClient()
- resolver.client = client
- vocabulary = IONameVocabulary(
- version="v1",
- max_vocab_size=20,
- terms=[
- IONameVocabTerm(
- name="content",
- definition="Content value." + ("x" * 200),
- aliases={"body", "body", ""},
- )
- ],
- )
- candidate = IONameCandidate(
- raw_value="input_text",
- token="input_text",
- description="Text supplied by the caller.",
- skill_id="long-skill-id",
- direction="input",
- data_type="text",
- )
-
- result = await resolver.resolve_async([[candidate]], vocabulary)
-
- payload = json.loads(client.call["user_content"])
- assert payload == {
- "candidates": [
- {
- "id": "i1",
- "token": "input_text",
- "description": "Text supplied by the caller.",
- "direction": "input",
- "type": "text",
- }
- ],
- "vocabulary": [
- {
- "name": "content",
- "definition": ("Content value." + ("x" * 200))[:160],
- "aliases": ["body"],
- }
- ],
- }
- assert result["input_text"].normalized_value == "content"
- assert "\n" not in client.call["user_content"]
-
-
-def test_io_resolution_reason_is_optional_and_truncated():
- vocabulary = IONameVocabulary(version="v1", max_vocab_size=20, terms=[])
-
- missing = _resolution_from_payload(
- {"action": "create_new", "target": "report", "confidence": 0.8},
- vocabulary,
- )
- long = _resolution_from_payload(
- {
- "action": "create_new",
- "target": "report",
- "confidence": 0.8,
- "reason": "r" * 200,
- },
- vocabulary,
- )
-
- assert missing.reason == ""
- assert long.reason == "r" * 160
-
-
-def _graph_fixture():
- source_output = ArtifactSpec(
- name="report",
- type="markdown",
- description="Generated report." + ("o" * 200),
- )
- target_input = ParameterSpec(
- name="document",
- type="markdown",
- description="Document to review." + ("i" * 200),
- )
- source = Fingerprint(
- type="skill",
- id="source-with-a-long-id",
- name="Source",
- description="Produces a report." + ("s" * 300),
- version="1",
- inputs=[],
- outputs=[source_output],
- )
- target = Fingerprint(
- type="skill",
- id="target-with-a-long-id",
- name="Target",
- description="Reviews a report." + ("t" * 300),
- version="1",
- inputs=[target_input],
- outputs=[],
- )
- mapping = {
- "source_output": "report",
- "source_type": "markdown",
- "target_input": "document",
- "target_type": "markdown",
- "match_method": "semantic_overlap_match",
- "match_reason": "descriptions overlap",
- }
- candidate = RelationCandidate(
- source_id=source.id,
- target_id=target.id,
- relation_hints=["can_feed"],
- candidate_methods=["semantic_overlap_match"],
- priority="medium",
- evidence={
- "directions": {
- f"{source.id}->{target.id}": {
- "source_outputs": [source_output.to_dict()],
- "target_inputs": [target_input.to_dict()],
- "port_mappings": [mapping],
- "matched_terms": ["report"],
- }
- }
- },
- )
- return SkillRegistry(skills={source.id: source, target.id: target}), candidate
-
-
-def test_graph_context_only_contains_compact_candidate_evidence():
- registry, candidate = _graph_fixture()
-
- context = graph_prompt.build_llm_context(registry, [candidate])
-
- assert set(context) == {"candidates"}
- item = context["candidates"][0]
- assert item["id"] == "c1"
- assert item["source"] == {
- "name": "Source",
- "description": registry.skills[candidate.source_id].description[:240],
- }
- assert item["target"] == {
- "name": "Target",
- "description": registry.skills[candidate.target_id].description[:240],
- }
- forward = item["directions"]["forward"]
- assert forward["outputs"] == [{
- "name": "report",
- "type": "markdown",
- "description": registry.skills[candidate.source_id].outputs[0].description[:160],
- }]
- assert forward["inputs"] == [{
- "name": "document",
- "type": "markdown",
- "required": True,
- "description": registry.skills[candidate.target_id].inputs[0].description[:160],
- }]
- assert forward["ports"] == [{
- "output": "report",
- "output_type": "markdown",
- "input": "document",
- "input_type": "markdown",
- }]
- assert not {
- "input_sha256",
- "allowed_relation_types",
- "priority",
- "candidate_methods",
- } & set(item)
-
-
-def test_graph_compact_response_is_expanded_from_candidate_evidence():
- registry, candidate = _graph_fixture()
- expand = getattr(graph_prompt, "expand_compact_llm_response", None)
-
- assert callable(expand)
- payload, diagnostics = expand(
- {
- "matches": [
- {
- "id": "c1",
- "direction": "forward",
- "confidence": 0.92,
- "reason": "r" * 200,
- }
- ]
- },
- [candidate],
- )
-
- assert diagnostics == []
- match = payload["matches"][0]
- assert match == {
- "candidate_id": candidate.key,
- "source_id": candidate.source_id,
- "target_id": candidate.target_id,
- "relation_type": "can_feed",
- "confidence": 0.92,
- "method": "llm_ontology_match",
- "reasons": ["r" * 160],
- "supporting_fields": {
- "port_mappings": [{"source_output": "report", "target_input": "document"}],
- "source_outputs": ["report"],
- "target_inputs": ["document"],
- },
- }
-
-
-def test_graph_compact_response_reports_unknown_and_duplicate_ids():
- _, candidate = _graph_fixture()
- expand = getattr(graph_prompt, "expand_compact_llm_response", None)
-
- assert callable(expand)
- payload, diagnostics = expand(
- {
- "matches": [
- {"id": "unknown", "direction": "forward", "confidence": 0.8},
- {"id": "c1", "direction": "forward", "confidence": 0.8},
- {"id": "c1", "direction": "forward", "confidence": 0.9},
- ]
- },
- [candidate],
- )
-
- assert len(payload["matches"]) == 1
- assert [item.code for item in diagnostics] == [
- "unknown_candidate_id",
- "duplicate_candidate_id",
- ]
-
-
-def test_graph_context_supports_legacy_direct_candidate_evidence_shape():
- registry, candidate = _graph_fixture()
- direct_candidate = RelationCandidate(
- source_id=candidate.source_id,
- target_id=candidate.target_id,
- relation_hints=candidate.relation_hints,
- candidate_methods=candidate.candidate_methods,
- priority=candidate.priority,
- evidence=candidate.evidence["directions"][candidate.key],
- )
-
- context = graph_prompt.build_llm_context(registry, [direct_candidate])
-
- assert "forward" in context["candidates"][0]["directions"]
-
-
-def test_graph_context_is_at_least_50_percent_smaller_than_previous_shape():
- registry, candidate = _graph_fixture()
- compact = graph_prompt.build_llm_context(registry, [candidate])
- previous = {
- "allowed_relation_types": ["can_feed"],
- "skills": [
- registry.skills[candidate.source_id].graph_identity_dict(),
- registry.skills[candidate.target_id].graph_identity_dict(),
- ],
- "candidates": [candidate.to_dict()],
- "input_sha256": "x" * 64,
- }
-
- compact_size = len(json.dumps(compact, ensure_ascii=False, separators=(",", ":")))
- previous_size = len(json.dumps(previous, ensure_ascii=False, separators=(",", ":")))
-
- assert compact_size <= previous_size * 0.5
-
-
-def test_prompt_protocol_versions_invalidate_fingerprint_and_relation_caches(
- monkeypatch,
-):
- config = symphony_config_from_dict({})
- llm_config = LLMConfig(model="test")
- first = build_module._fingerprint_signature(config, llm_config)
- monkeypatch.setattr(
- build_module,
- "SCHEMA_EXTRACTION_PROTOCOL_VERSION",
- "symphony-schema-extraction-v3",
- )
- second = build_module._fingerprint_signature(config, llm_config)
- matcher = OpenAICompatibleOntologyMatcher(llm_config)
-
- assert first != second
- assert matcher.prompt_version == "Orchestration-graph-match-v2"
diff --git a/tests/unit_tests/symphony/test_llm_required.py b/tests/unit_tests/symphony/test_llm_required.py
deleted file mode 100644
index 6de0ab5781..0000000000
--- a/tests/unit_tests/symphony/test_llm_required.py
+++ /dev/null
@@ -1,29 +0,0 @@
-import pytest
-
-from jiuwenswarm.symphony.llm import create_llm_client
-from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
-from jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlanner
-
-
-def test_create_llm_client_requires_config():
- with pytest.raises(ValueError, match="requires LLMConfig"):
- create_llm_client(None)
-
-
-async def test_fast_planner_requires_llm_config_or_client(tmp_path):
- planner = FastOneShotPlanner(
- ScoreArtifacts(
- score_dir=tmp_path,
- manifest={},
- skills=[],
- graph={"edges": []},
- lookup={},
- ),
- llm_config=None,
- llm_client=None,
- min_edge_confidence=0.7,
- )
-
- with pytest.raises(ValueError, match="requires llm_config or llm_client"):
- await planner.plan("test")
diff --git a/tests/unit_tests/symphony/test_planning_modules.py b/tests/unit_tests/symphony/test_planning_modules.py
deleted file mode 100644
index 6f0e10757c..0000000000
--- a/tests/unit_tests/symphony/test_planning_modules.py
+++ /dev/null
@@ -1,88 +0,0 @@
-from jiuwenswarm.symphony.orchestration.planning.models import (
- ArtifactRef,
- PlanStep,
- SearchState,
-)
-from jiuwenswarm.symphony.orchestration.planning.plan_builder import (
- plan_stages,
- state_to_plan,
-)
-
-
-def test_plan_stages_parallelizes_roots():
- steps = [_step("review"), _step("draft"), _step("publish")]
- edges = [
- {"source_id": "draft", "target_id": "publish"},
- {"source_id": "review", "target_id": "publish"},
- ]
-
- stages = plan_stages(steps, edges)
-
- assert [[skill["skill_id"] for skill in stage["skills"]] for stage in stages] == [
- ["draft", "review"],
- ["publish"],
- ]
-
-
-def test_state_to_plan_projects_inputs_outputs_and_edge_metadata():
- skills = {
- "draft": {
- "id": "draft",
- "name": "Draft",
- "inputs": [{"name": "brief", "type": "text", "required": True}],
- "outputs": [{"name": "draft", "type": "markdown"}],
- },
- "review": {
- "id": "review",
- "name": "Review",
- "inputs": [{"name": "draft", "type": "markdown", "required": True}],
- "outputs": [{"name": "review", "type": "markdown"}],
- },
- }
- edges = [
- {
- "source": "skill:draft",
- "target": "skill:review",
- "confidence": 0.92,
- "method": "llm",
- "evidence": {
- "reasons": ["draft feeds review"],
- "supporting_fields": {
- "source_outputs": ["draft"],
- "target_inputs": ["draft"],
- "port_mappings": [
- {"source_output": "draft", "target_input": "draft"}
- ],
- },
- },
- }
- ]
-
- plan = state_to_plan(
- state=SearchState(skill_ids=("draft", "review"), edges=(0,)),
- seed_skill_ids=("review",),
- skill_by_id=skills,
- can_feed_edges=edges,
- )
-
- assert plan.status == "needs_input"
- assert [step.skill_id for step in plan.steps] == ["draft", "review"]
- assert plan.missing_inputs == [
- {"name": "brief", "type": "text", "skill_id": "draft"}
- ]
- assert plan.consumed_user_artifacts == 0
- assert plan.produced_artifacts == [
- ArtifactRef(name="draft", type="markdown", source="skill_output"),
- ArtifactRef(name="review", type="markdown", source="skill_output"),
- ]
- assert plan.can_feed_edges[0]["source_id"] == "draft"
- assert plan.can_feed_edges[0]["target_id"] == "review"
-
-
-def _step(skill_id: str) -> PlanStep:
- return PlanStep(
- skill_id=skill_id,
- name=skill_id.title(),
- inputs=[],
- outputs=[],
- )
diff --git a/tests/unit_tests/symphony/test_registry.py b/tests/unit_tests/symphony/test_registry.py
deleted file mode 100644
index 8f50da78c7..0000000000
--- a/tests/unit_tests/symphony/test_registry.py
+++ /dev/null
@@ -1,48 +0,0 @@
-import pytest
-
-from jiuwenswarm.extensions.registry import ExtensionRegistry
-
-
-class _CallbackFramework:
- @staticmethod
- def register_sync(*args, **kwargs):
- return None
-
- async def trigger(self, *args, **kwargs):
- return None
-
-
-def setup_function():
- ExtensionRegistry.reset_instance()
-
-
-def teardown_function():
- ExtensionRegistry.reset_instance()
-
-
-def test_extension_registry_registers_rpc_handlers():
- registry = ExtensionRegistry.create_instance(
- callback_framework=_CallbackFramework(),
- config={},
- logger=object(),
- )
-
- async def handler(params, *, request=None):
- return {"params": params, "request_id": getattr(request, "request_id", "")}
-
- registry.register_rpc_handler("symphony.plan", handler)
-
- assert registry.get_rpc_handler("symphony.plan") is handler
- assert registry.get_rpc_handler("symphony.missing") is None
- assert registry.list_rpc_methods() == ["symphony.plan"]
-
-
-def test_extension_registry_rejects_invalid_rpc_method():
- registry = ExtensionRegistry.create_instance(
- callback_framework=_CallbackFramework(),
- config={},
- logger=object(),
- )
-
- with pytest.raises(ValueError):
- registry.register_rpc_handler("", lambda params: params)
diff --git a/tests/unit_tests/symphony/test_service.py b/tests/unit_tests/symphony/test_service.py
deleted file mode 100644
index 0c447e6129..0000000000
--- a/tests/unit_tests/symphony/test_service.py
+++ /dev/null
@@ -1,1151 +0,0 @@
-import json
-
-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:
- def __init__(self, response: dict):
- self.response = response
- self.calls = []
-
- async def complete_json_async(self, **kwargs):
- self.calls.append(kwargs)
- return json.dumps(self.response)
-
-
-def _artifacts(tmp_path, *, graph_skill_prefix: bool = False):
- def graph_id(value: str) -> str:
- return f"skill:{value}" if graph_skill_prefix else value
-
- return ScoreArtifacts(
- score_dir=tmp_path,
- manifest={},
- skills=[
- {
- "id": "skill-a",
- "name": "Alpha Skill",
- "description": "Creates an alpha draft.",
- "inputs": [{"name": "brief", "type": "text", "required": True}],
- "outputs": [{"name": "draft", "type": "markdown"}],
- },
- {
- "id": "skill-b",
- "name": "Beta Skill",
- "description": "Reviews an alpha draft for beta quality.",
- "inputs": [{"name": "draft", "type": "markdown", "required": True}],
- "outputs": [{"name": "review", "type": "markdown"}],
- },
- {
- "id": "skill-c",
- "name": "Gamma Skill",
- "description": "Publishes a gamma report.",
- "inputs": [{"name": "review", "type": "markdown", "required": True}],
- "outputs": [{"name": "report", "type": "markdown"}],
- },
- ],
- graph={
- "edges": [
- {
- "type": "can_feed",
- "source": graph_id("skill-a"),
- "target": graph_id("skill-b"),
- "confidence": 0.91,
- "method": "llm",
- "evidence": {
- "reasons": ["draft feeds review"],
- "supporting_fields": {
- "source_outputs": ["draft"],
- "target_inputs": ["draft"],
- },
- },
- },
- {
- "type": "can_feed",
- "source": graph_id("skill-a"),
- "target": graph_id("skill-c"),
- "confidence": 0.2,
- "method": "llm",
- "evidence": {"reasons": ["weak relation"]},
- },
- {
- "type": "can_feed",
- "source": graph_id("skill-b"),
- "target": graph_id("skill-c"),
- "confidence": 0.88,
- "method": "llm",
- "evidence": {
- "reasons": ["review feeds report"],
- "supporting_fields": {
- "source_outputs": ["review"],
- "target_inputs": ["review"],
- },
- },
- },
- ]
- },
- lookup={},
- )
-
-
-async def test_plan_from_score_fast_uses_one_shot_planner(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "title": "Fast plan",
- "status": "ready",
- "reason": "Alpha feeds beta.",
- "steps": [
- {"skill_id": "skill-a", "reason": "Create draft."},
- {"skill_id": "skill-b", "reason": "Review draft."},
- ],
- "can_feed_edges": [
- {"source_id": "skill-a", "target_id": "skill-b"},
- ],
- }
- )
-
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "unrelated user request",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(
- mode="fast",
- min_edge_confidence=0.7,
- ),
- language="en",
- )
-
- assert len(llm.calls) == 1
- assert result["planning_mode"] == "one_shot_fast"
- assert result["language"] == "en"
- assert result["llm_call_count"] == 1
- assert result["recommended_plans"][0]["title"] == "Fast plan"
- assert result["recommended_plans"][0]["steps"][0]["inputs"] == [
- {"name": "brief", "type": "text", "required": True}
- ]
- assert result["recommended_plans"][0]["steps"][0]["outputs"] == [
- {"name": "draft", "type": "markdown"}
- ]
- assert result["execution_graph"]["edges"][0]["source"] == "skill-a"
-
- prompt_payload = json.loads(llm.calls[0]["user_content"])
- assert set(prompt_payload) == {"query", "skills", "can_feed_edges"}
- assert "language" not in prompt_payload
- assert "planning_instructions" not in prompt_payload
- assert "Write all user-visible natural-language fields in English" in (
- llm.calls[0]["system_prompt"]
- )
- assert "Keep Skill IDs, original Skill names, status values" in (
- llm.calls[0]["system_prompt"]
- )
- assert prompt_payload["can_feed_edges"] == [
- {
- "source_id": "skill-a",
- "target_id": "skill-b",
- },
- {
- "source_id": "skill-b",
- "target_id": "skill-c",
- },
- ]
- assert all("inputs" not in skill for skill in prompt_payload["skills"])
- assert all("outputs" not in skill for skill in prompt_payload["skills"])
- system_prompt = llm.calls[0]["system_prompt"]
- assert "Infer a missing relationship only when needed" in system_prompt
- assert "explicitly including an inferred edge" in system_prompt
- assert "Symphony infers adjacent step edges during validation" in system_prompt
- assert "missing_inputs does not describe a Skill I/O schema" in system_prompt
- assert llm.calls[0]["request_overrides"] == {
- "extra_body": {"thinking": {"type": "disabled"}},
- }
-
-
-async def test_plan_from_score_fast_accepts_prefixed_graph_skill_ids(
- monkeypatch,
- tmp_path,
-):
- artifacts = _artifacts(tmp_path, graph_skill_prefix=True)
- llm = _FakeLLMClient(
- {
- "title": "Fast plan",
- "status": "ready",
- "steps": [
- {"skill_id": "skill-a"},
- {"skill_id": "skill-b"},
- ],
- "can_feed_edges": [
- {"source_id": "skill-a", "target_id": "skill-b"},
- ],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "prefixed graph",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(
- mode="fast",
- min_edge_confidence=0.7,
- ),
- )
-
- prompt_payload = json.loads(llm.calls[0]["user_content"])
- assert result["candidate_edge_count"] == 2
- assert prompt_payload["can_feed_edges"] == [
- {"source_id": "skill-a", "target_id": "skill-b"},
- {"source_id": "skill-b", "target_id": "skill-c"},
- ]
- assert result["recommended_plans"][0]["can_feed_edges"][0]["source_id"] == "skill-a"
- assert result["execution_graph"]["edges"][0]["source"] == "skill-a"
-
-
-async def test_plan_from_score_fast_rejects_unknown_skill_once(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "title": "Invalid",
- "status": "ready",
- "steps": [{"skill_id": "missing-skill"}],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "unrelated user request",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(mode="fast"),
- )
-
- assert len(llm.calls) == 1
- assert result["success"] is False
- assert "unknown skill IDs" in result["detail"]
- assert result["execution_graph"]["nodes"] == []
-
-
-async def test_plan_from_score_fast_no_plan_calls_llm_once(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "title": "No useful plan",
- "status": "no_plan",
- "reason": "Candidates do not satisfy the request.",
- "steps": [],
- "can_feed_edges": [],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "unrelated user request",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(mode="fast"),
- )
-
- assert len(llm.calls) == 1
- assert result["status"] == "no_plan"
- assert result["recommended_plans"] == []
- assert result["execution_graph"]["nodes"] == []
-
-
-async def test_plan_from_score_fast_accepts_low_confidence_edge_as_inferred(
- monkeypatch,
- tmp_path,
-):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "title": "Invalid edge",
- "status": "ready",
- "steps": [
- {"skill_id": "skill-a"},
- {"skill_id": "skill-c"},
- ],
- "can_feed_edges": [
- {
- "source_id": "skill-a",
- "target_id": "skill-c",
- "reason": "The selected capabilities should run in sequence.",
- },
- ],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "unrelated user request",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(
- mode="fast",
- min_edge_confidence=0.7,
- ),
- )
-
- prompt_payload = json.loads(llm.calls[0]["user_content"])
- assert len(llm.calls) == 1
- assert prompt_payload["can_feed_edges"] == [
- {
- "source_id": "skill-a",
- "target_id": "skill-b",
- },
- {
- "source_id": "skill-b",
- "target_id": "skill-c",
- },
- ]
- inferred_edge = result["recommended_plans"][0]["can_feed_edges"][0]
- assert inferred_edge["method"] == "fast_llm_inferred"
- assert inferred_edge["confidence"] is None
- assert inferred_edge["reason"] == "The selected capabilities should run in sequence."
- assert result["execution_graph"]["edges"][0]["method"] == "fast_llm_inferred"
-
-
-async def test_plan_from_score_fast_uses_input_candidates_and_neighbors(
- monkeypatch,
- tmp_path,
-):
- artifacts = _artifacts(tmp_path)
- artifacts.skills.extend(
- [
- {
- "id": "skill-d",
- "name": "Delta Skill",
- "description": "Unrelated high-confidence source.",
- "inputs": [],
- "outputs": [{"name": "delta", "type": "markdown"}],
- },
- {
- "id": "skill-e",
- "name": "Echo Skill",
- "description": "Unrelated high-confidence target.",
- "inputs": [{"name": "delta", "type": "markdown"}],
- "outputs": [{"name": "echo", "type": "markdown"}],
- },
- ]
- )
- artifacts.graph["edges"].append(
- {
- "type": "can_feed",
- "source": "skill-d",
- "target": "skill-e",
- "confidence": 0.99,
- "method": "llm",
- "evidence": {"reasons": ["unrelated"]},
- }
- )
- llm = _FakeLLMClient(
- {
- "title": "Retrieved fast plan",
- "status": "ready",
- "steps": [{"skill_id": "skill-b", "reason": "Retrieved seed."}],
- "can_feed_edges": [],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "use beta",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(
- mode="fast",
- min_edge_confidence=0.7,
- ),
- candidate_skill_ids=["skill-b"],
- )
-
- prompt_payload = json.loads(llm.calls[0]["user_content"])
- prompt_skill_ids = {skill["id"] for skill in prompt_payload["skills"]}
- assert prompt_skill_ids == {"skill-a", "skill-b", "skill-c"}
- assert "skill-d" not in prompt_skill_ids
- assert result["skill_retrieval"]["source"] == "input"
- assert result["skill_retrieval"]["used"] is True
- assert result["skill_retrieval"]["candidate_skill_ids"] == ["skill-b"]
-
-
-async def test_plan_from_score_filters_disabled_skills_from_prompt(
- monkeypatch,
- tmp_path,
-):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "title": "Enabled-only plan",
- "status": "ready",
- "steps": [{"skill_id": "skill-a", "reason": "Enabled seed."}],
- "can_feed_edges": [],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "use beta",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(
- mode="fast",
- min_edge_confidence=0.7,
- ),
- candidate_skill_ids=["skill-b"],
- disabled_skill_names=["Beta Skill"],
- )
-
- prompt_payload = json.loads(llm.calls[0]["user_content"])
- prompt_skill_ids = {skill["id"] for skill in prompt_payload["skills"]}
- assert prompt_skill_ids == {"skill-a", "skill-c"}
- assert prompt_payload["can_feed_edges"] == []
- assert result["skill_retrieval"] == {
- "source": "input",
- "used": False,
- "candidate_skill_ids": [],
- "candidate_count": 0,
- "fallback_reason": "candidate_skill_ids did not match current score",
- }
-
-
-async def test_plan_from_score_fast_without_candidates_uses_default_subgraph(
- monkeypatch,
- tmp_path,
-):
- artifacts = _artifacts(tmp_path)
- artifacts.skills.extend(
- [
- {
- "id": "skill-d",
- "name": "Delta Skill",
- "description": "Unrelated high-confidence source.",
- "inputs": [],
- "outputs": [{"name": "delta", "type": "markdown"}],
- },
- {
- "id": "skill-e",
- "name": "Echo Skill",
- "description": "Unrelated high-confidence target.",
- "inputs": [{"name": "delta", "type": "markdown"}],
- "outputs": [{"name": "echo", "type": "markdown"}],
- },
- ]
- )
- artifacts.graph["edges"].append(
- {
- "type": "can_feed",
- "source": "skill-d",
- "target": "skill-e",
- "confidence": 0.99,
- "method": "llm",
- "evidence": {"reasons": ["unrelated"]},
- }
- )
- llm = _FakeLLMClient(
- {
- "title": "Default fast plan",
- "status": "ready",
- "steps": [{"skill_id": "skill-d", "reason": "Default seed."}],
- "can_feed_edges": [],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "use beta",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(
- mode="fast",
- min_edge_confidence=0.7,
- ),
- )
-
- prompt_payload = json.loads(llm.calls[0]["user_content"])
- prompt_skill_ids = {skill["id"] for skill in prompt_payload["skills"]}
- assert {"skill-d", "skill-e"}.issubset(prompt_skill_ids)
- assert result["skill_retrieval"] == {
- "source": "input",
- "used": False,
- "candidate_skill_ids": [],
- "candidate_count": 0,
- "fallback_reason": "candidate_skill_ids not provided",
- }
-
-
-async def test_plan_from_score_resolves_unique_skill_names(
- monkeypatch,
- tmp_path,
-):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "title": "Named candidate plan",
- "status": "ready",
- "steps": [{"skill_id": "skill-b", "reason": "Named seed."}],
- "can_feed_edges": [],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "use beta",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(mode="fast"),
- candidate_skill_ids=["Beta Skill", "skill-a", "Beta Skill"],
- )
-
- assert result["skill_retrieval"]["candidate_skill_ids"] == [
- "skill-b",
- "skill-a",
- ]
-
-
-async def test_plan_from_score_does_not_guess_ambiguous_skill_names(
- monkeypatch,
- tmp_path,
-):
- artifacts = _artifacts(tmp_path)
- artifacts.skills.append(
- {
- "id": "skill-beta-copy",
- "name": "Beta Skill",
- "description": "Another skill with the same display name.",
- "inputs": [],
- "outputs": [],
- }
- )
- llm = _FakeLLMClient(
- {
- "title": "Fallback plan",
- "status": "ready",
- "steps": [{"skill_id": "skill-a", "reason": "Fallback."}],
- "can_feed_edges": [],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "use beta",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(mode="fast"),
- candidate_skill_ids=["Beta Skill"],
- )
-
- assert result["skill_retrieval"] == {
- "source": "input",
- "used": False,
- "candidate_skill_ids": [],
- "candidate_count": 0,
- "fallback_reason": "candidate_skill_ids did not match current score",
- }
-
-
- ("candidate_skill_ids", "fallback_reason"),
- [
- ([], "candidate_skill_ids is empty"),
- (
- ["missing-skill", "missing-skill", ""],
- "candidate_skill_ids did not match current score",
- ),
- ],
-)
-async def test_plan_from_score_fast_falls_back_for_empty_or_unknown_candidates(
- monkeypatch,
- tmp_path,
- candidate_skill_ids,
- fallback_reason,
-):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "title": "Fallback fast plan",
- "status": "ready",
- "steps": [{"skill_id": "skill-a", "reason": "Fallback seed."}],
- "can_feed_edges": [],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "use beta",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(
- mode="fast",
- min_edge_confidence=0.7,
- ),
- candidate_skill_ids=candidate_skill_ids,
- )
-
- prompt_payload = json.loads(llm.calls[0]["user_content"])
- prompt_skill_ids = {skill["id"] for skill in prompt_payload["skills"]}
- assert prompt_skill_ids == {"skill-a", "skill-b", "skill-c"}
- assert result.get("success") is not False
- assert result["skill_retrieval"] == {
- "source": "input",
- "used": False,
- "candidate_skill_ids": [],
- "candidate_count": 0,
- "fallback_reason": fallback_reason,
- }
-
-
-async def test_plan_from_score_beam_uses_bidirectional_planner(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- seen = {}
-
- class FakeBeamPlanner:
- def __init__(self, artifacts_arg, **kwargs):
- seen["artifacts"] = artifacts_arg
- seen["kwargs"] = kwargs
-
- async def plan(self, query):
- seen["query"] = query
- return {
- "planning_mode": "bidirectional_beam",
- "recommended_plans": [],
- "plans": [],
- "status": "no_plan",
- }
-
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
- monkeypatch.setattr(service, "BidirectionalBeamPlanner", FakeBeamPlanner)
-
- result = await service.plan_from_score(
- tmp_path,
- "beam plan",
- llm_client=object(),
- orchestration_config=SymphonyOrchestrationConfig(
- mode="beam",
- top_k=2,
- max_depth=3,
- min_edge_confidence=0.7,
- ),
- candidate_skill_ids=["skill-a", "unknown"],
- )
-
- assert result["planning_mode"] == "bidirectional_beam"
- assert result["execution_graph"]["nodes"] == []
- assert result["skill_retrieval"]["candidate_skill_ids"] == ["skill-a"]
- assert seen["artifacts"] is artifacts
- assert seen["query"] == "beam plan"
- assert seen["kwargs"]["top_k"] == 2
- assert seen["kwargs"]["max_depth"] == 3
- assert seen["kwargs"]["candidate_skill_ids"] == ("skill-a",)
-
-
-async def test_plan_from_score_rejects_unknown_mode(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- with pytest.raises(ValueError, match="Unsupported orchestration mode"):
- await service.plan_from_score(
- tmp_path,
- "graph plan",
- llm_client=object(),
- orchestration_config=SymphonyOrchestrationConfig(mode="graph"),
- )
-
-
-def _custom_artifacts(tmp_path, skill_ids, edges):
- return ScoreArtifacts(
- score_dir=tmp_path,
- manifest={},
- skills=[
- {
- "id": current_skill_id,
- "name": current_skill_id,
- "description": f"Capability {current_skill_id}",
- "inputs": [],
- "outputs": [],
- }
- for current_skill_id in skill_ids
- ],
- graph={"edges": edges},
- lookup={},
- )
-
-
-def _score_edge(source, target, confidence=0.9):
- return {
- "type": "can_feed",
- "source": source,
- "target": target,
- "confidence": confidence,
- "method": "test",
- "evidence": {"reasons": [f"{source} feeds {target}"]},
- }
-
-
-async def test_retrieval_forest_prefers_shortest_path(monkeypatch, tmp_path):
- artifacts = _custom_artifacts(
- tmp_path,
- ["seed-a", "seed-b", "bridge", "incoming", "outgoing"],
- [
- _score_edge("seed-a", "seed-b", 0.71),
- _score_edge("seed-a", "bridge", 0.99),
- _score_edge("bridge", "seed-b", 0.99),
- _score_edge("incoming", "seed-a", 0.98),
- _score_edge("seed-b", "outgoing", 0.97),
- ],
- )
- llm = _FakeLLMClient(
- {
- "status": "ready",
- "steps": [{"skill_id": "seed-a"}, {"skill_id": "seed-b"}],
- "can_feed_edges": [
- {"source_id": "seed-a", "target_id": "seed-b"},
- ],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- await service.plan_from_score(
- tmp_path,
- "connect seeds",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(mode="fast", max_depth=3),
- candidate_skill_ids=["seed-a", "seed-b"],
- )
-
- prompt = json.loads(llm.calls[0]["user_content"])
- assert [skill["id"] for skill in prompt["skills"]] == ["seed-a", "seed-b"]
- assert prompt["can_feed_edges"] == [
- {"source_id": "seed-a", "target_id": "seed-b"}
- ]
-
-
-async def test_retrieval_forest_prefers_higher_confidence_for_equal_hops(
- monkeypatch,
- tmp_path,
-):
- artifacts = _custom_artifacts(
- tmp_path,
- ["seed-a", "seed-b", "weak", "strong"],
- [
- _score_edge("seed-a", "weak", 0.8),
- _score_edge("weak", "seed-b", 0.8),
- _score_edge("seed-a", "strong", 0.9),
- _score_edge("strong", "seed-b", 0.9),
- ],
- )
- llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": "strong"}]})
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- await service.plan_from_score(
- tmp_path,
- "connect seeds",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(mode="fast", max_depth=2),
- candidate_skill_ids=["seed-a", "seed-b"],
- )
-
- prompt = json.loads(llm.calls[0]["user_content"])
- assert [skill["id"] for skill in prompt["skills"]] == [
- "seed-a",
- "seed-b",
- "strong",
- ]
- assert prompt["can_feed_edges"] == [
- {"source_id": "seed-a", "target_id": "strong"},
- {"source_id": "strong", "target_id": "seed-b"},
- ]
-
-
-async def test_retrieval_forest_keeps_components_beyond_max_depth(
- monkeypatch,
- tmp_path,
-):
- artifacts = _custom_artifacts(
- tmp_path,
- ["seed-a", "seed-b", "bridge"],
- [
- _score_edge("seed-a", "bridge"),
- _score_edge("bridge", "seed-b"),
- ],
- )
- llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": "seed-a"}]})
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- await service.plan_from_score(
- tmp_path,
- "keep separate",
- llm_client=llm,
- orchestration_config=SymphonyOrchestrationConfig(mode="fast", max_depth=1),
- candidate_skill_ids=["seed-a", "seed-b"],
- )
-
- prompt = json.loads(llm.calls[0]["user_content"])
- assert {skill["id"] for skill in prompt["skills"]} == {
- "seed-a",
- "seed-b",
- "bridge",
- }
- assert prompt["can_feed_edges"] == [
- {"source_id": "seed-a", "target_id": "bridge"}
- ]
-
-
-async def test_fast_default_subgraph_has_no_skill_or_edge_limit(monkeypatch, tmp_path):
- skill_ids = [f"skill-{index:02d}" for index in range(42)]
- edges = []
- for source_index in range(len(skill_ids)):
- for target_index in range(source_index + 1, len(skill_ids)):
- edges.append(_score_edge(skill_ids[source_index], skill_ids[target_index]))
- if len(edges) == 82:
- break
- if len(edges) == 82:
- break
- artifacts = _custom_artifacts(tmp_path, skill_ids, edges)
- llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": skill_ids[0]}]})
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(tmp_path, "all candidates", llm_client=llm)
-
- prompt = json.loads(llm.calls[0]["user_content"])
- assert len(prompt["skills"]) == 42
- assert len(prompt["can_feed_edges"]) == 82
- assert result["candidate_skill_count"] == 42
- assert result["candidate_edge_count"] == 82
-
-
-async def test_fast_retrieval_forest_has_no_skill_limit(monkeypatch, tmp_path):
- skill_ids = [f"skill-{index:02d}" for index in range(42)]
- edges = [
- _score_edge(skill_ids[index], skill_ids[index + 1])
- for index in range(len(skill_ids) - 1)
- ]
- edge_keys = {(edge["source"], edge["target"]) for edge in edges}
- for source_index in range(len(skill_ids)):
- for target_index in range(source_index + 1, len(skill_ids)):
- key = (skill_ids[source_index], skill_ids[target_index])
- if key not in edge_keys:
- edges.append(_score_edge(*key))
- edge_keys.add(key)
- if len(edges) == 82:
- break
- if len(edges) == 82:
- break
- artifacts = _custom_artifacts(tmp_path, skill_ids, edges)
- llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": skill_ids[0]}]})
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "all retrieved candidates",
- llm_client=llm,
- candidate_skill_ids=skill_ids,
- )
-
- prompt = json.loads(llm.calls[0]["user_content"])
- assert len(edges) == 82
- assert len(prompt["skills"]) == 42
- assert result["candidate_skill_count"] == 42
-
-
-async def test_fast_default_subgraph_uses_all_skills_without_edges(monkeypatch, tmp_path):
- skill_ids = [f"skill-{index:02d}" for index in range(45)]
- artifacts = _custom_artifacts(tmp_path, skill_ids, [])
- llm = _FakeLLMClient({"status": "ready", "steps": [{"skill_id": skill_ids[0]}]})
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- await service.plan_from_score(tmp_path, "all skills", llm_client=llm)
-
- prompt = json.loads(llm.calls[0]["user_content"])
- assert len(prompt["skills"]) == 45
- assert prompt["can_feed_edges"] == []
-
-
-async def test_fast_plan_materializes_existing_and_inferred_edges(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- artifacts.graph["edges"] = artifacts.graph["edges"][:1]
- llm = _FakeLLMClient(
- {
- "status": "ready",
- "steps": [
- {"skill_id": "skill-a"},
- {"skill_id": "skill-b"},
- {"skill_id": "skill-c"},
- ],
- "can_feed_edges": [
- {"source_id": "skill-a", "target_id": "skill-b"},
- {
- "source_id": "skill-b",
- "target_id": "skill-c",
- "reason": "Continue with the selected publisher.",
- },
- ],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(
- tmp_path,
- "mixed edges",
- llm_client=llm,
- candidate_skill_ids=["skill-a", "skill-b", "skill-c"],
- )
-
- edges = result["recommended_plans"][0]["can_feed_edges"]
- assert [edge["method"] for edge in edges] == ["llm", "fast_llm_inferred"]
- assert result["execution_graph"]["edges"][1]["method"] == "fast_llm_inferred"
-
-
-async def test_fast_plan_infers_adjacent_edges_when_omitted(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "status": "ready",
- "steps": [{"skill_id": "skill-a"}, {"skill_id": "skill-c"}],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(tmp_path, "infer adjacency", llm_client=llm)
-
- edge = result["recommended_plans"][0]["can_feed_edges"][0]
- assert edge["source_id"] == "skill-a"
- assert edge["target_id"] == "skill-c"
- assert edge["method"] == "fast_llm_inferred"
-
-
- ("steps", "edges", "detail"),
- [
- (
- ["skill-a", "skill-b"],
- [{"source_id": "skill-a", "target_id": "skill-c"}],
- "outside plan steps",
- ),
- (
- ["skill-a", "skill-b"],
- [{"source_id": "skill-b", "target_id": "skill-a"}],
- "violate step order",
- ),
- (
- ["skill-a", "skill-b"],
- [
- {"source_id": "skill-a", "target_id": "skill-b"},
- {"source_id": "skill-a", "target_id": "skill-b"},
- ],
- "duplicate can_feed edges",
- ),
- ],
-)
-async def test_fast_plan_rejects_invalid_inferred_edges(
- monkeypatch,
- tmp_path,
- steps,
- edges,
- detail,
-):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "status": "ready",
- "steps": [{"skill_id": skill} for skill in steps],
- "can_feed_edges": edges,
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(tmp_path, "invalid edge", llm_client=llm)
-
- assert result["success"] is False
- assert detail in result["detail"]
-async def test_fast_plan_drops_single_step_self_loop_edge(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "status": "ready",
- "steps": [{"skill_id": "skill-a"}],
- "can_feed_edges": [
- {
- "source_id": "skill-a",
- "target_id": "skill-a",
- "reason": "Self reuse should not become a can_feed edge.",
- }
- ],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(tmp_path, "self loop", llm_client=llm)
-
- assert result["validation"]["valid"] is True
- plan = result["recommended_plans"][0]
- assert [step["skill_id"] for step in plan["steps"]] == ["skill-a"]
- assert plan["can_feed_edges"] == []
-
-
-async def test_fast_plan_drops_self_loop_and_keeps_valid_edge(monkeypatch, tmp_path):
- artifacts = _artifacts(tmp_path)
- llm = _FakeLLMClient(
- {
- "status": "ready",
- "steps": [{"skill_id": "skill-a"}, {"skill_id": "skill-b"}],
- "can_feed_edges": [
- {
- "source_id": "skill-a",
- "target_id": "skill-a",
- "reason": "Self reuse should not become a can_feed edge.",
- },
- {"source_id": "skill-a", "target_id": "skill-b"},
- ],
- }
- )
- monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
-
- result = await service.plan_from_score(tmp_path, "mixed edges", llm_client=llm)
-
- assert result["validation"]["valid"] is True
- edges = result["recommended_plans"][0]["can_feed_edges"]
- assert [(edge["source_id"], edge["target_id"]) for edge in edges] == [
- ("skill-a", "skill-b")
- ]
-
-
-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
index 6ff1358e3b..76d277be8a 100644
--- a/tests/unit_tests/symphony/test_session_consumer.py
+++ b/tests/unit_tests/symphony/test_session_consumer.py
@@ -29,7 +29,7 @@ def _plan_records(plan_id="plan-1"):
"role": "assistant",
"request_id": "req-plan",
"event_type": "chat.tool_result",
- "tool_name": "symphony_compose_score",
+ "tool_name": "symphony_compose_graph",
"success": True,
"raw_output": {
"success": True,
@@ -157,7 +157,7 @@ def test_wait_for_request_history_observes_late_terminal_record(
def test_session_consumer_records_cross_turn_success(monkeypatch, tmp_path):
session_root = tmp_path / "sessions"
- score_dir = tmp_path / "score"
+ graph_dir = tmp_path / "graph"
records = _plan_records() + _success_records()
_write_history(session_root, "session-1", records)
monkeypatch.setattr(
@@ -168,22 +168,22 @@ def test_session_consumer_records_cross_turn_success(monkeypatch, tmp_path):
result = consume_session_history(
"session-1",
completed_request_id="req-run",
- score_dir=score_dir,
+ graph_dir=graph_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)
+ events = read_events(graph_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)
+ overlay = read_overlay(graph_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)
+ feedback = session_feedback_status(graph_dir)
assert feedback["plans_observed"] == 1
assert feedback["outcomes_recorded"] == 1
assert feedback["last_result"]["plan_id"] == "plan-1"
@@ -191,7 +191,7 @@ def test_session_consumer_records_cross_turn_success(monkeypatch, tmp_path):
def test_session_consumer_maps_package_ids_from_skill_frontmatter(monkeypatch, tmp_path):
session_root = tmp_path / "sessions"
- score_dir = tmp_path / "score"
+ graph_dir = tmp_path / "graph"
run_records = _success_records()
run_records[1]["tool_call"]["arguments"] = json.dumps(
{"skill_name": "ocr-invoice-1.1.0"}
@@ -222,15 +222,15 @@ def test_session_consumer_maps_package_ids_from_skill_frontmatter(monkeypatch, t
result = consume_session_history(
"session-package-ids",
completed_request_id="req-run",
- score_dir=score_dir,
+ graph_dir=graph_dir,
)
assert result["outcomes"][0]["outcome"] == "success"
- event = read_events(score_dir)[0]
+ event = read_events(graph_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)
+ overlay = read_overlay(graph_dir)
assert overlay["edges"]["ocr-invoice->verify-invoice:can_feed"][
"success_count"
] == 1
@@ -238,7 +238,7 @@ def test_session_consumer_maps_package_ids_from_skill_frontmatter(monkeypatch, t
def test_session_consumer_does_not_treat_plan_display_as_success(monkeypatch, tmp_path):
session_root = tmp_path / "sessions"
- score_dir = tmp_path / "score"
+ graph_dir = tmp_path / "graph"
_write_history(session_root, "session-plan-only", _plan_records())
monkeypatch.setattr(
"jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",
@@ -248,12 +248,12 @@ def test_session_consumer_does_not_treat_plan_display_as_success(monkeypatch, tm
result = consume_session_history(
"session-plan-only",
completed_request_id="req-plan",
- score_dir=score_dir,
+ graph_dir=graph_dir,
)
assert result["outcomes"] == []
- assert read_events(score_dir) == []
- feedback = session_feedback_status(score_dir)
+ assert read_events(graph_dir) == []
+ feedback = session_feedback_status(graph_dir)
assert feedback["pending_plan_count"] == 1
@@ -262,7 +262,7 @@ def test_session_consumer_does_not_trust_confirmation_without_execution(
tmp_path,
):
session_root = tmp_path / "sessions"
- score_dir = tmp_path / "score"
+ graph_dir = tmp_path / "graph"
records = _plan_records() + [
{
"role": "user",
@@ -285,17 +285,17 @@ def test_session_consumer_does_not_trust_confirmation_without_execution(
result = consume_session_history(
"session-no-execution",
completed_request_id="req-run",
- score_dir=score_dir,
+ graph_dir=graph_dir,
)
assert result["outcomes"] == []
- assert read_events(score_dir) == []
- assert session_feedback_status(score_dir)["pending_plan_count"] == 1
+ assert read_events(graph_dir) == []
+ assert session_feedback_status(graph_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"
+ graph_dir = tmp_path / "graph"
failure_records = [
{
"role": "user",
@@ -345,28 +345,28 @@ def test_session_consumer_records_tool_failure_and_is_idempotent(monkeypatch, tm
first = consume_session_history(
"session-failure",
completed_request_id="req-run",
- score_dir=score_dir,
+ graph_dir=graph_dir,
)
second = consume_session_history(
"session-failure",
completed_request_id="req-run",
- score_dir=score_dir,
+ graph_dir=graph_dir,
)
assert first["outcomes"][0]["outcome"] == "failure"
assert second["outcomes"] == []
- assert len(read_events(score_dir)) == 1
- overlay = read_overlay(score_dir)
+ assert len(read_events(graph_dir)) == 1
+ overlay = read_overlay(graph_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)
+ status = evolution_status(graph_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"
+ graph_dir = tmp_path / "graph"
records = _plan_records() + [
{
"role": "user",
@@ -398,9 +398,9 @@ def test_session_consumer_does_not_learn_unobserved_plan_edges(monkeypatch, tmp_
result = consume_session_history(
"session-partial",
completed_request_id="req-run",
- score_dir=score_dir,
+ graph_dir=graph_dir,
)
assert result["outcomes"] == []
- assert read_events(score_dir) == []
- assert session_feedback_status(score_dir)["pending_plan_count"] == 1
+ assert read_events(graph_dir) == []
+ assert session_feedback_status(graph_dir)["pending_plan_count"] == 1
diff --git a/tests/unit_tests/symphony/test_toolkit.py b/tests/unit_tests/symphony/test_toolkit.py
index bdc79881be..417d7692d1 100644
--- a/tests/unit_tests/symphony/test_toolkit.py
+++ b/tests/unit_tests/symphony/test_toolkit.py
@@ -10,24 +10,7 @@ from jiuwenswarm.agents.harness.common.tool_progress_context import (
from jiuwenswarm.agents.harness.common.tools.symphony_toolkits import (
SymphonyToolkit,
)
-from jiuwenswarm.extensions.registry import ExtensionRegistry
-
-
-class _CallbackFramework:
- @staticmethod
- def register_sync(*args, **kwargs):
- return None
-
- async def trigger(self, *args, **kwargs):
- return None
-
-
-def setup_function():
- ExtensionRegistry.reset_instance()
-
-
-def teardown_function():
- ExtensionRegistry.reset_instance()
+from jiuwenswarm.symphony.service import SwarmSymphonyService
@pytest.fixture(autouse=True)
@@ -43,28 +26,26 @@ def enabled_symphony_config(monkeypatch):
)
-def _registry() -> ExtensionRegistry:
- return ExtensionRegistry.create_instance(
- callback_framework=_CallbackFramework(),
- config={},
- logger=object(),
- )
-
-
-def test_plan_calls_compose_rpc_once_without_language():
- registry = _registry()
+async def test_plan_calls_process_service_once_without_language():
calls = []
- async def handler(params, request=None):
- del request
- calls.append(params)
+ async def handler(query, **kwargs):
+ calls.append({"query": query, **kwargs})
return {"success": True, "content": "## Plan", "direct_display": True}
- registry.register_rpc_handler("symphony.plan", handler)
-
- result = asyncio.run(SymphonyToolkit().plan("use installed skills"))
+ result = await SymphonyToolkit(SimpleNamespace(plan=handler)).plan(
+ "use installed skills"
+ )
- assert calls == [{"query": "use installed skills"}]
+ assert calls == [
+ {
+ "query": "use installed skills",
+ "mode": None,
+ "candidate_skill_ids": None,
+ "progress": None,
+ }
+ ]
assert result == {
"success": True,
"content": "## Plan",
@@ -74,57 +55,56 @@ def test_plan_calls_compose_rpc_once_without_language():
}
-def test_plan_passes_mode_and_deduplicated_candidates():
- registry = _registry()
+async def test_plan_passes_mode_and_deduplicated_candidates():
seen = {}
- async def handler(params, request=None):
- del request
- seen.update(params)
+ async def handler(query, **kwargs):
+ seen.update({"query": query, **kwargs})
return {"success": True}
- registry.register_rpc_handler("symphony.plan", handler)
-
- asyncio.run(
- SymphonyToolkit().plan(
- "compose",
- mode="beam",
- candidate_skill_ids=["skill-a", "skill-a", "Skill B"],
- )
+ await SymphonyToolkit(SimpleNamespace(plan=handler)).plan(
+ "compose",
+ mode="beam",
+ candidate_skill_ids=["skill-a", "skill-a", "Skill B"],
)
assert seen == {
"query": "compose",
"mode": "beam",
"candidate_skill_ids": ["skill-a", "Skill B"],
+ "progress": None,
}
-def test_plan_preserves_progress_callback_on_extension_request():
- registry = _registry()
+async def test_plan_passes_current_progress_callback_directly_to_service():
events = []
- async def handler(params, request=None):
- del params
- callback = request.metadata["symphony_progress_callback"]
+ async def handler(query, *, progress=None, **kwargs):
+ del query, kwargs
+ callback = progress
await callback({"event": "started", "graph": {"nodes": [], "edges": []}})
return {"success": True}
- registry.register_rpc_handler("symphony.plan", handler)
- token = bind_tool_progress(events.append)
+ async def progress(event):
+ events.append(event)
+
+ token = bind_tool_progress(progress)
try:
- asyncio.run(SymphonyToolkit().plan("compose", mode="beam"))
+ await SymphonyToolkit(SimpleNamespace(plan=handler)).plan(
+ "compose", mode="beam"
+ )
finally:
reset_tool_progress(token)
assert events == [{"event": "started", "graph": {"nodes": [], "edges": []}}]
-def test_plan_returns_compact_plan_and_beam_graph():
- registry = _registry()
-
- async def handler(params, request=None):
- del params, request
+async def test_plan_returns_compact_plan_and_beam_graph():
+ async def handler(*args, **kwargs):
+ del args, kwargs
return {
"success": True,
"content": "## Beam Plan",
@@ -157,9 +137,9 @@ def test_plan_returns_compact_plan_and_beam_graph():
},
}
- registry.register_rpc_handler("symphony.plan", handler)
-
- result = asyncio.run(SymphonyToolkit().plan("compose", mode="beam"))
+ result = await SymphonyToolkit(SimpleNamespace(plan=handler)).plan(
+ "compose", mode="beam"
+ )
assert result["beam_search"] == {
"language": "cn",
@@ -182,11 +162,10 @@ 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
+async def test_plan_preserves_dynamic_graph_metadata():
+ async def handler(*args, **kwargs):
+ del args, kwargs
return {
"success": True,
"plan_id": "plan-session-1",
@@ -194,9 +173,7 @@ def test_plan_preserves_dynamic_graph_metadata():
"result": {"recommended_plans": []},
}
- registry.register_rpc_handler("symphony.plan", handler)
-
- result = asyncio.run(SymphonyToolkit().plan("compose"))
+ result = await SymphonyToolkit(SimpleNamespace(plan=handler)).plan("compose")
assert result["plan_id"] == "plan-session-1"
assert result["dynamic_graph_enabled"] is True
@@ -222,36 +199,107 @@ def test_toolkit_compacts_inferred_edge_provenance():
}
-def test_plan_reports_missing_rpc_handler():
- _registry()
+async def test_plan_reports_service_failure():
+ async def handler(*args, **kwargs):
+ del args, kwargs
+ raise RuntimeError("service unavailable")
- result = asyncio.run(SymphonyToolkit().plan("compose"))
+ result = await SymphonyToolkit(SimpleNamespace(plan=handler)).plan("compose")
assert result["success"] is False
- assert "handler not registered" in result["detail"]
+ assert "service unavailable" in result["detail"]
+
+async def test_status_and_refresh_remain_explicit_tools():
+ async def graph_status():
+ return {"success": True, "exists": True}
-def test_status_and_refresh_remain_explicit_tools():
- registry = _registry()
- registry.register_rpc_handler(
- "symphony.score_status",
- lambda params, request=None: {"success": True, "exists": True},
+ async def refresh_graph(*, progress=None):
+ assert progress is None
+ return {"success": True, "rebuilt": True}
+
+ toolkit = SymphonyToolkit(
+ SimpleNamespace(graph_status=graph_status, refresh_graph=refresh_graph)
)
- registry.register_rpc_handler(
- "symphony.build_score",
- lambda params, request=None: {"success": True, "rebuilt": True},
+ assert (await toolkit.graph_status())["exists"] is True
+ assert (await toolkit.refresh_graph())["rebuilt"] is True
+
+
+async def test_refresh_timeout_aborts_blocked_progress_without_leaking_worker(
+ monkeypatch,
+ tmp_path,
+):
+ config = SimpleNamespace(
+ paths=SimpleNamespace(
+ skills_root=tmp_path / "skills",
+ graph_dir=tmp_path / "graph",
+ )
)
+ callback_entered = asyncio.Event()
+ callback_cancelled = asyncio.Event()
- assert asyncio.run(SymphonyToolkit().score_status())["exists"] is True
- assert asyncio.run(SymphonyToolkit().refresh_score())["rebuilt"] is True
+ async def blocking_progress(_event):
+ callback_entered.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ callback_cancelled.set()
+ async def fake_build_graph(*args, **kwargs):
+ del args, kwargs
+ return SimpleNamespace(to_dict=lambda: {"success": True, "version": "v1"})
-def test_get_tools_describes_fast_and_beam_without_language():
- compose_tool = next(
- tool
- for tool in SymphonyToolkit().get_tools()
- if tool.card.name == "symphony_compose_score"
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.load_symphony_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.LLMConfig.from_default_model",
+ lambda: object(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.service.service_build_graph",
+ fake_build_graph,
+ )
+ monkeypatch.setattr(
+ SymphonyToolkit,
+ "_resolve_timeout_s",
+ staticmethod(lambda default_s=1800.0: 0.05),
)
+ service = SwarmSymphonyService()
+ toolkit = SymphonyToolkit(service)
+ token = bind_tool_progress(blocking_progress)
+ try:
+ task = asyncio.create_task(toolkit.refresh_graph())
+ await callback_entered.wait()
+ result = await asyncio.wait_for(task, timeout=0.5)
+ finally:
+ reset_tool_progress(token)
+
+ assert result["success"] is False
+ assert "timeout" in result["detail"]
+ assert callback_cancelled.is_set()
+ assert service._active_build_task is None
+ assert not [
+ task
+ for task in asyncio.all_tasks()
+ if task.get_name() == "symphony-build-progress"
+ ]
+
+
+def test_get_tools_exposes_only_graph_named_contracts():
+ tools = SymphonyToolkit().get_tools()
+ assert [tool.card.name for tool in tools] == [
+ "symphony_read_graph",
+ "symphony_refresh_graph",
+ "symphony_compose_graph",
+ ]
+ assert all("score" not in tool.card.name for tool in tools)
+
+ compose_tool = tools[-1]
properties = compose_tool.card.input_params["properties"]
assert properties["mode"]["enum"] == ["fast", "beam"]
diff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.py
index e36e0ce800..4dc3b1021c 100644
--- a/tests/unit_tests/test_app_web_handlers.py
+++ b/tests/unit_tests/test_app_web_handlers.py
@@ -1310,10 +1310,26 @@ 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
+def test_web_exposes_graph_methods_and_rejects_legacy_symphony_methods():
+ skill_graph_methods = {
+ "skills.graph.build",
+ "skills.graph.status",
+ "skills.graph.get",
+ "skills.graph.cancel",
+ }
+ assert skill_graph_methods.issubset(app_web_handlers._FORWARD_REQ_METHODS)
+
+ legacy_symphony_methods = {
+ "symphony.build_score",
+ "symphony.pause_build",
+ "symphony.score_status",
+ "symphony.graph",
+ "symphony.plan",
+ "symphony.evolution_status",
+ "symphony.evolution_record_outcome",
+ "symphony.evolution_rebuild",
+ }
+ assert legacy_symphony_methods.isdisjoint(app_web_handlers._FORWARD_REQ_METHODS)
def test_web_forwards_only_canonical_personal_context_rpc_methods():