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(evolution): 支持多个信号输入、多条经验生成,前端展示相应适配
gl_zhouf0d3a8d2fb8a
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex 32314ae166..f0ccb5e475 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -1197,7 +1197,11 @@ class JiuWenClaw:"is_processing": True,"current_task": "thinking",}-+ if chunk_type == "processing_complete":+ return {+ "event_type": "chat.processing_status",+ "is_processing": False,+ }if chunk_type == "todo.updated":todos = (payload.get("todos", [])diff --git a/jiuwenclaw/agentserver/react_agent.py b/jiuwenclaw/agentserver/react_agent.pyindex 2b9cb9cdb1..f00bbcb78a 100644--- a/jiuwenclaw/agentserver/react_agent.py+++ b/jiuwenclaw/agentserver/react_agent.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport asyncioimport importlib.util+import reimport sysimport uuidfrom pathlib import Path@@ -316,6 +317,7 @@ class JiuClawReActAgent(ReActAgent):raise ValueError("Input must be dict with 'query' or str")stripped = user_input.strip()+ stripped = EvolutionService.extract_user_content(stripped)# Intercept slash commands (skip ReAct reasoning loop to save tokens)if stripped.startswith(_CMD_EVOLVE):if self._evolution_service is None:@@ -450,10 +452,13 @@ class JiuClawReActAgent(ReActAgent):)for i, (_result, tool_msg) in enumerate(results):+ tc = allowed_tool_calls[i] if i < len(allowed_tool_calls) else None+ if tc is not None:+ tool_msg = self._maybe_inject_body_experience(tc, tool_msg)await context.add_messages(tool_msg)if session is not None:- tc = allowed_tool_calls[i] if i < len(allowed_tool_calls) else Noneawait self._emit_tool_result(session, tc, _result)+tool_messages_added = True# Detect if todo tool was called, emit todo.updated if so@@ -606,6 +611,15 @@ class JiuClawReActAgent(ReActAgent):# Handle auto-scan evolution after answerhistory = self._pending_auto_evolution_historyif history is not None and self._evolution_service is not None and session is not None:+ # Signal frontend that main processing is done before evolution starts,+ # so new user input is treated as a normal submit (not interrupt).+ await session.write_stream(+ OutputSchema(+ type="processing_complete",+ index=0,+ payload={},+ )+ )try:await self._evolution_service.run_auto_evolution(session, history)except Exception as e:@@ -990,13 +1004,12 @@ class JiuClawReActAgent(ReActAgent):def _get_skill_messages(self) -> List[SystemMessage]:"""Build Skill summary SystemMessage list.- Includes:- 1. skill_prompt- 2. evolution summaries+ For each skill, its description is listed, and any pending description+ experiences are appended directly after it. Body experiences are NOT+ included here (they are solidified into SKILL.md)."""prompt_parts: List[str] = []- # 1. skill_prompt (skill list description)if self._skill_util is not None and self._skill_util.has_skill():skill_info = self._skill_util.get_skill_prompt()lines = skill_info.split("\n\n")[-1].strip().split("\n")@@ -1010,21 +1023,54 @@ class JiuClawReActAgent(ReActAgent):"(SKILL.MD) using view_file and follow its workflow.\n\n""Here are the skills available:\n")- prompt_parts.append(header + "\n".join(f"- {line}" for line in skill_lines))-- # 2. Skill evolution summary- if self._evolution_service is not None:- store = self._evolution_service.store- skill_names = store.list_skill_names()- summaries = store.get_all_evolution_summaries(skill_names)- if summaries:- prompt_parts.append(summaries)+ augmented: List[str] = []+ for line in skill_lines:+ aug_line = f"- {line}"+ if self._evolution_service is not None:+ m = re.search(r"Skill name:\s*(\S+?);", line)+ if m:+ skill_name = m.group(1)+ desc_text = self._evolution_service.store.format_desc_experience_text(skill_name)+ if desc_text:+ aug_line += f"\n Skill description patch: {desc_text}"+ augmented.append(aug_line)+ prompt_parts.append(header + "\n".join(augmented))if not prompt_parts:return []return [SystemMessage(content="\n\n".join(prompt_parts))]+ _SKILL_MD_RE = re.compile(r"[/\\]([^/\\]+)[/\\]SKILL\.md", re.IGNORECASE)++ def _maybe_inject_body_experience(self, tc: Any, tool_msg: Any) -> Any:+ """Append body-experience text when the agent reads a SKILL.md via view_file."""+ if self._evolution_service is None:+ return tool_msg+ if getattr(tc, "name", "") != "view_file":+ return tool_msg++ try:+ import json as _json+ args = _json.loads(tc.arguments) if isinstance(tc.arguments, str) else tc.arguments+ file_path: str = args.get("file_path", "")+ except Exception:+ return tool_msg++ m = self._SKILL_MD_RE.search(file_path)+ if not m:+ return tool_msg++ skill_name = m.group(1)+ body_text = self._evolution_service.store.format_body_experience_text(skill_name)+ if not body_text:+ return tool_msg++ original = tool_msg.content if isinstance(tool_msg.content, str) else str(tool_msg.content)+ tool_msg.content = original + body_text+ logger.info("[ReActAgent] injected body experience for skill=%s", skill_name)+ return tool_msg+async def _get_session_messages(self, session: Optional[Any]) -> List[Any]:"""Get raw historical message list from session.diff --git a/jiuwenclaw/evolution/__init__.py b/jiuwenclaw/evolution/__init__.pyindex 379bfbc384..ebe84ca406 100644--- a/jiuwenclaw/evolution/__init__.py+++ b/jiuwenclaw/evolution/__init__.py@@ -5,7 +5,7 @@Provides EvolutionService as the unified facade, backed by:- SignalDetector: rules-based signal extraction with evolution type classification- SkillEvolver: LLM-based experience generation with history dedup- - EvolutionStore: pure IO layer for evolutions.json and SKILL.md+ - EvolutionStore: pure IO layer for evolutions_desc.json / evolutions_body.json and SKILL.md"""from jiuwenclaw.evolution.schema import (EvolutionChange,@@ -13,6 +13,7 @@ from jiuwenclaw.evolution.schema import (EvolutionFile,EvolutionSignal,EvolutionType,+ ExperienceTarget,)from jiuwenclaw.evolution.signal_detector import SignalDetectorfrom jiuwenclaw.evolution.evolver import SkillEvolver@@ -25,6 +26,7 @@ __all__ = ["EvolutionFile","EvolutionSignal","EvolutionType",+ "ExperienceTarget","SignalDetector","SkillEvolver","EvolutionStore",diff --git a/jiuwenclaw/evolution/evolver.py b/jiuwenclaw/evolution/evolver.pyindex 757e31c371..18ffd346f9 100644--- a/jiuwenclaw/evolution/evolver.py+++ b/jiuwenclaw/evolution/evolver.py@@ -10,55 +10,103 @@ from typing import Any, List, Optionalfrom jiuwenclaw.evolution.schema import (EvolutionChange,EvolutionEntry,+ ExperienceContext,EvolutionSignal,+ ExperienceTarget,VALID_SECTIONS,)from jiuwenclaw.utils import logger_GENERATE_PROMPT = """\-你是一个 Skill 优化专家。-根据以下 Skill 内容和对话信号,生成一条演进记录。+你是一个 Skill 优化专家。根据对话中发现的问题信号和对话历史,为 Skill 生成演进经验。-## 当前 Skill 内容(摘要)+## 输入信息++### 当前 Skill 内容{skill_content}-## 演进信号+### 预检测信号(规则引擎自动提取){signals_json}-## 对话片段(作为上下文)+### 对话历史{conversation_snippet}-## 已有演进经验(已存在的记录)-{existing_entries_summary}+### 已有 description 经验+{existing_desc_summary}++### 已有 body 经验+{existing_body_summary}++## 经验来源++经验来自两个渠道,都要处理:++**渠道 A — 预检测信号**:上方「预检测信号」中列出的条目,由规则引擎自动从对话中提取,可能包含误报。++**渠道 B — 对话历史直接分析**:直接审视「对话历史」,发现规则引擎未捕获的有价值经验,包括但不限于:+- Agent 经过多次尝试/重试才成功的 workaround(说明 Skill 缺少相关指导)+- 用户含蓄的纠正或补充说明(未使用"错了""不对"等显式关键词)+- 低效的工具调用模式(如多余步骤、错误的调用顺序)+- Agent 遗漏的关键步骤(用户不得不手动补充)+- 需要特殊处理的边界情况(Skill 中未覆盖的场景)++如果对话历史中没有额外发现,不需要强制生成;如果有发现,与预检测信号的经验一起输出。++## 数量限制++最终输出的有效经验(action 为 append 的条目)**不得超过 2 条**。+如果候选经验超过 2 条,按以下优先级保留最重要的 2 条,其余标记为 skip:+1. 导致任务失败或产出错误结果的问题 > 导致效率低下但最终成功的问题+2. 高频/可复现的模式 > 单次偶发现象+3. 渠道 A(预检测信号)与渠道 B(对话分析)的发现同等对待,仅按影响程度排序++## 决策流程(对每条潜在经验按顺序执行)++### 第一步:相关性判断+判断该经验是否与 Skill 本身相关:+- 相关:问题由 Skill 的指令、脚本、示例或排查逻辑导致 -> 继续第二步+- 不相关:问题由外部因素导致(网络、环境、权限、第三方服务等)-> 输出 {{"action": "skip", "skip_reason": "irrelevant"}}++### 第二步:去重判断+对比已有演进经验(description 和 body 两个列表):+- 实质相同:与某条已有记录内容重复 -> 输出 {{"action": "skip", "skip_reason": "duplicate"}}+- 高度相似但有增量:与某条已有记录相关但有新信息 -> 输出合并后的完整内容,并设置 "merge_target" 为目标记录 id+- 全新:与已有记录无关 -> 继续第三步-## 要求-1. 语言必须一致(强制):输出语言必须与 Skill 完全一致。若 Skill 是中文,输出中文;若 Skill 是英文,输出英文。禁止自行决定语言!+### 第三步:优先级筛选与生成+将所有通过前两步的候选经验按优先级排序,仅为排名前 2 的候选生成内容,其余输出 {{"action": "skip", "skip_reason": "low_priority"}}。+确定经验归属层(target)和章节(section),然后生成内容。++**target 判断(二选一):**+- **description**(描述/元数据层):涉及 Skill 适用场景判断错误、描述不准确、缺少关键词导致未被选中或误选+- **body**(正文/指令层):涉及执行步骤、工具调用错误、操作流程、排查逻辑++**section 选择参考:**+- execution_failure / workaround 类:通常归入 Troubleshooting+- user_correction / 流程偏差类:通常归入 Instructions 或 Examples++## 内容生成规范+1. 语言一致:输出语言必须与 Skill 完全一致(中文 Skill 输出中文,英文 Skill 输出英文)2. 标题层级:使用与 Skill 相同的标题层级(##、### 等)-3. 记录格式(强制):只生成 1 条记录!禁止 2 条或更多!输出 JSON 的 content 字段只能有 1 个标题 + 2-3 个分点!-4. 聚焦信号:优先选择与当前任务直接相关的信号,忽略无关噪音-5. 提取通用规则:生成可复用的规则,非临时补丁- - 好:"遇到 X 类型错误时,先检查 Y 是否正确再执行 Z"- - 差:"某用户某次提到某问题"-6. 专注单一类型:一次只生成一个 section 类型的改进(Instructions/Examples/Troubleshooting 之一),不混合多类型-7. 分点格式:只使用无序列表(- 或 *),禁止层级(不能有子分点)-8. 精炼语言:内容简洁,避免冗余描述-9. 高质量增量:生成的演进内容必须是 Skill 中未提及的新知识,能指导后续使用并提升 Agent 执行效率。-10. 相关性判断(强制):判断当前发现的问题是否与 Skill 本身相关- - 相关:问题由 Skill 的指令、脚本、示例或排查逻辑导致 -> 输出 {{"relevant": true}}- - 不相关:问题由外部因素导致(如网络、环境、权限、第三方服务等)-> 输出 {{"relevant": false}}-11. 去重判断(强制):对比「已有演进经验」- - 相同:新生成的内容与已有记录实质相同 -> 输出 {{"action": "skip"}}- - 相似:新内容与某条已有记录高度相关但有增量信息 -> 输出合并后的完整内容,并标注 "merge_target": "<目标记录 id>"- - 全新:与已有记录无关 -> 正常输出--只输出以下 JSON,不要其他内容:-{{- "section": "Instructions | Examples | Troubleshooting",- "action": "append | skip",- "relevant": true | false,- "content": "Markdown 内容,1 个标题 + 2-3 个分点,无层级(只生成 1 条记录,禁止重复内容)",- "merge_target": "ev_xxxxxxxx 或 null"-}}"""+3. 每条记录:1 个标题 + 2-3 个无序列表分点(- 或 *),禁止子层级+4. 每条记录只涉及一个 section 类型,不混合+5. 提取可复用的通用规则,非临时补丁(好:"遇到 X 错误时,先检查 Y 再执行 Z";差:"某用户某次提到某问题")+6. 内容必须是 Skill 中未提及的新知识,精炼简洁+7. 多个发现指向同一问题时合并为一条;不同问题分别生成+8. 有效经验(action 为 append)最多 2 条,宁缺毋滥——只保留对 Skill 改进影响最大的发现++## 输出格式+只输出以下 JSON 数组,不要其他内容(即使只有一条,也必须用数组包裹):+[+ {{+ "action": "append | skip",+ "skip_reason": "irrelevant | duplicate | low_priority(仅 action 为 skip 时填写,否则为 null)",+ "target": "description | body",+ "section": "Instructions | Examples | Troubleshooting",+ "content": "Markdown 内容(仅 action 为 append 时填写)",+ "merge_target": "ev_xxxxxxxx 或 null"+ }}+]"""def build_conversation_snippet(@@ -88,8 +136,8 @@ def build_conversation_snippet(for msg in messages[-max_messages:]:role = msg.get("role", "unknown")text = _extract_text(msg).strip() or "(无文本)"- if len(text) > content_preview_chars:- text = text[:content_preview_chars] + "..."+ # if len(text) > content_preview_chars:+ # text = text[:content_preview_chars] + "..."tool_calls = msg.get("tool_calls")if role == "assistant" and tool_calls:@@ -114,42 +162,34 @@ class SkillEvolver:self._model = modelasync def generate_skill_experience(- self,- skill_name: str,- signals: List[EvolutionSignal],- skill_content: str,- conversation_snippet: str,- existing_entries: List[EvolutionEntry],- ) -> Optional[EvolutionEntry]:- """Generate an evolution entry via LLM, with history dedup.-- Args:- skill_name: Target skill name.- signals: Detected signals attributed to this skill.- skill_content: Current SKILL.md content.- conversation_snippet: Recent conversation summary.- existing_entries: Already-pending entries for dedup comparison.+ self, ctx: ExperienceContext,+ ) -> List[EvolutionEntry]:+ """Generate evolution entries via LLM, with history dedup.Returns:- A new EvolutionEntry, or None if LLM decides to skip.+ A list of new EvolutionEntry objects (empty list if LLM decides to skip all)."""- if not signals:- return None+ if not ctx.signals:+ return []++ conversation_snippet = build_conversation_snippet(ctx.messages)signals_json = json.dumps(- [s.to_dict() for s in signals], ensure_ascii=False, indent=2+ [s.to_dict() for s in ctx.signals], ensure_ascii=False, indent=2)- existing_summary = self._build_existing_summary(existing_entries)+ desc_summary = self._build_existing_summary(ctx.existing_desc_entries, "description")+ body_summary = self._build_existing_summary(ctx.existing_body_entries, "body")prompt = _GENERATE_PROMPT.format(- skill_content=skill_content[:2000],+ skill_content=ctx.skill_content,signals_json=signals_json,conversation_snippet=(conversation_snippet or "").strip(),- existing_entries_summary=existing_summary or "(无已有记录)",+ existing_desc_summary=desc_summary or "(无已有记录)",+ existing_body_summary=body_summary or "(无已有记录)",)- logger.info("[SkillEvolver] calling LLM (skill=%s)", skill_name)+ logger.info("[SkillEvolver] calling LLM (skill=%s)", ctx.skill_name)try:response = await self._llm.invoke(model=self._model,@@ -158,28 +198,33 @@ class SkillEvolver:raw = response.content if hasattr(response, "content") else str(response)except Exception as exc:logger.error("[SkillEvolver] LLM call failed: %s", exc)- return None-- change = self._parse_llm_response(raw)- if change is None:- return None- if change.action == "skip":- logger.info("[SkillEvolver] LLM decided to skip (dedup)")- return None- if not change.content.strip() or not change.relevant:- logger.info("[SkillEvolver] LLM thinks no changes needed")- return None-- source = signals[0].type if signals else "unknown"- context = "; ".join(s.excerpt for s in signals)- entry = EvolutionEntry.make(source=source, context=context, change=change)- logger.info(- "[SkillEvolver] generated entry %s -> [%s] merge_target=%s",- entry.id,- change.section,- change.merge_target,- )- return entry+ return []++ changes = self._parse_llm_response(raw)+ entries: List[EvolutionEntry] = []+ source = ctx.signals[0].type+ context = "; ".join(s.excerpt for s in ctx.signals)++ for change in changes:+ if change.action == "skip":+ logger.info(+ "[SkillEvolver] LLM decided to skip (reason=%s)",+ change.skip_reason or "unknown",+ )+ continue+ if not change.content.strip():+ logger.info("[SkillEvolver] LLM returned empty content, skipping")+ continue+ entry = EvolutionEntry.make(source=source, context=context, change=change)+ logger.info(+ "[SkillEvolver] generated entry %s -> [%s] target=%s merge_target=%s",+ entry.id,+ change.section,+ change.target.value,+ change.merge_target,+ )+ entries.append(entry)+ return entries[:2]def update_llm(self, llm: Any, model: str) -> None:self._llm = llm@@ -190,46 +235,80 @@ class SkillEvolver:# ------------------------------------------------------------------@staticmethod- def _build_existing_summary(entries: List[EvolutionEntry]) -> str:+ def _build_existing_summary(entries: List[EvolutionEntry], label: str = "") -> str:if not entries:return ""lines: List[str] = []for e in entries:- lines.append(f"- [{e.id}] [{e.change.section}] {e.change.content}")+ prefix = f"[{label}] " if label else ""+ lines.append(f"- {prefix}[{e.id}] [{e.change.section}] {e.change.content}")return "\n".join(lines)@staticmethod- def _parse_llm_response(raw: str) -> Optional[EvolutionChange]:- """从 LLM 返回里解析出 EvolutionChange。"""+ def _parse_llm_response(raw: str) -> List[EvolutionChange]:+ """从 LLM 返回里解析出 EvolutionChange 列表(支持数组和单对象两种格式)。"""raw = raw.strip()raw = re.sub(r"^```(?:json)?\s*", "", raw, flags=re.MULTILINE)raw = re.sub(r"```\s*$", "", raw, flags=re.MULTILINE)raw = raw.strip()+ data = Nonetry:data = json.loads(raw)except json.JSONDecodeError:- m = re.search(r"\{.*\}", raw, re.DOTALL)- if not m:+ # 先尝试匹配数组+ m = re.search(r"\[.*\]", raw, re.DOTALL)+ if m:+ try:+ data = json.loads(m.group(0))+ except json.JSONDecodeError:+ pass+ # 回退:尝试匹配单个对象+ if data is None:+ m = re.search(r"\{.*\}", raw, re.DOTALL)+ if m:+ try:+ data = json.loads(m.group(0))+ except json.JSONDecodeError:+ pass+ if data is None:logger.warning("[SkillEvolver] cannot parse LLM response as JSON: %s",raw[:200],)- return None- try:- data = json.loads(m.group(0))- except json.JSONDecodeError:- logger.warning("[SkillEvolver] JSON parse failed")- return None+ return []++ items = data if isinstance(data, list) else [data]+ changes: List[EvolutionChange] = []+ for item in items:+ if not isinstance(item, dict):+ continue+ change = SkillEvolver._parse_single_change(item)+ if change is not None:+ changes.append(change)+ return changes+ @staticmethod+ def _parse_single_change(data: dict) -> Optional[EvolutionChange]:+ """从单个 JSON 对象解析出 EvolutionChange。"""action = data.get("action", "append")if action == "skip":- return EvolutionChange(section="", action="skip", content="", relevant=False)+ skip_reason = data.get("skip_reason", "unknown")+ return EvolutionChange(+ section="", action="skip", content="",+ skip_reason=skip_reason,+ )section = data.get("section", "Troubleshooting")if section not in VALID_SECTIONS:section = "Troubleshooting"+ raw_target = data.get("target", "body")+ try:+ target = ExperienceTarget(raw_target)+ except ValueError:+ target = ExperienceTarget.BODY+merge_target = data.get("merge_target")if merge_target == "null" or merge_target is None:merge_target = None@@ -238,6 +317,6 @@ class SkillEvolver:section=section,action="append",content=data.get("content", ""),- relevant=data.get("relevant", True),+ target=target,merge_target=merge_target,)diff --git a/jiuwenclaw/evolution/schema.py b/jiuwenclaw/evolution/schema.pyindex b810e6b624..3abcbd884c 100644--- a/jiuwenclaw/evolution/schema.py+++ b/jiuwenclaw/evolution/schema.py@@ -19,12 +19,20 @@ class EvolutionType(str, Enum):NEW_SKILL = "new_skill"+class ExperienceTarget(str, Enum):+ """Which layer of the skill the experience targets."""++ DESCRIPTION = "description"+ BODY = "body"++@dataclassclass EvolutionChange:section: str # "Instructions" | "Examples" | "Troubleshooting"action: str # "append" | "skip"content: str # Markdown content to append- relevant: bool = True+ target: ExperienceTarget = ExperienceTarget.BODY+ skip_reason: Optional[str] = None # "irrelevant" | "duplicate" (only when action=="skip")merge_target: Optional[str] = None # existing entry id to replace (dedup merge)def to_dict(self) -> dict:@@ -32,19 +40,27 @@ class EvolutionChange:"section": self.section,"action": self.action,"content": self.content,- "relevant": self.relevant,+ "target": self.target.value,}+ if self.skip_reason:+ d["skip_reason"] = self.skip_reasonif self.merge_target:d["merge_target"] = self.merge_targetreturn d@classmethoddef from_dict(cls, d: dict) -> "EvolutionChange":+ raw_target = d.get("target", "body")+ try:+ target = ExperienceTarget(raw_target)+ except ValueError:+ target = ExperienceTarget.BODYreturn cls(section=d.get("section", "Troubleshooting"),action=d.get("action", "append"),content=d.get("content", ""),- relevant=d.get("relevant", True),+ target=target,+ skip_reason=d.get("skip_reason"),merge_target=d.get("merge_target"),)@@ -135,6 +151,18 @@ class EvolutionFile:return cls(skill_id=skill_id)+@dataclass+class ExperienceContext:+ """All inputs needed for LLM-based experience generation."""++ skill_name: str+ signals: List["EvolutionSignal"]+ skill_content: str+ messages: List[dict]+ existing_desc_entries: List[EvolutionEntry]+ existing_body_entries: List[EvolutionEntry]++@dataclassclass EvolutionSignal:type: str # "execution_failure" | "user_correction" | "repeated_failure"diff --git a/jiuwenclaw/evolution/service.py b/jiuwenclaw/evolution/service.pyindex 6648bcb714..55c9fcc71b 100644--- a/jiuwenclaw/evolution/service.py+++ b/jiuwenclaw/evolution/service.py@@ -8,20 +8,26 @@ import jsonimport uuidfrom typing import Any, Dict, List, Optional-from jiuwenclaw.evolution.evolver import SkillEvolver, build_conversation_snippet-from jiuwenclaw.evolution.schema import EvolutionSignal, EvolutionType+from jiuwenclaw.evolution.evolver import SkillEvolver+from jiuwenclaw.evolution.schema import (+ EvolutionEntry,+ EvolutionSignal,+ EvolutionType,+ ExperienceContext,+)from jiuwenclaw.evolution.signal_detector import SignalDetectorfrom jiuwenclaw.evolution.store import EvolutionStorefrom jiuwenclaw.utils import logger_APPROVAL_TIMEOUT = 300 # seconds+_MAX_PROCESSED_SIGNAL_KEYS = 500 # safety cap to prevent unbounded growth across sessionsclass EvolutionService:"""Unified facade for the skill online evolution system.Owns SignalDetector, SkillEvolver, and EvolutionStore.- Handles the complete lifecycle: detect -> truncate -> route -> generate+ Handles the complete lifecycle: detect -> deduplicate -> route -> generate-> approve -> persist."""@@ -36,6 +42,7 @@ class EvolutionService:self._evolver = SkillEvolver(llm, model)self._auto_scan = auto_scanself._pending_approvals: Dict[str, asyncio.Future] = {}+ self._processed_signal_keys: set[tuple[str, str]] = set()# ------------------------------------------------------------------# Properties@@ -64,6 +71,15 @@ class EvolutionService:def update_llm(self, llm: Any, model: str) -> None:self._evolver.update_llm(llm, model)+ def clear_processed_signals(self) -> None:+ """Clear the processed-signal fingerprint cache.++ Call this at conversation boundaries so signals from the previous+ conversation do not suppress detection in the next one.+ """+ self._processed_signal_keys.clear()+ logger.info("[EvolutionService] processed signal keys cleared")+# ------------------------------------------------------------------# Manual trigger: /evolve command# ------------------------------------------------------------------@@ -118,36 +134,48 @@ class EvolutionService:"result_type": "answer",}attributed = [s for s in signals if s.skill_name == skill_name]- entry = await self._generate_experience_for_skill(skill_name, attributed, parsed)- if entry is None:+ entries = await self._generate_experience_for_skill(skill_name, attributed, parsed)+ if not entries:return {"output": "当前对话未发现明确的演进信号(无工具执行失败、无用户纠正)。\n","result_type": "answer",}if session is not None:- keep = await self._request_approval(session, skill_name, entry)- if keep:- self._store.append_entry(skill_name, entry)+ tagged = [(skill_name, e) for e in entries]+ kept = await self._request_batch_approval(session, tagged)+ kept_entries = [entry for _, entry in kept]+ for sn, entry in kept:+ self._store.append_entry(sn, entry)+ if kept_entries:+ summaries = "\n".join(+ f" {i+1}. **[{e.change.section}]** {e.change.content[:200]}"+ for i, e in enumerate(kept_entries)+ )return {"output": (- f"已记录演进经验到 Skill '{skill_name}':\n"- f" **[{entry.change.section}]** {entry.change.content[:200]}\n\n"+ f"已记录 {len(kept_entries)} 条演进经验到 Skill '{skill_name}':\n"+ f"{summaries}\n\n"f"(evolutions.json 已更新,自动生效;"f"可使用 `/solidify {skill_name}` 将经验固化到 SKILL.md 本体)"),"result_type": "answer",}return {- "output": f"已丢弃 Skill '{skill_name}' 的演进内容,evolutions.json 未变更。",+ "output": f"已丢弃 Skill '{skill_name}' 的全部演进内容,evolutions.json 未变更。","result_type": "answer",}- self._store.append_entry(skill_name, entry)+ for entry in entries:+ self._store.append_entry(skill_name, entry)+ summaries = "\n".join(+ f" {i+1}. **[{e.change.section}]** {e.change.content[:200]}"+ for i, e in enumerate(entries)+ )return {"output": (- f"已记录演进经验到 Skill '{skill_name}':\n"- f" **[{entry.change.section}]** {entry.change.content[:200]}"+ f"已记录 {len(entries)} 条演进经验到 Skill '{skill_name}':\n"+ f"{summaries}"),"result_type": "answer",}@@ -197,13 +225,95 @@ class EvolutionService:# Approval flow (migrated from react_agent.py)# ------------------------------------------------------------------- async def _request_approval(+ @staticmethod+ def _build_approval_questions(+ entries: List[tuple],+ ) -> list:+ """Build the questions payload for a batch approval request."""+ questions = []+ for skill_name, entry in entries:+ content_preview = entry.change.content[:1000]+ questions.append({+ "question": (+ f"**Skill '{skill_name}' 演进生成了新内容:**\n\n"+ f"{content_preview}"+ ),+ "header": "演进审批",+ "options": [+ {"label": "接收", "description": "保留此演进经验"},+ {"label": "拒绝", "description": "丢弃此演进经验"},+ ],+ "multi_select": False,+ })+ return questions++ @staticmethod+ def _parse_approval_answers(+ answers: list,+ entries: List[tuple],+ ) -> List[tuple]:+ """Return the (skill_name, entry) pairs that user chose to keep."""+ kept: List[tuple] = []+ for i, (skill_name, entry) in enumerate(entries):+ keep = (+ i < len(answers)+ and isinstance(answers[i], dict)+ and "接收" in answers[i].get("selected_options", [])+ )+ if keep:+ kept.append((skill_name, entry))+ return kept++ async def _request_batch_approval(self,session: Any,- skill_name: str,- entry: Any,- ) -> bool:- """Send approval request to user. Returns True=keep, False=discard."""+ entries: List[tuple],+ ) -> List[tuple]:+ """Send a single batch approval request and block until answered.++ Used by /evolve command where we need a synchronous result.+ Returns the (skill_name, entry) pairs that user chose to keep.+ """+ from openjiuwen.core.session.stream import OutputSchema++ request_id = f"evolve_approve_{uuid.uuid4().hex[:8]}"+ loop = asyncio.get_running_loop()+ future: asyncio.Future = loop.create_future()+ self._pending_approvals[request_id] = future++ questions = self._build_approval_questions(entries)+ try:+ await session.write_stream(+ OutputSchema(+ type="chat.ask_user_question",+ index=0,+ payload={"request_id": request_id, "questions": questions},+ )+ )+ except Exception:+ logger.debug("[EvolutionService] batch approval send failed", exc_info=True)+ self._pending_approvals.pop(request_id, None)+ return list(entries)++ try:+ answers = await asyncio.wait_for(future, timeout=_APPROVAL_TIMEOUT)+ return self._parse_approval_answers(answers, entries)+ except asyncio.TimeoutError:+ logger.info("[EvolutionService] batch approval timeout, auto-keeping all")+ return list(entries)+ finally:+ self._pending_approvals.pop(request_id, None)++ async def _request_batch_approval_async(+ self,+ session: Any,+ entries: List[tuple],+ ) -> None:+ """Send a single batch approval request then return immediately.++ A background task handles the wait and persistence so the stream+ session is not blocked by the approval timeout.+ """from openjiuwen.core.session.stream import OutputSchemarequest_id = f"evolve_approve_{uuid.uuid4().hex[:8]}"@@ -211,44 +321,59 @@ class EvolutionService:future: asyncio.Future = loop.create_future()self._pending_approvals[request_id] = future- content_preview = entry.change.content[:1000]+ questions = self._build_approval_questions(entries)try:await session.write_stream(OutputSchema(type="chat.ask_user_question",index=0,- payload={- "request_id": request_id,- "questions": [- {- "question": (- f"**Skill '{skill_name}' 演进生成了新内容:**\n\n"- f"{content_preview}"- ),- "header": "演进审批",- "options": [- {"label": "接收", "description": "保留此演进经验"},- {"label": "拒绝", "description": "丢弃此演进经验"},- ],- "multi_select": False,- }- ],- },+ payload={"request_id": request_id, "questions": questions},))except Exception:- logger.debug("[EvolutionService] approval popup send failed", exc_info=True)+ logger.debug("[EvolutionService] batch approval send failed", exc_info=True)self._pending_approvals.pop(request_id, None)- return True+ for skill_name, entry in entries:+ self._store.append_entry(skill_name, entry)+ logger.info(+ "[EvolutionService] send failed, auto-keeping %d entries", len(entries),+ )+ return++ asyncio.create_task(+ self._wait_and_persist_batch(future, request_id, entries)+ )+ async def _wait_and_persist_batch(+ self,+ future: asyncio.Future,+ request_id: str,+ entries: List[tuple],+ ) -> None:+ """Background task: wait for batch approval then persist kept entries."""try:- return await asyncio.wait_for(future, timeout=_APPROVAL_TIMEOUT)+ answers = await asyncio.wait_for(future, timeout=_APPROVAL_TIMEOUT)+ kept = self._parse_approval_answers(answers, entries)+ for skill_name, entry in kept:+ self._store.append_entry(skill_name, entry)+ logger.info("[EvolutionService] kept: skill=%s id=%s", skill_name, entry.id)+ discarded = len(entries) - len(kept)+ if discarded:+ logger.info("[EvolutionService] discarded %d entries", discarded)except asyncio.TimeoutError:logger.info(- "[EvolutionService] approval timeout (skill=%s), auto-keeping",- skill_name,+ "[EvolutionService] batch approval timeout, auto-discarding %d entries",+ len(entries),+ )+ except asyncio.CancelledError:+ for skill_name, entry in entries:+ self._store.append_entry(skill_name, entry)+ logger.info(+ "[EvolutionService] batch approval cancelled, auto-keeping %d entries",+ len(entries),)- return True+ except Exception as exc:+ logger.warning("[EvolutionService] batch approval wait error: %s", exc)finally:self._pending_approvals.pop(request_id, None)@@ -256,27 +381,24 @@ class EvolutionService:"""Resolve a pending approval future with user's answer.Called by interface.py on chat.user_answer.+ Passes the raw answers list to the waiting future so that both+ _request_batch_approval and _wait_and_persist_batch can interpret it.Returns True if resolved, False if not found."""future = self._pending_approvals.get(request_id)if future is None or future.done():return False- keep = (- "接收" in answers[0].get("selected_options", [])- if answers and isinstance(answers[0], dict)- else False- )- future.set_result(keep)+ future.set_result(answers)logger.info(- "[EvolutionService] approval resolved: request_id=%s keep=%s",+ "[EvolutionService] approval resolved: request_id=%s answers=%d",request_id,- keep,+ len(answers),)return True# ------------------------------------------------------------------- # Core internal: detect -> truncate -> route+ # Core internal: detect -> deduplicate -> route# ------------------------------------------------------------------def _detect_signals(@@ -284,7 +406,7 @@ class EvolutionService:parsed_messages: List[dict],skill_names: List[str],) -> List[EvolutionSignal]:- """Call SignalDetector + truncate to last signal.+ """Call SignalDetector and filter already-processed signals by fingerprint.Args:parsed_messages: Already-normalized message dicts (call _parse_messages upstream).@@ -298,17 +420,28 @@ class EvolutionService:detector = SignalDetector(skill_dir_map=skill_dir_map)signals = detector.detect(parsed_messages)- if len(signals) > 1:- signals = signals[-1:]- logger.info("[EvolutionService] truncated to last signal")+ new_signals = [+ sig for sig in signals+ if (sig.type, sig.excerpt[:100]) not in self._processed_signal_keys+ ]+ for sig in new_signals:+ self._processed_signal_keys.add((sig.type, sig.excerpt[:100]))++ if len(self._processed_signal_keys) > _MAX_PROCESSED_SIGNAL_KEYS:+ logger.info(+ "[EvolutionService] _processed_signal_keys exceeded cap (%d), clearing",+ _MAX_PROCESSED_SIGNAL_KEYS,+ )+ self._processed_signal_keys.clear()- if signals:+ if new_signals:logger.info(- "[EvolutionService] detected %d signal(s): %s",- len(signals),- json.dumps([s.to_dict() for s in signals], ensure_ascii=False),+ "[EvolutionService] detected %d new signal(s) (filtered %d already-processed): %s",+ len(new_signals),+ len(signals) - len(new_signals),+ json.dumps([s.to_dict() for s in new_signals], ensure_ascii=False),)- return signals+ return new_signalsasync def _route_and_process(self,@@ -316,64 +449,77 @@ class EvolutionService:parsed_messages: List[dict],session: Any,) -> None:- """Route signals to the appropriate handler.+ """Route signals to the appropriate handler, grouped by skill.- Currently only SKILL_EXPERIENCE is implemented. Signals are already- truncated to at most one by _detect_signals, so we process directly- without grouping.+ Signals attributed to the same skill are batched into a single LLM call+ to avoid redundant generation and duplicate experiences."""+ skill_groups: Dict[str, List[EvolutionSignal]] = {}for sig in signals:if sig.evolution_type == EvolutionType.SKILL_EXPERIENCE and sig.skill_name:- await self._evolve_skill_experience(sig, signals, parsed_messages, session)+ skill_groups.setdefault(sig.skill_name, []).append(sig)# Future: elif sig.evolution_type == EvolutionType.NEW_SKILL:# await self._evolve_new_skill(...)- async def _evolve_skill_experience(- self,- signal: EvolutionSignal,- all_signals: List[EvolutionSignal],- parsed_messages: List[dict],- session: Any,- ) -> None:- """Evolve an existing skill: generate experience -> approve -> persist."""- skill_name = signal.skill_name- attributed = [s for s in all_signals if s.skill_name == skill_name]- entry = await self._generate_experience_for_skill(skill_name, attributed, parsed_messages)- if entry is None:- return- try:- keep = await self._request_approval(session, skill_name, entry)- if keep:- self._store.append_entry(skill_name, entry)- logger.info("[EvolutionService] kept: skill=%s id=%s", skill_name, entry.id)- else:- logger.info("[EvolutionService] discarded: skill=%s id=%s", skill_name, entry.id)- except Exception as exc:- logger.warning(- "[EvolutionService] approval flow error (skill=%s): %s",- skill_name,- exc,+ all_entries: List[tuple] = []+ for skill_name, skill_signals in skill_groups.items():+ entries = await self._generate_experience_for_skill(+ skill_name, skill_signals, parsed_messages)+ for entry in entries:+ all_entries.append((skill_name, entry))++ if all_entries:+ try:+ await self._request_batch_approval_async(session, all_entries)+ except Exception as exc:+ logger.warning(+ "[EvolutionService] batch approval error: %s", exc,+ )async def _generate_experience_for_skill(self,skill_name: str,signals: List[EvolutionSignal],messages: List[dict],- ) -> Any:- """Generate an evolution entry for a single skill."""- skill_content = self._store.read_skill_content(skill_name)- existing = self._store.get_pending_entries(skill_name)- snippet = build_conversation_snippet(messages)+ ) -> List[EvolutionEntry]:+ """Generate evolution entries for a single skill."""+ ctx = ExperienceContext(+ skill_name=skill_name,+ signals=signals,+ skill_content=self._store.read_skill_content(skill_name),+ messages=messages,+ existing_desc_entries=self._store.load_desc_pending_entries(skill_name),+ existing_body_entries=self._store.load_body_pending_entries(skill_name),+ )try:- return await self._evolver.generate_skill_experience(- skill_name, signals, skill_content, snippet, existing- )+ return await self._evolver.generate_skill_experience(ctx)except Exception as exc:logger.warning("[EvolutionService] generate failed (skill=%s): %s", skill_name, exc)- return None+ return []++ @staticmethod+ def extract_user_content(raw: str) -> str:+ """Extract decoded user content from build_user_prompt JSON wrapper.++ The wrapper format is:+ 你收到一条消息:\n{"source": ..., "content": "...", ...}+ Returns the inner *content* value (with unicode escapes decoded),+ or falls back to *raw* if parsing fails.+ """+ prefix = "你收到一条消息:\n"+ if not raw.startswith(prefix):+ return raw+ json_part = raw[len(prefix):]+ try:+ payload = json.loads(json_part)+ if isinstance(payload, dict) and "content" in payload:+ return payload["content"]+ except (json.JSONDecodeError, TypeError):+ pass+ return raw@staticmethoddef _parse_messages(messages: List[Any]) -> List[dict]:@@ -383,10 +529,11 @@ class EvolutionService:if isinstance(msg, dict):result.append(msg)elif hasattr(msg, "role"):- d: dict = {- "role": getattr(msg, "role", ""),- "content": str(getattr(msg, "content", "") or ""),- }+ content = str(getattr(msg, "content", "") or "")+ role = getattr(msg, "role", "")+ if role == "user":+ content = EvolutionService.extract_user_content(content)+ d: dict = {"role": role, "content": content}tool_calls = getattr(msg, "tool_calls", None)if tool_calls:d["tool_calls"] = [diff --git a/jiuwenclaw/evolution/signal_detector.py b/jiuwenclaw/evolution/signal_detector.pyindex 384768ffe2..bf9efcc8b6 100644--- a/jiuwenclaw/evolution/signal_detector.py+++ b/jiuwenclaw/evolution/signal_detector.py@@ -52,7 +52,7 @@ _CORRECTION_PATTERNS = [_CORRECTION_PATTERN = re.compile("|".join(_CORRECTION_PATTERNS), re.IGNORECASE)_SKILL_MD_PATTERN = re.compile(r"[/\\]+([^/\\]+)[/\\]+SKILL\.md", re.IGNORECASE)-_TOOL_SCHEMA_PATTERN = re.compile(r"^---\nname:\s*\w+\ndescription:", re.MULTILINE)+_TOOL_SCHEMA_PATTERN = re.compile(r"^---\nname:\s*[^\n]+\ndescription:", re.MULTILINE)class SignalDetector:diff --git a/jiuwenclaw/evolution/store.py b/jiuwenclaw/evolution/store.pyindex 06927b701c..a3e94b8d2e 100644--- a/jiuwenclaw/evolution/store.py+++ b/jiuwenclaw/evolution/store.py@@ -7,12 +7,13 @@ import jsonimport refrom datetime import datetime, timezonefrom pathlib import Path-from typing import List, Optional+from typing import Dict, List, Optionalfrom jiuwenclaw.evolution.schema import (EvolutionChange,EvolutionEntry,EvolutionFile,+ ExperienceTarget,)from jiuwenclaw.utils import logger@@ -24,9 +25,9 @@ class EvolutionStore:Responsibilities:- Skill directory scanning and SKILL.md reading- - evolutions.json read/write- - Solidification (writing pending entries into SKILL.md)- - Evolution summary generation for system prompts+ - evolutions.json read/write (single unified file; target distinguished by entry.change.target)+ - Solidification (writing pending body entries into SKILL.md)+ - Experience text formatting for system prompts"""def __init__(self, skills_base_dir: str) -> None:@@ -66,30 +67,45 @@ class EvolutionStore:return ""# ------------------------------------------------------------------- # evolutions.json read/write+ # Evolution file read/write (unified file, target distinguished by field)# ------------------------------------------------------------------- def load_evolution_file(self, name: str) -> EvolutionFile:+ def load_evolution_file(+ self, name: str, target: Optional[ExperienceTarget] = None,+ ) -> EvolutionFile:+ """Load the unified evolution file for the given skill.++ Args:+ name: Skill name.+ target: If provided, returns a view with only entries matching that+ target (entries list is filtered; the returned object should be+ treated as read-only for save purposes). Pass ``None`` to get+ all entries.+ """skill_dir = self._base / name- evo_path = skill_dir / _EVOLUTION_FILENAME- if evo_path.exists():- try:- data = json.loads(evo_path.read_text(encoding="utf-8"))- return EvolutionFile.from_dict(data)- except Exception as exc:- logger.warning("[EvolutionStore] read evolutions.json failed: %s", exc)- return EvolutionFile.empty(skill_id=name)+ unified_path = skill_dir / _EVOLUTION_FILENAME- def get_pending_entries(self, name: str) -> List[EvolutionEntry]:- return self.load_evolution_file(name).pending_entries+ if unified_path.exists():+ evo_file = self._read_evo_json(unified_path, name)+ else:+ evo_file = EvolutionFile.empty(skill_id=name)++ if target is not None:+ evo_file = EvolutionFile(+ skill_id=evo_file.skill_id,+ version=evo_file.version,+ updated_at=evo_file.updated_at,+ entries=[e for e in evo_file.entries if e.change.target == target],+ )+ return evo_filedef append_entry(self, name: str, entry: EvolutionEntry) -> None:- """Append an evolution entry to evolutions.json.+ """Append an evolution entry to the unified evolutions.json.- If ``entry.change.merge_target`` is set, replaces the target entry+ If ``entry.change.merge_target`` is set, replaces the matching entryinstead of appending."""- evo_file = self.load_evolution_file(name)+ evo_file = self._load_full_evolution_file(name)merge_target = getattr(entry.change, "merge_target", None)if merge_target:@@ -112,22 +128,47 @@ class EvolutionStore:evo_file.updated_at = datetime.now(tz=timezone.utc).isoformat()self._save_evolution_file(name, evo_file)logger.info(- "[EvolutionStore] wrote %s/evolutions.json (id=%s)", name, entry.id+ "[EvolutionStore] wrote %s/%s (id=%s, target=%s)",+ name, _EVOLUTION_FILENAME, entry.id, entry.change.target.value,)# ------------------------------------------------------------------- # Solidification+ # Typed pending-entry loaders+ # ------------------------------------------------------------------++ def load_desc_pending_entries(self, name: str) -> List[EvolutionEntry]:+ """Load pending description-experience entries for a skill."""+ return self.load_evolution_file(name, ExperienceTarget.DESCRIPTION).pending_entries++ def load_body_pending_entries(self, name: str) -> List[EvolutionEntry]:+ """Load pending body-experience entries for a skill."""+ return self.load_evolution_file(name, ExperienceTarget.BODY).pending_entries++ def get_pending_entries(+ self, name: str, target: Optional[ExperienceTarget] = None,+ ) -> List[EvolutionEntry]:+ """Load pending entries, optionally filtered by target.++ If *target* is ``None``, returns all pending entries from the unified file.+ """+ return self.load_evolution_file(name, target).pending_entries++ # ------------------------------------------------------------------+ # Solidification (body experiences only)# ------------------------------------------------------------------def solidify(self, name: str) -> int:- """Write pending entries into SKILL.md, mark them as applied.+ """Write pending **body** entries into SKILL.md, mark them as applied.++ Description experiences are not solidified into SKILL.md; they live+ in evolutions.json and are injected at prompt-build time.Returns:Number of entries solidified."""skill_dir = self._base / name- evo_file = self.load_evolution_file(name)- pending = evo_file.pending_entries+ evo_file = self._load_full_evolution_file(name)+ pending = [e for e in evo_file.pending_entries if e.change.target == ExperienceTarget.BODY]if not pending:return 0@@ -144,53 +185,84 @@ class EvolutionStore:skill_md_path.write_text(content, encoding="utf-8")evo_file.updated_at = datetime.now(tz=timezone.utc).isoformat()self._save_evolution_file(name, evo_file)- logger.info("[EvolutionStore] solidified %d entries (skill=%s)", len(pending), name)+ logger.info("[EvolutionStore] solidified %d body entries (skill=%s)", len(pending), name)return len(pending)# ------------------------------------------------------------------- # Summaries (for system prompt injection)+ # Experience text formatting# ------------------------------------------------------------------- def get_evolution_summary(self, name: str) -> str:- """Return single skill's pending evolution summary as Markdown."""- pending = self.get_pending_entries(name)+ def format_desc_experience_text(self, name: str) -> str:+ """Format pending description experiences for a single skill.++ Returns a compact Markdown string suitable for appending after the+ skill's description line in the system prompt.+ """+ pending = self.load_desc_pending_entries(name)if not pending:return ""- lines = [f"\n\n### Skill '{name}' 演进经验(自动注入,待固化)\n"]+ lines: List[str] = []for entry in pending:- lines.append(f"- **[{entry.change.section}]** {entry.change.content}")+ lines.append(f"- {entry.change.content}")return "\n".join(lines)- def get_all_evolution_summaries(self, names: List[str]) -> str:- """Aggregate pending evolution summaries for multiple skills."""- parts: List[str] = []+ def format_all_desc_experiences(self, names: List[str]) -> Dict[str, str]:+ """Batch-format description experiences for multiple skills.++ Returns:+ ``{skill_name: formatted_text}`` for skills that have pending+ description experiences.+ """+ result: Dict[str, str] = {}for name in names:- summary = self.get_evolution_summary(name)- if summary:- parts.append(summary)- return "\n".join(parts)+ text = self.format_desc_experience_text(name)+ if text:+ result[name] = text+ return result++ def format_body_experience_text(self, name: str) -> str:+ """Format pending body experiences for a single skill.++ Useful for ``/evolve list`` display and for passing to the evolver+ as existing-entries context.+ """+ pending = self.load_body_pending_entries(name)+ if not pending:+ return ""+ lines = [f"\n\n# Skill '{name}' body 演进经验\n"]+ for index, entry in enumerate(pending):+ lines.append(f"{index + 1}. **[{entry.change.section}]** {entry.change.content}")+ return "\n".join(lines)def list_pending_summary(self, names: List[str]) -> str:"""Return a human-readable pending summary for multiple skills."""lines: List[str] = []count = 0for name in names:- pending = self.get_pending_entries(name)- if pending:- count += 1- lines.append(f"{count}. **{name}** - 共 {len(pending)} 条 pending 经验")- for e in pending:- content = e.change.content- title = content.split("\n")[0] if "\n" in content else content[:50]- lines.append(f" - **{title}**: ")- if "\n" in content:- body_lines = content.split("\n")[1:]- if body_lines:- summary = " ".join(- ln.strip().lstrip("- ") for ln in body_lines if ln.strip()- )- lines.append(f" {summary[:100].replace('**', '')}")- lines.append("")+ desc_pending = self.load_desc_pending_entries(name)+ body_pending = self.load_body_pending_entries(name)+ all_pending = desc_pending + body_pending+ if not all_pending:+ continue++ count += 1+ lines.append(+ f"{count}. **{name}** - 共 {len(all_pending)} 条 pending 经验"+ f"(description: {len(desc_pending)}, body: {len(body_pending)})"+ )+ for e in all_pending:+ tag = "description" if e.change.target == ExperienceTarget.DESCRIPTION else "body"+ content = e.change.content+ title = content.split("\n")[0] if "\n" in content else content[:50]+ lines.append(f" - [{tag}] **{title}**: ")+ if "\n" in content:+ body_lines = content.split("\n")[1:]+ if body_lines:+ summary = " ".join(+ ln.strip().lstrip("- ") for ln in body_lines if ln.strip()+ )+ lines.append(f" {summary[:100].replace('**', '')}")+ lines.append("")if not lines:return "当前所有 Skill 暂无演进信息。"@@ -200,6 +272,14 @@ class EvolutionStore:# Internal helpers# ------------------------------------------------------------------+ def _load_full_evolution_file(self, name: str) -> EvolutionFile:+ """Load the full (unfiltered) unified evolution file for *name*."""+ skill_dir = self._base / name+ unified_path = skill_dir / _EVOLUTION_FILENAME+ if unified_path.exists():+ return self._read_evo_json(unified_path, name)+ return EvolutionFile.empty(skill_id=name)+def _save_evolution_file(self, name: str, evo_file: EvolutionFile) -> None:skill_dir = self._base / nameskill_dir.mkdir(parents=True, exist_ok=True)@@ -210,7 +290,16 @@ class EvolutionStore:encoding="utf-8",)except Exception as exc:- logger.error("[EvolutionStore] write evolutions.json failed: %s", exc)+ logger.error("[EvolutionStore] write %s failed: %s", _EVOLUTION_FILENAME, exc)++ @staticmethod+ def _read_evo_json(path: Path, skill_id: str) -> EvolutionFile:+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ return EvolutionFile.from_dict(data)+ except Exception as exc:+ logger.warning("[EvolutionStore] read %s failed: %s", path.name, exc)+ return EvolutionFile.empty(skill_id=skill_id)@staticmethoddef _find_skill_md(skill_dir: Path) -> Optional[Path]:diff --git a/jiuwenclaw/web/src/components/ChatPanel/InlineQuestionCard.tsx b/jiuwenclaw/web/src/components/ChatPanel/InlineQuestionCard.tsxindex 1d2ae2ee09..ddd649c5f7 100644--- a/jiuwenclaw/web/src/components/ChatPanel/InlineQuestionCard.tsx+++ b/jiuwenclaw/web/src/components/ChatPanel/InlineQuestionCard.tsx@@ -3,10 +3,12 @@** 在聊天流内以内联卡片形式展示用户审批请求(接收/拒绝),* 替代全屏大弹窗(UserQuestionModal)。- * 点击选项后立即提交,卡片切换为已确认状态保留在消息流中。+ *+ * 单问题模式:点击选项后立即提交。+ * 多问题模式(批量审批):逐条选择后统一提交,并提供"全部接收"快捷操作。*/-import { useState, useCallback } from 'react';+import { useState, useCallback, useMemo, useEffect } from 'react';import { useTranslation } from 'react-i18next';import { useChatStore } from '../../stores';import { UserAnswer } from '../../types';@@ -20,34 +22,72 @@ interface InlineQuestionCardProps {export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {const { t } = useTranslation();const { pendingQuestion, setPendingQuestion } = useChatStore();- const [submittedAnswers, setSubmittedAnswers] = useState<Map<string, string>>(new Map());+ const [selections, setSelections] = useState<Map<number, string>>(new Map());+ const [submitted, setSubmitted] = useState(false);++ const requestId = pendingQuestion?.request_id;+ useEffect(() => {+ setSelections(new Map());+ setSubmitted(false);+ }, [requestId]);++ const isBatch = (pendingQuestion?.questions.length ?? 0) > 1;++ const allAnswered = useMemo(() => {+ if (!pendingQuestion) return false;+ return pendingQuestion.questions.every((_, idx) => selections.has(idx));+ }, [pendingQuestion, selections]);++ const buildAnswers = useCallback(+ (selMap: Map<number, string>): UserAnswer[] => {+ return (pendingQuestion?.questions ?? []).map((q, idx) => {+ const sel = selMap.get(idx);+ if (sel) return { selected_options: [sel] };+ return { selected_options: q.options.length > 0 ? [q.options[0].label] : [] };+ });+ },+ [pendingQuestion]+ );++ const doSubmit = useCallback(+ (selMap: Map<number, string>) => {+ if (!pendingQuestion) return;+ setSubmitted(true);+ onSubmit(pendingQuestion.request_id, buildAnswers(selMap));+ setPendingQuestion(null);+ },+ [pendingQuestion, buildAnswers, onSubmit, setPendingQuestion]+ );const handleSelect = useCallback(- (requestId: string, questionIndex: number, optionLabel: string, isMultiSelect: boolean) => {- if (submittedAnswers.has(`${requestId}-${questionIndex}`)) return;-- if (!isMultiSelect) {- // 单选:立即提交- const allAnswers: UserAnswer[] = (pendingQuestion?.questions ?? []).map((q, idx) => {- if (idx === questionIndex) {- return { selected_options: [optionLabel] };- }- return { selected_options: q.options.length > 0 ? [q.options[0].label] : [] };- });-- setSubmittedAnswers((prev) => {- const next = new Map(prev);- next.set(`${requestId}-${questionIndex}`, optionLabel);- return next;- });-- onSubmit(requestId, allAnswers);- setPendingQuestion(null);+ (questionIndex: number, optionLabel: string) => {+ if (submitted) return;++ const next = new Map(selections);+ next.set(questionIndex, optionLabel);+ setSelections(next);++ if (!isBatch) {+ doSubmit(next);}},- [pendingQuestion, submittedAnswers, onSubmit, setPendingQuestion]+ [submitted, selections, isBatch, doSubmit]);+ const handleAcceptAll = useCallback(() => {+ if (!pendingQuestion || submitted) return;+ const acceptLabel = t('chatUi.inlineQuestion.accept');+ const all = new Map<number, string>();+ pendingQuestion.questions.forEach((_, idx) => all.set(idx, acceptLabel));+ setSelections(all);+ doSubmit(all);+ }, [pendingQuestion, submitted, t, doSubmit]);++ const handleSubmitBatch = useCallback(() => {+ if (!allAnswered || submitted) return;+ doSubmit(selections);+ }, [allAnswered, submitted, selections, doSubmit]);+if (!pendingQuestion) {return null;}@@ -63,70 +103,84 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {>{/* 标题行 */}<div- className="px-4 py-2.5 flex items-center gap-2"+ className="px-4 py-2.5 flex items-center justify-between"style={{borderBottom: '1px solid var(--border)',backgroundColor: 'var(--panel-strong)',}}>- <svg- className="w-3.5 h-3.5 flex-shrink-0"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- strokeWidth={2}- style={{ color: 'var(--accent)' }}- >- <path- strokeLinecap="round"- strokeLinejoin="round"- d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0112 15a9.065 9.065 0 00-6.23-.693L5 14.5m14.8.8l1.402 1.402c1.232 1.232.65 3.318-1.067 3.611A48.309 48.309 0 0112 21c-2.773 0-5.491-.235-8.135-.687-1.718-.293-2.3-2.379-1.067-3.61L5 14.5"- />- </svg>- <span- className="text-xs font-semibold"- style={{ color: 'var(--accent)' }}- >- {pendingQuestion.questions[0]?.header ?? t('chatUi.inlineQuestion.header')}- </span>+ <div className="flex items-center gap-2">+ <svg+ className="w-3.5 h-3.5 flex-shrink-0"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ strokeWidth={2}+ style={{ color: 'var(--accent)' }}+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0112 15a9.065 9.065 0 00-6.23-.693L5 14.5m14.8.8l1.402 1.402c1.232 1.232.65 3.318-1.067 3.611A48.309 48.309 0 0112 21c-2.773 0-5.491-.235-8.135-.687-1.718-.293-2.3-2.379-1.067-3.61L5 14.5"+ />+ </svg>+ <span+ className="text-xs font-semibold"+ style={{ color: 'var(--accent)' }}+ >+ {pendingQuestion.questions[0]?.header ?? t('chatUi.inlineQuestion.header')}+ </span>+ {isBatch && (+ <span+ className="text-xs"+ style={{ color: 'var(--muted)' }}+ >+ {t('chatUi.inlineQuestion.entryCount', { count: pendingQuestion.questions.length })}+ </span>+ )}+ </div>+ {isBatch && !submitted && (+ <button+ onClick={handleAcceptAll}+ className="text-xs font-medium px-2.5 py-1 rounded-md transition-opacity hover:opacity-80"+ style={{+ color: 'white',+ background: 'linear-gradient(135deg, var(--ok), var(--accent))',+ }}+ >+ {t('chatUi.inlineQuestion.acceptAll')}+ </button>+ )}</div>- {/* 问题内容 */}- {pendingQuestion.questions.map((question, qIndex) => {- const submittedKey = `${pendingQuestion.request_id}-${qIndex}`;- const submittedLabel = submittedAnswers.get(submittedKey);+ {/* 问题列表 */}+ <div+ className="overflow-y-auto"+ style={{ maxHeight: '60vh' }}+ >+ {pendingQuestion.questions.map((question, qIndex) => {+ const selectedLabel = selections.get(qIndex);- return (- <div key={qIndex}>- {/* 问题正文 */}+ return (<div- className="px-4 pt-3 pb-2 text-sm prose prose-sm max-w-none prose-headings:font-semibold prose-headings:text-sm prose-ul:my-1 prose-li:my-0 prose-li:pl-1"- style={{ color: 'var(--text)' }}+ key={qIndex}+ style={+ qIndex > 0+ ? { borderTop: '1px solid var(--border)' }+ : undefined+ }>- <ReactMarkdown remarkPlugins={[remarkGfm]}>- {question.question}- </ReactMarkdown>- </div>-- {/* 选项按钮或已提交状态 */}- {submittedLabel ? (+ {/* 问题正文 */}<div- className="px-4 pb-3 flex items-center gap-2 text-xs"- style={{ color: 'var(--muted)' }}+ className="px-4 pt-3 pb-2 text-sm prose prose-sm max-w-none prose-headings:font-semibold prose-headings:text-sm prose-ul:my-1 prose-li:my-0 prose-li:pl-1"+ style={{ color: 'var(--text)' }}>- <svg- className="w-3.5 h-3.5 flex-shrink-0"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- strokeWidth={2.5}- style={{ color: 'var(--ok)' }}- >- <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />- </svg>- {t('chatUi.inlineQuestion.selected')}: <span style={{ color: 'var(--text-strong)' }}>{submittedLabel}</span>+ <ReactMarkdown remarkPlugins={[remarkGfm]}>+ {question.question}+ </ReactMarkdown></div>- ) : (++ {/* 选项按钮 */}<div className="px-4 pb-3 flex flex-col gap-2">{question.options.map((option) => {const isAccept = option.label === t('chatUi.inlineQuestion.accept')@@ -136,24 +190,35 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {|| option.label === '总是允许';const isReject = option.label === t('chatUi.inlineQuestion.reject')|| option.label === '拒绝';+ const isSelected = selectedLabel === option.label;+return (<buttonkey={option.label}- onClick={() =>- handleSelect(- pendingQuestion.request_id,- qIndex,- option.label,- question.multi_select || false- )- }+ onClick={() => handleSelect(qIndex, option.label)}+ disabled={submitted}className="w-full text-left px-4 py-2.5 text-sm font-medium rounded-lg transition-all"style={{- backgroundColor: 'var(--bg-elevated)',- border: `1px solid var(--border)`,- color: 'var(--text)',+ backgroundColor: isSelected+ ? (isAccept+ ? 'var(--ok-subtle, rgba(34,197,94,0.12))'+ : isReject+ ? 'var(--danger-subtle, rgba(239,68,68,0.12))'+ : 'var(--accent-subtle)')+ : 'var(--bg-elevated)',+ border: `1px solid ${+ isSelected+ ? (isAccept ? 'var(--ok)' : isReject ? 'var(--danger)' : 'var(--accent)')+ : 'var(--border)'+ }`,+ color: isSelected+ ? (isAccept ? 'var(--ok)' : isReject ? 'var(--danger)' : 'var(--text-strong)')+ : 'var(--text)',+ opacity: submitted ? 0.6 : 1,+ cursor: submitted ? 'default' : 'pointer',}}onMouseOver={(e) => {+ if (submitted || isSelected) return;const el = e.currentTarget;if (isAccept) {el.style.backgroundColor = 'var(--ok-subtle, rgba(34,197,94,0.12))';@@ -173,6 +238,7 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {}}}onMouseOut={(e) => {+ if (submitted || isSelected) return;const el = e.currentTarget;el.style.backgroundColor = 'var(--bg-elevated)';el.style.borderColor = 'var(--border)';@@ -191,10 +257,42 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {);})}</div>- )}- </div>- );- })}+ </div>+ );+ })}+ </div>++ {/* 批量模式底部操作栏 */}+ {isBatch && !submitted && (+ <div+ className="px-4 py-3 flex items-center justify-between"+ style={{+ borderTop: '1px solid var(--border)',+ backgroundColor: 'var(--panel-strong)',+ }}+ >+ <span+ className="text-xs"+ style={{ color: 'var(--muted)' }}+ >+ {selections.size}/{pendingQuestion.questions.length}+ </span>+ <button+ onClick={handleSubmitBatch}+ disabled={!allAnswered}+ className="px-4 py-1.5 text-xs font-medium text-white rounded-lg transition-opacity"+ style={{+ background: allAnswered+ ? 'linear-gradient(135deg, var(--accent), var(--accent-2))'+ : 'var(--border)',+ opacity: allAnswered ? 1 : 0.5,+ cursor: allAnswered ? 'pointer' : 'not-allowed',+ }}+ >+ {t('chatUi.inlineQuestion.submit')}+ </button>+ </div>+ )}</div></div>);diff --git a/jiuwenclaw/web/src/i18n/locales/en.json b/jiuwenclaw/web/src/i18n/locales/en.jsonindex 73f29c4030..266daddde3 100644--- a/jiuwenclaw/web/src/i18n/locales/en.json+++ b/jiuwenclaw/web/src/i18n/locales/en.json@@ -606,7 +606,10 @@"accept": "Accept","reject": "Reject","allowOnce": "Allow once",- "alwaysAllow": "Always allow"+ "alwaysAllow": "Always allow",+ "acceptAll": "Accept all",+ "submit": "Submit",+ "entryCount": "{{count}} entries total"}},"network": {diff --git a/jiuwenclaw/web/src/i18n/locales/zh.json b/jiuwenclaw/web/src/i18n/locales/zh.jsonindex dc68865ba2..9e835f78a2 100644--- a/jiuwenclaw/web/src/i18n/locales/zh.json+++ b/jiuwenclaw/web/src/i18n/locales/zh.json@@ -606,7 +606,10 @@"accept": "接收","reject": "拒绝","allowOnce": "本次允许",- "alwaysAllow": "总是允许"+ "alwaysAllow": "总是允许",+ "acceptAll": "全部接收",+ "submit": "确认提交",+ "entryCount": "共 {{count}} 条演进经验"}},"network": {