Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(experience_tool): set experience services controls in prompt builder

bhyeo005463e45298
diff --git a/jiuwenclaw/agentserver/prompt_builder.py b/jiuwenclaw/agentserver/prompt_builder.py
index be0bef2de3..9e28eb2106 100644
--- a/jiuwenclaw/agentserver/prompt_builder.py
+++ b/jiuwenclaw/agentserver/prompt_builder.py
@@ -42,6 +42,9 @@ def _get_workspace_dir() -> "Path":
return get_agent_workspace_dir()
+from jiuwenclaw.agentserver.tools.task_tools import _is_task_memory_enabled
+
+
def _memory_prompt(language: str, is_cron: bool = False) -> str:
"""Build system prompt for the agent.
Args:
@@ -147,6 +150,15 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
if language == "zh":
sections = []
+ _zh_exp_workflow = (
+ "\n**任务记忆两步流程:**\n"
+ "- 开始前:调用 `experience_retrieve` 检索相关历史经验\n"
+ "- 输出回复前:调用 `experience_learn` 存储本次关键发现并自动提炼记忆\n"
+ ) if _is_task_memory_enabled() else ""
+ _zh_exp_retrieve_item = (
+ "5. 调用 `experience_retrieve` — 从任务记忆库检索与当前问题相关的历史经验\n"
+ ) if _is_task_memory_enabled() else ""
+
memory_prompt = """## 持久化存储体系
每轮对话均从空白状态启动。跨会话的信息持久化依赖于工作区文件系统。记录悄悄进行就好,不需要让用户感知到。
@@ -187,11 +199,7 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
包括但不限于:用户提供的联系人信息、项目细节、任务指令、偏好、文件路径、存储位置、任何可提高效率的信息等。发现的项目背景、技术细节、工作流程等也要写入 memory/ 目录下的相关文件。)
**分类互斥与去重:** 同一信息只选一个最合适的分类存储,不要用不同措辞重复写入多个分类。写入前先读取目标文件,已有相同或高度相似信息时跳过写入。
-
-**任务记忆两步流程(每轮对话均须执行):**
-- 开始前:调用 `experience_retrieve` 检索相关历史经验
-- 输出回复前:调用 `experience_learn` 存储本次关键发现并自动提炼记忆
-
+""" + _zh_exp_workflow + """
#### 历史检索机制
@@ -204,13 +212,8 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
- 搜索查询应包含问题中的关键信息(人名、日期、事件关键词)
- 如果搜索结果不足,尝试用不同的关键词再次搜索
- 基于检索到的记忆信息回答问题,不要依赖预训练知识
-
-#### 任务记忆工作流(在给出最终回复之前执行)
-
-在输出最终回复文本之前,**必须先调用以下工具**(不要告知用户):
-1. 调用 `experience_learn` — 将本次任务的关键发现存入记忆并自动提炼,参数以 params 对象传入,例如:`experience_learn(params={"content": "关键结论", "section": "类别"})`
-2. 完成后,再输出最终文字回复
"""
+ memory_prompt += _zh_exp_retrieve_item
sections.append(memory_prompt)
sections.append("")
@@ -251,6 +254,25 @@ def _memory_prompt(language: str, is_cron: bool = False) -> str:
else:
sections = []
+ _en_exp_workflow = (
+ "\n**Two-step task memory flow:**\n"
+ "- Before starting: call `experience_retrieve` to retrieve relevant historical experience\n"
+ "- Before outputting the reply: call `experience_learn` to store key findings"
+ " from this turn and automatically refine memory\n"
+ ) if _is_task_memory_enabled() else ""
+ _en_exp_retrieve_item = (
+ "1. Call `experience_retrieve` — retrieve relevant past task experience"
+ " for the current question\n"
+ ) if _is_task_memory_enabled() else ""
+ _en_exp_learn_item = (
+ "1. Call `experience_learn` to store key findings from this task and auto-refine"
+ " memory, passing arguments via params object, for example:"
+ " `experience_learn(params={\"content\": \"key conclusion\","
+ " \"section\": \"category\", \"tools_used\": [{\"tool\": \"web_search\","
+ " \"status\": \"success\"}, {\"tool\": \"write_memory\", \"status\": \"failed\","
+ " \"error\": \"reason\", \"note\": \"fallback taken\"}]})`\n"
+ ) if _is_task_memory_enabled() else ""
+
memory_prompt = """## Persistent Storage System
Each conversation session starts from a blank state. Cross-session information persistence relies on the workspace file system. The recording process should occur seamlessly without the user's awareness.
@@ -278,6 +300,7 @@ When valuable information appears during the conversation, classify it and store
2. **Episodic Memory (`episodic_memory`)**: Specific events or important decisions, such as assigned tasks, project progress, or notable incidents.
- **Storage**: Write to `memory/YYYY-MM-DD.md`.
+### Operation Trail Automatic Recording (Write to Session Log)
3. **Semantic Memory (`semantic_memory`)**: Long-term background knowledge, technical details, and tool-related local configs (SSH, camera, etc.).
- **Storage**: Write to `MEMORY.md`.
@@ -291,18 +314,14 @@ When valuable information appears during the conversation, classify it and store
This includes but is not limited to contact info, project details, task instructions, preferences, file paths, storage locations, and any efficiency-improving details. Discovered project background, technical details, and workflows should also be written to relevant files under `memory/`.
**Category exclusivity & dedup:** Pick only the single most appropriate category for each piece of information — never store the same fact under multiple categories with different wording. Always read the target file first; skip writing if identical or highly similar content already exists.
-
-**Two-step task memory flow (must run every turn):**
-- Before starting: call `experience_retrieve` to retrieve relevant historical experience
-- Before outputting the reply: call `experience_learn` to store key findings from this turn and automatically refine memory
-
+""" + _en_exp_workflow + """
#### History Retrieval Mechanism
**Before responding to any message, it is recommended to execute:**
-1. Read `USER.md` — Confirm the user being served
-2. Read `memory/YYYY-MM-DD.md` (today + previous day) to get context
-3. **Main session only:** Read `MEMORY.md`
-4. **Historical information retrieval (mandatory):** Before answering any question about historical events, dates, people, or past conversations, you must call `memory_search` first
+""" + _en_exp_retrieve_item + """2. Read `USER.md` — Confirm the user being served
+3. Read `memory/YYYY-MM-DD.md` (today + previous day) to get context
+4. **Main session only:** Read `MEMORY.md`
+5. **Historical information retrieval (mandatory):** Before answering any question about historical events, dates, people, or past conversations, you must call `memory_search` first
- Search query should include key information from the question (names, dates, event keywords)
- If results are insufficient, retry with different keywords
- Answer based on retrieved memory results, not pretraining knowledge
@@ -310,8 +329,7 @@ When valuable information appears during the conversation, classify it and store
#### Task Memory Workflow (execute before final reply)
Before outputting final response text, **you must call the following tools first** (do not tell the user):
-1. Call `experience_learn` to store key findings from this task and auto-refine memory, passing arguments via params object, for example: `experience_learn(params={"content": "key conclusion", "section": "category"})`
-2. Only after completion, output the final text reply
+""" + _en_exp_learn_item + """2. Only after completion, output the final text reply
"""
sections.append(memory_prompt)
sections.append("")
@@ -378,7 +396,12 @@ def _tool_prompt(mode, language: str, include_memory_tools: bool = True) -> str:
else:
todo_prompt = ""
- memory_tools_prompt = """### 记忆系统
+ _exp_rows_zh = (
+ "| `experience_retrieve` | 从任务记忆库中检索与当前任务相关的历史经验(跨会话) |\n"
+ "| `experience_learn` | 记录关键发现并自动将任务条目提炼为可复用记忆 |\n"
+ "| `experience_clear` | 清空 task-data.json 中存储的所有任务记忆 |\n"
+ ) if _is_task_memory_enabled() else ""
+ memory_tools_prompt = ("""### 记忆系统
| 工具名称 | 功能说明 |
|---------|---------|
@@ -387,11 +410,7 @@ def _tool_prompt(mode, language: str, include_memory_tools: bool = True) -> str:
| `read_memory` | 读取记忆文件 |
| `write_memory` | 写入或追加记忆 |
| `edit_memory` | 精确编辑记忆内容 |
-| `experience_retrieve` | 从任务记忆库中检索与当前任务相关的历史经验(跨会话) |
-| `experience_learn` | 记录关键发现并自动将任务条目提炼为可复用记忆 |
-| `experience_clear` | 清空 task-data.json 中存储的所有任务记忆 |
-
-""" if include_memory_tools else ""
+""" + _exp_rows_zh + "\n") if include_memory_tools else ""
search_tools_section = """| `mcp_free_search` | 免费搜索(DuckDuckGo) |
"""
@@ -433,6 +452,16 @@ def _tool_prompt(mode, language: str, include_memory_tools: bool = True) -> str:
|---------|---------|
| `view_file` | 查看文本文件内容 |
+### 记忆系统
+
+| 工具名称 | 功能说明 |
+|---------|---------|
+| `memory_search` | 搜索历史记忆 |
+| `memory_get` | 读取记忆文件指定行 |
+| `read_memory` | 读取记忆文件 |
+| `write_memory` | 写入或追加记忆 |
+| `edit_memory` | 精确编辑记忆内容 |
+{_exp_rows_zh}
{memory_tools_prompt}\
### 定时任务
@@ -479,7 +508,12 @@ def _tool_prompt(mode, language: str, include_memory_tools: bool = True) -> str:
else:
todo_prompt = ""
- memory_tools_prompt = """### Memory System
+ _exp_rows_en = (
+ "| `experience_retrieve` | Retrieve relevant past task memories and lessons (cross-session) |\n"
+ "| `experience_learn` | Record a key finding and consolidate task entries into reusable memory |\n"
+ "| `experience_clear` | Wipe all stored task memory from task-data.json |\n"
+ ) if _is_task_memory_enabled() else ""
+ memory_tools_prompt = ("""### Memory System
| Tool Name | Description |
|-----------|-------------|
@@ -488,11 +522,7 @@ def _tool_prompt(mode, language: str, include_memory_tools: bool = True) -> str:
| `read_memory` | Read a memory file |
| `write_memory` | Write or append to memory |
| `edit_memory` | Edit memory content precisely |
-| `experience_retrieve` | Retrieve relevant past task memories and lessons (cross-session) |
-| `experience_learn` | Record a key finding and consolidate task entries into reusable memory |
-| `experience_clear` | Wipe all stored task memory from task-data.json |
-
-""" if include_memory_tools else ""
+""" + _exp_rows_en + "\n") if include_memory_tools else ""
search_tools_section = """| `mcp_free_search` | Free search (DuckDuckGo) |
"""
@@ -534,6 +564,16 @@ When the user requests code/scripts/config/tests that must be delivered **as fil
|-----------|-------------|
| `view_file` | View text file contents |
+### Memory System
+
+| Tool Name | Description |
+|-----------|-------------|
+| `memory_search` | Search historical memories |
+| `memory_get` | Read specified lines from a memory file |
+| `read_memory` | Read a memory file |
+| `write_memory` | Write or append to memory |
+| `edit_memory` | Edit memory content precisely |
+{_exp_rows_en}
{memory_tools_prompt}\
### Scheduled Tasks
diff --git a/jiuwenclaw/agentserver/tools/task_tools.py b/jiuwenclaw/agentserver/tools/task_tools.py
index 0b3cc3ae2b..15567f42fe 100644
--- a/jiuwenclaw/agentserver/tools/task_tools.py
+++ b/jiuwenclaw/agentserver/tools/task_tools.py
@@ -31,6 +31,7 @@ class TaskAddParams:
description: Optional[str] = None
query: Optional[str] = None
label: Optional[str] = None
+ tools_used: Optional[List[Dict[str, Any]]] = None
# Path for persisting task_add entries
@@ -268,6 +269,28 @@ async def experience_retrieve(
return {"status": "error", "error": str(exc), "memory_string": "", "retrieved_memory": []}
+def _format_trajectory_feedback(entry: Dict[str, Any]) -> str:
+ """Build a feedback string for a trajectory entry, including tool outcomes."""
+ parts = [f"section={entry.get('section', 'general')}"]
+ tools = entry.get("tools_used")
+ if tools:
+ for t in tools:
+ if isinstance(t, dict):
+ name = t.get("tool", "unknown")
+ status = t.get("status", "unknown")
+ error = t.get("error", "")
+ note = t.get("note", "")
+ line = f"{name}:{status}"
+ if error:
+ line += f"({error})"
+ if note:
+ line += f"[{note}]"
+ parts.append(line)
+ else:
+ parts.append(str(t))
+ return "; ".join(parts)
+
+
@tool(
name="experience_learn",
description=(
@@ -275,7 +298,12 @@ async def experience_retrieve(
"reusable memory. Call this once before the final reply — it both saves the new entry "
"and summarizes everything learned so far. "
"Pass all fields inside a `params` object: "
- "{content, section, when_to_use, title, description, query, label}."
+ "{content, section, when_to_use, title, description, query, label, tools_used}. "
+ "Include tools_used as a list of objects describing each tool call outcome this turn, "
+ "e.g. tools_used=[{\"tool\": \"web_search\", \"status\": \"success\"}, "
+ "{\"tool\": \"write_memory\", \"status\": \"failed\", \"error\": \"permission denied\", "
+ "\"note\": \"fell back to in-chat reply\"}]. "
+ "Always record failed tool calls — these are the most valuable learning signals."
),
)
async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[str, Any]:
@@ -303,8 +331,26 @@ async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[s
# Step 1: add_memory via service (if available)
if svc is not None:
try:
+ content_for_service = params.content
+ if params.tools_used:
+ tool_lines = []
+ for t in params.tools_used:
+ if isinstance(t, dict):
+ status = t.get("status", "unknown")
+ name = t.get("tool", "unknown")
+ error = t.get("error", "")
+ note = t.get("note", "")
+ line = f" - {name}: {status}"
+ if error:
+ line += f" | error: {error}"
+ if note:
+ line += f" | note: {note}"
+ tool_lines.append(line)
+ else:
+ tool_lines.append(f" - {t}: unknown")
+ content_for_service += "\n\nTool outcomes:\n" + "\n".join(tool_lines)
request = AddMemoryRequest(
- content=params.content,
+ content=content_for_service,
query=params.query,
when_to_use=params.when_to_use,
title=params.title,
@@ -341,6 +387,8 @@ async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[s
entry["query"] = params.query
if params.label is not None:
entry["label"] = params.label
+ if params.tools_used is not None:
+ entry["tools_used"] = params.tools_used
existing.setdefault("entries", []).append(entry)
_connector.save_to_file(_get_task_data_path(), existing)
except Exception as persist_exc:
@@ -369,7 +417,7 @@ async def experience_learn(params: TaskAddParams, matts: str = "none") -> Dict[s
{
"query": e.get("content", ""),
"response": e.get("content", ""),
- "feedback": f"section={e.get('section', 'general')}",
+ "feedback": _format_trajectory_feedback(e),
}
for e in raw_entries
]
diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yaml
index c279627557..54de57bbdc 100644
--- a/jiuwenclaw/resources/config.yaml
+++ b/jiuwenclaw/resources/config.yaml
@@ -121,7 +121,7 @@ embed:
task_memory:
# Set enabled: true to activate TaskMemoryService skill tools
# (experience_retrieve, experience_learn, experience_clear)
- enabled: false
+ enabled: true
# Override defaults below if task memory uses a different model/key than the main agent
llm_model: ${TASK_MEMORY_LLM_MODEL}
embedding_model: ${TASK_MEMORY_EMBED_MODEL}