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(todo): 任务段未关闭时先补 todo_modify,再发纯文本收尾

n993577028536a4d0508f6
diff --git a/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py
index b5ba6a9b84..5fa3ee6758 100644
--- a/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py
@@ -45,10 +45,11 @@ _CN_PROTOCOL = """## 技能执行规范(强制)
- **更新时搭便车(强制)**:`todo_modify` **必须**和下一个任务的工作工具在同一轮发出,禁止 `todo_modify` 独占一轮。系统会在工作工具被调用时自动将 pending 推进为 in_progress,你只需要用 `todo_modify` 标记 completed/cancelled。
- ✅ 正确:`[write_file(...), todo_modify(action="update", todos=[{"id":"step1","status":"completed"}])]`
- ❌ 禁止:`[todo_modify(action="update", todos=[{"id":"step1","status":"completed"}])]` ← 独占一轮,浪费 LLM 调用
- - 唯一例外:所有工作完成后、即将给出最终回复的最后一轮,可以单独调 `todo_modify`。
+ - 唯一例外:纯文本最终回复的前一轮。若仍有 `in_progress`,这一轮必须单独调 `todo_modify`,不要在这一轮写给用户的正文。
+ - 判定粒度是**这一条步骤**是否做完,不是整个任务是否交付。已做完的标 `completed`;还没开始的保持 `pending`;只有整件事确定不再继续(含第 9 条的用户打断)才标 `cancelled`。缺文件、跳过问答、等待用户补输入,都不是把已做完步骤留在 `in_progress` 的理由。
- 可在连续推进多个任务后用一次 `todo_modify` 统一批量更新状态。
放弃、跳过或决定不再执行某步骤时(如用户说「不生成 PPT 了」),**必须**立即 `todo_modify` 将该条标为 `cancelled`;
- 禁止仅用口头回复收尾而仍保留 `in_progress`/`pending` 项。
+ 禁止仅用口头回复收尾而仍保留已开始的 `in_progress` 项。还没开始的 `pending` 在等待用户补输入时保持 `pending`。
3. **严格顺序**:按 SKILL.md 定义的顺序逐步执行,**禁止跳过、合并或重排步骤**,除非 SKILL.md 或用户明确允许。
4. **闸门等待**:遇到需要用户确认/审批的步骤时,**必须等待用户回复,禁止自行假设用户同意**。
5. **不确定时重读**:只能再次调用 `skill_tool`,**不得**用其它工具获取 SKILL.md。
@@ -85,11 +86,12 @@ Then execute the workflow; the rules below govern execution.
- **Piggyback on updates (MANDATORY)**: `todo_modify` **MUST** be called alongside the next task's work tool in the same response — never alone. The system auto-advances pending tasks to in_progress when work tools are called, so you only need `todo_modify` to mark tasks completed/cancelled.
- ✅ CORRECT: `[write_file(...), todo_modify(action="update", todos=[{"id":"step1","status":"completed"}])]`
- ❌ PROHIBITED: `[todo_modify(action="update", todos=[{"id":"step1","status":"completed"}])]` ← wastes an entire LLM round
- - The ONLY exception: the very final round when all work is done and you are about to give the final answer.
+ - The ONLY exception: the turn immediately before the plain-text final reply. If any item is still `in_progress`, that turn MUST call `todo_modify` alone and must not contain the user-facing answer.
+ - Judge each step on its own, not on whether the whole task is delivered. Mark a finished step `completed`; leave steps that have not started `pending`; mark `cancelled` only when the whole task will not continue, including the user-interruption cases in rule 9. Missing files, a skipped question, or waiting for input are not reasons to leave a finished step `in_progress`.
- You may run several tasks back-to-back and update statuses in a single batched `todo_modify`.
When abandoning or skipping a step (e.g. the user says not to generate the PPT), you **must** call
- `todo_modify` to mark it `cancelled` immediately; never end with text only while items stay
- `in_progress` or `pending`.
+ `todo_modify` to mark it `cancelled` immediately; never end with text only while a started item
+ stays `in_progress`. Leave not-yet-started `pending` items `pending` while waiting for the user.
3. **Strict order**: Execute steps in the order defined by SKILL.md. **Do not skip, merge, or reorder steps** unless SKILL.md or the user explicitly allows it.
4. **Gate enforcement**: When a step requires user confirmation/approval, **you MUST wait for the user's response. Never assume approval.**
5. **Re-read when unsure**: Refresh the SKILL.md body **only** by calling `skill_tool` again — **never** use any other tool to obtain SKILL.md.
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index d8ac19ef03..835e17bf98 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -56,6 +56,7 @@ from jiuwenswarm.agents.harness.common.rails.read_file_validation import (
)
from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (
SKILL_TURBO_OUTER_TODO_ACTIVE_EXTRA_KEY,
+ is_todo_close_nudge,
)
from jiuwenswarm.agents.harness.common.tools.todo_resume import (
filter_todos_for_display,
@@ -1231,7 +1232,7 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
tool_name == "skill_acceleration_exec"
and extra.get(RESUME_USER_INPUT_KEY) is not None
)
- if not skip_resume_tool_call:
+ if not skip_resume_tool_call and not is_todo_close_nudge(tc):
await self._emit_tool_call(session, tc, model_display_name=model_display)
if not ctx.extra.get("_skip_tool"):
await self._emit_tool_update(session, tc, status="in_progress")
@@ -1410,6 +1411,8 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
and _extract_tool_interrupt(ctx.inputs.tool_result) is not None
):
return
+ if is_todo_close_nudge(tc):
+ return
normalize_read_file_tool_outcome(ctx)
self._annotate_whitespace_path_fix(ctx)
diff --git a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
index faf4682b7a..83d10d9bf6 100644
--- a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
@@ -16,12 +16,13 @@ import re
import stat
import threading
import time
+import uuid
from contextvars import ContextVar
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal, NamedTuple
-from openjiuwen.core.foundation.llm import ToolMessage
+from openjiuwen.core.foundation.llm import ToolCall, ToolMessage
from openjiuwen.core.session.agent import Session
from openjiuwen.core.session.stream import OutputSchema
from openjiuwen.core.single_agent.rail.base import (
@@ -49,6 +50,17 @@ _ACTIVE_TASK_ID: ContextVar[str | None] = ContextVar(
SKILL_TURBO_OUTER_TODO_ACTIVE_EXTRA_KEY = (
"_jiuwenswarm_skill_turbo_outer_todo_active"
)
+# 纯文本收尾前插入的一次调用。名字用已注册的 todo_modify,避免下一轮
+# 请求里出现未注册工具名被模型接口拒绝。id 前缀把它和真改状态分开:
+# 不执行、不改 todo.json、不向前端发工具卡片,只回一条要求模型自己改状态的说明。
+TODO_CLOSE_NUDGE_ID_PREFIX = "todo-close-nudge-"
+TODO_CLOSE_NUDGE_TOOL_NAME = "todo_modify"
+
+
+def is_todo_close_nudge(tool_call: Any) -> bool:
+ """True when this call is the internal close nudge, not a real todo_modify."""
+ tool_call_id = str(getattr(tool_call, "id", "") or "")
+ return tool_call_id.startswith(TODO_CLOSE_NUDGE_ID_PREFIX)
def get_current_task_id() -> str | None:
@@ -56,6 +68,45 @@ def get_current_task_id() -> str | None:
return _ACTIVE_TASK_ID.get()
+def _todo_close_nudge_message(
+ open_tasks: list[tuple[str, dict[str, Any]]],
+) -> str:
+ """Tell the model to close started todos before the plain-text final.
+
+ task.complete is emitted only after todo_modify sets status to completed.
+ A text-only turn while a started item is still in_progress leaves the
+ frontend task segment open, so the stop explanation stays inside it.
+ """
+ lines = [
+ (
+ "[TODO_CLOSE_REQUIRED] 纯文本收尾被拦住:已开始的待办仍是 "
+ "in_progress,task.complete 还没发出。本轮只调用 todo_modify,"
+ "不要写给用户的正文。"
+ ),
+ "规则:",
+ (
+ "- 这一条步骤的工作已经做完就标 completed,即使后面的步骤被缺文件、"
+ "用户跳过或等待输入卡住。"
+ ),
+ "- 还没开始的保持 pending。",
+ "- 这一条自己的工作还没做完,不要标 completed。",
+ (
+ "- 只有整件事确定不再继续才标 cancelled"
+ "(含技能协议第 9 条的用户打断)。跳过问答、等待补文件都不是放弃。"
+ ),
+ (
+ "上一轮已经写出的正文没有送达用户,视为作废。"
+ "todo_modify 返回后,下一轮必须完整重写最终回复,"
+ "禁止用「如上所述」概括或引用上一轮。"
+ ),
+ "当前已开始且仍 in_progress:",
+ ]
+ for raw_id, task in open_tasks:
+ content = str(task.get("content", "")).replace("\n", " ")
+ lines.append(f"- id={raw_id} content={content}")
+ return "\n".join(lines)
+
+
# 图像产物扩展名白名单
_IMAGE_ARTIFACT_EXTENSIONS = frozenset({
".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg",
@@ -1318,6 +1369,9 @@ class TaskExecutionRail(DeepAgentRail):
# 暂不发 task.start/complete,等前缀完成后按列表顺序补发。
self._todo_complete_deferred: set[str] = set()
self._todo_start_deferred: set[str] = set()
+ # 同一次 invoke 只拦一次纯文本收尾。模型仍不改状态就放行,
+ # 不伪造 completed,也不把未完成项全部 cancelled。
+ self._todo_close_nudge_used: bool = False
def set_skill_turbo_request_metadata(self, metadata: dict | None) -> None:
"""注入当前请求 metadata 副本,供 before_tool_call 解析请求级工作区。"""
@@ -1403,6 +1457,7 @@ class TaskExecutionRail(DeepAgentRail):
self._todo_started = set()
self._todo_complete_deferred = set()
self._todo_start_deferred = set()
+ self._todo_close_nudge_used = False
self._tool_start_times = {}
_ACTIVE_TASK_ID.set(None)
if isinstance(ctx.inputs, InvokeInputs):
@@ -1425,11 +1480,108 @@ class TaskExecutionRail(DeepAgentRail):
"""Bind task_id before LLM calls."""
self._bind_context_to_in_progress_task()
+ async def after_model_call(self, ctx: AgentCallbackContext) -> None:
+ """Hold a text-only ending while a started todo is still in_progress.
+
+ The ReAct loop treats a response with no tool calls as the final
+ answer. task.complete is only emitted when todo_modify sets
+ completed, so that answer would stay inside the open task segment.
+ Attach one internal tool call so the loop continues; the tool body
+ is replaced with an instruction to call todo_modify. A second
+ text-only response in the same invoke is left alone.
+
+ Not applied when the model output was truncated (``finish_reason``
+ ``length``): the truncation retry persists this assistant message
+ without a matching tool result. Not applied on the last ReAct
+ iteration, which has no room for the follow-up reply. ``force_finish``
+ paths (deepresearch direct display and similar) never reach this
+ hook and stay on their existing end behavior.
+ """
+ if self._todo_close_nudge_used or ctx.session is None:
+ return
+ response = getattr(ctx.inputs, "response", None)
+ if response is None or getattr(response, "tool_calls", None):
+ return
+ if str(getattr(response, "finish_reason", "") or "") == "length":
+ return
+ if self._is_last_react_iteration(ctx):
+ return
+ content = str(getattr(response, "content", None) or "").strip()
+ if not content:
+ return
+ open_tasks = self._started_in_progress_tasks()
+ if not open_tasks:
+ return
+ # 流式正文已经推给前端。历史里留下这段字会让下一轮当成已经送达。
+ response.content = ""
+ response.tool_calls = [
+ ToolCall(
+ id=f"todo-close-nudge-{uuid.uuid4().hex[:12]}",
+ type="function",
+ name=TODO_CLOSE_NUDGE_TOOL_NAME,
+ arguments="{}",
+ )
+ ]
+ self._todo_close_nudge_used = True
+ logger.info(
+ "[TaskExecutionRail] todo close nudge: open=%s",
+ [raw_id for raw_id, _task in open_tasks],
+ )
+
+ def _is_last_react_iteration(self, ctx: AgentCallbackContext) -> bool:
+ """True when this model call is the final ReAct iteration."""
+ iteration = int(getattr(ctx.inputs, "react_iteration", 0) or 0)
+ agent = self._deep_agent
+ react = getattr(agent, "_react_agent", None)
+ config = getattr(react, "_config", None)
+ max_iterations = getattr(config, "max_iterations", None)
+ if iteration <= 0 or not isinstance(max_iterations, int):
+ return False
+ if max_iterations <= 0:
+ return False
+ return iteration >= max_iterations
+
+ def _started_in_progress_tasks(self) -> list[tuple[str, dict[str, Any]]]:
+ """Todos that must be closed before a plain-text ending.
+
+ Prefer items whose ``task.start`` was emitted in this invoke. HITL
+ resume clears ``_todo_started`` / ``_active_tasks`` in
+ ``before_invoke``, while ``todo.json`` and the already-open frontend
+ segment remain. Fall back to in-progress rows on disk so a text-only
+ resume still gets the nudge.
+ """
+ found: list[tuple[str, dict[str, Any]]] = []
+ seen: set[str] = set()
+ for full_id in self._active_tasks:
+ raw_id = full_id.removeprefix("todo:")
+ if raw_id not in self._todo_started:
+ continue
+ task = self._todo_map.get(raw_id)
+ if task is None:
+ continue
+ if str(task.get("status", "")).lower() != "in_progress":
+ continue
+ found.append((raw_id, task))
+ seen.add(raw_id)
+ if found:
+ return found
+ for raw_id, task in self._todo_map.items():
+ if raw_id in seen:
+ continue
+ if str(task.get("status", "")).lower() != "in_progress":
+ continue
+ found.append((raw_id, task))
+ return found
+
async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
if not isinstance(ctx.inputs, ToolCallInputs):
return
tool_name = ctx.inputs.tool_name
+ if is_todo_close_nudge(ctx.inputs.tool_call):
+ self._reject_todo_close_nudge(ctx)
+ return
+
if tool_name in self.TODO_TOOLS:
session_id = ""
if ctx.session is not None:
@@ -1498,11 +1650,25 @@ class TaskExecutionRail(DeepAgentRail):
_ACTIVE_TASK_ID.get() is not None
)
+ def _reject_todo_close_nudge(self, ctx: AgentCallbackContext) -> None:
+ """Skip the internal nudge tool and return the todo_modify instruction."""
+ tc = ctx.inputs.tool_call
+ tool_call_id = str(getattr(tc, "id", "") or "")
+ msg = _todo_close_nudge_message(self._started_in_progress_tasks())
+ ctx.extra["_skip_tool"] = True
+ ctx.inputs.tool_result = msg
+ ctx.inputs.tool_msg = ToolMessage(
+ content=msg, tool_call_id=tool_call_id,
+ )
+
async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
if not isinstance(ctx.inputs, ToolCallInputs):
return
tool_name = ctx.inputs.tool_name
+ if is_todo_close_nudge(ctx.inputs.tool_call):
+ return
+
if tool_name in self.TODO_TOOLS:
await self._sync_todo_and_emit_transitions(ctx)
return
diff --git a/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py b/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py
index c33fe749fe..851a4b1c47 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py
@@ -53,7 +53,7 @@ def _build_skill_turbo_guide_text(language: str, skill_names: list[str]) -> str:
若你已先调用了 `skill_tool` 加载了对应技能正文(即**不属于**上述例外,只是误触),**仍须立即调用 `skill_acceleration_exec`**——不要因"已经加载了 SKILL.md"或"已经做了研究"而放弃加速通道。
-若 `skill_acceleration_exec` 返回成功(产物已生成),**禁止**再用 `skill_tool` 重复同一任务——直接向用户总结结果即可。若 `skill_acceleration_exec` 返回失败或未处理,**必须**继续用 `skill_tool` 加载对应技能走标准流程完成用户任务。
+若 `skill_acceleration_exec` 返回成功(产物已生成),**禁止**再用 `skill_tool` 重复同一任务。若待办仍有 `in_progress`,先单独调 `todo_modify` 把对应步骤标为 `completed`,再向用户总结结果。若 `skill_acceleration_exec` 返回失败或未处理,**必须**继续用 `skill_tool` 加载对应技能走标准流程完成用户任务。
⏸️ **暂停不是失败**:当 `skill_acceleration_exec` 暂停等待用户回答(返回"技能加速已暂停"类信息,或向用户弹出补充问题卡片,或返回结果中包含 `__skill_turbo_hitl__` 标记时)时,这是任务流的正常提问环节。**必须停止后续工具调用,等待用户回答**;用户回答后加速通道会自动从断点继续。**禁止**把暂停当成失败而改走 `skill_tool` 标准流程,那会丢弃已完成的阶段并从头重跑。
@@ -66,7 +66,7 @@ def _build_skill_turbo_guide_text(language: str, skill_names: list[str]) -> str:
If you have already mistakenly called `skill_tool` to load the corresponding skill body (i.e. this does **NOT** fall under the exception above - it was just a misfire), **you MUST still call `skill_acceleration_exec` immediately** - do NOT abandon the acceleration channel because "SKILL.md is already loaded" or "research is already done."
-If `skill_acceleration_exec` returns success (the artifact is already generated), you are **forbidden** from calling `skill_tool` again for the same task — just summarize the result to the user. If `skill_acceleration_exec` returns failure or is not handled, you **MUST** fall back to `skill_tool` to load the corresponding skill and complete the user's task via the standard flow.
+If `skill_acceleration_exec` returns success (the artifact is already generated), you are **forbidden** from calling `skill_tool` again for the same task. If any todo is still `in_progress`, first call `todo_modify` alone to mark that step `completed`, then summarize the result to the user. If `skill_acceleration_exec` returns failure or is not handled, you **MUST** fall back to `skill_tool` to load the corresponding skill and complete the user's task via the standard flow.
⏸️ **Pause is NOT failure**: When `skill_acceleration_exec` pauses to wait for the user's answer (returning a "skill acceleration paused" style message, showing a follow-up question card to the user, or returning a result containing the `__skill_turbo_hitl__` marker), that is a normal clarification step of the pipeline. You **MUST stop making further tool calls and wait for the user's answer**; the acceleration channel will automatically resume from the breakpoint once answered. **DO NOT** treat the pause as a failure and switch to the `skill_tool` standard flow — that would discard completed stages and rerun from scratch.
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
index e5b26b27d9..5ab142e695 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
@@ -250,14 +250,18 @@ _SKILL_TURBO_STOP_HINT_NEUTRAL = {
_PPT_DELIVERY_SUMMARY_POST_TOOL_HINT = {
"cn": (
"\n\n[SYSTEM] PPT 交付总结骨架将由系统在本工具结果之后通过流式通道发送给用户,"
- "无需在本回合重复输出交付总结。禁止 tool_call,禁止再调 "
+ "无需在本回合重复输出交付总结。禁止再调 "
"send_file_to_user / skill_tool / skill_acceleration_exec。"
+ "若待办仍是 in_progress,下一轮先调 todo_modify 把对应步骤标为 completed,"
+ "再给最终回复。"
),
"en": (
"\n\n[SYSTEM] The PPT delivery summary skeleton will be streamed to the user "
"by the system after this tool result; do NOT repeat the delivery summary "
- "in this turn. No further tool calls. Do NOT call send_file_to_user / "
- "skill_tool / skill_acceleration_exec again."
+ "in this turn. Do NOT call send_file_to_user / skill_tool / "
+ "skill_acceleration_exec again. If a todo is still in_progress, call "
+ "todo_modify on the next turn to mark that step completed, then send "
+ "the final reply."
),
}
diff --git a/tests/unit_tests/agentserver/rails/test_task_execution_todo_close_nudge.py b/tests/unit_tests/agentserver/rails/test_task_execution_todo_close_nudge.py
new file mode 100644
index 0000000000..14c6ed4bf9
--- /dev/null
+++ b/tests/unit_tests/agentserver/rails/test_task_execution_todo_close_nudge.py
@@ -0,0 +1,267 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from openjiuwen.core.foundation.llm import AssistantMessage, ToolCall
+from openjiuwen.core.single_agent.rail.base import ToolCallInputs
+
+from jiuwenswarm.agents.harness.common.rails.skill_protocol_prompt_rail import (
+ _build_skill_protocol_section_text,
+)
+from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
+ JiuSwarmStreamEventRail,
+)
+from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (
+ TODO_CLOSE_NUDGE_ID_PREFIX,
+ TODO_CLOSE_NUDGE_TOOL_NAME,
+ TaskExecutionRail,
+)
+
+
+class _FakeSession:
+ def get_session_id(self) -> str:
+ return "sess-1"
+
+ async def write_stream(self, schema: object) -> None:
+ return None
+
+
+def _rail_with_open_task() -> TaskExecutionRail:
+ rail = TaskExecutionRail()
+ rail._todo_map = {
+ "env": {
+ "id": "env",
+ "content": "环境预检",
+ "status": "in_progress",
+ },
+ "source": {
+ "id": "source",
+ "content": "清点源文件",
+ "status": "pending",
+ },
+ }
+ rail._todo_started.add("env")
+ rail._active_tasks["todo:env"] = SimpleNamespace()
+ return rail
+
+
+def _text_ctx(content: str, tool_calls: list | None = None) -> SimpleNamespace:
+ response = AssistantMessage(content=content, tool_calls=tool_calls or [])
+ return SimpleNamespace(
+ session=_FakeSession(),
+ inputs=SimpleNamespace(response=response),
+ extra={},
+ )
+
+
+async def test_text_only_ending_attaches_one_todo_close_nudge() -> None:
+ rail = _rail_with_open_task()
+ ctx = _text_ctx("流程在此暂停,请上传源文件。")
+
+ await rail.after_model_call(ctx)
+ calls = ctx.inputs.response.tool_calls
+ assert len(calls) == 1
+ assert calls[0].name == TODO_CLOSE_NUDGE_TOOL_NAME
+ assert str(calls[0].id).startswith(TODO_CLOSE_NUDGE_ID_PREFIX)
+ assert ctx.inputs.response.content == ""
+ assert rail._todo_close_nudge_used is True
+
+ await rail.after_model_call(ctx)
+ assert len(ctx.inputs.response.tool_calls) == 1
+
+
+async def test_truncated_text_does_not_attach_nudge() -> None:
+ rail = _rail_with_open_task()
+ ctx = _text_ctx("正文被截断")
+ ctx.inputs.response.finish_reason = "length"
+
+ await rail.after_model_call(ctx)
+
+ assert ctx.inputs.response.tool_calls == []
+ assert ctx.inputs.response.content == "正文被截断"
+ assert rail._todo_close_nudge_used is False
+
+
+async def test_last_react_iteration_does_not_attach_nudge() -> None:
+ rail = _rail_with_open_task()
+ rail._deep_agent = SimpleNamespace(
+ _react_agent=SimpleNamespace(
+ _config=SimpleNamespace(max_iterations=15),
+ ),
+ )
+ ctx = _text_ctx("最后一轮正文")
+ ctx.inputs.react_iteration = 15
+
+ await rail.after_model_call(ctx)
+
+ assert ctx.inputs.response.tool_calls == []
+ assert rail._todo_close_nudge_used is False
+
+
+async def test_text_only_ending_keeps_real_tool_calls() -> None:
+ rail = _rail_with_open_task()
+ existing = ToolCall(
+ id="call-1", type="function", name="todo_modify", arguments="{}",
+ )
+ ctx = _text_ctx("同时改状态", tool_calls=[existing])
+
+ await rail.after_model_call(ctx)
+
+ assert ctx.inputs.response.tool_calls == [existing]
+ assert rail._todo_close_nudge_used is False
+
+
+async def test_text_only_ending_skipped_without_open_task() -> None:
+ rail = TaskExecutionRail()
+ ctx = _text_ctx("没有进行中的步骤。")
+
+ await rail.after_model_call(ctx)
+
+ assert ctx.inputs.response.tool_calls == []
+ assert rail._todo_close_nudge_used is False
+
+
+async def test_nudge_tool_is_skipped_and_does_not_advance_todos() -> None:
+ rail = _rail_with_open_task()
+ tool_call = ToolCall(
+ id="todo-close-nudge-1",
+ type="function",
+ name=TODO_CLOSE_NUDGE_TOOL_NAME,
+ arguments="{}",
+ )
+ ctx = SimpleNamespace(
+ session=_FakeSession(),
+ inputs=ToolCallInputs(
+ tool_call=tool_call,
+ tool_name=TODO_CLOSE_NUDGE_TOOL_NAME,
+ tool_args={},
+ ),
+ extra={},
+ )
+ advanced: list[str] = []
+
+ async def _record_advance(_ctx: object, task_id: str | None = None) -> None:
+ advanced.append(task_id or "")
+
+ rail._auto_advance_pending_to_in_progress = _record_advance # type: ignore[method-assign]
+
+ await rail.before_tool_call(ctx)
+ await rail.after_tool_call(ctx)
+
+ assert ctx.extra["_skip_tool"] is True
+ assert "todo_modify" in ctx.inputs.tool_result
+ assert "没有送达用户" in ctx.inputs.tool_result
+ assert "完整重写" in ctx.inputs.tool_result
+ assert "env" in ctx.inputs.tool_result
+ assert ctx.inputs.tool_msg.tool_call_id == "todo-close-nudge-1"
+ assert rail._todo_map["env"]["status"] == "in_progress"
+ assert rail._todo_map["source"]["status"] == "pending"
+ assert advanced == []
+
+
+def test_skill_turbo_success_hint_closes_todo_before_summary() -> None:
+ from jiuwenswarm.server.runtime.skill_turbo.rails.skill_prompt_rail import (
+ _build_skill_turbo_guide_text,
+ )
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ _PPT_DELIVERY_SUMMARY_POST_TOOL_HINT,
+ )
+
+ cn = _build_skill_turbo_guide_text("cn", ["pptx-craft"])
+ en = _build_skill_turbo_guide_text("en", ["pptx-craft"])
+ assert "先单独调 `todo_modify`" in cn
+ assert "直接向用户总结结果即可" not in cn
+ assert "first call `todo_modify` alone" in en
+ assert "just summarize the result to the user" not in en
+ assert "todo_modify" in _PPT_DELIVERY_SUMMARY_POST_TOOL_HINT["cn"]
+ assert "禁止 tool_call" not in _PPT_DELIVERY_SUMMARY_POST_TOOL_HINT["cn"]
+ assert "No further tool calls" not in _PPT_DELIVERY_SUMMARY_POST_TOOL_HINT["en"]
+
+
+def test_skill_protocol_allows_standalone_todo_modify_before_final() -> None:
+ cn = _build_skill_protocol_section_text("cn")
+ en = _build_skill_protocol_section_text("en")
+ assert "纯文本最终回复的前一轮" in cn
+ assert "第 9 条的用户打断" in cn
+ assert "including the user-interruption cases in rule 9" in en
+ assert "所有工作完成后" not in cn
+ assert "the turn immediately before the plain-text final reply" in en
+ assert "when all work is done" not in en
+
+
+async def test_stream_rail_does_not_emit_todo_close_nudge(monkeypatch) -> None:
+ rail = JiuSwarmStreamEventRail()
+ emitted: list[str] = []
+
+ async def _record(name: str, *_args: object, **_kwargs: object) -> None:
+ emitted.append(name)
+
+ monkeypatch.setattr(rail, "_emit_tool_call", lambda *a, **k: _record("call", *a, **k))
+ monkeypatch.setattr(
+ rail, "_emit_tool_update", lambda *a, **k: _record("update", *a, **k),
+ )
+ monkeypatch.setattr(
+ rail, "_emit_tool_result", lambda *a, **k: _record("result", *a, **k),
+ )
+ tool_call = ToolCall(
+ id="todo-close-nudge-1",
+ type="function",
+ name=TODO_CLOSE_NUDGE_TOOL_NAME,
+ arguments="{}",
+ )
+ ctx = SimpleNamespace(
+ session=_FakeSession(),
+ inputs=ToolCallInputs(
+ tool_call=tool_call,
+ tool_name=TODO_CLOSE_NUDGE_TOOL_NAME,
+ tool_args={},
+ tool_result="nudge",
+ ),
+ extra={},
+ exception=None,
+ )
+
+ await rail.before_tool_call(ctx)
+ await rail.after_tool_call(ctx)
+
+ assert emitted == []
+
+
+async def test_text_only_resume_nudges_disk_in_progress_without_memory() -> None:
+ rail = TaskExecutionRail()
+ rail._todo_map = {
+ "env": {
+ "id": "env",
+ "content": "环境预检",
+ "status": "in_progress",
+ },
+ }
+ ctx = _text_ctx("问答之后直接说明卡点。")
+
+ await rail.after_model_call(ctx)
+
+ calls = ctx.inputs.response.tool_calls
+ assert len(calls) == 1
+ assert str(calls[0].id).startswith(TODO_CLOSE_NUDGE_ID_PREFIX)
+
+
+async def test_before_invoke_resets_nudge_budget() -> None:
+ rail = _rail_with_open_task()
+ rail._todo_close_nudge_used = True
+ ctx = SimpleNamespace(session=None, inputs=object(), extra={})
+
+ await rail.before_invoke(ctx)
+
+ assert rail._todo_close_nudge_used is False