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(task_todo): add task reminder into prompt

ldstyle8af36c629435e
diff --git a/jiuwenswarm/agents/harness/code/rails/code_task_planning_rail.py b/jiuwenswarm/agents/harness/code/rails/code_task_planning_rail.py
index 76b78e9530..7b142858b9 100644
--- a/jiuwenswarm/agents/harness/code/rails/code_task_planning_rail.py
+++ b/jiuwenswarm/agents/harness/code/rails/code_task_planning_rail.py
@@ -1,14 +1,16 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Code-mode TaskPlanningRail — CC-aligned todo tools, no system prompt injection."""
+"""Code-mode TaskPlanningRail with CC-aligned todo tools and reminders."""
from __future__ import annotations
from openjiuwen.core.common.logging import logger
from openjiuwen.core.foundation.tool import ToolCard
from openjiuwen.core.runner import Runner
-from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ToolCallInputs
+from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmentKind
from openjiuwen.harness.rails.task_planning_rail import TaskPlanningRail
+from openjiuwen.harness.schema.task import TodoItem, TodoStatus
from openjiuwen.harness.tools.todo import TodoTool
from openjiuwen.harness.workspace.workspace import WorkspaceNode
@@ -19,16 +21,106 @@ from jiuwenswarm.agents.harness.code.tools.code_todo_tools import (
CodeTodoModifyTool,
)
+_TASK_REMINDER_SECTION = "task_reminder"
+_TASK_REMINDER_KIND = PromptAttachmentKind.TODO_REMINDER
+_TASK_REMINDER_SOURCE = "jiuwenswarm.code_task_planning.task_reminder"
+_TASK_REMINDER_TURNS_SINCE_MANAGEMENT = 10
+_TASK_REMINDER_TURNS_BETWEEN_REMINDERS = 10
+_MAX_TRACKED_TASK_REMINDER_SESSIONS = 1000
+
class CodeTaskPlanningRail(TaskPlanningRail):
- """Register code-mode todo tools with CC-aligned metadata.
+ """Register code-mode todo tools.
- Uses CodeTodo* tool classes (shorter descriptions, coarse-milestone guidance).
- - Skips before_model_call prompt injection (no openjiuwen todo system section).
+ - Skips the openjiuwen static todo system section.
+ - Adds a task_reminder prompt attachment only when todo management
+ has been absent for several model turns.
"""
+ def __init__(
+ self,
+ *args,
+ task_reminder_turns_since_management: int = _TASK_REMINDER_TURNS_SINCE_MANAGEMENT,
+ task_reminder_turns_between_reminders: int = _TASK_REMINDER_TURNS_BETWEEN_REMINDERS,
+ max_tracked_task_reminder_sessions: int = _MAX_TRACKED_TASK_REMINDER_SESSIONS,
+ **kwargs,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+ self.task_reminder_turns_since_management = task_reminder_turns_since_management
+ self.task_reminder_turns_between_reminders = task_reminder_turns_between_reminders
+ self.max_tracked_task_reminder_sessions = max(1, max_tracked_task_reminder_sessions)
+ self._turns_since_task_management: dict[str, int] = {}
+ self._turns_since_task_reminder: dict[str, int] = {}
+ self._tracked_task_reminder_sessions: list[str] = []
+
async def before_model_call(self, ctx: AgentCallbackContext) -> None:
- _ = ctx
+ """Refresh the per-call task_reminder attachment.
+
+ Code mode intentionally avoids the parent rail's static todo prompt
+ section. It still preserves the parent's model-selection behavior:
+ when the model has gone many turns without using todo tools, add one
+ runtime prompt attachment that reminds it of the task tools and includes
+ current todos.
+ """
+
+ await self._switch_model_if_needed(ctx)
+
+ session_id = self._session_id(ctx)
+ manager = getattr(getattr(ctx, "agent", None), "prompt_attachment_manager", None)
+ if not session_id or manager is None or self._find_todo_tool() is None:
+ return
+
+ self._track_task_reminder_session(session_id)
+ turns_since_management = self._turns_since_task_management.get(session_id, 0) + 1
+ turns_since_reminder = self._turns_since_task_reminder.get(session_id, 0) + 1
+ self._turns_since_task_management[session_id] = turns_since_management
+ self._turns_since_task_reminder[session_id] = turns_since_reminder
+
+ should_remind = (
+ turns_since_management >= self.task_reminder_turns_since_management
+ and turns_since_reminder >= self.task_reminder_turns_between_reminders
+ )
+ if not should_remind:
+ await self._clear_task_reminder_attachment(manager, session_id)
+ return
+
+ todos = await self._load_fresh_todos(session_id)
+ content = self._build_task_reminder_content(todos)
+ await manager.add_section(
+ session_id=session_id,
+ section=_TASK_REMINDER_SECTION,
+ kind=_TASK_REMINDER_KIND,
+ content=content,
+ priority=60,
+ source=_TASK_REMINDER_SOURCE,
+ metadata={"item_count": len(todos)},
+ content_kind="text/markdown",
+ )
+ self._turns_since_task_reminder[session_id] = 0
+
+ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
+ await super().after_tool_call(ctx)
+
+ if not self._is_todo_tool_call(ctx):
+ return
+
+ session_id = self._session_id(ctx)
+ manager = getattr(getattr(ctx, "agent", None), "prompt_attachment_manager", None)
+ if not session_id:
+ return
+
+ self._turns_since_task_management[session_id] = 0
+ if manager is not None:
+ await self._clear_task_reminder_attachment(manager, session_id)
+
+ async def after_invoke(self, ctx: AgentCallbackContext) -> None:
+ session_id = self._session_id(ctx)
+ try:
+ await super().after_invoke(ctx)
+ finally:
+ if session_id:
+ self._clear_task_reminder_session_state(session_id)
def init(self, agent) -> None:
"""Register CC-aligned todo tools on the agent."""
@@ -91,3 +183,114 @@ class CodeTaskPlanningRail(TaskPlanningRail):
logger.warning(
"CodeTaskPlanningRail: failed to add tool, error: %s", exc
)
+
+ @staticmethod
+ def _session_id(ctx: AgentCallbackContext) -> str | None:
+ session = getattr(ctx, "session", None)
+ if session is not None and hasattr(session, "get_session_id"):
+ return session.get_session_id()
+ return None
+
+ @staticmethod
+ def _is_todo_tool_call(ctx: AgentCallbackContext) -> bool:
+ inputs = getattr(ctx, "inputs", None)
+ if isinstance(inputs, ToolCallInputs):
+ tool_name = inputs.tool_name
+ else:
+ tool_name = getattr(inputs, "tool_name", "")
+ return bool(tool_name and str(tool_name).startswith("todo_"))
+
+ @staticmethod
+ async def _clear_task_reminder_attachment(manager, session_id: str) -> None:
+ try:
+ await manager.clear_section(
+ session_id=session_id,
+ section=_TASK_REMINDER_SECTION,
+ )
+ except Exception:
+ logger.debug("CodeTaskPlanningRail: failed to clear task reminder")
+
+ async def _switch_model_if_needed(self, ctx: AgentCallbackContext) -> None:
+ if not self._model_selection:
+ return
+
+ if self._default_llm is None:
+ self._default_llm = getattr(ctx.agent, "_llm", None)
+
+ selected_model_id = await self._get_fresh_in_progress_model_id(ctx)
+ if selected_model_id and selected_model_id in self._model_id_to_model:
+ target_model = self._model_id_to_model[selected_model_id]
+ else:
+ target_model = self._default_llm
+
+ if target_model is not None:
+ ctx.agent.set_llm(target_model)
+ ctx.agent.config.model_name = target_model.model_config.model_name
+ logger.debug(
+ "CodeTaskPlanningRail: switched to model_id=%s", selected_model_id
+ )
+
+ def _track_task_reminder_session(self, session_id: str) -> None:
+ if session_id in self._tracked_task_reminder_sessions:
+ self._tracked_task_reminder_sessions.remove(session_id)
+ self._tracked_task_reminder_sessions.append(session_id)
+
+ while len(self._tracked_task_reminder_sessions) > self.max_tracked_task_reminder_sessions:
+ evicted_session_id = self._tracked_task_reminder_sessions.pop(0)
+ self._clear_task_reminder_session_state(evicted_session_id)
+
+ def _clear_task_reminder_session_state(self, session_id: str) -> None:
+ self._turns_since_task_management.pop(session_id, None)
+ self._turns_since_task_reminder.pop(session_id, None)
+ if session_id in self._tracked_task_reminder_sessions:
+ self._tracked_task_reminder_sessions.remove(session_id)
+
+ async def _get_fresh_in_progress_model_id(
+ self,
+ ctx: AgentCallbackContext,
+ ) -> str | None:
+ """Return selected_model_id from freshly loaded todos."""
+ session_id = self._session_id(ctx)
+ if session_id is None:
+ return None
+
+ todos = await self._load_fresh_todos(session_id)
+ for todo in todos:
+ if todo.status == TodoStatus.IN_PROGRESS:
+ return todo.selected_model_id
+ return None
+
+ async def _load_fresh_todos(self, session_id: str) -> list[TodoItem]:
+ tool = self._find_todo_tool()
+ if tool is None:
+ return []
+
+ try:
+ todos = await tool.load_todos(session_id)
+ except Exception:
+ logger.debug("CodeTaskPlanningRail: failed to load fresh todos")
+ return []
+
+ self._todos_cache[session_id] = todos
+ return todos
+
+ @staticmethod
+ def _build_task_reminder_content(todos: list[TodoItem]) -> str:
+ message = (
+ "The task tools haven't been used recently. If you're working on "
+ "tasks that would benefit from tracking progress, consider using "
+ "todo_create to add new tasks and todo_modify to update task status "
+ "(set to in_progress when starting, completed when done). Also "
+ "consider cleaning up the task list if it has become stale. Only "
+ "use these if relevant to the current work. This is just a gentle "
+ "reminder - ignore if not applicable. Make sure that you NEVER "
+ "mention this reminder to the user"
+ )
+ if not todos:
+ return message
+
+ task_items = []
+ for todo in todos:
+ status = todo.status.value if hasattr(todo.status, "value") else str(todo.status)
+ task_items.append(f"#{todo.id}. [{status}] {todo.content}")
+ return f"{message}\n\nHere are the existing tasks:\n\n" + "\n".join(task_items)
diff --git a/tests/unit_tests/agents/harness/code/test_code_task_planning_rail.py b/tests/unit_tests/agents/harness/code/test_code_task_planning_rail.py
new file mode 100644
index 0000000000..2802c58fbf
--- /dev/null
+++ b/tests/unit_tests/agents/harness/code/test_code_task_planning_rail.py
@@ -0,0 +1,296 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+# pylint: disable=protected-access
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from openjiuwen.core.foundation.tool import ToolCard
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ToolCallInputs
+from openjiuwen.harness.prompts.prompt_attachment_manager import PromptAttachmentManager
+from openjiuwen.harness.schema.task import TodoItem, TodoStatus
+from openjiuwen.harness.tools.todo import TodoTool
+
+from jiuwenswarm.agents.harness.code.rails.code_task_planning_rail import (
+ CodeTaskPlanningRail,
+)
+
+
+class FakeSession:
+ def __init__(self, session_id: str = "sess1") -> None:
+ self._session_id = session_id
+
+ def get_session_id(self) -> str:
+ return self._session_id
+
+
+class FakeAgent:
+ def __init__(self) -> None:
+ self.prompt_attachment_manager = PromptAttachmentManager()
+ self.config = SimpleNamespace(model_name="")
+ self._llm = None
+
+ def set_llm(self, llm) -> None:
+ self._llm = llm
+
+
+class FakeTodoTool(TodoTool):
+ def __init__(self, todos: list[TodoItem]) -> None:
+ self._card = ToolCard(
+ id="fake_todo_list",
+ name="todo_list",
+ description="fake todo tool",
+ input_params={"type": "object", "properties": {}, "required": []},
+ )
+ self.todos = todos
+
+ async def load_todos(self, session_id: str) -> list[TodoItem]:
+ assert session_id
+ return self.todos
+
+
+class FakeModel:
+ def __init__(self, client_id: str, model_name: str) -> None:
+ self.model_client_config = SimpleNamespace(client_id=client_id)
+ self.model_config = SimpleNamespace(model_name=model_name)
+
+
+def _ctx(agent: FakeAgent, *, tool_name: str = "", session_id: str = "sess1") -> AgentCallbackContext:
+ return AgentCallbackContext(
+ agent=agent,
+ session=FakeSession(session_id),
+ inputs=ToolCallInputs(tool_name=tool_name),
+ )
+
+
+def _rail(todos: list[TodoItem], **kwargs) -> CodeTaskPlanningRail:
+ rail = CodeTaskPlanningRail(**kwargs)
+ rail.tools = [FakeTodoTool(todos)]
+ return rail
+
+
+async def _task_reminders(agent: FakeAgent):
+ return await agent.prompt_attachment_manager.list_by_filter(
+ session_id="sess1",
+ section="task_reminder",
+ source="jiuwenswarm.code_task_planning.task_reminder",
+ )
+
+
+async def test_code_task_planning_rail_does_not_inject_before_threshold():
+ agent = FakeAgent()
+ rail = _rail([])
+
+ await rail.before_model_call(_ctx(agent))
+
+ assert await _task_reminders(agent) == []
+
+
+async def test_code_task_planning_rail_injects_task_reminder_attachment_after_threshold():
+ agent = FakeAgent()
+ rail = _rail(
+ [
+ TodoItem(
+ id="locate",
+ content="Locate failing behavior",
+ activeForm="Locating failing behavior",
+ description="Find the relevant code path",
+ status=TodoStatus.IN_PROGRESS,
+ ),
+ TodoItem(
+ id="verify",
+ content="Verify the fix",
+ activeForm="Verifying the fix",
+ description="Run focused checks",
+ status=TodoStatus.PENDING,
+ ),
+ ]
+ )
+
+ for _ in range(10):
+ await rail.before_model_call(_ctx(agent))
+
+ reminders = await _task_reminders(agent)
+ assert len(reminders) == 1
+ reminder = reminders[0]
+ assert reminder.kind == "todo_reminder"
+ assert "The task tools haven't been used recently" in reminder.content
+ assert "#locate. [in_progress] Locate failing behavior" in reminder.content
+ assert "#verify. [pending] Verify the fix" in reminder.content
+
+ rendered = agent.prompt_attachment_manager.render(reminders)
+ assert '<prompt-attachment type="todo_reminder">' in rendered
+ assert "<system-reminder>" in rendered
+
+
+async def test_code_task_planning_rail_resets_and_clears_reminder_after_todo_tool_use():
+ agent = FakeAgent()
+ rail = _rail([])
+
+ for _ in range(10):
+ await rail.before_model_call(_ctx(agent))
+ assert len(await _task_reminders(agent)) == 1
+
+ await rail.after_tool_call(_ctx(agent, tool_name="todo_modify"))
+ await rail.before_model_call(_ctx(agent))
+
+ assert await _task_reminders(agent) == []
+
+
+async def test_code_task_planning_rail_preserves_parent_model_selection_without_static_prompt():
+ default_model = _model("default-client", "default-model")
+ target_model = _model("target-client", "target-model")
+ agent = FakeAgent()
+ agent._llm = default_model
+ rail = _rail(
+ [
+ TodoItem(
+ id="implement",
+ content="Implement fix",
+ activeForm="Implementing fix",
+ description="Apply code changes",
+ status=TodoStatus.IN_PROGRESS,
+ selected_model_id="target-client",
+ )
+ ],
+ model_selection={target_model: "Target model"},
+ )
+ prompt_builder = SimpleNamespace(
+ language="en",
+ added_sections=[],
+ removed_sections=[],
+ add_section=lambda section: prompt_builder.added_sections.append(section),
+ remove_section=lambda section: prompt_builder.removed_sections.append(section),
+ )
+ rail.system_prompt_builder = prompt_builder
+
+ await rail.before_model_call(_ctx(agent))
+
+ assert agent._llm is target_model
+ assert agent.config.model_name == "target-model"
+ assert prompt_builder.added_sections == []
+
+
+async def test_code_task_planning_rail_uses_fresh_todos_for_model_selection():
+ default_model = _model("default-client", "default-model")
+ stale_model = _model("stale-client", "stale-model")
+ target_model = _model("target-client", "target-model")
+ agent = FakeAgent()
+ agent._llm = default_model
+ rail = _rail(
+ [
+ TodoItem(
+ id="fresh",
+ content="Fresh task",
+ activeForm="Working fresh task",
+ description="Use the fresh selected model",
+ status=TodoStatus.IN_PROGRESS,
+ selected_model_id="target-client",
+ )
+ ],
+ model_selection={
+ stale_model: "Stale model",
+ target_model: "Target model",
+ },
+ )
+ rail._todos_cache["sess1"] = [
+ TodoItem(
+ id="stale",
+ content="Stale task",
+ activeForm="Working stale task",
+ description="Old cached model choice",
+ status=TodoStatus.IN_PROGRESS,
+ selected_model_id="stale-client",
+ )
+ ]
+
+ await rail.before_model_call(_ctx(agent))
+
+ assert agent._llm is target_model
+ assert agent.config.model_name == "target-model"
+
+
+async def test_code_task_planning_rail_loads_fresh_todos_for_reminder_instead_of_cache():
+ agent = FakeAgent()
+ stale = TodoItem(
+ id="stale",
+ content="Old cached task",
+ activeForm="Old cached task",
+ description="Old cached task",
+ status=TodoStatus.IN_PROGRESS,
+ )
+ fresh = TodoItem(
+ id="fresh",
+ content="Fresh task from storage",
+ activeForm="Fresh task from storage",
+ description="Fresh task from storage",
+ status=TodoStatus.IN_PROGRESS,
+ )
+ rail = _rail(
+ [fresh],
+ task_reminder_turns_since_management=1,
+ task_reminder_turns_between_reminders=1,
+ )
+ rail._todos_cache["sess1"] = [stale]
+
+ await rail.before_model_call(_ctx(agent))
+
+ reminders = await _task_reminders(agent)
+ assert len(reminders) == 1
+ assert "#fresh. [in_progress] Fresh task from storage" in reminders[0].content
+ assert "Old cached task" not in reminders[0].content
+
+
+async def test_code_task_planning_rail_clamps_non_positive_session_cap():
+ rail = _rail([], max_tracked_task_reminder_sessions=0)
+ agent = FakeAgent()
+
+ await rail.before_model_call(_ctx(agent, session_id="sess1"))
+ await rail.before_model_call(_ctx(agent, session_id="sess2"))
+
+ assert rail.max_tracked_task_reminder_sessions == 1
+ assert set(rail._turns_since_task_management) == {"sess2"}
+ assert set(rail._turns_since_task_reminder) == {"sess2"}
+
+
+async def test_code_task_planning_rail_bounds_task_reminder_session_state():
+ rail = _rail([], max_tracked_task_reminder_sessions=2)
+ agent = FakeAgent()
+
+ await rail.before_model_call(_ctx(agent, session_id="sess1"))
+ await rail.before_model_call(_ctx(agent, session_id="sess2"))
+ await rail.before_model_call(_ctx(agent, session_id="sess3"))
+
+ assert set(rail._turns_since_task_management) == {"sess2", "sess3"}
+ assert set(rail._turns_since_task_reminder) == {"sess2", "sess3"}
+
+
+async def test_code_task_planning_rail_clears_task_reminder_state_when_parent_cleanup_fails():
+ rail = _rail([])
+ agent = FakeAgent()
+ rail._turns_since_task_management["sess1"] = 3
+ rail._turns_since_task_reminder["sess1"] = 4
+ rail._tracked_task_reminder_sessions.append("sess1")
+
+ with pytest.raises(AttributeError):
+ await rail.after_invoke(_ctx(agent))
+
+ assert "sess1" not in rail._turns_since_task_management
+ assert "sess1" not in rail._turns_since_task_reminder
+ assert "sess1" not in rail._tracked_task_reminder_sessions
+
+
+def _model(client_id: str, model_name: str) -> FakeModel:
+ return FakeModel(client_id, model_name)