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(harness): deepsearch error 相位续跑死锁与报告占位符容错
KevinLLLovef10478cef271
diff --git a/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.pyindex c634733372..1093e1cfc8 100644--- a/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py@@ -294,9 +294,11 @@ def _bridge_stale_workflow(new ∪ error(wait_feedback/wait_outline 卡由交互卡 id 自带 alias,不入候选;cancelled 是显式放弃的死终态,不入候选);③ query 与停止认领同口径;④ 显式 conversation_id 不抢别的会话;⑤ 过滤后- 唯一。探针门:in-flight 与 error 候选须存在优雅停止快照(in-flight- 防活子进程交叉写坏;error 可能是子进程失败退出无快照可恢复)才桥;- new 相位候选免门(停止终态已返回,子进程必已退出)。+ 唯一。探针门:in-flight 候选须存在优雅停止快照(防活子进程交叉+ 写坏)才桥;error 候选放行停止快照与交互中断快照(修复8:error+ 写入可能覆盖原 wait_* 相位,残留的中断快照可桥接后由 execution+ 重弹原交互卡;子进程已失败退出无交叉写坏风险);new 相位候选免+ 门(停止终态已返回,子进程必已退出)。"""if tool_call_id in states:return ""@@ -317,7 +319,20 @@ def _bridge_stale_workflow(if phase != "new":state_cid = str(state.get("conversation_id") or "").strip()probe = _probe_resumable_checkpoint(state_cid) if state_cid else None- if not (isinstance(probe, Mapping) and probe.get("stopped")):+ # 修复8:error 相位放行停止快照与交互中断快照;in-flight+ # 相位仍硬要求 stopped 优雅停止快照(防活子进程交叉写坏)。+ if phase == "error":+ if not isinstance(probe, Mapping):+ logger.warning(+ "[deepresearch_execution_rail] bridge rejected: "+ "candidate state has no resumable checkpoint; "+ "tool_call_id=%s workflow_id=%s phase=%s",+ tool_call_id,+ workflow_id,+ phase,+ )+ continue+ elif not (isinstance(probe, Mapping) and probe.get("stopped")):logger.warning("[deepresearch_execution_rail] bridge rejected: ""candidate state has no stopped snapshot; "@@ -671,20 +686,33 @@ class DeepResearchExecutionRail(DeepAgentRail):# 研究。改写为禁止自动重启的面向模型口径,且不含# conversation_id(切断模型拿 cid 直通重启的最短路径);# 用户明确要求继续时模型凭原主题 query 重调,修复9' 的- # 扫库认领会自动认领停止快照。恢复入口双指引(2026-10-15- # 19:52 回归实证:停止后新请求中 execute 被 ProgressiveToolRail- # 过滤,单 execute 指引是死信,模型绕行 stream start 全新- # 起跑丢快照——stream 侧已同口径扫库认领)。+ # 扫库认领会自动认领停止快照。恢复入口统一 skill_tool 重载+ # 指引(2026-11-03 改版:原 stream 回落双指引与 SKILL.md+ # 降级规则打架,门控拒绝被误读为入口未开放而直降模型研究+ # 路径;统一口径后 Main Agent 不再触碰 deepresearch_stream)。+ # 2026-11-05 B+ 补强:线上 9973ed6e 会话中排队 55s 的+ # “继续”晚于备选方案回复投递,被模型误读为采纳方案而+ # 转走模型自主研究路径;文案与 execution._stopped_result+ # 同步增加停止定性(用户主动、非故障/非历史失败)、+ # “继续”优先于备选方案解读、消息信封 timestamp 时序+ # 意识三重防御。ctx.inputs.tool_msg = ToolMessage(content=("DeepResearch 任务已被用户停止,执行进度已保存。"- "请勿代替用户决定继续,也不要自动重新调用研究工具;"- "仅当用户明确要求继续该研究时才恢复执行:优先再次"- "调用 deepresearch_execute(传入原研究主题即可自动"- "认领停止快照);若该工具当前不可见,可调用"- " deepresearch_stream(action='start',传入原研究"- "主题,同样会自动认领)。恢复将从停止处继续,已完成"- "阶段不会重跑。"+ "停止是用户的主动操作,不代表系统故障、超时或会话"+ "残留,也不要因记忆中该主题曾有失败记录而绕过研究"+ "工具。请勿代替用户决定继续,也不要自动重新调用"+ "研究工具;仅当用户明确要求继续该研究时才恢复执行:"+ "再次调用 deepresearch_execute(传入原研究主题即可"+ "自动认领停止快照);若该工具当前不可见,先调用 "+ "skill_tool(skill_name=\"deepresearch\") 重新加载本"+ "技能,再按上述方式调用。恢复将从停止处继续,已完成"+ "阶段不会重跑。用户回复“继续”“继续研究”即属明确"+ "要求继续:即使你曾向用户提供过备选方案,也应优先"+ "按上述方式续跑,而非将其理解为采纳备选方案或改走"+ "模型自主研究路径。另注意用户消息信封自带 "+ "timestamp,晚于你最近一条回复到达的消息未必是对"+ "该回复的回应,解读用户意图前先核对消息时序。"),tool_call_id=history_id,)@@ -719,7 +747,23 @@ class DeepResearchExecutionRail(DeepAgentRail):and isinstance(fallback, Mapping)and fallback.get("mode") == "model_research")- if not (model_handoff or (isinstance(state, Mapping) and state.get("materials_prepared"))):+ # fix-4c:error 终态不再弹 state(参照 stopped 终态的保留范式)。+ # error 写入可能覆盖原 wait_* 相位(execution.py 修复点3.2:取消+ # 转译的 stopped 写入被同 revision 的 error 覆盖写吞掉),其+ # checkpoint 残留可恢复快照(stopped 直通续跑 / 中断交互卡重弹 /+ # salvage 止损)。弹掉 state 后下一次调用 state miss → 无 bridge+ # 候选 → 全新 cid 从头重跑(生产事故 10-27 双轮场景:暂停后续跑+ # 丢上下文、研究全部重来)。保留后由 _bridge_stale_workflow 的+ # error 相位候选(探针门已放行中断快照)桥接续跑。防死锁配套:+ # execution 判死路已把 phase 回落 new(同 _stopped_result),+ # 换主题/重新发起不会被 error 相位反复判死。completed/cancelled+ # 仍是干净终态,维持清弹。+ error_terminal = payload.get("kind") == "error"+ if not (+ model_handoff+ or error_terminal+ or (isinstance(state, Mapping) and state.get("materials_prepared"))+ ):states.pop(workflow_id, None)_save_states(ctx.session, states)aliases = {diff --git a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.pyindex e97ae0b706..08d0205359 100644--- a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py@@ -154,7 +154,7 @@ class ProgressiveToolRail(DeepAgentRail):# parent rails by reference; the child's init then rebinds the shared# instance and overwrites the cache with the child's smaller tool set.# Parent tools_search / invoke_tool for deferred names such as- # subagent_wait then miss (「未注册或不在按需可见工具列表中」) while the+ # subagent_wait then miss (「工具 ... 未注册」) while the# child is still running. react.tool_lazy_load.subagents.enabled is# already false — this flag makes factory honor that.inherit_to_subagents = False@@ -1472,6 +1472,43 @@ class ProgressiveToolRail(DeepAgentRail):),}+ if not result_matches:+ # 反查全量注册表识别技能未激活场景:skill 未激活时 deferred+ # 搜索缓存被过滤导致 matches 为空,但全量注册表(unfiltered)+ # 仍保留门控工具卡片,可据此给出与 invoke_tool 门控拒绝分支+ # 一致的重载指引,避免模型据此降级到非技能路径。注意 declared+ # 卡片被 _deferred_tools 无条件排除,技能激活态下 matches 同样+ # 为空——须先比对当前激活技能再下结论,已激活时直接可见可调用。+ registered_card = self._tool_by_name(+ getattr(self, "_cached_all_tool_infos", ()),+ tool_name,+ )+ _, required_skill = _required_skill_requirement(registered_card)+ if required_skill:+ if required_skill == self._current_active_skill():+ return {+ "success": False,+ "matches": [],+ "count": 0,+ "message": (+ f"工具 '{tool_name}' 已随技能 '{required_skill}' "+ "激活并直接可见,请直接调用,无需 tools_search。"+ ),+ }+ return {+ "success": False,+ "matches": [],+ "count": 0,+ "message": (+ f"工具 '{tool_name}' 属于技能 '{required_skill}' 的"+ "专属入口,当前该技能未激活(技能可能因闲置过期或"+ "会话切换而处于未激活状态)。请先调用 skill_tool("+ f'skill_name="{required_skill}") 重新加载技能,'+ "再直接调用该工具。这属于技能未激活,不代表能力"+ "不可用,不要据此降级或改用其他工具绕过。"+ ),+ }+return {"success": bool(result_matches),"matches": result_matches,@@ -1736,16 +1773,18 @@ class ProgressiveToolRail(DeepAgentRail):getattr(self, "_cached_all_tool_infos", ()),tool_name,)- if registered_card is None:- registered_card = self._tool_by_name(- self._cached_deferred_tool_infos,- tool_name,- )- declared, _required_skill = _required_skill_requirement(registered_card)+ declared, required_skill = _required_skill_requirement(registered_card)if declared:+ skill_hint = f"(required_skill={required_skill})" if required_skill else ""return {"success": False,- "error": f"工具 '{tool_name}' 未注册或不在按需可见工具列表中。",+ "error": (+ f"工具 '{tool_name}' 是技能门控工具{skill_hint},"+ "不能通过 invoke_tool 代理调用。若其当前不可见,通常是"+ "所属技能未激活或授权已失效:请先通过 skill_tool 重新"+ "加载对应技能,再直接调用该工具。这属于技能未激活,"+ "不代表能力不可用,不要据此降级或改用其他工具绕过。"+ ),"tool_name": tool_name,}@@ -1808,7 +1847,11 @@ class ProgressiveToolRail(DeepAgentRail):}return {"success": False,- "error": f"工具 '{tool_name}' 未注册或不在按需可见工具列表中。",+ "error": (+ f"工具 '{tool_name}' 未注册。若它属于某个技能(声明了 "+ "required_skill),其可见性依赖技能激活:先通过 skill_tool "+ "加载对应技能,再直接调用该工具,不要据此判定能力不可用。"+ ),"tool_name": tool_name,}diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.pyindex b67823ad2b..c59e4608ad 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py@@ -933,11 +933,21 @@ def _stopped_result(扫库认领接住);content 不含 conversation_id(与 rail 改写口径对齐——cid 是模型直通重启的最短路径,rail 挂载与否不应影响该防线;认领与恢复靠 query + 归属守卫,cid 的功能载体是- state 而非 content 文本)。恢复入口给双指引:execute 优先,- 其不可见时(停止后新请求 skill 激活态重置,execute 被- ProgressiveToolRail 过滤)回落 deepresearch_stream action='start'- ——stream 侧已同口径扫库认领(2026-10-15 19:52 回归实证:单- execute 指引是死信,模型绕行 stream 全新起跑丢快照)。+ state 而非 content 文本)。恢复入口统一为 skill_tool 重载指引:+ 停止后新请求 skill 激活态重置、execute 被 ProgressiveToolRail+ 过滤时,先 skill_tool 重新加载技能再调 execute(2026-11-03 改版:+ 原 stream 回落双指引与 SKILL.md 降级规则打架,invoke_tool 门控+ 拒绝被误读为“专用入口未开放”而直降模型研究路径丢快照;统一+ skill_tool 口径后 Main Agent 不再触碰 deepresearch_stream,快照+ 认领仍凭原主题 query)。+ 2026-11-05 B+ 补强(officeclaw 线上 9973ed6e 会话复盘):adapter+ 在 in-flight turn 期间排队用户消息、当轮 assistant 回复后才投递,+ 排队 55s 的“继续”被模型按呈现顺序误读为对备选方案回复的采纳,+ 转走模型自主研究路径(停止快照完好,非链路故障)。文案新增三重+ 防御:停止定性为用户主动行为(防猜测系统故障/因历史失败记忆+ 绕过工具);“继续”即明确续跑指令且优先于备选方案解读(防方案+ 劫持);提示消息信封 timestamp 时序意识(防排队晚达消息误读;+ 信封构建方在 adapter 仓,时序说明只能提示词侧补偿)。"""state = _persist(context, state, "new", conversation_id=conversation_id)return _result(@@ -945,12 +955,18 @@ def _stopped_result(state,content=("DeepResearch 任务已被用户停止,执行进度已保存。"- "请勿代替用户决定继续,也不要自动重新调用本工具;仅当用户"- "明确要求继续该研究时才恢复执行:优先再次调用 "- "deepresearch_execute(传入原研究主题即可自动认领停止快照),"- "若该工具当前不可见则调用 deepresearch_stream(action='start',"- "传入原研究主题,同样会自动认领)。届时将从停止处恢复,已完成"- "阶段不会重跑。"+ "停止是用户的主动操作,不代表系统故障、超时或会话残留,"+ "也不要因记忆中该主题曾有失败记录而绕过本工具。请勿代替"+ "用户决定继续,也不要自动重新调用本工具;仅当用户明确要求"+ "继续该研究时才恢复执行:再次调用 deepresearch_execute"+ "(传入原研究主题即可自动认领停止快照);若该工具当前不可见,"+ "先调用 skill_tool(skill_name=\"deepresearch\") 重新加载本技能,"+ "再按上述方式调用。届时将从停止处恢复,已完成阶段不会重跑。"+ "用户回复“继续”“继续研究”即属明确要求继续:即使你曾向用户"+ "提供过备选方案,也应优先按上述方式续跑,而非将其理解为"+ "采纳备选方案或改走模型自主研究路径。另注意用户消息信封"+ "自带 timestamp,晚于你最近一条回复到达的消息未必是对该"+ "回复的回应,解读用户意图前先核对消息时序。"),)@@ -1233,6 +1249,134 @@ def _is_claimable_stopped_probe()+async def _replay_interrupt_card(+ context: DeepResearchExecutionContext,+ state: dict[str, Any],+ claimed_cid: str,+ probe: Mapping[str, Any] | None,+) -> dict[str, Any] | None:+ """重弹交互卡(修复8):interrupt 快照认领后恢复原交互卡。++ 停在 feedback_handler / outline_interaction 中断快照的会话认领后+ 重弹原卡,用户答复后从原会话 resume:feedback_handler 从快照恢复+ 问题清单重弹问题确认卡(wait_feedback);outline_interaction 重弹+ 大纲审阅卡(wait_outline,DB 快照 outline_json 优先,修复5 缓存+ 兜底仅在 DB 确认存在可恢复中断时启用)。phase=new 与 phase=error+ 两个相位入口共用。命中返回交互结果;无卡可弹(非中断快照、问题或+ 大纲缺失)返回 None,由调用方继续认领链(salvage 止损 / 全新起跑)。+ """+ stopped_probe = bool(probe and probe.get("stopped"))+ probe_node = str(probe.get("node") or "") if probe else ""+ if claimed_cid and not stopped_probe and probe_node == "feedback_handler":+ # 认领成功:旧会话停在研究问题确认阶段(含跨进程重启),从+ # checkpointer.db 恢复问题清单出反馈卡;用户答复后从原会话 resume。+ questions = _split_questions(probe.get("questions"))+ if questions:+ options = await _guard_user_stop(+ context,+ state,+ _generate_options(+ context,+ str(state.get("query") or ""),+ questions,+ ),+ )+ if not isinstance(options, list):+ # 取消已被守卫转译为 stopped 业务终态(返回 dict),直接透传,+ # 不得按下标构造交互卡(否则 KeyError 会丢失 stopped 终态,+ # 退回框架通用 [Interrupted] 分支)。+ return options+ cards = [+ {+ "header": "研究方向反馈",+ "question": question,+ "options": options[index],+ }+ for index, question in enumerate(questions)+ ]+ state = _persist(+ context,+ state,+ "wait_feedback",+ conversation_id=claimed_cid,+ questions=questions,+ )+ logger.info(+ "[deepresearch_execute] claimed interrupted conversation "+ "tool_call_id=%s conversation_id=%s node=feedback_handler",+ context.tool_call_id,+ claimed_cid,+ )+ return _result(+ "interaction",+ state,+ interaction={+ "query": "请回答以下研究主题澄清问题",+ "return_json": True,+ "questions": cards,+ },+ )+ claimed_outline = (+ probe.get("outline_json")+ if probe_node == "outline_interaction"+ and not stopped_probe+ else None+ )+ claim_source = "db" if isinstance(claimed_outline, dict) else ""+ if not isinstance(claimed_outline, dict):+ # 修复5:缓存兜底仅在 DB 确认存在 outline_interaction 可恢复中断+ # 时启用(probe 命中但快照缺 outline_json 的场景)。probe 未命中+ # (会话已正常完结被清理/快照损坏/不存在)时一律不信内存缓存:+ # 事故中 probe=None 却用残留缓存大纲弹卡,用户确认后 resume 无+ # 快照可恢复而全新起跑,6 秒崩溃并删除该会话全部数据。+ if (+ claimed_cid+ and probe_node == "outline_interaction"+ and not stopped_probe+ ):+ cached_outline = _get_cached_outline_json(+ _get_route(), claimed_cid+ )+ if isinstance(cached_outline, dict):+ claimed_outline = cached_outline+ claim_source = "cache"+ else:+ # 停止快照未被认领(含换主题)时,缓存兜底同样不得复用旧会话+ # 大纲,否则会把旧主题的大纲弹给新研究。+ claimed_outline = {}+ claimed_sections = claimed_outline.get("sections")+ if claimed_cid and isinstance(claimed_sections, list) and claimed_sections:+ # 认领成功:旧会话已生成大纲且停在大纲确认(DB 快照或其缓存+ # 兜底),复用大纲出审阅卡片,跳过 start 重跑;用户答复后从原+ # 会话 resume。+ outline_text = (+ _format_outline_card_markdown(claimed_outline)+ or "大纲已生成,请确认是否继续研究。"+ )+ state = _persist(+ context,+ state,+ "wait_outline",+ conversation_id=claimed_cid,+ outline_presented=True,+ outline_sections=_outline_sections(outline_text),+ )+ logger.info(+ "[deepresearch_execute] claimed interrupted conversation "+ "tool_call_id=%s conversation_id=%s node=outline_interaction "+ "source=%s",+ context.tool_call_id,+ claimed_cid,+ claim_source or "db",+ )+ return _result(+ "interaction",+ state,+ interaction=_outline_review_interaction(outline_text),+ )+ return None++async def _run_sdk_step(context: DeepResearchExecutionContext,state: dict[str, Any],@@ -1439,6 +1583,28 @@ async def _execute_workflow(probe_node=str(error_probe.get("node") or ""),),)+ # 修复8:error 相位 interrupt 认领。error 写入可能覆盖原 wait_*+ # 相位,其 checkpoint 残留的是交互中断快照(feedback_handler /+ # outline_interaction,子进程已失败退出)。stopped 认领未命中时+ # 对中断快照重弹原交互卡(与 phase=new 同一 _replay_interrupt_card),+ # 用户答复后从原会话 resume,而不是直接落 salvage/死路丢掉交互上下文。+ if (+ error_cid+ and error_probe+ and _query_matches_stopped_claim(query, state)+ ):+ replay = await _replay_interrupt_card(+ context, state, error_cid, error_probe+ )+ if replay is not None:+ logger.info(+ "[deepresearch_execute] claimed interrupted "+ "conversation from error phase "+ "tool_call_id=%s conversation_id=%s",+ context.tool_call_id,+ error_cid,+ )+ return replay# 修复7:error 相位死路(无可恢复快照)同样先尝试止损交付已落盘# 的报告(同主题追问场景),失败才判死。if error_cid and _query_matches_stopped_claim(query, state):@@ -1463,6 +1629,14 @@ async def _execute_workflow(state, salvage.get("html_style_status")),)+ # fix-4c:判死回落 new(参照 _stopped_result 的保留范式)。rail 已对+ # error 终态保留 state,phase=error 幸存后下一次同主题调用会被+ # bridge 再次桥回本相位(换主题的重新发起被守卫③拦下走全新起跑),+ # 同主题却无可恢复快照时会反复判死——「请重新发起」永远无法重新+ # 发起。回落 new 保留 conversation_id:下一次调用走 new 分支扫库+ # 认领,无可恢复快照时按修复9'/全新起跑分支换成新 id 从头执行,+ # 重新发起不再死锁。+ state = _persist(context, state, "new", conversation_id=error_cid)return _result("error",state,@@ -1680,112 +1854,11 @@ async def _execute_workflow(probe_node=probe_node,),)- if (- claimed_cid- and not stopped_probe- and probe_node == "feedback_handler"- ):- # 认领成功:旧会话停在研究问题确认阶段(含跨进程重启),从- # checkpointer.db 恢复问题清单出反馈卡;用户答复后从原会话 resume。- questions = _split_questions(probe.get("questions"))- if questions:- options = await _guard_user_stop(- context,- state,- _generate_options(- context,- str(state.get("query") or ""),- questions,- ),- )- cards = [- {- "header": "研究方向反馈",- "question": question,- "options": options[index],- }- for index, question in enumerate(questions)- ]- state = _persist(- context,- state,- "wait_feedback",- conversation_id=claimed_cid,- questions=questions,- )- logger.info(- "[deepresearch_execute] claimed interrupted conversation "- "tool_call_id=%s conversation_id=%s node=feedback_handler",- context.tool_call_id,- claimed_cid,- )- return _result(- "interaction",- state,- interaction={- "query": "请回答以下研究主题澄清问题",- "return_json": True,- "questions": cards,- },- )- claimed_outline = (- probe.get("outline_json")- if probe_node == "outline_interaction"- and not stopped_probe- else None- )- claim_source = "db" if isinstance(claimed_outline, dict) else ""- if not isinstance(claimed_outline, dict):- # 修复5:缓存兜底仅在 DB 确认存在 outline_interaction 可恢复中断- # 时启用(probe 命中但快照缺 outline_json 的场景)。probe 未命中- # (会话已正常完结被清理/快照损坏/不存在)时一律不信内存缓存:- # 事故中 probe=None 却用残留缓存大纲弹卡,用户确认后 resume 无- # 快照可恢复而全新起跑,6 秒崩溃并删除该会话全部数据。- if (- claimed_cid- and probe_node == "outline_interaction"- and not stopped_probe- ):- cached_outline = _get_cached_outline_json(- _get_route(), claimed_cid- )- if isinstance(cached_outline, dict):- claimed_outline = cached_outline- claim_source = "cache"- else:- # 停止快照未被认领(含换主题)时,缓存兜底同样不得复用旧会话- # 大纲,否则会把旧主题的大纲弹给新研究。- claimed_outline = {}- claimed_sections = claimed_outline.get("sections")- if claimed_cid and isinstance(claimed_sections, list) and claimed_sections:- # 认领成功:旧会话已生成大纲且停在大纲确认(DB 快照或其缓存- # 兜底),复用大纲出审阅卡片,跳过 start 重跑;用户答复后从原- # 会话 resume。- outline_text = (- _format_outline_card_markdown(claimed_outline)- or "大纲已生成,请确认是否继续研究。"- )- state = _persist(- context,- state,- "wait_outline",- conversation_id=claimed_cid,- outline_presented=True,- outline_sections=_outline_sections(outline_text),- )- logger.info(- "[deepresearch_execute] claimed interrupted conversation "- "tool_call_id=%s conversation_id=%s node=outline_interaction "- "source=%s",- context.tool_call_id,- claimed_cid,- claim_source or "db",- )- return _result(- "interaction",- state,- interaction=_outline_review_interaction(outline_text),- )+ # 修复8:feedback_handler / outline_interaction 中断快照的重弹卡+ # 逻辑提取为 _replay_interrupt_card(phase=new 与 phase=error 共用)。+ replay = await _replay_interrupt_card(context, state, claimed_cid, probe)+ if replay is not None:+ return replay# A claimed checkpoint returned above. Its original source identities# cannot be reconstructed from today's connections, so keep them empty.if new_workflow and context.mcp_servers:diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/report_bundle.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/report_bundle.pyindex 09af482236..f3c8f1c785 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/report_bundle.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/report_bundle.py@@ -583,7 +583,15 @@ def _rewrite_chart_placeholders(chart_index = {str(item["chart_id"]).strip(): item for item in chart_messages}def _replace(match: re.Match[str]) -> str:- chart_id = _validate_bundle_id(match.group(1), "chart placeholder")+ # 修复1:占位符 ID 由宽松正则([^)]+)捕获,可能含中文、斜杠、+ # 空格等非法字符;不再对它施加 SAFE_BUNDLE_ID_RE 严格校验抛错,+ # 否则报告文本里一个非法占位符就会让整条报告写入链失败。+ # chart_ids 内的 ID 均已在 _validate_resources 过严格校验,非法+ # 占位符 ID 必不在 chart_ids 中,原样保留不会漏替换任何合法图表+ # (与 _rewrite_inference_links 的容错模式同构)。+ chart_id = str(match.group(1)).strip()+ if not chart_id or not SAFE_BUNDLE_ID_RE.fullmatch(chart_id):+ return match.group(0)if chart_id not in chart_ids:return match.group(0)chart_info = chart_index[chart_id]diff --git a/jiuwenswarm/agents/harness/docs/bugfix/B_02_deepresearch-error-phase-resume-and-report-tolerance.md b/jiuwenswarm/agents/harness/docs/bugfix/B_02_deepresearch-error-phase-resume-and-report-tolerance.mdnew file mode 100644index 0000000000..ef0001fe3c--- /dev/null+++ b/jiuwenswarm/agents/harness/docs/bugfix/B_02_deepresearch-error-phase-resume-and-report-tolerance.md@@ -0,0 +1,137 @@+# B_02 — deepsearch 续跑在 error 相位全链路死锁 + chart 占位符严格校验放大报告写入失败++## 元信息++| 项 | 值 |+|---|---|+| 类型 | bugfix |+| 编号 / slug | B_02 / deepresearch-error-phase-resume-and-report-tolerance |+| 关联模块 | `jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py`、`common/tools/deepresearch/execution.py`、`common/tools/deepresearch_plugin/report_bundle.py` |+| 修复日期 | 2026-11-03 |+| 关联 spec | 无(全量 grep `docs/specs/` 实证:修复未触及 S_01~S_21 已归档路径,无需 spec 修订) |+| 关联测试 | `tests/unit_tests/agentserver/test_deepresearch_execute_tool.py`、`tests/unit_tests/agentserver/test_deepresearch_report_bundle.py` |+| 配套修复 | relay-claw `office-claw-skills/deepresearch/scripts/run_deepsearch.py`(自然完成 checkpoint 保留,见 relay-claw `docs/issues/2026-11-03-deepsearch-checkpoint-retention.md`) |++## 复现场景++两起生产事故(用户提供的会话日志摘录,2026-10-26/27,原始日志未留存本地仓库):++**场景A(会话 8c7faba3,2026-10-26)— 自然完成后报告写入失败 → resume 全拒**:+主 run 17.5 分钟自然完成,工具侧写报告文件失败(`report_file_write_failed`),phase 置+error;此后模型所有 resume 尝试因 "no workflow checkpoint exists" 被拒,最终只能+salvage `raw_report.md` 兜底交付。用户视角:研究跑完了,成品报告却没有,且无法通过+对话修复。++**场景B(会话 517dadf3 / b0037703,2026-10-27 双轮)— 交互中断后取消 → 下一轮全量重跑**:+Turn1 在交互中断(等待反馈 / 大纲审阅)时用户取消,phase 被写为 error(覆盖原+wait_* 相位);Turn2 用户再次发起研究,执行链无法从 error 相位认领中断快照,SDK 侧+按全新 run 处理——已有研究成果全部丢弃、从头重跑(两轮各 19.83 / 18.24 分钟白跑,+且丢失上下文)。++触发条件:deepsearch 工作流进入 error 相位后,用户在后续轮次尝试续跑或续交互。++## 根因++error 相位原先是一条"只进不出"的死路,五个环节叠加:++1. **chart 占位符严格校验(场景A 放大器)**:`_rewrite_chart_placeholders._replace`+ 对占位符 ID 调 `_validate_bundle_id`(`SAFE_BUNDLE_ID_RE`),非法即抛+ ValueError——而占位符捕获正则本身是宽松的 `[^)]+`,报告正文里一个含中文/斜杠/+ 空格的占位符就让整条报告写入链失败,把"自然完成"打成 error。+2. **rail 探针门硬要求 stopped**:`_bridge_stale_workflow` 对所有候选 phase 一律要求+ `probe.get("stopped")`;error 相位的探针常是交互中断快照(无 stopped 标志)→+ bridge 全拒 → stale workflow 状态无法桥接进当前轮。+3. **error 终态弹 state**:rail 在 `_persist` 后仅对 model_handoff /+ materials_prepared 保留 state,error 终态一律 pop——error 之后 conversation 上已无+ 状态可供认领。+4. **execution 无 interrupt 认领**:error 相位下只有 stopped 认领(要求探针+ stopped);重弹交互卡的逻辑只存在于 phase=new 分支(约 110 行内联),中断快照无从+ 认领。+5. **判死无回落**:认领全未命中时直接以 error 终态返回,不回落 phase=new、不保留+ conversation_id——后续轮次永远卡在"请重新发起"。++配套根因(场景A "resume 全拒"的直接来源,修复在 relay-claw 侧):openjiuwen+`PersistenceCheckpointer.post_workflow_execute` 的自然完成分支清除 io 侧 workflow+checkpoint 与图侧快照——写报告失败后即便 error 相位想 resume 也无 checkpoint 可用。++## 修复口径++jiuwenswarm 侧三文件,六个改动点:++1. **修复①(report_bundle.py `_rewrite_chart_placeholders`)**:`_replace` 对非法+ 占位符 ID 原样保留(不匹配 `SAFE_BUNDLE_ID_RE` 即返回原文),不再抛错。chart_ids+ 内 ID 均已在 `_validate_resources` 严格校验,非法占位符必不在其中——不漏替换任何+ 合法图表;与 `_rewrite_inference_links` 的容错模式同构。+2. **修复③ 探针门放行(deepresearch_execution_rail.py `_bridge_stale_workflow`)**:+ error 相位候选只要有可恢复 checkpoint(Mapping 探针)即放行(停止快照 ∪ 交互+ 中断快照);in-flight 相位维持原硬要求 stopped 不变。+3. **修复③ error 终态保留 state(deepresearch_execution_rail.py `_persist` 后)**:+ `error_terminal` 与 model_handoff / materials_prepared 同列保留条件,不再 pop。+4. **修复③ interrupt 认领共用化(execution.py `_replay_interrupt_card`,新函数)**:+ 从 phase=new 分支提取——feedback_handler 恢复问题清单出反馈卡(wait_feedback)、+ outline_interaction 重弹大纲审阅卡(wait_outline;DB 快照优先,缓存兜底仅在 DB+ 确认可恢复时启用);phase=new 与 phase=error 两入口共用,原 phase=new 分支约 110+ 行内联逻辑替换为对该函数的调用。+ 检视修复(2026-11-05):feedback 分支的选项生成经 `_guard_user_stop` 包裹后,+ 须对返回值加 `isinstance(options, list)` 守卫——`_guard_user_stop` 正常路径透传+ `list[list[dict]]`,CancelledError 路径返回 `_stopped_result(...)` 的 dict;+ 不加守卫时取消路径的 dict 被按下标访问(`options[index]`)抛 KeyError,stopped+ 终态丢失、退回框架通用 [Interrupted] 分支,违背 `_guard_user_stop` 的停止转译+ 契约。非 list 时直接透传(phase 已回落 new、保留 conversation_id 的可续跑终态)。+5. **修复③ error 相位接入 interrupt 认领(execution.py error 分支)**:stopped 认领+ 未命中后,`_query_matches_stopped_claim` 通过时调 `_replay_interrupt_card`,命中即+ 返回交互结果——场景B 的 Turn2 从中断点继续而非全量重跑。+6. **fix-4c 判死回落(execution.py error 分支末)**:认领全未命中时+ `_persist(context, state, "new", conversation_id=error_cid)` 后再以 error 结果返回+ ——保留 conversation_id、回落 phase=new,防"请重新发起"死锁。++配套修复②(relay-claw 侧 run_deepsearch.py):自然完成后保留 checkpoint(io save ++图侧哨兵终态快照,全新 run 时延迟清除),resume 时 PregelLoop 0 步结束不重跑、工具侧+completed 分支重新写报告文件——解决场景A 的 "no workflow checkpoint exists"。++## 验证++- **jiuwenswarm 定向回归**:`test_deepresearch_execute_tool.py` ++ `test_deepresearch_report_bundle.py` → **182 passed / 4 skipped**(.venv)。+- **新增 / 改写测试**:+ - `test_error_phase_replays_feedback_card_from_interrupt_snapshot` /+ `test_error_phase_replays_outline_card_from_interrupt_snapshot`(新增):error 相位+ 从中断快照重弹反馈卡 / 大纲卡。+ - `test_replay_interrupt_card_cancelled_option_generation_returns_stopped`+ (检视修复新增,2026-11-05):mock `model.invoke` 抛 `asyncio.CancelledError`,+ 断言 `_replay_interrupt_card` 返回 `kind=stopped` 终态(phase 回落 new、保留+ conversation_id)而非抛 KeyError。+ - `test_build_report_bundle_keeps_invalid_chart_placeholder_as_is`(新增,参数化+ `../escape` / `图表一` / `chart a`):非法占位符原样保留 + 同文本内合法图表正常+ 替换落盘。+ - `test_build_report_bundle_cleans_owned_resources_after_rewrite_failure`(改写):+ 原用非法占位符 `../escape` 触发 ValueError——修复①后该注入手段失效(本身即"先红"+ 证据),改用 monkeypatch 注入 rewrite 失败,断言不变。+- **修复②单元级集成验证**(relay-claw 侧,真实 PersistenceCheckpointer + SQLite KV ++ PregelLoop):T0-T9 十场景全 PASS——自然完成保留哨兵终态快照 →+ `validate_interactive_resume` 放行 → PregelLoop 恢复哨兵快照后 0 步结束不重跑 →+ 全新 run 延迟清除等价旧行为 → 非哨兵残留 raise 原错误 / interrupt / exception 分支+ 保持 SDK 原行为 → patch 幂等安装。+- 相关存量测试 37 个(error / bridge / rail / terminal / phase 关键词)全数通过。+- 检视修复回归(2026-11-05):`test_deepresearch_execute_tool.py` ++ `test_skill_required_tool_visibility.py` → **172 passed**(.venv,含取消注入新用例)。++## 防错教训++- 中断 / 错误相位不能是"只进不出"的终态:每个把 phase 写成 error 的入口都要有对应的+ 恢复(认领重弹)或回落(phase=new)路径,否则用户侧表现为死锁("请重新发起")或+ 全量重跑。error 相位的探针门、终态保留、认领链、回落路径四者必须成套设计。+- 对自由文本中的占位符做严格校验 + 抛错,等于把一个格式问题升级成整条交付链失败。+ 正确姿势:宽松捕获 + 命中即替换、未命中原样保留(本例与+ `_rewrite_inference_links` 同构)。+- monkey-patch SDK 内部行为(修复②)必须 fail-open:patch 安装失败 / 执行失败均退化为+ SDK 原行为并记 warning,不阻断研究主流程。++## 遗留与后续++- officeClaw 线上部署需同步本修复(harness 三文件)与 relay-claw 侧 run_deepsearch.py+ 后自然恢复;均为代码侧修复,不依赖线上数据迁移。+- 修复②以 monkey-patch 覆盖 `PersistenceCheckpointer` 的 pre/post_workflow_execute,+ 依赖 openjiuwen 内部属性(`_workflow_storage` / `_graph_state`);openjiuwen 升级若+ 改动这些内部 API,patch 自动退化为原行为(记 warning,仅失去"完成后可 resume"能力)+ ——长期应在 SDK 侧提供官方的"自然完成保留 checkpoint"选项。diff --git a/jiuwenswarm/agents/harness/docs/bugfix/B_03_tools-search-skill-gated-guidance.md b/jiuwenswarm/agents/harness/docs/bugfix/B_03_tools-search-skill-gated-guidance.mdnew file mode 100644index 0000000000..3881c33935--- /dev/null+++ b/jiuwenswarm/agents/harness/docs/bugfix/B_03_tools-search-skill-gated-guidance.md@@ -0,0 +1,116 @@+# B_03 — skill 未激活时 tools_search 无匹配裸文案缺失重载指引,续跑降级到模型研究路径++## 元信息++| 项 | 值 |+|---|---|+| 类型 | bugfix |+| 编号 / slug | B_03 / tools-search-skill-gated-guidance |+| 关联模块 | `jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py` |+| 修复日期 | 2026-11-04 |+| 关联 spec | 无(全量 grep `docs/specs/` 实证:progressive tool rail 的 deferred 可见性与 required_skill 门控不在 S_01~S_21 已归档域内,无需 spec 修订) |+| 关联测试 | `tests/unit_tests/agentserver/test_skill_required_tool_visibility.py` |+| 配套修复 | HANDOVER `deepsearch skill_tool 口径统一` 线 fix-e;fix-a/b/c/d 为前置系列(invoke_tool 门控拒绝文案 / SKILL.md 指引等,见仓库根 `HANDOVER_deepsearch_skill_tool口径统一.md`) |++## 复现场景++officeClaw 部署环境 DeepResearch 中断续跑(full.log,进程 5556,2026-11-04):++1. 09:52:08 会话中断,stopped 转译生效;同刻 skill 激活态重置(可见工具 121→14)。+2. 09:52:09 用户「继续」;模型为找回 deepresearch_execute 调+ `tools_search(tool_name="deepresearch_execute")`。+3. skill 未激活 → deferred 搜索缓存被过滤 → 无匹配,返回裸文案+ 「未找到名为 'deepresearch_execute' 的按需可见工具,请检查名称是否与导航列表一致。」+ ——无任何 skill_tool 重载指引。+4. 模型挣扎 45 秒(上下文压着引擎历史失败记忆 212000/211901 与上一轮助手+ 「方案 2 手动研究」),09:53:35 todo create 分解手工研究任务,降级到模型+ 研究路径——已部署的 DeepResearch 能力被绕过。++触发条件:会话中断 / 闲置过期 / 会话切换导致 skill 未激活后,模型在续跑轮次+通过 tools_search 找回门控工具。++## 根因++skill_tool 口径统一线的收尾缺口——三条信号通道只堵了两条:++1. **tools_search 无匹配文案无重载指引**(本修复):skill 未激活时+ `_refresh_deferred_tool_cache` 的过滤条件把 declared(声明 required_skill)+ 工具排除在 deferred 搜索列表外,tools_search 必然无匹配;最终 return 的+ else 分支只提示「检查名称是否与导航列表一致」,模型无从得知该走+ skill_tool 重载。+2. **invoke_tool 拒绝文案已修(fix-b)但不可达**:拒绝分支已带重载指引,但+ 工具不在 function definitions 里,模型在续跑场景不会发起 invoke_tool。+3. **SKILL.md 指引是死路径**:触发条件写「若 deepresearch_execute **返回**+ 工具不可用」,而工具不可见时该返回永不出现。++三通道中 tools_search 是续跑场景模型唯一会真实触发的信号入口;该入口缺失+重载指引时,模型在记忆压秤(引擎历史失败)下选择降级。++## 修复口径++`progressive_tool_rail.py` `_search_tools` 最终 return 前(dead-instance 分支+之后)插入反查逻辑,复用 invoke_tool declared 分支(fix-b)已验证的模式:++1. 无匹配时反查全量注册表:`_cached_all_tool_infos`(unfiltered,skill 未+ 激活时门控工具卡片仍在其中)。`_cached_deferred_tool_infos` 恒为它的+ 过滤子集(同函数内成对构建),无需二次兜底查找。+2. `_required_skill_requirement` 提取 required_skill,命中有效值即返回对齐+ fix-b 口径的重载指引:点明工具属于哪个技能、泛化重置成因(技能可能因+ 闲置过期或会话切换而未激活)、给出明确调用方式+ `skill_tool(skill_name="<skill>")`、明示「这属于技能未激活,不代表能力+ 不可用,不要据此降级或改用其他工具绕过」。+3. 普通工具(反查无 required_skill、或 declared 但值为 malformed)保持原+ 通用文案不变——零行为变化,fail-safe 到现状(`_required_skill_requirement`+ 对 None 输入安全返回 `(False, None)`)。++检视修复(2026-11-05):required_skill 命中后须先比对激活态再下结论——+`_refresh_deferred_tool_cache` 对 declared 卡片无条件排除(不区分激活态),技能+已激活时延迟缓存同样 0 命中,反查全量注册表命中 required_skill 后若直接断言+「技能未激活」与事实相反,会诱导模型对已激活技能重复执行 skill_tool 重载(若+重载有副作用还会打断进行中的研究上下文)。修复:命中 required_skill 后比对+`_current_active_skill()`,已激活时返回「工具已随技能激活并直接可见,请直接调用,+无需 tools_search」;未激活才保留原重载指引。disabled 前置检查在前(「已禁用」+文案不进反查分支),不受影响。++## 验证++- **新增测试**(`test_skill_required_tool_visibility.py`,门控行为专属文件):+ - `test_inactive_skill_search_returns_skill_reload_guidance`:用+ deepresearch_execute 真名复现线上故障——skill 未激活时 tools_search 断言+ 返回含 `skill_name="deepresearch"` 与「不要据此降级」的重载指引,而非+ 裸「未找到」。+ - `test_ordinary_missing_tool_search_keeps_generic_message`:非门控工具+ 无匹配保持通用文案,不误报技能重载指引。+ - `test_active_skill_search_reports_direct_visibility_without_reload`+ (检视修复新增,2026-11-05):`active_skill_provider` 返回激活技能名时,+ tools_search 命中该技能门控工具返回「已随技能激活并直接可见」的直接调用+ 提示,文案不含 skill_tool 重载指令——激活态不再误报「技能未激活」。+- **fail-safe 既有覆盖**:`test_invalid_required_skill_fails_closed_everywhere`+ 参数化组(None / "" / 42 / 路径穿越等)——malformed required_skill 反查得+ None 落回通用文案。+- **回归**:`test_skill_required_tool_visibility.py` 30 passed;progressive+ rail 相关六文件(code_adapter / disabled_filter / deepresearch_context /+ prefix_cache / stale_id / inherit_flag)156 passed;+ `test_request_scoped_office_claw_mcp.py` + `test_deepresearch_execute_tool.py`+ 225 passed(含「tools_search 0 matches 后 LLM 回退 web_search」既有场景,+ 确认不误伤)。合计 411 passed / 0 failed(.venv)。+- **检视修复回归**(2026-11-05):`test_skill_required_tool_visibility.py` ++ `test_deepresearch_execute_tool.py` → **172 passed**(.venv,含激活态新用例;+ 未激活用例断言保持不变)。++## 防错教训++- 面向模型的错误文案是行为契约的一部分:同一事实(技能未激活)在多条信号+ 通道(tools_search / invoke_tool / SKILL.md)上的口径必须统一——任何一条+ 通道缺失重载指引,都可能让模型在记忆偏差压秤下选择降级路径。+- 文档指引的触发条件必须对应真实可达的信号:SKILL.md 写「若工具返回不可用」+ 但工具不可见时该返回永不出现,等于把指引写在死路径上。+- 「搜索无匹配」不等于「能力不存在」:反查 unfiltered 全量注册表可区分+ 「技能未激活」与「真未注册」两种无匹配,前者的正确响应是重载而非降级。++## 遗留与后续++- officeClaw 线上部署需同步 harness 侧 `progressive_tool_rail.py` 后自然恢复;+ 纯文案补齐,不依赖线上数据迁移。+- fix-e 落地后 skill_tool 口径统一线(fix-a/b/c/d/e)在 jiuwenswarm 侧收口;+ 线上验证需在中断续跑场景观察模型收到重载指引后是否走 skill_tool 而非降级。diff --git a/jiuwenswarm/agents/harness/docs/bugfix/B_04_stopped-copy-triple-defense.md b/jiuwenswarm/agents/harness/docs/bugfix/B_04_stopped-copy-triple-defense.mdnew file mode 100644index 0000000000..63bd327788--- /dev/null+++ b/jiuwenswarm/agents/harness/docs/bugfix/B_04_stopped-copy-triple-defense.md@@ -0,0 +1,100 @@+# B_04 — 排队晚达的「继续」被误读为采纳备选方案,stopped 终态文案三重防御补强++## 元信息++| 项 | 值 |+|---|---|+| 类型 | bugfix |+| 编号 / slug | B_04 / stopped-copy-triple-defense |+| 关联模块 | `jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py`、`common/rails/deepresearch_execution_rail.py` |+| 修复日期 | 2026-11-05 |+| 关联 spec | 无(面向模型的终态文案补强,未触及 S_01~S_21 已归档路径 / 不变量) |+| 关联测试 | `tests/unit_tests/agentserver/test_deepresearch_execute_tool.py` |+| 配套修复 | skill_tool 口径统一线 fix-c(stopped 双指引统一)的线上验证补强;fix-e 见 [[B_03]],error 相位续跑见 [[B_02]],线路全貌见仓库根 `HANDOVER_deepsearch_skill_tool口径统一.md` |++## 复现场景++officeClaw 部署环境(full.log,2026-11-05,conversation `9973ed6e`)——fix-c 新版+stopped 文案**已部署且被模型收到**的条件下,续跑指令仍被误读:++1. 10:42:44 全新 DeepResearch 启动(修复后链路正常,claim probe=none)。+2. 10:44:26 outline HITL 中断 → 10:44:29 用户答复续跑(interrupt 认领链验证通过)。+3. 10:45:38 用户停止;**10:45:41 用户发「继续」**(停止动作后 3 秒)。+4. 10:46:08 graceful 30s 超时 → 10:46:10 stopped 转译(fix-c 文案生效)。+5. 10:46:36.9 停止当轮 assistant 回复——**完全遵守文案**:未自主重启,汇报停止+ 状态并提供两方案(1 恢复专用引擎 / 2 模型直接研究)。+6. **10:46:37 排队 55s 的「继续」才投递**——追加在两方案回复之后(消息信封+ timestamp 仍为 10:45:41)。+7. Turn 3 模型 reasoning:「[助手]提供了两个方案,用户回复"继续"」→ 解读为+ 采纳方案 → 转走模型自主研究路径,重新规划研究任务。++停止快照完好(skill 侧 `checkpointer.db` 该会话 8 个 key 全部保留,agent-core /+deepsearch 停止保留修复在位)——**非链路故障,是模型对续跑指令的解读错误**。++## 根因++**主因(adapter 消息排队时序颠倒,不在本仓控制)**:officeclaw adapter 在+in-flight turn 期间把到达的用户消息排队,当轮 assistant 回复生成后才投递——+真实因果序(用户发送时刻)与呈现序(模型看到的顺序)被破坏。「继续」+(10:45:41)比两方案回复(10:46:36.9)早 55 秒,但呈现顺序相反,模型按呈现+顺序把「继续」当成了对两方案的答复。++**文案失守模式(本仓可修,三个)**:++1. **F1 停止来源误判**:模型 reasoning 出现「This is confusing... system timeout /+ pre-existing state」——文案未定性停止来源,模型自行猜测为系统故障或会话残留。+2. **F2 「继续」被备选方案劫持**:文案只约束「仅当用户明确要求继续」,未定义+ 「继续」「继续研究」这类短语即属明确要求,也未声明其优先级高于模型自拟的+ 备选方案——模型提供了两方案后,任何后续用户短语都倾向被解读为方案选择。+3. **F3 历史失败记忆绕过**:模型引用记忆中的引擎失败错误码(211901 / 212000)+ 认定引擎不稳定而绕过——文案未禁止凭历史记忆降级。++## 修复口径++stopped 终态文案两处落点(`execution.py` `_stopped_result` content 与+`deepresearch_execution_rail.py` stopped 改写 content——fix-c 已确立两处同步+契约)同步新增三重防御;原契约条款(禁止自主重启 / skill_tool 重载指引 /+content 不含 conversation_id)不变:++1. **停止定性(封 F1 + F3)**:「停止是用户的主动操作,不代表系统故障、超时或+ 会话残留,也不要因记忆中该主题曾有失败记录而绕过本工具」。+2. **「继续」优先级(封 F2)**:「用户回复"继续""继续研究"即属明确要求继续:+ 即使你曾向用户提供过备选方案,也应优先按上述方式续跑,而非将其理解为采纳+ 备选方案或改走模型自主研究路径」。+3. **timestamp 时序意识(针对主因的通用防御)**:「另注意用户消息信封自带+ timestamp,晚于你最近一条回复到达的消息未必是对该回复的回应,解读用户意图+ 前先核对消息时序」。消息信封构建方在 adapter 仓(全仓 grep 实证),在排队+ 消息的 supplementary_info 附时序说明超出本仓控制,只能以提示词侧补偿。++## 验证++- **定向回归**:`test_deepresearch_execute_tool.py` → **141 passed**(.venv)。+- **新增断言(两处)**:+ - `test_cancelled_during_sdk_window_translates_to_stopped_without_error_overwrite`:+ result content 断言含「停止是用户的主动操作」「失败记录」「备选方案」+ 「timestamp」。+ - `test_execution_rail_rewrites_stopped_result_to_block_auto_restart`:rail+ 改写 content 同步断言三重防御关键词——两处口径一致性被测试锁定。+- **既有断言不变**:无 conversation_id、无邀请式旧文案、「请勿」「明确要求继续」+ 在位。++## 防错教训++- 面向模型的终态文案不仅要约束「能否重调」,还要约束「如何解读停止之后的用户+ 消息」——用户在停止后的下一个短语(继续 / 重启 / 算了)是意图路由的关键输入;+ 文案不定义其归属时,模型会按消息呈现顺序自行猜测。+- 消息系统的因果序(发送时刻)与呈现序(模型看到的顺序)可能不一致:排队 /+ 重试 / 多端同步都会颠倒两者;提示词侧要求模型核对信封 timestamp 是低成本+ 通用补偿。+- 修复文案的线上验证要看「模型收到后的**下一轮**行为」,不能只看当轮是否遵守+ ——本次当轮完全遵守(未自主重启、汇报 + 给方案),下一轮仍因误读「继续」失守。++## 遗留与后续++- adapter 排队投递机制(时序颠倒主因)不在本仓控制;长期方向为收窄版 A——停止+ 终态专用窗口的 pending 消息查询(通用消息注入方案已评估消息丢失 / HITL 路由+ 冲突 / 跨仓改造 / 注入竞态 / 意图绑定五大风险后否决)。+- 线上部署同步本补强后,需在「停止 + 立即『继续』」场景复验:模型应直接+ skill_tool 重载 + `deepresearch_execute` 认领快照续跑,而非解读备选方案。+- 本次 9973ed6e 会话未触发 tools_search(模型凭 reasoning 直接决策),+ [[B_03]](fix-e)生效性仍待后续线上验证。diff --git a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.pyindex d636a3406d..5cb1d886e3 100644--- a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py+++ b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py@@ -1406,6 +1406,35 @@ async def test_option_generation_preserves_model_defaults_and_completion_budget(assert "不得输出分析或推理过程" in prompt+async def test_replay_interrupt_card_cancelled_option_generation_returns_stopped():+ """选项生成 await 点被取消时,重弹路径透传 stopped 终态而不是抛 KeyError。++ 回归检视意见:_guard_user_stop 取消路径返回 _stopped_result 的 dict+ (kind=stopped),修复前 _replay_interrupt_card 直接按 options[index]+ 构造交互卡,dict 无整数键抛 KeyError,stopped 转译失效退回框架通用+ [Interrupted] 分支。phase=new 与 phase=error 两个重弹入口共用本路径。+ """+ model = _Model(_option_payload("方向A"))+ model.invoke = AsyncMock(side_effect=asyncio.CancelledError())+ context = de.DeepResearchExecutionContext(+ tool_call_id="call-1",+ state=None,+ user_input=None,+ model=model,+ agent_id="jiuwenswarm",+ save_state=lambda _value: None,+ )+ state = {"query": "研究智能家电竞争格局", "conversation_id": "conv-stop-1"}+ probe = {"node": "feedback_handler", "questions": ["重点研究哪些品类?"]}++ result = await de._replay_interrupt_card(context, state, "conv-stop-1", probe)++ assert isinstance(result, dict)+ assert result["kind"] == "stopped"+ assert "已被用户停止" in str(result["content"])++def test_option_description_is_truncated_without_rejecting_valid_options():payload = json.dumps({@@ -1946,6 +1975,13 @@ async def test_cancelled_during_sdk_window_translates_to_stopped_without_error_oassert "明确要求继续" in result["content"]assert "如需继续,请再次调用" not in result["content"]assert "conversation-1" not in result["content"]+ # 2026-11-05 B+ 补强(9973ed6e 线上事故回归):停止定性为用户+ # 主动行为(防猜测故障/因历史失败绕过)、“继续”优先于备选方案+ # 解读、消息信封 timestamp 时序意识三重防御须在文案在位。+ assert "停止是用户的主动操作" in result["content"]+ assert "失败记录" in result["content"]+ assert "备选方案" in result["content"]+ assert "timestamp" in result["content"]@pytest.mark.asyncio@@ -2063,11 +2099,97 @@ async def test_error_phase_without_stopped_snapshot_reports_finished():patch.object(de, "_probe_resumable_checkpoint", new=Mock(return_value=None)),patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,):- result, _ = await _invoke(state=state)+ result, saved = await _invoke(state=state)assert result["kind"] == "error"assert "请重新发起" in result["content"]stream.assert_not_awaited()+ # fix-4c:判死回落 new(参照 _stopped_result)。rail 对 error 终态保留+ # state 后,phase=error 幸存会让同主题的重新发起被反复判死(死锁);+ # 回落 new 保留 conversation_id,下一次调用走 new 分支扫库认领或全新+ # 起跑,重新发起可自愈。+ assert saved[-1]["phase"] == "new"+ assert saved[-1]["conversation_id"] == "conversation-1"+++async def test_error_phase_replays_feedback_card_from_interrupt_snapshot():+ """修复8:error 相位 + feedback_handler 中断快照 → 重弹原反馈卡。++ error 写入可能覆盖原 wait_feedback 相位(子进程失败退出),+ checkpoint 残留的是交互中断快照:不判死,重弹原反馈卡,+ 用户答复后从原会话 resume,交互上下文不丢。+ """+ state = {+ "schema_version": 1,+ "phase": "error",+ "revision": 4,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "C-FB-E",+ }+ probe = {+ "node": "feedback_handler",+ "questions": ["1. 重点研究哪些品类?", "2. 覆盖哪些市场?"],+ }+ model = _Model(_option_payload("重点研究哪些品类?", "覆盖哪些市场?"))+ with (+ patch.object(de, "_probe_resumable_checkpoint", new=Mock(return_value=probe)),+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, saved = await _invoke(state=state, model=model)++ stream.assert_not_awaited()+ assert result["kind"] == "interaction"+ cards = result["interaction"]["questions"]+ assert [card["question"] for card in cards] == [+ "重点研究哪些品类?",+ "覆盖哪些市场?",+ ]+ assert all(len(card["options"]) == 2 for card in cards)+ final = saved[-1]+ assert final["phase"] == "wait_feedback"+ assert final["conversation_id"] == "C-FB-E"+ # 与 new 相位认领同口径:probe 问题经 _split_questions 剥掉编号后入 state。+ assert final["questions"] == ["重点研究哪些品类?", "覆盖哪些市场?"]+++async def test_error_phase_replays_outline_card_from_interrupt_snapshot():+ """修复8:error 相位 + outline_interaction 中断快照 → 重弹大纲审阅卡。"""+ state = {+ "schema_version": 1,+ "phase": "error",+ "revision": 4,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "C-OL-E",+ }+ probe = {+ "node": "outline_interaction",+ "outline_json": {+ "title": "智能家电竞争格局研究",+ "thought": "先规模后玩家",+ "sections": [+ {"title": "市场规模", "is_core_section": True},+ {"title": "主要玩家", "is_core_section": False},+ ],+ },+ }+ with (+ patch.object(de, "_probe_resumable_checkpoint", new=Mock(return_value=probe)),+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, saved = await _invoke(state=state)++ stream.assert_not_awaited()+ assert result["kind"] == "interaction"+ final = saved[-1]+ assert final["phase"] == "wait_outline"+ assert final["conversation_id"] == "C-OL-E"+ assert final["outline_presented"] is True+ question = result["interaction"]["questions"][0]+ assert "**研究思路**:先规模后玩家" in question["preview"]["text"]@pytest.mark.asyncio@@ -2335,6 +2457,12 @@ async def test_execution_rail_rewrites_stopped_result_to_block_auto_restart():assert ctx.inputs.tool_msg.tool_call_id == "call-1"assert "已被用户停止" in ctx.inputs.tool_msg.contentassert "请勿" in ctx.inputs.tool_msg.content+ # 2026-11-05 B+ 补强(9973ed6e 线上事故回归):rail 改写口径与+ # execution._stopped_result 同步——停止定性、备选方案优先级、+ # timestamp 时序意识三重防御在位。+ assert "停止是用户的主动操作" in ctx.inputs.tool_msg.content+ assert "备选方案" in ctx.inputs.tool_msg.content+ assert "timestamp" in ctx.inputs.tool_msg.content# conversation_id 与内部 state 字段不泄露进 LLM 历史assert "conversation-1" not in ctx.inputs.tool_msg.contentassert "schema_version" not in ctx.inputs.tool_msg.contentdiff --git a/tests/unit_tests/agentserver/test_deepresearch_report_bundle.py b/tests/unit_tests/agentserver/test_deepresearch_report_bundle.pyindex 89c613afd5..e04d8654a2 100644--- a/tests/unit_tests/agentserver/test_deepresearch_report_bundle.py+++ b/tests/unit_tests/agentserver/test_deepresearch_report_bundle.py@@ -295,13 +295,19 @@ def test_build_report_bundle_cleans_only_owned_resources_after_publication_failuassert not (chart_dir / "second.png").exists()-def test_build_report_bundle_cleans_owned_resources_after_rewrite_failure(tmp_path):+def test_build_report_bundle_cleans_owned_resources_after_rewrite_failure(+ tmp_path, monkeypatch+):report_base = tmp_path / "report-v1"- with pytest.raises(ValueError):+ def fail_rewrite(*args, **kwargs):+ raise ValueError("injected chart rewrite failure")++ monkeypatch.setattr(bundle_module, "_rewrite_chart_placeholders", fail_rewrite)+ with pytest.raises(ValueError, match="injected chart rewrite failure"):build_report_bundle(_payload(- response_content="(#insertChart:../escape)",+ response_content="(#insertChart:chart-a)",chart_messages=[_chart("chart-a")],),report_base,@@ -310,6 +316,25 @@ def test_build_report_bundle_cleans_owned_resources_after_rewrite_failure(tmp_paassert not (tmp_path / "report-v1_charts").exists()[email protected]("placeholder_id", ["../escape", "图表一", "chart a"])+def test_build_report_bundle_keeps_invalid_chart_placeholder_as_is(+ tmp_path, placeholder_id+):+ bundle = build_report_bundle(+ _payload(+ response_content=(+ f"(#insertChart:{placeholder_id})\n(#insertChart:chart-a)"+ ),+ chart_messages=[_chart("chart-a")],+ ),+ tmp_path / "report-v1",+ )++ assert f"(#insertChart:{placeholder_id})" in bundle.markdown_text+ assert "" in bundle.markdown_text+ assert (tmp_path / "report-v1_charts" / "chart-a.png").exists()++@pytest.mark.skipif(os.name == "nt", reason="POSIX directory descriptor contract")diff --git a/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py b/tests/unit_tests/agentserver/test_skill_required_tool_visibility.pyindex 6e4a9861ab..3426f5dc49 100644--- a/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py+++ b/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py@@ -358,6 +358,95 @@ async def test_other_skill_and_disabled_override_keep_gated_tool_hidden() -> Nonassert disabled_ctx.inputs.tools == []+async def test_inactive_skill_search_returns_skill_reload_guidance() -> None:+ """tools_search 无匹配且命中门控卡片时返回 skill_tool 重载指引。++ 回归续跑降级缺口:skill 未激活(会话中断重置/闲置过期)时+ deferred 搜索缓存被过滤,tools_search 只返回裸「未找到」,+ 模型缺乏重载指引而降级到非技能路径。修复后反查全量注册表+ 命中 required_skill 卡片,返回与 invoke_tool 门控拒绝分支一致+ 的重载口径。+ """+ cards = [deepresearch_execute.card, _card("ordinary_deferred")]+ agent = _agent(cards)+ rail = ProgressiveToolRail(+ eager_tools=["read_file"],+ active_skill_provider=lambda: None,+ )+ rail.init(agent)+ ctx = _model_ctx(agent, cards)+ await rail.before_model_call(ctx)++ result = await rail._search_tools(+ None,+ ToolsSearchInput(tool_name="deepresearch_execute"),+ )++ assert result["success"] is False+ assert result["matches"] == []+ message = str(result["message"])+ assert 'skill_name="deepresearch"' in message+ assert "不要据此降级" in message+++async def test_active_skill_search_reports_direct_visibility_without_reload() -> None:+ """技能激活态下 tools_search 命中门控工具不再误报「技能未激活」。++ 回归检视意见:declared 卡片被 _deferred_tools 无条件排除,激活态下+ deferred 搜索同样 0 命中;修复前反查全量注册表命中 required_skill 后+ 无条件返回 skill_tool 重载指引,诱导模型对已激活技能重复重载。修复后+ 先比对当前激活技能:已激活提示直接调用,未激活才给重载指引。+ """+ cards = [deepresearch_execute.card, _card("ordinary_deferred")]+ agent = _agent(cards)+ rail = ProgressiveToolRail(+ eager_tools=["read_file"],+ active_skill_provider=lambda: "deepresearch",+ )+ rail.init(agent)+ ctx = _model_ctx(agent, cards)+ await rail.before_model_call(ctx)++ result = await rail._search_tools(+ None,+ ToolsSearchInput(tool_name="deepresearch_execute"),+ )++ assert result["success"] is False+ assert result["matches"] == []+ message = str(result["message"])+ assert "已随技能 'deepresearch' 激活并直接可见" in message+ assert "直接调用" in message+ assert "skill_tool" not in message+++async def test_ordinary_missing_tool_search_keeps_generic_message() -> None:+ """非门控工具的无匹配保持通用文案,不误报技能重载指引。"""+ ordinary = _card("ordinary_deferred")+ agent = _agent([ordinary])+ rail = ProgressiveToolRail(+ eager_tools=["read_file"],+ active_skill_provider=lambda: None,+ )+ rail.init(agent)+ ctx = _model_ctx(agent, [ordinary])+ await rail.before_model_call(ctx)++ result = await rail._search_tools(+ None,+ ToolsSearchInput(tool_name="missing_ordinary"),+ )++ assert result["success"] is False+ assert result["matches"] == []+ message = str(result["message"])+ assert "skill_tool" not in message+ assert "未找到" in message++@pytest.mark.asyncioasync def test_required_skill_card_in_place_update_invalidates_deferred_cache() -> None:active_skill = {"name": "research-skill"}