Skip to content

Self-improving AI Employees for everyone

fix(teams): let the lead act on task completions; retry/reassign actually re-run work

trohitg4f35db972329
diff --git a/server/nodes/agent/_inline.py b/server/nodes/agent/_inline.py
index 7e135c3f..d1df34fb 100644
--- a/server/nodes/agent/_inline.py
+++ b/server/nodes/agent/_inline.py
@@ -6,9 +6,13 @@ method:
1. :func:`services.plugin.edge_walker.collect_agent_connections` —
gather memory / skills / tools / input / task data.
-2. Task-context injection + tool-strip when ``task_data.status`` is
- ``completed`` / ``error`` (so the agent reports results instead of
- re-delegating).
+2. Task-context injection when a taskTrigger firing carries a
+ completed / errored task. Tools are deliberately KEPT: the injected
+ guidance tells a team lead to ``list_tasks`` / ``accept_task`` /
+ ``reassign_task``, which requires the Task Manager tool. An earlier
+ version stripped every tool here "so the agent reports instead of
+ re-delegating" — that made the lead unable to accept or reassign
+ anything, which read as the lead forgetting its plan.
3. Auto-prompt fallback when the ``prompt`` field is empty and a
connected upstream node produced output.
@@ -66,7 +70,8 @@ async def prepare_agent_call(
log_prefix=log_prefix,
)
- # Step 1: task-context injection + tool-strip.
+ # Step 1: task-context injection. Tools are kept — the injected
+ # guidance requires the Task Manager tool to act on the completion.
if task_data:
task_context = format_task_context(task_data)
original_prompt = parameters.get("prompt", "")
@@ -74,13 +79,6 @@ async def prepare_agent_call(
logger.info(
f"{log_prefix} Task context injected for task_id={task_data.get('task_id')}",
)
- task_status = task_data.get("status", "")
- if task_status in ("completed", "error") and tool_data:
- original_tool_count = len(tool_data)
- tool_data = []
- logger.info(
- f"{log_prefix} Stripped ALL {original_tool_count} tools for " "task completion handling",
- )
# Step 2: auto-prompt fallback.
if not parameters.get("prompt") and input_data:
diff --git a/server/nodes/tool/task_manager/__init__.py b/server/nodes/tool/task_manager/__init__.py
index b63c3e1d..ff787b76 100644
--- a/server/nodes/tool/task_manager/__init__.py
+++ b/server/nodes/tool/task_manager/__init__.py
@@ -221,6 +221,7 @@ async def _execute_task_manager(args: Dict[str, Any], config: Dict[str, Any]) ->
)
if not task_id:
raise ValueError(f"{operation} requires task_id")
+ current: Optional[Dict[str, Any]] = None
if revision is None:
current = await service.get_durable_task(**scope, task_id=task_id)
revision = current.get("revision")
@@ -228,9 +229,33 @@ async def _execute_task_manager(args: Dict[str, Any], config: Dict[str, Any]) ->
raise ValueError(f"{operation} requires expected_revision")
mapped = "accept" if operation in {"accept_task", "mark_done"} else operation.removesuffix("_task")
payload = {k: args[k] for k in ("title", "mission", "context", "acceptance_criteria", "reason") if k in args}
+ # Resolve the runner BEFORE mutating so a disconnected assignee fails
+ # the operation cleanly instead of flipping the row and then stalling.
+ delegate: Optional[Dict[str, Any]] = None
if operation == "reassign_task":
- payload["assignee_node_id"] = _resolve_teammate(config, args)["node_id"]
+ delegate = _resolve_teammate(config, args)
+ payload["assignee_node_id"] = delegate["node_id"]
+ elif operation == "retry_task":
+ if current is None:
+ current = await service.get_durable_task(**scope, task_id=task_id)
+ delegate = _resolve_teammate(
+ config, {"assignee_node_id": current.get("assigned_to")}
+ )
task = await service.mutate_durable_task(
**scope, task_id=task_id, revision=int(revision), operation=mapped, **payload,
)
- return {"success": True, "operation": operation, "task": task}
+ result: Dict[str, Any] = {"success": True, "operation": operation, "task": task}
+ if delegate is not None:
+ # retry/reassign move the row to "queued", and nothing sweeps queued
+ # rows — the ONLY runner is this scheduling envelope, which the
+ # Temporal AgentWorkflow bridges to a DelegatedTaskWorkflow exactly
+ # like a fresh assign_task. Without it the mutation flipped the DB
+ # row and the work silently never re-ran.
+ result["delegation_request"] = {
+ "team_task_id": task["id"],
+ "assignee_node_id": delegate["node_id"],
+ "delegate_name": delegate["delegate_tool_name"],
+ "task": str(task.get("mission") or task.get("description") or ""),
+ "context": task.get("context") or {},
+ }
+ return result
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index b4390ffb..efc5570a 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -2113,6 +2113,21 @@ class AgentWorkflow:
f"AgentWorkflow compaction failed terminally "
f"(iteration {iteration + 1}): {compact_detail}"
)
+ # Same terminal-cleanup contract as the LLM-failure
+ # path: clear turn-scoped skill badges before the
+ # error status, or the canvas stays stuck on the last
+ # capability after the workflow has ended.
+ await workflow.execute_activity(
+ "agent.skill.clear",
+ args=[{
+ "workflow_id": payload.get("workflow_id"),
+ "execution_id": task_scope_execution_id,
+ "agent_node_id": agent_node_id,
+ }],
+ activity_id="clear-active-skills-compaction-failed",
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
await self._emit_phase(
agent_node_id,
agent_workflow_id,
diff --git a/server/tests/nodes/test_agent_prepare_call.py b/server/tests/nodes/test_agent_prepare_call.py
new file mode 100644
index 00000000..565eb917
--- /dev/null
+++ b/server/tests/nodes/test_agent_prepare_call.py
@@ -0,0 +1,56 @@
+"""Contracts for the shared agent pre-dispatch flow (prepare_agent_call)."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+
+def _connections(*, task_data=None, tool_data=None):
+ return (
+ None, # memory_data
+ None, # skill_data
+ tool_data,
+ None, # input_data
+ task_data,
+ )
+
+
[email protected]("status", ["completed", "error"])
+async def test_completion_firing_keeps_tools(status):
+ """The taskTrigger prompt tells a lead to list/accept/reassign via the
+ Task Manager tool — stripping tools on exactly that firing made the
+ lead unable to act on any completion (it could only answer in prose,
+ which read as the lead forgetting its plan)."""
+ import nodes.agent._inline as inline
+
+ tools = [
+ {"node_id": "tm-1", "node_type": "taskManager", "label": "Task Manager"},
+ {"node_id": "search-1", "node_type": "braveSearch", "label": "Search"},
+ ]
+ task = {"task_id": "task-1", "status": status, "result": "done"}
+
+ with patch.object(
+ inline,
+ "collect_agent_connections",
+ AsyncMock(return_value=_connections(task_data=task, tool_data=tools)),
+ ), patch.object(
+ inline,
+ "collect_teammate_connections",
+ AsyncMock(return_value=[]),
+ ), patch(
+ "services.status_broadcaster.get_status_broadcaster",
+ MagicMock(),
+ ):
+ prepared = await inline.prepare_agent_call(
+ node_id="lead-1",
+ node_type="orchestrator_agent",
+ parameters={"prompt": "review"},
+ context={},
+ database=object(),
+ )
+
+ assert prepared["tool_data"] == tools
+ # The task context is still injected ahead of the original prompt.
+ assert "task-1" in prepared["parameters"]["prompt"]
+ assert prepared["parameters"]["prompt"].endswith("review")
diff --git a/server/tests/nodes/test_ai_agents.py b/server/tests/nodes/test_ai_agents.py
index d8b30f25..8fc0533a 100644
--- a/server/tests/nodes/test_ai_agents.py
+++ b/server/tests/nodes/test_ai_agents.py
@@ -210,11 +210,13 @@ class TestAIAgent:
assert "shell-skill" not in names
assert skill_data[0]["parameters"]["instructions"] == "Use python."
- async def test_task_completion_strips_all_tools(self, harness):
- """When an input-task edge delivers a completed task, tool_data is cleared.
+ async def test_task_completion_keeps_tools(self, harness):
+ """A completed-task firing must NOT strip the agent's tools.
- Documented as a CRITICAL FIX in the handler: binding tools while telling
- the LLM "do not use tools" confused Gemini.
+ The injected task context tells a team lead to list/accept/reassign
+ via the Task Manager tool — the old strip removed exactly that tool
+ on exactly that firing, so the lead could only answer in prose,
+ which read as "the orchestrator forgot its plan".
"""
agent_id = "agent-4"
trigger_id = "task-trig-1"
@@ -257,8 +259,11 @@ class TestAIAgent:
)
_, kwargs = harness.ai_service.execute_agent.call_args
- # Tools stripped on task completion
- assert kwargs["tool_data"] is None
+ # Tools survive the completion firing
+ assert kwargs["tool_data"]
+ assert any(
+ t.get("node_id") == tool_id for t in kwargs["tool_data"]
+ )
# Prompt got the task context prepended
sent_params = harness.ai_service.execute_agent.call_args.kwargs["parameters"]
@@ -394,8 +399,8 @@ class TestChatAgent:
# Teammate params come along so delegation knows provider/model
assert teammate_tool["parameters"]["model"] == "gpt"
- async def test_chat_agent_task_error_strips_tools(self, harness):
- """Same tool-strip behaviour as aiAgent on task failure."""
+ async def test_chat_agent_task_error_keeps_tools(self, harness):
+ """Same keep-tools behaviour as aiAgent on task failure."""
chat_id = "chat-4"
trig_id = "trig-4"
tool_id = "tool-b"
@@ -426,7 +431,8 @@ class TestChatAgent:
)
_, kwargs = harness.ai_service.execute_chat_agent.call_args
- assert kwargs["tool_data"] is None
+ assert kwargs["tool_data"]
+ assert any(t.get("node_id") == tool_id for t in kwargs["tool_data"])
sent_params = harness.ai_service.execute_chat_agent.call_args.kwargs["parameters"]
assert "failed" in sent_params["prompt"].lower()
diff --git a/server/tests/nodes/test_specialized_agents.py b/server/tests/nodes/test_specialized_agents.py
index 2073cf71..03837dc1 100644
--- a/server/tests/nodes/test_specialized_agents.py
+++ b/server/tests/nodes/test_specialized_agents.py
@@ -128,8 +128,8 @@ class TestGenericSpecializedAgents:
_, kwargs = harness.ai_service.execute_chat_agent.await_args
assert kwargs["parameters"]["prompt"] == "upstream prompt"
- async def test_task_completion_strips_tools(self, harness):
- """When task_data.status is completed, tool_data is stripped to []."""
+ async def test_task_completion_keeps_tools(self, harness):
+ """A completed-task firing must NOT strip the agent's tools."""
harness.ai_service.execute_chat_agent = AsyncMock(return_value={"success": True, "result": {"response": "done"}})
# Wire a tool and a task trigger to the agent.
@@ -166,8 +166,11 @@ class TestGenericSpecializedAgents:
)
_, kwargs = harness.ai_service.execute_chat_agent.await_args
- # Tools should be stripped (kwarg value is None or []).
- assert not kwargs.get("tool_data")
+ # Tools survive the completion firing.
+ assert kwargs.get("tool_data")
+ assert any(
+ t.get("node_id") == "tool-1" for t in kwargs["tool_data"]
+ )
@pytest.mark.parametrize("node_type", TEAM_LEAD_AGENTS)
async def test_team_lead_collects_teammates_as_tools(self, harness, node_type):
diff --git a/server/tests/nodes/test_task_manager_delegation_bridge.py b/server/tests/nodes/test_task_manager_delegation_bridge.py
index e4796627..d5050abe 100644
--- a/server/tests/nodes/test_task_manager_delegation_bridge.py
+++ b/server/tests/nodes/test_task_manager_delegation_bridge.py
@@ -86,6 +86,71 @@ async def test_accept_never_guesses_when_multiple_tasks_are_submitted():
await _execute_task_manager({"operation": "accept_task"}, _config())
+async def test_reassign_returns_delegation_request_for_the_new_assignee():
+ """reassign moves the row to queued, and nothing sweeps queued rows —
+ the scheduling envelope is the ONLY runner. Without it the mutation
+ flipped the DB row and the work silently never re-ran."""
+ service = SimpleNamespace(
+ mutate_durable_task=AsyncMock(return_value={
+ "id": "task-3", "revision": 6, "status": "queued",
+ "assigned_to": "child-1", "mission": "Find evidence",
+ "context": {"topic": "queues"},
+ }),
+ )
+ with patch("services.agent_team.get_agent_team_service", return_value=service):
+ result = await _execute_task_manager({
+ "operation": "reassign_task", "task_id": "task-3",
+ "expected_revision": 5, "assignee_node_id": "child-1",
+ }, _config())
+
+ assert result["task"]["status"] == "queued"
+ envelope = result["delegation_request"]
+ assert envelope["team_task_id"] == "task-3"
+ assert envelope["assignee_node_id"] == "child-1"
+ assert envelope["delegate_name"]
+ assert envelope["task"] == "Find evidence"
+ assert envelope["context"] == {"topic": "queues"}
+
+
+async def test_retry_returns_delegation_request_for_the_current_assignee():
+ row = {
+ "id": "task-4", "revision": 2, "status": "failed",
+ "assigned_to": "child-1", "mission": "Find evidence", "context": {},
+ }
+ service = SimpleNamespace(
+ get_durable_task=AsyncMock(return_value=row),
+ mutate_durable_task=AsyncMock(return_value={
+ **row, "revision": 3, "status": "queued",
+ }),
+ )
+ with patch("services.agent_team.get_agent_team_service", return_value=service):
+ result = await _execute_task_manager(
+ {"operation": "retry_task", "task_id": "task-4"}, _config()
+ )
+
+ envelope = result["delegation_request"]
+ assert envelope["team_task_id"] == "task-4"
+ assert envelope["assignee_node_id"] == "child-1"
+ assert envelope["task"] == "Find evidence"
+
+
+async def test_accept_returns_no_delegation_request():
+ submitted = {"id": "task-5", "revision": 4, "status": "submitted"}
+ service = SimpleNamespace(
+ list_durable_tasks=AsyncMock(return_value=[submitted]),
+ mutate_durable_task=AsyncMock(
+ return_value={**submitted, "revision": 5, "status": "accepted"}
+ ),
+ )
+ with patch("services.agent_team.get_agent_team_service", return_value=service):
+ result = await _execute_task_manager({"operation": "accept_task"}, _config())
+
+ assert "delegation_request" not in result
+
+
@pytest.mark.asyncio
async def test_list_tasks_can_include_prior_executions():
service = SimpleNamespace(list_durable_task_history=AsyncMock(return_value=[