Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
Fix/skill tool memory (#514)
JJF347c28910f68
diff --git a/.gitignore b/.gitignoreindex 07a04e77f..e4953a7ab 100644--- a/.gitignore+++ b/.gitignore@@ -162,3 +162,4 @@ test_scripts/examples/data/openviking/_version.pyspecs/+.trae/diff --git a/openviking/prompts/templates/compression/field_compress.yaml b/openviking/prompts/templates/compression/field_compress.yamlnew file mode 100644index 000000000..56c0b3f47--- /dev/null+++ b/openviking/prompts/templates/compression/field_compress.yaml@@ -0,0 +1,38 @@+metadata:+ id: "compression.field_compress"+ name: "Field Content Compression"+ description: "Compress field content while preserving key information"+ version: "1.0.0"+ language: "en"+ category: "compression"++variables:+ - name: "field_name"+ type: "string"+ description: "Field name (e.g., best_for, optimal_params)"+ required: true+ - name: "content"+ type: "string"+ description: "Original content to compress"+ required: true+ - name: "max_length"+ type: "integer"+ description: "Maximum length in characters"+ required: true++template: |+ Compress the following "{{ field_name }}" field content to fit within {{ max_length }} characters.++ Original content:+ {{ content }}++ Requirements:+ - Preserve the most important and unique information+ - Remove redundancy and duplicates+ - Use concise language+ - Maintain semantic structure (keep items separated by semicolons if applicable)+ - Output must be <= {{ max_length }} characters+ - Return compressed content only, no explanation++llm_config:+ temperature: 0.0diff --git a/openviking/prompts/templates/compression/memory_extraction.yaml b/openviking/prompts/templates/compression/memory_extraction.yamlindex da1ff2754..704726b89 100644--- a/openviking/prompts/templates/compression/memory_extraction.yaml+++ b/openviking/prompts/templates/compression/memory_extraction.yaml@@ -338,8 +338,12 @@ template: |"category": "tools","tool_name": "web_search","abstract": "web_search: Technical docs search optimal, needs specific query terms",- "overview": "## Tool Info\\n- **Name**: web_search\\n- **Type**: external_api\\n\\n## Statistics\\n- **Success Rate**: 92%\\n- **Avg Time**: 2.3s\\n\\n## Best Scenarios\\n- Technical documentation (95%)\\n- Tutorials (90%)\\n\\n## Optimal Parameters\\n- max_results: 5-20\\n- language: 'en'",- "content": "## Recommendations\\n\\n### Query Optimization\\n- Use specific multi-word queries\\n- Add qualifiers like 'tutorial', 'guide'\\n\\n## Good Cases\\n- 'Python asyncio tutorial' → 3 high-quality results\\n\\n## Bad Cases\\n- 'programming' → timeout (too broad)"+ "best_for": "Technical documentation, tutorials, API references",+ "optimal_params": "max_results: 5-20 (larger values may timeout); language: 'en' for better results; query: specific multi-word phrases with qualifiers",+ "common_failures": "Single-word queries return irrelevant results; max_results>50 causes timeout; non-English queries have lower quality",+ "recommendation": "Use specific multi-word queries like 'Python asyncio tutorial'; add qualifiers like 'guide', 'docs', 'example'",+ "overview": "## Tool Info\\n- **Name**: web_search\\n- **Type**: external_api\\n\\n## Statistics\\n- **Success Rate**: 92%\\n- **Avg Time**: 2.3s\\n\\n## Tool Memory Context\\n- Best for: Technical documentation, tutorials, API references\\n- Optimal params: max_results: 5-20; language: 'en'; query: specific multi-word phrases\\n- Common failures: Single-word queries; max_results>50 timeout\\n- Recommendation: Use specific multi-word queries with qualifiers",+ "content": "## Guidelines\\n\\n### Query Optimization\\n- Use specific multi-word queries (e.g., 'FastAPI dependency injection guide')\\n- Add qualifiers: 'tutorial', 'guide', 'docs', 'example'\\n- Prefer English for technical content\\n\\n### Good Cases\\n- Query: 'Python asyncio tutorial for beginners' → Found 3 high-quality beginner tutorials\\n- Query: 'FastAPI dependency injection docs' → Located official documentation accurately\\n\\n### Bad Cases\\n- Query: 'programming' → Timeout, results too broad\\n- Query: 'how to code' → Irrelevant results, no specific context"}```@@ -350,8 +354,13 @@ template: |"category": "skills","skill_name": "create_presentation","abstract": "create_presentation: Collect materials first for better efficiency",- "overview": "## Skill Info\\n- **Name**: create_presentation\\n- **Type**: workflow\\n\\n## Statistics\\n- **Success Rate**: 85%\\n- **Avg Time**: 120s\\n\\n## Recommended Flow\\n1. Collect materials\\n2. Generate outline\\n3. Create slides\\n4. Refine content\\n\\n## Key Dependencies\\n- Clear topic\\n- Target audience",- "content": "## Execution Strategy\\n\\n### Preparation\\n1. Confirm topic and audience\\n2. Collect reference materials\\n\\n## Good Cases\\n- Tech sharing: collected asyncio docs first → 90s, high quality\\n\\n## Bad Cases\\n- 'Make a PPT' without topic → multiple reworks needed"+ "best_for": "Slide creation tasks with clear topic and target audience",+ "recommended_flow": "1. Confirm topic and audience → 2. Collect reference materials → 3. Generate outline → 4. Create slides → 5. Refine content",+ "key_dependencies": "Clear topic (e.g., 'Q3 project update', 'Python tutorial'); Target audience (e.g., 'executives', 'beginners'); Reference materials (optional but recommended)",+ "common_failures": "Vague topic like 'make a PPT' leads to multiple rework cycles; Missing audience info causes style mismatch; No reference materials results in generic content",+ "recommendation": "Always confirm topic and audience before starting; Collect 2-3 reference materials for better quality",+ "overview": "## Skill Info\\n- **Name**: create_presentation\\n- **Type**: workflow\\n\\n## Statistics\\n- **Success Rate**: 85%\\n\\n## Skill Memory Context\\n- Best for: Slide creation with clear topic and audience\\n- Recommended flow: Confirm → Collect → Outline → Create → Refine\\n- Key dependencies: Clear topic; target audience; reference materials\\n- Common failures: Vague topic; missing audience; no references\\n- Recommendation: Confirm topic/audience first; collect reference materials",+ "content": "## Guidelines\\n\\n### Preparation\\n1. Confirm topic (e.g., 'Q3 Sales Report', 'Python Basics Tutorial')\\n2. Identify audience (e.g., executives, beginners, engineers)\\n3. Collect 2-3 reference materials or examples\\n\\n### Good Cases\\n- Topic: 'Python asyncio tutorial for beginners' + Audience: 'developers new to async' → Collected official docs first, generated 10 slides with code examples, completed in 90s\\n- Topic: 'Q3 project update' + Audience: 'stakeholders' → Gathered metrics first, created data-driven slides, positive feedback\\n\\n### Bad Cases\\n- Request: 'Make a PPT' (no topic specified) → Generated generic content, required 3 rounds of rework\\n- Request: 'Create presentation' (no audience) → Style mismatch, had to regenerate for different audience"}```@@ -365,8 +374,14 @@ template: |"abstract": "Merge types use `[Merge key]: [Description]`, independent types use specific description","overview": "Structured Markdown, use different heading templates by category","content": "Free Markdown, complete narrative",- "tool_name": "Only for tools category: the tool name from input [ToolCall] record (must copy exactly)",- "skill_name": "Only for skills category: inferred from full conversation context (descriptive name for the skill/workflow)"+ "tool_name": "[REQUIRED for tools] The tool name from [ToolCall] record - MUST copy exactly, no modification",+ "skill_name": "[REQUIRED for skills] The skill name - copy from [ToolCall] skill_name if present, otherwise infer from context",+ "best_for": "Optional: tools/skills only, what this tool/skill is best used for",+ "optimal_params": "Optional: tools only, GENERAL parameter ranges/best practices (NOT specific case values)",+ "recommended_flow": "Optional: skills only, recommended execution flow",+ "key_dependencies": "Optional: skills only, prerequisites/inputs needed",+ "common_failures": "Optional: tools/skills only, common failure patterns",+ "recommendation": "Optional: tools/skills only, short actionable recommendations"}]}@@ -376,8 +391,11 @@ template: |- Only extract truly valuable personalized information- If nothing worth recording, return {"memories": []}- For preferences, keep each memory as one independently updatable facet; do not combine unrelated facets in one memory- - For tools category: tool_name MUST be copied from [ToolCall] tool_name field exactly, do NOT modify it- - For skills category: skill_name should be inferred from the full conversation context (skill may involve internal tools not shown in [ToolCall]). Use a descriptive name that represents the skill/workflow.+ - **CRITICAL for tools category**: "tool_name" is REQUIRED. You MUST copy the exact tool_name value from the [ToolCall] record. Do NOT omit this field. Do NOT modify the name.+ - **CRITICAL for skills category**: "skill_name" is REQUIRED. If [ToolCall] contains skill_name, copy it exactly. If not present, infer a descriptive name from context. Do NOT omit this field.+ - **CRITICAL for tools/skills content field**: The "content" field MUST include structured sections with EXACT English headings: `## Guidelines` (with best practices), `### Good Cases` (successful usage examples), and `### Bad Cases` (failed usage examples). The section content can be in {{ output_language }}, but the headings MUST remain in English.+ - For tools/skills category: Fill "best_for/recommended_flow/key_dependencies/common_failures/recommendation" based on observed usage patterns. Infer reasonable values from the tool/skill nature when direct evidence is limited.+ - For tools category: "optimal_params" should describe GENERAL best practices (e.g., "max_results=5-20", "timeout>30s for large files"), NOT specific case values (e.g., "command: 'echo hello'", "file: '/path/to/specific/file'").llm_config:temperature: 0.0diff --git a/openviking/session/compressor.py b/openviking/session/compressor.pyindex 927d54c64..3f7eb432d 100644--- a/openviking/session/compressor.py+++ b/openviking/session/compressor.py@@ -156,6 +156,10 @@ class SessionCompressor:viking_fs = get_viking_fs()tool_parts = self._extract_tool_parts(messages)+ from .tool_skill_utils import collect_skill_stats, collect_tool_stats++ tool_stats_map = collect_tool_stats(tool_parts)+ skill_stats_map = collect_skill_stats(tool_parts)for candidate in candidates:# Profile: skip dedup, always merge@@ -176,6 +180,31 @@ class SessionCompressor:candidate, tool_parts)candidate.tool_status = tool_status+ if tool_name:+ candidate.tool_name = tool_name+ if skill_name:+ candidate.skill_name = skill_name++ if tool_name and candidate.call_time == 0:+ tool_stats = tool_stats_map.get(tool_name, {})+ candidate.call_time = tool_stats.get("call_count", candidate.call_time)+ candidate.success_time = tool_stats.get(+ "success_time", candidate.success_time+ )+ candidate.duration_ms = tool_stats.get("duration_ms", candidate.duration_ms)+ candidate.prompt_tokens = tool_stats.get(+ "prompt_tokens", candidate.prompt_tokens+ )+ candidate.completion_tokens = tool_stats.get(+ "completion_tokens", candidate.completion_tokens+ )++ if skill_name and candidate.call_time == 0:+ skill_stats = skill_stats_map.get(skill_name, {})+ candidate.call_time = skill_stats.get("call_count", candidate.call_time)+ candidate.success_time = skill_stats.get(+ "success_time", candidate.success_time+ )if skill_name:memory = await self.extractor._merge_skill_memory(skill_name, candidate, ctx=ctx@@ -292,43 +321,22 @@ class SessionCompressor:Returns:(tool_name, skill_name, tool_status) tuple"""- candidate_tool = candidate.tool_name- candidate_skill = candidate.skill_name-- calibrated_tool = ""- calibrated_skill = ""- tool_status = "completed"-- for part in tool_parts:- if part.skill_uri:- part_skill_name = self._extract_skill_name_from_uri(part.skill_uri)- if candidate_skill:- if self._is_similar_name(candidate_skill, part_skill_name):- calibrated_skill = part_skill_name- tool_status = part.tool_status or "completed"- else:- calibrated_skill = candidate_skill- else:- calibrated_skill = part_skill_name+ from .tool_skill_utils import calibrate_skill_name, calibrate_tool_name++ if candidate.category == MemoryCategory.TOOLS:+ candidate_tool = (candidate.tool_name or "").strip()+ if not candidate_tool:+ return ("", "", "completed")+ calibrated_name, status = calibrate_tool_name(candidate_tool, tool_parts)+ return (calibrated_name, "", status)++ if candidate.category == MemoryCategory.SKILLS:+ candidate_skill = (candidate.skill_name or "").strip()+ if not candidate_skill:+ return ("", "", "completed")+ calibrated_name, status = calibrate_skill_name(candidate_skill, tool_parts)+ return ("", calibrated_name, status)- elif part.tool_name:- if candidate_tool:- if self._is_similar_name(candidate_tool, part.tool_name):- calibrated_tool = part.tool_name- tool_status = part.tool_status or "completed"- else:- calibrated_tool = candidate_tool- else:- calibrated_tool = part.tool_name-- if calibrated_skill:- return ("", calibrated_skill, tool_status)- if calibrated_tool:- return (calibrated_tool, "", tool_status)- if candidate_skill:- return ("", candidate_skill, "completed")- if candidate_tool:- return (candidate_tool, "", "completed")return ("", "", "completed")def _is_similar_name(self, name1: str, name2: str) -> bool:@@ -353,13 +361,6 @@ class SessionCompressor:ratio = SequenceMatcher(None, n1, n2).ratio()return ratio >= 0.7- def _extract_skill_name_from_uri(self, skill_uri: str) -> str:- """从 skill_uri 提取 skill_name-- 例如: viking://agent/skills/create_presentation -> create_presentation- """- return skill_uri.rstrip("/").split("/")[-1]-def _extract_used_uris(self, messages: List[Message]) -> Dict[str, List[str]]:"""Extract URIs used in messages."""uris = {"memories": set(), "resources": set(), "skills": set()}diff --git a/openviking/session/memory_extractor.py b/openviking/session/memory_extractor.pyindex 4d411b6ca..cf9ba87c8 100644--- a/openviking/session/memory_extractor.py+++ b/openviking/session/memory_extractor.py@@ -18,12 +18,23 @@ from openviking.core.context import Context, ContextType, Vectorizefrom openviking.prompts import render_promptfrom openviking.server.identity import RequestContextfrom openviking.storage.viking_fs import get_viking_fs+from openviking_cli.exceptions import NotFoundErrorfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_loggerfrom openviking_cli.utils.config import get_openviking_configlogger = get_logger(__name__)+FIELD_MAX_LENGTH = 1000+FIELD_MAX_LENGTHS = {+ "best_for": 500,+ "optimal_params": 800,+ "common_failures": 1000,+ "recommendation": 500,+ "recommended_flow": 800,+ "key_dependencies": 500,+}+class MemoryCategory(str, Enum):"""Memory category enumeration."""@@ -68,6 +79,12 @@ class ToolSkillCandidateMemory(CandidateMemory):completion_tokens: int = 0 # 输出 Tokencall_time: int = 0 # 调用次数success_time: int = 0 # 成功调用次数+ best_for: str = ""+ optimal_params: str = ""+ recommended_flow: str = ""+ key_dependencies: str = ""+ common_failures: str = ""+ recommendation: str = ""@dataclass@@ -112,6 +129,8 @@ class MemoryExtractor:def __init__(self):"""Initialize memory extractor."""+ self._tool_desc_cache: dict[str, str] = {}+ self._tool_desc_cache_ready: bool = False@staticmethoddef _get_owner_space(category: MemoryCategory, ctx: RequestContext) -> str:@@ -195,37 +214,6 @@ class MemoryExtractor:return "\n".join(lines) if lines else ""- def _collect_tool_stats_from_messages(self, messages: list) -> dict:- """从消息中收集工具统计数据"""- from openviking.message.part import ToolPart-- stats_map = {}- for msg in messages:- parts = getattr(msg, "parts", [])- for part in parts:- if isinstance(part, ToolPart):- name = part.tool_name- if not name:- continue- if name not in stats_map:- stats_map[name] = {- "duration_ms": 0,- "prompt_tokens": 0,- "completion_tokens": 0,- "success_time": 0,- "call_count": 0,- }- stats_map[name]["call_count"] += 1- if part.duration_ms is not None:- stats_map[name]["duration_ms"] += part.duration_ms- if part.prompt_tokens is not None:- stats_map[name]["prompt_tokens"] += part.prompt_tokens- if part.completion_tokens is not None:- stats_map[name]["completion_tokens"] += part.completion_tokens- if part.tool_status == "completed":- stats_map[name]["success_time"] += 1- return stats_map-async def extract(self,context: dict,@@ -240,10 +228,23 @@ class MemoryExtractor:return []messages = context["messages"]+ from openviking.message.part import ToolPart++ from .tool_skill_utils import (+ calibrate_skill_name,+ calibrate_tool_name,+ collect_skill_stats,+ collect_tool_stats,+ )- tool_stats_map = self._collect_tool_stats_from_messages(messages)+ tool_parts = []+ for msg in messages:+ for part in getattr(msg, "parts", []):+ if isinstance(part, ToolPart):+ tool_parts.append(part)- # logger.warning(f"tool_stats_map={tool_stats_map}")+ tool_stats_map = collect_tool_stats(tool_parts)+ skill_stats_map = collect_skill_stats(tool_parts)formatted_lines = []for m in messages:@@ -300,9 +301,31 @@ class MemoryExtractor:# 只在 tools/skills 时使用 ToolSkillCandidateMemoryif category in (MemoryCategory.TOOLS, MemoryCategory.SKILLS):- tool_name = mem.get("tool_name", "")- skill_name = mem.get("skill_name", "")- stats = tool_stats_map.get(tool_name or skill_name, {})+ llm_tool_name = mem.get("tool_name", "") or ""+ llm_skill_name = mem.get("skill_name", "") or ""++ tool_name = ""+ skill_name = ""+ stats = {}++ if category == MemoryCategory.TOOLS:+ canonical_tool_name, _ = calibrate_tool_name(llm_tool_name, tool_parts)+ if not canonical_tool_name:+ continue+ tool_name = canonical_tool_name+ stats = tool_stats_map.get(tool_name, {})++ if category == MemoryCategory.SKILLS:+ canonical_skill_name, _ = calibrate_skill_name(llm_skill_name, tool_parts)+ if not canonical_skill_name:+ continue+ skill_name = canonical_skill_name+ stats = skill_stats_map.get(skill_name, {})++ call_time = stats.get("call_count", 0)+ if call_time == 0:+ continue+candidates.append(ToolSkillCandidateMemory(category=category,@@ -314,11 +337,29 @@ class MemoryExtractor:language=output_language,tool_name=tool_name,skill_name=skill_name,- call_time=stats.get("call_count", 0),+ call_time=call_time,success_time=stats.get("success_time", 0),- duration_ms=stats.get("duration_ms", 0),- prompt_tokens=stats.get("prompt_tokens", 0),- completion_tokens=stats.get("completion_tokens", 0),+ duration_ms=(+ stats.get("duration_ms", 0)+ if category == MemoryCategory.TOOLS+ else 0+ ),+ prompt_tokens=(+ stats.get("prompt_tokens", 0)+ if category == MemoryCategory.TOOLS+ else 0+ ),+ completion_tokens=(+ stats.get("completion_tokens", 0)+ if category == MemoryCategory.TOOLS+ else 0+ ),+ best_for=str(mem.get("best_for", "") or "").strip(),+ optimal_params=str(mem.get("optimal_params", "") or "").strip(),+ recommended_flow=str(mem.get("recommended_flow", "") or "").strip(),+ key_dependencies=str(mem.get("key_dependencies", "") or "").strip(),+ common_failures=str(mem.get("common_failures", "") or "").strip(),+ recommendation=str(mem.get("recommendation", "") or "").strip(),))else:@@ -547,40 +588,111 @@ class MemoryExtractor:existing = ""try:existing = await viking_fs.read_file(uri, ctx=ctx) or ""- except Exception:- pass+ except NotFoundError:+ existing = ""+ except Exception as e:+ logger.warning(+ "Failed to read existing tool memory %s: %s; skipping write to avoid data loss",+ uri,+ e,+ )+ return None- if isinstance(candidate, ToolSkillCandidateMemory):- new_stats = {- "total_calls": candidate.call_time,- "success_count": candidate.success_time,- "fail_count": candidate.call_time - candidate.success_time,- "total_time_ms": candidate.duration_ms or 0,- "total_tokens": (candidate.prompt_tokens or 0) + (candidate.completion_tokens or 0),- }- else:- new_stats = self._parse_tool_statistics(candidate.content)- if new_stats["total_calls"] == 0:- new_stats["total_calls"] = 1- tool_status = getattr(candidate, "tool_status", "completed")- if tool_status == "error":- new_stats["fail_count"] = 1- new_stats["success_count"] = 0- else:- new_stats["success_count"] = 1- new_stats["fail_count"] = 0+ if not isinstance(candidate, ToolSkillCandidateMemory):+ logger.warning("Tool memory merge requires ToolSkillCandidateMemory, skipping")+ return None++ if candidate.call_time <= 0:+ logger.warning("Tool memory merge skipped due to call_time=0: %s", tool_name)+ return None++ new_stats = {+ "total_calls": candidate.call_time,+ "success_count": candidate.success_time,+ "fail_count": candidate.call_time - candidate.success_time,+ "total_time_ms": candidate.duration_ms or 0,+ "total_tokens": (candidate.prompt_tokens or 0) + (candidate.completion_tokens or 0),+ }+ new_guidelines = (candidate.content or "").strip()+ abstract_override: Optional[str] = None+ new_fields = {+ "best_for": (candidate.best_for or "").strip(),+ "optimal_params": (candidate.optimal_params or "").strip(),+ "common_failures": (candidate.common_failures or "").strip(),+ "recommendation": (candidate.recommendation or "").strip(),+ }+ fallback_fields = self._extract_tool_memory_context_fields_from_text(+ "\n".join([str(candidate.overview or "").strip(), str(candidate.content or "").strip()])+ )+ for k, v in fallback_fields.items():+ if not new_fields.get(k) and v:+ new_fields[k] = v.strip()if not existing.strip():merged_stats = self._compute_statistics_derived(new_stats)- merged_content = self._generate_tool_memory_content(tool_name, merged_stats, candidate)+ merged_content = self._generate_tool_memory_content(+ tool_name, merged_stats, new_guidelines, fields=new_fields+ )await viking_fs.write_file(uri=uri, content=merged_content, ctx=ctx)return self._create_tool_context(uri, candidate, ctx)existing_stats = self._parse_tool_statistics(existing)merged_stats = self._merge_tool_statistics(existing_stats, new_stats)- merged_content = self._generate_tool_memory_content(tool_name, merged_stats, candidate)+ if merged_stats.get("total_calls", 0) < existing_stats.get("total_calls", 0):+ logger.warning(+ "Tool memory merge violates monotonic total_calls: tool=%s existing=%s merged=%s; skipping write",+ tool_name,+ existing_stats.get("total_calls", 0),+ merged_stats.get("total_calls", 0),+ )+ return None+ existing_guidelines = self._extract_tool_guidelines(existing)+ if existing_guidelines is None:+ existing_guidelines = ""+ existing_fields = self._extract_tool_memory_context_fields_from_text(existing)+ merged_fields = {+ "best_for": await self._merge_kv_field(+ existing_fields.get("best_for", ""), new_fields.get("best_for", ""), "best_for"+ ),+ "optimal_params": await self._merge_kv_field(+ existing_fields.get("optimal_params", ""),+ new_fields.get("optimal_params", ""),+ "optimal_params",+ ),+ "common_failures": await self._merge_kv_field(+ existing_fields.get("common_failures", ""),+ new_fields.get("common_failures", ""),+ "common_failures",+ ),+ "recommendation": await self._merge_kv_field(+ existing_fields.get("recommendation", ""),+ new_fields.get("recommendation", ""),+ "recommendation",+ ),+ }+ if new_guidelines:+ payload = await self._merge_memory_bundle(+ existing_abstract="",+ existing_overview="",+ existing_content=existing_guidelines,+ new_abstract=candidate.abstract,+ new_overview=candidate.overview,+ new_content=new_guidelines,+ category="tools",+ output_language=candidate.language,+ )+ if payload and payload.content:+ merged_guidelines = payload.content.strip()+ if payload.abstract:+ abstract_override = payload.abstract.strip() or None+ else:+ merged_guidelines = (existing_guidelines + "\n\n" + new_guidelines).strip()++ merged_content = self._generate_tool_memory_content(+ tool_name, merged_stats, merged_guidelines, fields=merged_fields+ )await viking_fs.write_file(uri=uri, content=merged_content, ctx=ctx)- return self._create_tool_context(uri, candidate, ctx)+ return self._create_tool_context(uri, candidate, ctx, abstract_override=abstract_override)async def _enqueue_semantic_for_parent(self, file_uri: str, ctx: "RequestContext") -> None:"""Enqueue semantic generation for parent directory."""@@ -626,27 +738,73 @@ class MemoryExtractor:"total_tokens": 0,}- match = re.search(r"总调用次数:\s*(\d+)", content)+ match = re.search(r"总调用次数(?:\*+)?\s*[::]\s*(\d+)", content)if match:stats["total_calls"] = int(match.group(1))+ else:+ match = re.search(r"(?im)^Based on\s+(\d+)\s+historical\s+calls\s*:", content)+ if match:+ stats["total_calls"] = int(match.group(1))- match = re.search(r"成功率:\s*([\d.]+)%", content)+ match = re.search(+ r"成功率(?:\*+)?\s*[::]\s*([\d.]+)%\s*[((]\s*(\d+)\s*成功\s*[,,]\s*(\d+)\s*失败",+ content,+ )if match:- success_rate = float(match.group(1)) / 100- stats["success_count"] = int(stats["total_calls"] * success_rate)- stats["fail_count"] = stats["total_calls"] - stats["success_count"]+ stats["success_count"] = int(match.group(2))+ stats["fail_count"] = int(match.group(3))+ if stats["total_calls"] <= 0:+ stats["total_calls"] = stats["success_count"] + stats["fail_count"]+ else:+ match = re.search(r"成功率(?:\*+)?\s*[::]\s*([\d.]+)%", content)+ if match and stats["total_calls"] > 0:+ success_rate = float(match.group(1)) / 100+ stats["success_count"] = int(stats["total_calls"] * success_rate)+ stats["fail_count"] = stats["total_calls"] - stats["success_count"]+ else:+ match = re.search(+ r"(?im)^-\s*Success rate:\s*([\d.]+)%\s*\((\d+)\s+successful,\s*(\d+)\s+failed\)",+ content,+ )+ if match:+ stats["success_count"] = int(match.group(2))+ stats["fail_count"] = int(match.group(3))+ if stats["total_calls"] <= 0:+ stats["total_calls"] = stats["success_count"] + stats["fail_count"]+ else:+ match = re.search(r"(?im)^-\s*Success rate:\s*([\d.]+)%", content)+ if match and stats["total_calls"] > 0:+ success_rate = float(match.group(1)) / 100+ stats["success_count"] = int(stats["total_calls"] * success_rate)+ stats["fail_count"] = stats["total_calls"] - stats["success_count"]- match = re.search(r"平均耗时:\s*([\d.]+)ms", content)+ match = re.search(r"平均耗时(?:\*+)?\s*[::]\s*([\d.]+)ms", content)if match and stats["total_calls"] > 0:stats["total_time_ms"] = float(match.group(1)) * stats["total_calls"]else:- match = re.search(r"平均耗时:\s*([\d.]+)s", content)+ match = re.search(r"平均耗时(?:\*+)?\s*[::]\s*([\d.]+)s", content)+ if match and stats["total_calls"] > 0:+ stats["total_time_ms"] = float(match.group(1)) * 1000 * stats["total_calls"]+ if stats["total_time_ms"] == 0:+ match = re.search(r"(?im)^-\s*Avg time:\s*([\d.]+)s", content)if match and stats["total_calls"] > 0:stats["total_time_ms"] = float(match.group(1)) * 1000 * stats["total_calls"]+ else:+ match = re.search(r"(?im)^-\s*Avg time:\s*([\d.]+)ms", content)+ if match and stats["total_calls"] > 0:+ stats["total_time_ms"] = float(match.group(1)) * stats["total_calls"]- match = re.search(r"平均Token:\s*(\d+)", content)+ match = re.search(r"平均Token(?:\*+)?\s*[::]\s*(\d+)", content)if match and stats["total_calls"] > 0:stats["total_tokens"] = int(match.group(1)) * stats["total_calls"]+ else:+ match = re.search(r"(?im)^-\s*Avg time:.*?Avg tokens:\s*(\d+)", content)+ if match and stats["total_calls"] > 0:+ stats["total_tokens"] = int(match.group(1)) * stats["total_calls"]+ else:+ match = re.search(r"(?im)^-\s*Avg tokens:\s*(\d+)", content)+ if match and stats["total_calls"] > 0:+ stats["total_tokens"] = int(match.group(1)) * stats["total_calls"]return stats@@ -685,24 +843,271 @@ class MemoryExtractor:formatted = f"{value_ms:.{decimals_needed}f}"return f"{formatted}ms"- def _generate_tool_memory_content(- self, tool_name: str, stats: dict, candidate: CandidateMemory+ def _format_duration(self, value_ms: float) -> str:+ if value_ms is None:+ return "N/A"+ try:+ value_ms = float(value_ms)+ except Exception:+ return "N/A"+ if value_ms <= 0:+ return "0s"+ if value_ms >= 1000:+ return f"{value_ms / 1000:.1f}s"+ return f"{int(round(value_ms))}ms"++ def _ensure_tool_desc_cache(self) -> None:+ if self._tool_desc_cache_ready:+ return+ self._tool_desc_cache_ready = True+ try:+ from vikingbot.agent.tools.factory import register_default_tools+ from vikingbot.agent.tools.registry import ToolRegistry+ from vikingbot.config.loader import load_config++ registry = ToolRegistry()+ config = load_config()+ register_default_tools(+ registry=registry,+ config=config,+ include_message_tool=False,+ include_spawn_tool=False,+ include_cron_tool=False,+ include_image_tool=False,+ include_viking_tools=True,+ )+ cache: dict[str, str] = {}+ for name in registry.tool_names:+ tool = registry.get(name)+ desc = getattr(tool, "description", "") if tool else ""+ if desc:+ cache[name] = str(desc)+ self._tool_desc_cache = cache+ except Exception:+ self._tool_desc_cache = {}++ def _get_tool_static_description(self, tool_name: str) -> str:+ if not tool_name:+ return ""+ self._ensure_tool_desc_cache()+ return (self._tool_desc_cache.get(tool_name) or "").strip()++ def _extract_content_field(self, content: str, keys: list[str]) -> str:+ if not content:+ return ""+ for key in keys:+ m = re.search(rf"(?im)^[ \t>*-]*{re.escape(key)}\s*[::]\s*(.+?)\s*$", content)+ if m:+ return (m.group(1) or "").strip()+ return ""++ def _extract_content_section(self, content: str, headings: list[str]) -> str:+ if not content:+ return ""+ for h in headings:+ m = re.search(+ rf"(?im)^[ \t]*##[ \t]*{re.escape(h)}[ \t]*\n([\s\S]*?)(?=^[ \t]*##[ \t]|\Z)",+ content,+ )+ if m:+ return (m.group(1) or "").strip()+ return ""++ def _compact_block(self, text: str) -> str:+ if not text:+ return ""+ lines = []+ for line in str(text).splitlines():+ s = line.strip()+ if not s:+ continue+ s = re.sub(r"^[>*\-\s]+", "", s).strip()+ if s:+ lines.append(s)+ return "; ".join(lines).strip()++ async def _merge_kv_field(+ self, existing_value: str, new_value: str, field_name: str = "") -> str:- """生成合并后的 Tool Memory 内容"""- return f"""## 工具信息-- **名称**: {tool_name}+ a = (existing_value or "").strip()+ b = (new_value or "").strip()+ if not a:+ return b+ if not b:+ return a+ if a == b:+ return a+ parts = []+ for s in (a, b):+ for p in [x.strip() for x in re.split(r"[;\n;]+", s)]:+ if p and p not in parts:+ parts.append(p)+ merged = "; ".join(parts).strip()++ max_length = FIELD_MAX_LENGTHS.get(field_name, FIELD_MAX_LENGTH)+ if len(merged) <= max_length:+ return merged++ compressed = await self._compress_field_content(merged, field_name, max_length)+ if compressed:+ return compressed+ return self._smart_truncate(merged, max_length)++ async def _compress_field_content(+ self, content: str, field_name: str, max_length: int+ ) -> Optional[str]:+ vlm = get_openviking_config().vlm+ if not vlm or not vlm.is_available():+ return None-## 调用统计-- **总调用次数**: {stats["total_calls"]}-- **成功率**: {stats["success_rate"] * 100:.1f}%({stats["success_count"]} 成功,{stats["fail_count"]} 失败)-- **平均耗时**: {self._format_ms(stats["avg_time_ms"])}-- **平均Token**: {int(stats["avg_tokens"])}+ target_length = int(max_length * 0.8)+ prompt = render_prompt(+ "compression.field_compress",+ {+ "field_name": field_name,+ "content": content,+ "max_length": target_length,+ },+ )-{candidate.content}-"""+ try:+ response = await vlm.get_completion_async(prompt)+ compressed = response.strip()+ if len(compressed) <= max_length:+ logger.info(+ "Field compression succeeded: field=%s original=%d compressed=%d target=%d",+ field_name,+ len(content),+ len(compressed),+ target_length,+ )+ return compressed+ logger.warning(+ "Compressed content still exceeds max_length: field=%s len=%d max=%d, using fallback",+ field_name,+ len(compressed),+ max_length,+ )+ return None+ except Exception as e:+ logger.warning(f"Field compression failed for {field_name}: {e}")+ return None++ def _smart_truncate(self, text: str, max_length: int) -> str:+ if len(text) <= max_length:+ return text+ truncated = text[:max_length]+ last_sep = truncated.rfind(";")+ if last_sep > max_length * 0.7:+ return truncated[:last_sep]+ last_space = truncated.rfind(" ")+ if last_space > max_length * 0.7:+ return truncated[:last_space]+ return truncated++ def _extract_tool_memory_context_fields_from_text(self, text: str) -> dict:+ return {+ "best_for": self._extract_content_field(+ text, ["Best for", "Best scenarios", "最佳场景", "适用场景"]+ ),+ "optimal_params": self._extract_content_field(+ text, ["Optimal params", "Optimal parameters", "最优参数", "推荐参数"]+ ),+ "common_failures": self._extract_content_field(+ text, ["Common failures", "常见失败", "失败模式"]+ ),+ "recommendation": self._extract_content_field(+ text, ["Recommendation", "Recommendations", "推荐", "建议"]+ ),+ }++ def _extract_skill_memory_context_fields_from_text(self, text: str) -> dict:+ return {+ "best_for": self._extract_content_field(text, ["Best for", "最佳场景", "适用场景"]),+ "recommended_flow": self._extract_content_field(+ text, ["Recommended flow", "Recommended Flow", "推荐流程", "推荐步骤"]+ ),+ "key_dependencies": self._extract_content_field(+ text, ["Key dependencies", "Key Dependencies", "关键依赖", "前置条件"]+ ),+ "common_failures": self._extract_content_field(+ text, ["Common failures", "常见失败", "失败模式"]+ ),+ "recommendation": self._extract_content_field(+ text, ["Recommendation", "Recommendations", "推荐", "建议"]+ ),+ }++ def _generate_tool_memory_content(+ self, tool_name: str, stats: dict, guidelines: str, fields: Optional[dict] = None+ ) -> str:+ static_desc = self._get_tool_static_description(tool_name) or "N/A"+ fields = fields or {}+ best_for = (fields.get("best_for") or "").strip()+ optimal_params = (fields.get("optimal_params") or "").strip()+ common_failures = (fields.get("common_failures") or "").strip()+ recommendation = (fields.get("recommendation") or "").strip()++ if not best_for:+ best_for = self._extract_content_field(+ guidelines, ["Best for", "Best scenarios", "最佳场景", "适用场景"]+ ) or self._compact_block(+ self._extract_content_section(+ guidelines, ["Best Scenarios", "Best for", "最佳场景"]+ )+ )+ if not optimal_params:+ optimal_params = self._extract_content_field(+ guidelines, ["Optimal params", "Optimal parameters", "最优参数", "推荐参数"]+ ) or self._compact_block(+ self._extract_content_section(+ guidelines, ["Optimal Parameters", "Optimal params", "最优参数"]+ )+ )+ if not common_failures:+ common_failures = self._extract_content_field(+ guidelines, ["Common failures", "常见失败", "失败模式"]+ ) or self._compact_block(+ self._extract_content_section(guidelines, ["Common Failures", "常见失败"])+ )+ if not recommendation:+ recommendation = self._extract_content_field(+ guidelines, ["Recommendation", "Recommendations", "推荐", "建议"]+ ) or self._compact_block(+ self._extract_content_section(+ guidelines, ["Recommendations", "Recommendation", "推荐"]+ )+ )++ best_for = best_for or ""+ optimal_params = optimal_params or ""+ common_failures = common_failures or ""+ recommendation = recommendation or ""++ return (+ "Tool: "+ + str(tool_name)+ + "\n\n"+ + "Static Description:\n"+ + f'"{static_desc}"\n\n'+ + "Tool Memory Context:\n"+ + f"Based on {stats['total_calls']} historical calls:\n"+ + f"- Success rate: {stats['success_rate'] * 100:.1f}% ({stats['success_count']} successful, {stats['fail_count']} failed)\n"+ + f"- Avg time: {self._format_duration(stats.get('avg_time_ms', 0))}, Avg tokens: {int(stats.get('avg_tokens', 0))}\n"+ + f"- Best for: {best_for}\n"+ + f"- Optimal params: {optimal_params}\n"+ + f"- Common failures: {common_failures}\n"+ + f"- Recommendation: {recommendation}\n\n"+ + (guidelines or "").strip()+ + "\n"+ )def _create_tool_context(- self, uri: str, candidate: CandidateMemory, ctx: "RequestContext"+ self,+ uri: str,+ candidate: CandidateMemory,+ ctx: "RequestContext",+ abstract_override: Optional[str] = None,) -> Context:"""创建 Tool Memory 的 Context 对象"""agent_space = ctx.user.agent_space_name()@@ -710,7 +1115,7 @@ class MemoryExtractor:uri=uri,parent_uri=f"viking://agent/{agent_space}/memories/tools",is_leaf=True,- abstract=candidate.abstract,+ abstract=abstract_override or candidate.abstract,context_type=ContextType.MEMORY.value,category=candidate.category.value,session_id=candidate.source_session,@@ -719,6 +1124,26 @@ class MemoryExtractor:owner_space=agent_space,)+ def _extract_tool_guidelines(self, content: str) -> str:+ headings = r"(使用指南|Guidelines|Guildlines)"+ m = re.search(rf"^##\s*{headings}\s*\n", content, flags=re.MULTILINE)+ if m:+ return content[m.end() :].strip()++ m = re.search(r"(?im)^Guidelines:\s*\n", content)+ if m:+ return content[m.end() :].strip()++ m = re.search(+ r"^##\s*工具信息[\s\S]*?^##\s*调用统计[\s\S]*?^\-\s*\*\*平均Token\*\*:.*$\n\n",+ content,+ flags=re.MULTILINE,+ )+ if m:+ return content[m.end() :].strip()++ return content.strip()+async def _merge_skill_memory(self, skill_name: str, candidate: CandidateMemory, ctx: "RequestContext") -> Optional[Context]:@@ -738,10 +1163,27 @@ class MemoryExtractor:existing = ""try:existing = await viking_fs.read_file(uri, ctx=ctx) or ""- except Exception:- pass+ except NotFoundError:+ existing = ""+ except Exception as e:+ logger.warning(+ "Failed to read existing skill memory %s: %s; skipping write to avoid data loss",+ uri,+ e,+ )+ return None- new_stats = self._parse_skill_statistics(candidate.content)+ new_stats = {+ "total_executions": 0,+ "success_count": 0,+ "fail_count": 0,+ }+ if isinstance(candidate, ToolSkillCandidateMemory) and candidate.call_time > 0:+ new_stats["total_executions"] = candidate.call_time+ new_stats["success_count"] = candidate.success_time+ new_stats["fail_count"] = max(0, candidate.call_time - candidate.success_time)+ else:+ new_stats = self._parse_skill_statistics(candidate.content)if new_stats["total_executions"] == 0:new_stats["total_executions"] = 1if "error" in candidate.content.lower() or "fail" in candidate.content.lower():@@ -750,20 +1192,99 @@ class MemoryExtractor:else:new_stats["success_count"] = 1new_stats["fail_count"] = 0+ new_guidelines = (candidate.content or "").strip()+ abstract_override: Optional[str] = None+ new_fields = {+ "best_for": "",+ "recommended_flow": "",+ "key_dependencies": "",+ "common_failures": "",+ "recommendation": "",+ }+ if isinstance(candidate, ToolSkillCandidateMemory):+ new_fields = {+ "best_for": (candidate.best_for or "").strip(),+ "recommended_flow": (candidate.recommended_flow or "").strip(),+ "key_dependencies": (candidate.key_dependencies or "").strip(),+ "common_failures": (candidate.common_failures or "").strip(),+ "recommendation": (candidate.recommendation or "").strip(),+ }+ fallback_fields = self._extract_skill_memory_context_fields_from_text(+ "\n".join([str(candidate.overview or "").strip(), str(candidate.content or "").strip()])+ )+ for k, v in fallback_fields.items():+ if not new_fields.get(k) and v:+ new_fields[k] = v.strip()if not existing.strip():merged_stats = self._compute_skill_statistics_derived(new_stats)merged_content = self._generate_skill_memory_content(- skill_name, merged_stats, candidate+ skill_name, merged_stats, new_guidelines, fields=new_fields)await viking_fs.write_file(uri=uri, content=merged_content, ctx=ctx)return self._create_skill_context(uri, candidate, ctx)existing_stats = self._parse_skill_statistics(existing)merged_stats = self._merge_skill_statistics(existing_stats, new_stats)- merged_content = self._generate_skill_memory_content(skill_name, merged_stats, candidate)+ if merged_stats.get("total_executions", 0) < existing_stats.get("total_executions", 0):+ logger.warning(+ "Skill memory merge violates monotonic total_executions: skill=%s existing=%s merged=%s; skipping write",+ skill_name,+ existing_stats.get("total_executions", 0),+ merged_stats.get("total_executions", 0),+ )+ return None+ existing_guidelines = self._extract_skill_guidelines(existing) or existing.strip()+ existing_fields = self._extract_skill_memory_context_fields_from_text(existing)+ merged_fields = {+ "best_for": await self._merge_kv_field(+ existing_fields.get("best_for", ""), new_fields.get("best_for", ""), "best_for"+ ),+ "recommended_flow": await self._merge_kv_field(+ existing_fields.get("recommended_flow", ""),+ new_fields.get("recommended_flow", ""),+ "recommended_flow",+ ),+ "key_dependencies": await self._merge_kv_field(+ existing_fields.get("key_dependencies", ""),+ new_fields.get("key_dependencies", ""),+ "key_dependencies",+ ),+ "common_failures": await self._merge_kv_field(+ existing_fields.get("common_failures", ""),+ new_fields.get("common_failures", ""),+ "common_failures",+ ),+ "recommendation": await self._merge_kv_field(+ existing_fields.get("recommendation", ""),+ new_fields.get("recommendation", ""),+ "recommendation",+ ),+ }+ merged_guidelines = existing_guidelines+ if new_guidelines:+ payload = await self._merge_memory_bundle(+ existing_abstract="",+ existing_overview="",+ existing_content=existing_guidelines,+ new_abstract=candidate.abstract,+ new_overview=candidate.overview,+ new_content=new_guidelines,+ category="skills",+ output_language=candidate.language,+ )+ if payload and payload.content:+ merged_guidelines = payload.content.strip()+ if payload.abstract:+ abstract_override = payload.abstract.strip() or None+ else:+ merged_guidelines = (existing_guidelines + "\n\n" + new_guidelines).strip()++ merged_content = self._generate_skill_memory_content(+ skill_name, merged_stats, merged_guidelines, fields=merged_fields+ )await viking_fs.write_file(uri=uri, content=merged_content, ctx=ctx)- return self._create_skill_context(uri, candidate, ctx)+ return self._create_skill_context(uri, candidate, ctx, abstract_override=abstract_override)def _compute_skill_statistics_derived(self, stats: dict) -> dict:"""计算 Skill 派生统计数据(成功率)"""@@ -781,15 +1302,48 @@ class MemoryExtractor:"fail_count": 0,}- match = re.search(r"总执行次数:\s*(\d+)", content)+ match = re.search(r"总执行次数(?:\*+)?\s*[::]\s*(\d+)", content)if match:stats["total_executions"] = int(match.group(1))+ else:+ match = re.search(+ r"(?im)^Based on\s+(\d+)\s+historical\s+executions\s*:",+ content,+ )+ if match:+ stats["total_executions"] = int(match.group(1))- match = re.search(r"成功率:\s*([\d.]+)%", content)+ match = re.search(+ r"成功率(?:\*+)?\s*[::]\s*([\d.]+)%\s*[((]\s*(\d+)\s*成功\s*[,,]\s*(\d+)\s*失败",+ content,+ )if match:- success_rate = float(match.group(1)) / 100- stats["success_count"] = int(stats["total_executions"] * success_rate)- stats["fail_count"] = stats["total_executions"] - stats["success_count"]+ stats["success_count"] = int(match.group(2))+ stats["fail_count"] = int(match.group(3))+ if stats["total_executions"] <= 0:+ stats["total_executions"] = stats["success_count"] + stats["fail_count"]+ else:+ match = re.search(r"成功率(?:\*+)?\s*[::]\s*([\d.]+)%", content)+ if match and stats["total_executions"] > 0:+ success_rate = float(match.group(1)) / 100+ stats["success_count"] = int(stats["total_executions"] * success_rate)+ stats["fail_count"] = stats["total_executions"] - stats["success_count"]+ else:+ match = re.search(+ r"(?im)^-\s*Success rate:\s*([\d.]+)%\s*\((\d+)\s+successful,\s*(\d+)\s+failed\)",+ content,+ )+ if match:+ stats["success_count"] = int(match.group(2))+ stats["fail_count"] = int(match.group(3))+ if stats["total_executions"] <= 0:+ stats["total_executions"] = stats["success_count"] + stats["fail_count"]+ else:+ match = re.search(r"(?im)^-\s*Success rate:\s*([\d.]+)%", content)+ if match and stats["total_executions"] > 0:+ success_rate = float(match.group(1)) / 100+ stats["success_count"] = int(stats["total_executions"] * success_rate)+ stats["fail_count"] = stats["total_executions"] - stats["success_count"]return stats@@ -806,22 +1360,82 @@ class MemoryExtractor:return mergeddef _generate_skill_memory_content(- self, skill_name: str, stats: dict, candidate: CandidateMemory+ self, skill_name: str, stats: dict, guidelines: str, fields: Optional[dict] = None) -> str:- """生成合并后的 Skill Memory 内容"""- return f"""## 技能信息-- **名称**: {skill_name}--## 执行统计-- **总执行次数**: {stats["total_executions"]}-- **成功率**: {stats["success_rate"] * 100:.1f}%({stats["success_count"]} 成功,{stats["fail_count"]} 失败)+ fields = fields or {}+ best_for = (fields.get("best_for") or "").strip()+ recommended_flow = (fields.get("recommended_flow") or "").strip()+ key_dependencies = (fields.get("key_dependencies") or "").strip()+ common_failures = (fields.get("common_failures") or "").strip()+ recommendation = (fields.get("recommendation") or "").strip()++ if not best_for:+ best_for = self._extract_content_field(+ guidelines, ["Best for", "最佳场景", "适用场景"]+ ) or self._compact_block(+ self._extract_content_section(+ guidelines, ["Best for", "Best Scenarios", "最佳场景"]+ )+ )+ if not recommended_flow:+ recommended_flow = self._extract_content_field(+ guidelines, ["Recommended flow", "推荐流程", "推荐步骤"]+ ) or self._compact_block(+ self._extract_content_section(+ guidelines, ["Recommended Flow", "推荐流程", "推荐步骤"]+ )+ )+ if not key_dependencies:+ key_dependencies = self._extract_content_field(+ guidelines, ["Key dependencies", "关键依赖", "前置条件"]+ ) or self._compact_block(+ self._extract_content_section(+ guidelines, ["Key Dependencies", "关键依赖", "前置条件"]+ )+ )+ if not common_failures:+ common_failures = self._extract_content_field(+ guidelines, ["Common failures", "常见失败", "失败模式"]+ ) or self._compact_block(+ self._extract_content_section(guidelines, ["Common Failures", "常见失败"])+ )+ if not recommendation:+ recommendation = self._extract_content_field(+ guidelines, ["Recommendation", "Recommendations", "推荐", "建议"]+ ) or self._compact_block(+ self._extract_content_section(+ guidelines, ["Recommendations", "Recommendation", "推荐"]+ )+ )-## Guildlines-{candidate.content}-"""+ best_for = best_for or ""+ recommended_flow = recommended_flow or ""+ key_dependencies = key_dependencies or ""+ common_failures = common_failures or ""+ recommendation = recommendation or ""++ return (+ "Skill: "+ + str(skill_name)+ + "\n\n"+ + "Skill Memory Context:\n"+ + f"Based on {stats['total_executions']} historical executions:\n"+ + f"- Success rate: {stats['success_rate'] * 100:.1f}% ({stats['success_count']} successful, {stats['fail_count']} failed)\n"+ + f"- Best for: {best_for}\n"+ + f"- Recommended flow: {recommended_flow}\n"+ + f"- Key dependencies: {key_dependencies}\n"+ + f"- Common failures: {common_failures}\n"+ + f"- Recommendation: {recommendation}\n\n"+ + (guidelines or "").strip()+ + "\n"+ )def _create_skill_context(- self, uri: str, candidate: CandidateMemory, ctx: "RequestContext"+ self,+ uri: str,+ candidate: CandidateMemory,+ ctx: "RequestContext",+ abstract_override: Optional[str] = None,) -> Context:"""创建 Skill Memory 的 Context 对象"""agent_space = ctx.user.agent_space_name()@@ -829,7 +1443,7 @@ class MemoryExtractor:uri=uri,parent_uri=f"viking://agent/{agent_space}/memories/skills",is_leaf=True,- abstract=candidate.abstract,+ abstract=abstract_override or candidate.abstract,context_type=ContextType.MEMORY.value,category=candidate.category.value,session_id=candidate.source_session,@@ -837,3 +1451,23 @@ class MemoryExtractor:account_id=ctx.account_id,owner_space=agent_space,)++ def _extract_skill_guidelines(self, content: str) -> str:+ headings = r"(使用指南|Guidelines|Guildlines)"+ m = re.search(rf"^##\s*{headings}\s*\n", content, flags=re.MULTILINE)+ if m:+ return content[m.end() :].strip()++ m = re.search(r"(?im)^Guidelines:\s*\n", content)+ if m:+ return content[m.end() :].strip()++ m = re.search(+ r"^##\s*技能信息[\s\S]*?^##\s*执行统计[\s\S]*?^\-\s*\*\*成功率\*\*:.*$\n\n",+ content,+ flags=re.MULTILINE,+ )+ if m:+ return content[m.end() :].strip()++ return content.strip()diff --git a/openviking/session/tool_skill_utils.py b/openviking/session/tool_skill_utils.pynew file mode 100644index 000000000..c007e06e8--- /dev/null+++ b/openviking/session/tool_skill_utils.py@@ -0,0 +1,127 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0++from __future__ import annotations++from difflib import SequenceMatcher+from typing import Any, Callable, Dict, Iterable, Tuple, Union++Number = Union[int, float]+++def normalize_name(name: str) -> str:+ return (name or "").lower().strip().replace("_", "").replace("-", "").replace(" ", "")+++def extract_skill_name_from_uri(uri: str) -> str:+ uri = (uri or "").strip()+ if not uri:+ return ""+ return uri.rstrip("/").split("/")[-1]+++def _calibrate_name(+ candidate_name: str,+ parts: Iterable[Any],+ name_getter: Callable[[Any], str],+ threshold: float,+) -> Tuple[str, str]:+ candidate_name = (candidate_name or "").strip()+ if not candidate_name:+ return ("", "completed")++ candidate_norm = normalize_name(candidate_name)+ best_ratio = -1.0+ best_name = ""+ best_status = "completed"++ for part in parts:+ part_name = (name_getter(part) or "").strip()+ if not part_name:+ continue++ part_norm = normalize_name(part_name)+ if part_name == candidate_name or (candidate_norm and part_norm == candidate_norm):+ return (part_name, getattr(part, "tool_status", None) or "completed")++ ratio = SequenceMatcher(None, candidate_norm, part_norm).ratio()+ # tie-break: prefer the last occurrence when multiple parts have the same similarity+ if ratio > best_ratio or (ratio == best_ratio and ratio >= 0):+ best_ratio = ratio+ best_name = part_name+ best_status = getattr(part, "tool_status", None) or "completed"++ if best_ratio >= threshold and best_name:+ return (best_name, best_status)+ return ("", "completed")+++def calibrate_tool_name(candidate_tool_name: str, tool_parts: Iterable[Any]) -> Tuple[str, str]:+ return _calibrate_name(+ candidate_name=candidate_tool_name,+ parts=tool_parts,+ name_getter=lambda p: getattr(p, "tool_name", "") or "",+ threshold=0.8,+ )+++def calibrate_skill_name(candidate_skill_name: str, tool_parts: Iterable[Any]) -> Tuple[str, str]:+ return _calibrate_name(+ candidate_name=candidate_skill_name,+ parts=tool_parts,+ name_getter=lambda p: extract_skill_name_from_uri(getattr(p, "skill_uri", "") or ""),+ threshold=0.8,+ )+++def collect_tool_stats(tool_parts: Iterable[Any]) -> Dict[str, Dict[str, Number]]:+ stats_map: Dict[str, Dict[str, Number]] = {}+ for part in tool_parts:+ name = (getattr(part, "tool_name", "") or "").strip()+ if not name:+ continue++ if name not in stats_map:+ stats_map[name] = {+ "duration_ms": 0,+ "prompt_tokens": 0,+ "completion_tokens": 0,+ "success_time": 0,+ "call_count": 0,+ }++ stats_map[name]["call_count"] += 1+ duration_ms = getattr(part, "duration_ms", None)+ if duration_ms is not None:+ stats_map[name]["duration_ms"] += duration_ms+ prompt_tokens = getattr(part, "prompt_tokens", None)+ if prompt_tokens is not None:+ stats_map[name]["prompt_tokens"] += int(prompt_tokens)+ completion_tokens = getattr(part, "completion_tokens", None)+ if completion_tokens is not None:+ stats_map[name]["completion_tokens"] += int(completion_tokens)+ if (getattr(part, "tool_status", None) or "") == "completed":+ stats_map[name]["success_time"] += 1++ return stats_map+++def collect_skill_stats(tool_parts: Iterable[Any]) -> Dict[str, Dict[str, Number]]:+ stats_map: Dict[str, Dict[str, Number]] = {}+ for part in tool_parts:+ skill_uri = getattr(part, "skill_uri", "") or ""+ skill_name = extract_skill_name_from_uri(skill_uri)+ if not skill_name:+ continue++ if skill_name not in stats_map:+ stats_map[skill_name] = {+ "success_time": 0,+ "call_count": 0,+ }++ stats_map[skill_name]["call_count"] += 1+ if (getattr(part, "tool_status", None) or "") == "completed":+ stats_map[skill_name]["success_time"] += 1++ return stats_mapdiff --git a/tests/unit/tool_skill/test_tool_skill_calibration.py b/tests/unit/tool_skill/test_tool_skill_calibration.pynew file mode 100644index 000000000..cf4f61e22--- /dev/null+++ b/tests/unit/tool_skill/test_tool_skill_calibration.py@@ -0,0 +1,83 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0+"""Tests for tool/skill name calibration in memory extraction."""++from openviking.message.part import ToolPart+from openviking.session.compressor import SessionCompressor+from openviking.session.memory_extractor import MemoryCategory, ToolSkillCandidateMemory+++def _candidate(+ category: MemoryCategory, tool_name: str = "", skill_name: str = ""+) -> ToolSkillCandidateMemory:+ return ToolSkillCandidateMemory(+ category=category,+ abstract="a",+ overview="o",+ content="c",+ source_session="s",+ user="u",+ tool_name=tool_name,+ skill_name=skill_name,+ )+++class TestToolSkillCalibration:+ def test_tools_candidate_returns_only_canonical_tool_name(self):+ compressor = SessionCompressor.__new__(SessionCompressor)+ tool_parts = [+ ToolPart(tool_name="read_file", tool_status="completed"),+ ToolPart(skill_uri="viking://agent/skills/weather", tool_status="completed"),+ ToolPart(tool_name="weather", tool_status="error"),+ ]+ candidate = _candidate(MemoryCategory.TOOLS, tool_name="weather")+ tool_name, skill_name, status = compressor._get_tool_skill_info(candidate, tool_parts)+ assert tool_name == "weather"+ assert skill_name == ""+ assert status == "error"++ def test_skills_candidate_returns_only_canonical_skill_name(self):+ compressor = SessionCompressor.__new__(SessionCompressor)+ tool_parts = [+ ToolPart(tool_name="read_file", tool_status="completed"),+ ToolPart(skill_uri="viking://agent/skills/weather", tool_status="error"),+ ToolPart(tool_name="weather", tool_status="completed"),+ ]+ candidate = _candidate(MemoryCategory.SKILLS, skill_name="weather")+ tool_name, skill_name, status = compressor._get_tool_skill_info(candidate, tool_parts)+ assert tool_name == ""+ assert skill_name == "weather"+ assert status == "error"++ def test_empty_candidate_name_is_skipped(self):+ compressor = SessionCompressor.__new__(SessionCompressor)+ tool_parts = [ToolPart(tool_name="weather", tool_status="completed")]+ candidate = _candidate(MemoryCategory.TOOLS, tool_name="")+ tool_name, skill_name, status = compressor._get_tool_skill_info(candidate, tool_parts)+ assert (tool_name, skill_name, status) == ("", "", "completed")++ def test_no_match_returns_empty_and_never_falls_back_to_candidate(self):+ compressor = SessionCompressor.__new__(SessionCompressor)+ tool_parts = [ToolPart(tool_name="weather", tool_status="completed")]+ candidate = _candidate(MemoryCategory.TOOLS, tool_name="calendar")+ tool_name, skill_name, status = compressor._get_tool_skill_info(candidate, tool_parts)+ assert (tool_name, skill_name, status) == ("", "", "completed")++ def test_suffix_like_weather_usage_does_not_match_weather(self):+ compressor = SessionCompressor.__new__(SessionCompressor)+ tool_parts = [ToolPart(skill_uri="viking://agent/skills/weather", tool_status="completed")]+ candidate = _candidate(MemoryCategory.SKILLS, skill_name="weather使用")+ tool_name, skill_name, status = compressor._get_tool_skill_info(candidate, tool_parts)+ assert (tool_name, skill_name, status) == ("", "", "completed")++ def test_best_match_tie_picks_most_recent_tool_part(self):+ compressor = SessionCompressor.__new__(SessionCompressor)+ tool_parts = [+ ToolPart(tool_name="abcdeXghij", tool_status="completed"),+ ToolPart(tool_name="abcdeYghij", tool_status="error"),+ ]+ candidate = _candidate(MemoryCategory.TOOLS, tool_name="abcdefghij")+ tool_name, skill_name, status = compressor._get_tool_skill_info(candidate, tool_parts)+ assert tool_name == "abcdeYghij"+ assert skill_name == ""+ assert status == "error"diff --git a/tests/unit/tool_skill/test_tool_skill_memory_guardrails.py b/tests/unit/tool_skill/test_tool_skill_memory_guardrails.pynew file mode 100644index 000000000..0a02ee099--- /dev/null+++ b/tests/unit/tool_skill/test_tool_skill_memory_guardrails.py@@ -0,0 +1,294 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++try:+ from openviking.session.memory_extractor import MemoryExtractor, ToolSkillCandidateMemory+ from openviking_cli.exceptions import NotFoundError+except Exception: # pragma: no cover - fallback for minimal local test env+ MemoryExtractor = None+ ToolSkillCandidateMemory = None++ class NotFoundError(Exception):+ pass+++pytestmark = pytest.mark.skipif(+ MemoryExtractor is None or ToolSkillCandidateMemory is None,+ reason="openviking.session.memory_extractor not available in this test env",+)+++def _ctx(agent_space: str = "agent_space_1"):+ return SimpleNamespace(+ account_id="acc_1",+ user=SimpleNamespace(agent_space_name=lambda: agent_space),+ )+++def _tool_candidate(+ tool_name: str = "tool_x",+ call_time: int = 2,+ success_time: int = 2,+ content: str = "some guidelines",+):+ return ToolSkillCandidateMemory(+ category=MagicMock(value="tools"),+ abstract="a",+ overview="o",+ content=content,+ source_session="s",+ user="u",+ language="zh-CN",+ tool_name=tool_name,+ skill_name="",+ call_time=call_time,+ success_time=success_time,+ duration_ms=10,+ prompt_tokens=1,+ completion_tokens=1,+ )+++def _skill_candidate(+ skill_name: str = "skill_x",+ content: str = "some guidelines",+):+ return ToolSkillCandidateMemory(+ category=MagicMock(value="skills"),+ abstract="a",+ overview="o",+ content=content,+ source_session="s",+ user="u",+ language="zh-CN",+ tool_name="",+ skill_name=skill_name,+ call_time=1,+ success_time=1,+ duration_ms=0,+ prompt_tokens=0,+ completion_tokens=0,+ )+++async def test_merge_tool_memory_read_failure_skips_write(monkeypatch):+ extractor = MemoryExtractor()+ fs = SimpleNamespace(+ read_file=AsyncMock(side_effect=RuntimeError("read failed")),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ ctx = _ctx()+ candidate = _tool_candidate()+ result = await extractor._merge_tool_memory("tool_x", candidate, ctx)+ assert result is None+ fs.write_file.assert_not_called()+++async def test_merge_tool_memory_not_found_allows_create(monkeypatch):+ extractor = MemoryExtractor()+ fs = SimpleNamespace(+ read_file=AsyncMock(side_effect=NotFoundError("missing", "file")),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ ctx = _ctx()+ candidate = _tool_candidate(content="guide")+ result = await extractor._merge_tool_memory("tool_x", candidate, ctx)+ assert result is not None+ fs.write_file.assert_called_once()+++async def test_merge_tool_memory_monotonic_violation_skips_write(monkeypatch):+ extractor = MemoryExtractor()+ fs = SimpleNamespace(+ read_file=AsyncMock(+ return_value="总调用次数: 10\n成功率: 100.0%\n平均耗时: 1ms\n平均Token: 1\n"+ ),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ monkeypatch.setattr(+ extractor,+ "_merge_tool_statistics",+ lambda existing, new: {**existing, "total_calls": existing["total_calls"] - 1},+ )++ ctx = _ctx()+ candidate = _tool_candidate(call_time=1, content="guide")+ result = await extractor._merge_tool_memory("tool_x", candidate, ctx)+ assert result is None+ fs.write_file.assert_not_called()+++async def test_merge_skill_memory_read_failure_skips_write(monkeypatch):+ extractor = MemoryExtractor()+ fs = SimpleNamespace(+ read_file=AsyncMock(side_effect=RuntimeError("read failed")),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ ctx = _ctx()+ candidate = _skill_candidate()+ result = await extractor._merge_skill_memory("skill_x", candidate, ctx)+ assert result is None+ fs.write_file.assert_not_called()+++async def test_merge_skill_memory_not_found_allows_create(monkeypatch):+ extractor = MemoryExtractor()+ fs = SimpleNamespace(+ read_file=AsyncMock(side_effect=NotFoundError("missing", "file")),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ ctx = _ctx()+ candidate = _skill_candidate(content="guide")+ result = await extractor._merge_skill_memory("skill_x", candidate, ctx)+ assert result is not None+ fs.write_file.assert_called_once()+++async def test_merge_skill_memory_monotonic_violation_skips_write(monkeypatch):+ extractor = MemoryExtractor()+ fs = SimpleNamespace(+ read_file=AsyncMock(return_value="总执行次数: 10\n成功率: 100.0%\n"),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ monkeypatch.setattr(+ extractor,+ "_merge_skill_statistics",+ lambda existing, new: {**existing, "total_executions": existing["total_executions"] - 1},+ )++ ctx = _ctx()+ candidate = _skill_candidate(content="guide")+ result = await extractor._merge_skill_memory("skill_x", candidate, ctx)+ assert result is None+ fs.write_file.assert_not_called()+++async def test_merge_tool_memory_old_format_upgrades_to_reme(monkeypatch):+ extractor = MemoryExtractor()+ monkeypatch.setattr(extractor, "_get_tool_static_description", lambda name: "static desc")+ monkeypatch.setattr(extractor, "_merge_memory_bundle", AsyncMock(return_value=None))++ existing = (+ "## 工具信息\n"+ "- **名称**: tool_x\n\n"+ "## 调用统计\n"+ "- **总调用次数**: 10\n"+ "- **成功率**: 50.0%(5 成功,5 失败)\n"+ "- **平均耗时**: 1ms\n"+ "- **平均Token**: 2\n\n"+ "## 使用指南\n"+ "old guide\n"+ )+ fs = SimpleNamespace(+ read_file=AsyncMock(return_value=existing),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ ctx = _ctx()+ candidate = _tool_candidate(call_time=2, success_time=2, content="new guide\nBest for: docs")+ result = await extractor._merge_tool_memory("tool_x", candidate, ctx)+ assert result is not None++ written = fs.write_file.call_args.kwargs["content"]+ assert "Tool: tool_x" in written+ assert "Tool Memory Context:" in written+ assert "Based on 12 historical calls:" in written+ assert "- Best for: docs" in written+ assert "Guidelines:" in written+ assert "old guide" in written+++async def test_merge_tool_memory_content_format_parses_and_merges(monkeypatch):+ extractor = MemoryExtractor()+ monkeypatch.setattr(extractor, "_get_tool_static_description", lambda name: "static desc")+ monkeypatch.setattr(extractor, "_merge_memory_bundle", AsyncMock(return_value=None))++ existing = (+ "Tool: tool_x\n\n"+ "Static Description:\n"+ '"static desc"\n\n'+ "Tool Memory Context:\n"+ "Based on 3 historical calls:\n"+ "- Success rate: 66.7% (2 successful, 1 failed)\n"+ "- Avg time: 2.0s, Avg tokens: 100\n"+ "- Best for: docs\n"+ "- Optimal params: N/A\n"+ "- Common failures: N/A\n"+ "- Recommendation: N/A\n\n"+ "Guidelines:\n"+ "old guide\n"+ )+ fs = SimpleNamespace(+ read_file=AsyncMock(return_value=existing),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ ctx = _ctx()+ candidate = _tool_candidate(call_time=1, success_time=1, content="new guide")+ result = await extractor._merge_tool_memory("tool_x", candidate, ctx)+ assert result is not None++ written = fs.write_file.call_args.kwargs["content"]+ assert "Based on 4 historical calls:" in written+ assert "Success rate:" in written+ assert "Guidelines:" in written+++async def test_merge_skill_memory_old_format_upgrades_to_aligned(monkeypatch):+ extractor = MemoryExtractor()+ monkeypatch.setattr(extractor, "_merge_memory_bundle", AsyncMock(return_value=None))++ existing = (+ "## 技能信息\n"+ "- **名称**: skill_x\n\n"+ "## 执行统计\n"+ "- **总执行次数**: 10\n"+ "- **成功率**: 80.0%(8 成功,2 失败)\n\n"+ "## 使用指南\n"+ "old guide\n"+ )+ fs = SimpleNamespace(+ read_file=AsyncMock(return_value=existing),+ write_file=AsyncMock(),+ )+ monkeypatch.setattr("openviking.session.memory_extractor.get_viking_fs", lambda: fs)++ ctx = _ctx()+ candidate = _skill_candidate(content="new guide\nRecommended flow: a->b")+ result = await extractor._merge_skill_memory("skill_x", candidate, ctx)+ assert result is not None++ written = fs.write_file.call_args.kwargs["content"]+ assert "Skill: skill_x" in written+ assert "Skill Memory Context:" in written+ assert "Based on 11 historical executions:" in written+ assert "- Recommended flow: a->b" in written+ assert "Guidelines:" in writtendiff --git a/tests/unit/tool_skill/test_tool_skill_utils.py b/tests/unit/tool_skill/test_tool_skill_utils.pynew file mode 100644index 000000000..cfaf63548--- /dev/null+++ b/tests/unit/tool_skill/test_tool_skill_utils.py@@ -0,0 +1,74 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: Apache-2.0++from openviking.message.part import ToolPart+from openviking.session.tool_skill_utils import (+ calibrate_skill_name,+ calibrate_tool_name,+ collect_skill_stats,+ collect_tool_stats,+ normalize_name,+)+++class TestToolSkillUtils:+ def test_normalize_name_removes_common_separators(self):+ assert normalize_name(" get-weather ") == normalize_name("get_weather")+ assert normalize_name("Get Weather") == normalize_name("get_weather")++ def test_calibrate_tool_name_matches_hyphen_to_underscore(self):+ tool_parts = [ToolPart(tool_name="get_weather", tool_status="completed")]+ tool_name, status = calibrate_tool_name("get-weather", tool_parts)+ assert tool_name == "get_weather"+ assert status == "completed"++ def test_collect_tool_stats_aggregates_counts_and_tokens(self):+ tool_parts = [+ ToolPart(+ tool_name="get_weather",+ tool_status="completed",+ duration_ms=10,+ prompt_tokens=5,+ completion_tokens=7,+ ),+ ToolPart(+ tool_name="get_weather",+ tool_status="error",+ duration_ms=20,+ prompt_tokens=1,+ completion_tokens=2,+ ),+ ]+ stats = collect_tool_stats(tool_parts)["get_weather"]+ assert stats["call_count"] == 2+ assert stats["success_time"] == 1+ assert stats["duration_ms"] == 30+ assert stats["prompt_tokens"] == 6+ assert stats["completion_tokens"] == 9++ def test_calibrate_skill_name_matches_by_skill_uri_suffix(self):+ tool_parts = [ToolPart(skill_uri="viking://agent/skills/weather", tool_status="error")]+ tool_name, status = calibrate_skill_name("weather", tool_parts)+ assert tool_name == "weather"+ assert status == "error"++ def test_collect_skill_stats_aggregates_by_skill_name(self):+ tool_parts = [+ ToolPart(+ skill_uri="viking://agent/skills/weather",+ tool_status="completed",+ duration_ms=3,+ prompt_tokens=2,+ completion_tokens=4,+ ),+ ToolPart(+ skill_uri="viking://agent/skills/weather",+ tool_status="error",+ duration_ms=7,+ prompt_tokens=1,+ completion_tokens=1,+ ),+ ]+ stats = collect_skill_stats(tool_parts)["weather"]+ assert stats["call_count"] == 2+ assert stats["success_time"] == 1