Skip to content

Self-improving AI Employees for everyone

fix(agent): tool-call dispatch, compaction contract, reset wipe, live events

trohitg656ccdd15ab4
diff --git a/server/nodes/context/__init__.py b/server/nodes/context/__init__.py
index ad2df308..1451b3c4 100644
--- a/server/nodes/context/__init__.py
+++ b/server/nodes/context/__init__.py
@@ -89,13 +89,51 @@ class AgentContextNode(ActionNode):
graph: dict,
database,
) -> dict:
- """Nothing to rotate: a Reset admits a new generation, and the
- generation is part of the conversation key, so the next run starts
- an empty conversation automatically. Prior-generation rows stay as
- readable history until the workflow is deleted or cleared."""
-
- del node_id, workflow_id, execution_id, generation, graph, database
- return {"reset": False, "rotated_threads": 0}
+ """Workflow Reset wipes this workflow's stored conversations.
+
+ The next Start admits a new generation (a new key) anyway, but the
+ panel shows the newest STORED generation — so surviving rows would
+ keep rendering the pre-Reset conversation as the live context and
+ Reset would look like it did nothing. Warm claude subprocesses
+ still holding the wiped conversation are terminated (the
+ generation fence in ``acquire`` covers the next Start
+ independently), and a ``context.updated`` broadcast refreshes any
+ open panel.
+ """
+
+ del graph
+ if generation <= 0:
+ return {"reset": False, "cleared_conversations": 0}
+ from services.agent_context import clear_conversation
+
+ cleared = await clear_conversation(
+ database, workflow_id=str(workflow_id)
+ )
+ try:
+ from services.cli_agent.factory import get_session_pool
+
+ pool = get_session_pool("claude")
+ terminate = getattr(pool, "terminate_conversations", None)
+ if callable(terminate):
+ await terminate(str(workflow_id))
+ except Exception:
+ # Best-effort: the acquire-time generation fence still protects
+ # the next Start from reusing a stale warm process.
+ pass
+ try:
+ from ._events import dispatch_context_updated
+
+ await dispatch_context_updated(
+ workflow_id=str(workflow_id),
+ generation=generation,
+ agent_node_id=str(node_id),
+ message_count=0,
+ )
+ except Exception:
+ # Lifecycle state is authoritative; the broadcast is a UI
+ # notification and may be retried by a manual panel refresh.
+ pass
+ return {"reset": True, "cleared_conversations": cleared}
__all__ = [
diff --git a/server/nodes/context/_handlers.py b/server/nodes/context/_handlers.py
index 5fe1f430..f4f82a19 100644
--- a/server/nodes/context/_handlers.py
+++ b/server/nodes/context/_handlers.py
@@ -111,12 +111,15 @@ async def handle_get_agent_context(
data: Dict[str, Any],
websocket: WebSocket,
) -> Dict[str, Any]:
- """Return the stored conversations for one workflow's Context node.
-
- ``conversations`` lists every stored row (newest generation first) so
- the panel can offer a selector; ``messages`` is the transcript of the
- selected row — the requested ``generation``/``agent_node_id`` when
- given, else the newest one.
+ """Return the live conversation for one workflow's Context node.
+
+ The panel shows the agent's CURRENT context only: rows from the newest
+ stored generation. Prior generations stay in the store as inert history
+ (cleared with the workflow) but are deliberately not browsable here.
+ ``conversations`` lists the live generation's agents so the panel can
+ offer a selector when several agents share the Context node;
+ ``messages`` is the transcript of the requested ``agent_node_id``, else
+ the newest row.
"""
workflow_id = str(data.get("workflow_id") or "")
@@ -126,20 +129,21 @@ async def handle_get_agent_context(
workflow_id=workflow_id,
context_node_id=context_node_id,
)
- generation = _optional_generation(data)
agent_node_id = str(data.get("agent_node_id") or "") or None
database = _database()
- conversations = await list_conversations(database, workflow_id=workflow_id)
+ rows = await list_conversations(database, workflow_id=workflow_id)
+ # list_conversations orders newest generation first; the live context
+ # is that generation only.
+ live_generation = rows[0]["generation"] if rows else None
+ conversations = [
+ row for row in rows if row["generation"] == live_generation
+ ]
selected = next(
(
row
for row in conversations
- if (generation is None or row["generation"] == generation)
- and (
- agent_node_id is None
- or row["agent_node_id"] == agent_node_id
- )
+ if agent_node_id is None or row["agent_node_id"] == agent_node_id
),
None,
)
diff --git a/server/nodes/tool/simple_memory/__init__.py b/server/nodes/tool/simple_memory/__init__.py
index 0ef986f7..15176ffd 100644
--- a/server/nodes/tool/simple_memory/__init__.py
+++ b/server/nodes/tool/simple_memory/__init__.py
@@ -155,18 +155,31 @@ class SimpleMemoryOutput(BaseModel):
class SimpleMemoryNode(ToolNode):
type = "simpleMemory"
- display_name = "Simple Memory"
- subtitle = "Explicit Durable Memory"
+ # Wire type stays "simpleMemory" (stored verbatim in graphs, pool keys
+ # and migrations — renaming it is a breaking graph change); only the
+ # human-facing name is "Memory".
+ display_name = "Memory"
+ subtitle = "Durable Agent Memory"
group = ("tool", "memory")
description = (
"Explicitly remember, recall, list, update, and forget durable facts"
)
component_kind = "tool"
tool_name = "memory"
+ # The LLM-facing contract. The imperative "check before claiming
+ # ignorance" clause is load-bearing: with the earlier passive wording
+ # ("store and retrieve when useful"), models answered "I don't know who
+ # you are" from priors while the user's name sat one recall away.
tool_description = (
- "Store and retrieve durable memories only when useful. Use remember "
- "for stable facts or decisions; use recall/list/get to retrieve them; "
- "use update/forget with the item's expected_version."
+ "Durable long-term memory that persists across conversations and "
+ "may already hold facts about the user (name, preferences, "
+ "decisions, prior work). ALWAYS check it first — recall with a "
+ "search query, or list — before answering anything about the user, "
+ "their preferences, or earlier decisions; never say you don't know "
+ "or lack access to such information without checking memory. Use "
+ "remember to store new stable facts the user shares; use "
+ "update/forget with the item's expected_version to correct or "
+ "remove them."
)
handles = (
{
@@ -284,6 +297,14 @@ class SimpleMemoryNode(ToolNode):
)
except MemoryStoreError as exc:
raise NodeUserError(str(exc)) from exc
+ if args.operation in ("remember", "update", "forget"):
+ from ._events import dispatch_memory_updated
+
+ await dispatch_memory_updated(
+ workflow_id=scope.workflow_id,
+ memory_node_id=scope.memory_node_id,
+ operation=args.operation,
+ )
return SimpleMemoryOutput.model_validate(result)
@classmethod
diff --git a/server/nodes/tool/simple_memory/_events.py b/server/nodes/tool/simple_memory/_events.py
new file mode 100644
index 00000000..1c1d76c9
--- /dev/null
+++ b/server/nodes/tool/simple_memory/_events.py
@@ -0,0 +1,70 @@
+"""CloudEvents factory for Simple Memory mutations.
+
+One event: ``memory.updated``, broadcast after a durable remember / update /
+forget / clear. Broadcast directly via the status broadcaster (not
+``services.events.dispatch.emit`` — no canary consumer exists for
+``com.opencompany.memory.*``, so routing through ``emit`` would run a
+Temporal Visibility query guaranteed to match nothing per mutation).
+
+The payload is identity-only — never item content: the broadcast fans out
+to every connected socket, and the panel refetches through the authorized
+``list_memory_items`` handler.
+"""
+
+from __future__ import annotations
+
+from core.logging import get_logger
+from services.events.envelope import WorkflowEvent
+
+logger = get_logger(__name__)
+
+_SOURCE = "opencompany://nodes/simple_memory"
+
+
+def memory_updated(
+ *,
+ workflow_id: str,
+ memory_node_id: str,
+ operation: str,
+) -> WorkflowEvent:
+ return WorkflowEvent(
+ source=_SOURCE,
+ type="com.opencompany.memory.updated",
+ subject=str(memory_node_id),
+ data={
+ "workflow_id": str(workflow_id),
+ "memory_node_id": str(memory_node_id),
+ "operation": str(operation),
+ },
+ )
+
+
+async def dispatch_memory_updated(
+ *,
+ workflow_id: str,
+ memory_node_id: str,
+ operation: str,
+) -> None:
+ """Best-effort panel notification; a broadcast failure never fails
+ the mutation that triggered it."""
+
+ try:
+ from services.status_broadcaster import get_status_broadcaster
+
+ await get_status_broadcaster().broadcast(
+ {
+ "type": "memory.updated",
+ "data": memory_updated(
+ workflow_id=workflow_id,
+ memory_node_id=memory_node_id,
+ operation=operation,
+ ).model_dump(mode="json", exclude_none=True),
+ }
+ )
+ except Exception as exc: # noqa: BLE001 — notification only
+ # WARNING, not debug: a silently failing broadcast is exactly how
+ # "the panel never updates live" becomes undiagnosable.
+ logger.warning("[Memory] update broadcast failed: %s", exc)
+
+
+__all__ = ["dispatch_memory_updated", "memory_updated"]
diff --git a/server/nodes/tool/simple_memory/_handlers.py b/server/nodes/tool/simple_memory/_handlers.py
index 42ae7073..36d08a07 100644
--- a/server/nodes/tool/simple_memory/_handlers.py
+++ b/server/nodes/tool/simple_memory/_handlers.py
@@ -23,6 +23,7 @@ from services.plugin.deps import get_database
from services.plugin.ws import ws_response
from . import SimpleMemoryToolInput
+from ._events import dispatch_memory_updated
def _authenticated_owner(websocket: WebSocket) -> str:
@@ -194,6 +195,11 @@ async def handle_remember_memory(
expires_at=args.expires_at,
operation_id=_operation_id(data, "remember"),
)
+ await dispatch_memory_updated(
+ workflow_id=scope.workflow_id,
+ memory_node_id=scope.memory_node_id,
+ operation="remember",
+ )
return {"success": True, **result}
@@ -214,6 +220,11 @@ async def handle_update_memory_item(
)
except MemoryStoreError as exc:
raise NodeUserError(str(exc)) from exc
+ await dispatch_memory_updated(
+ workflow_id=scope.workflow_id,
+ memory_node_id=scope.memory_node_id,
+ operation="update",
+ )
return {"success": True, **result}
@@ -232,6 +243,11 @@ async def handle_forget_memory_item(
)
except MemoryStoreError as exc:
raise NodeUserError(str(exc)) from exc
+ await dispatch_memory_updated(
+ workflow_id=scope.workflow_id,
+ memory_node_id=scope.memory_node_id,
+ operation="forget",
+ )
return {"success": True, **result}
@@ -245,6 +261,11 @@ async def handle_clear_memory_items(
scope,
operation_id=_operation_id(data, "clear"),
)
+ await dispatch_memory_updated(
+ workflow_id=scope.workflow_id,
+ memory_node_id=scope.memory_node_id,
+ operation="clear",
+ )
return {"success": True, **result}
diff --git a/server/services/agent_context/conversation.py b/server/services/agent_context/conversation.py
index fab23421..fe70a74d 100644
--- a/server/services/agent_context/conversation.py
+++ b/server/services/agent_context/conversation.py
@@ -62,6 +62,42 @@ async def load_conversation(
return list(row.messages or []) if row else []
+def _without_ts(message: Dict[str, Any]) -> Dict[str, Any]:
+ return {key: value for key, value in message.items() if key != "ts"}
+
+
+def _stamp_messages(
+ incoming: List[Dict[str, Any]],
+ existing: List[Any],
+ now_iso: str,
+) -> List[Dict[str, Any]]:
+ """Attach a ``ts`` to every stored message.
+
+ Callers regenerate wires from live ``Message`` objects each turn, so an
+ incoming list never carries stamps of its own. The conversation is
+ append-only per turn: an incoming entry that matches the stored entry
+ at the same index (ignoring ``ts``) keeps its original stamp; anything
+ new or changed is stamped now. ``ts`` is a stored-view field only —
+ ``message_from_wire`` ignores it, so it never reaches a provider.
+ """
+
+ stamped: List[Dict[str, Any]] = []
+ for index, message in enumerate(incoming):
+ entry = dict(message)
+ previous = existing[index] if index < len(existing) else None
+ if (
+ not entry.get("ts")
+ and isinstance(previous, dict)
+ and previous.get("ts")
+ and _without_ts(previous) == _without_ts(entry)
+ ):
+ entry["ts"] = previous["ts"]
+ elif not entry.get("ts"):
+ entry["ts"] = now_iso
+ stamped.append(entry)
+ return stamped
+
+
async def save_conversation(
database: Any,
*,
@@ -88,7 +124,11 @@ async def save_conversation(
generation=generation,
agent_node_id=agent_node_id,
)
- row.messages = [dict(m) for m in messages if isinstance(m, dict)]
+ row.messages = _stamp_messages(
+ [dict(m) for m in messages if isinstance(m, dict)],
+ list(row.messages or []),
+ datetime.now(timezone.utc).isoformat(),
+ )
row.updated_at = datetime.now(timezone.utc)
session.add(row)
await session.commit()
diff --git a/server/services/agent_context/listeners.py b/server/services/agent_context/listeners.py
index eeb4d818..5276f746 100644
--- a/server/services/agent_context/listeners.py
+++ b/server/services/agent_context/listeners.py
@@ -66,7 +66,11 @@ async def notify_conversation_saved(
message_count=message_count,
)
except Exception: # noqa: BLE001 — a notification may never fail a save
- logger.debug(
+ # WARNING, not debug: a silently failing listener is exactly how
+ # "the panel never updates live" becomes undiagnosable — the save
+ # succeeds, the run continues, and nothing in the operator log
+ # hints that the broadcast chain is broken.
+ logger.warning(
"Conversation listener failed",
listener=getattr(listener, "__qualname__", repr(listener)),
exc_info=True,
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index 0a64b276..782373b7 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -417,6 +417,23 @@ class BaseNode:
context=context,
connection_factory=_make_connection_factory(cls, context),
)
+ # An LLM-invoked tool call carries its unmerged model arguments
+ # in ``context["tool_args"]`` (Temporal per-type activity path).
+ # ToolNodes must take execute_as_tool so a split ToolInput schema
+ # validates the model's arguments — plain execute validates
+ # against Params, whose extra="ignore" silently drops them (a
+ # Simple Memory remember degraded to a no-op list this way).
+ # Dual-purpose ActionNodes keep their documented merged-params
+ # contract unchanged.
+ from services.plugin.tool import ToolNode
+
+ tool_args = context.get("tool_args")
+ if isinstance(tool_args, dict) and isinstance(instance, ToolNode):
+ return await instance.execute_as_tool(
+ tool_args,
+ parameters,
+ ctx,
+ )
return await instance.execute(node_id, parameters, ctx)
_legacy.__node_class__ = cls # type: ignore[attr-defined]
@@ -1030,6 +1047,11 @@ class BaseNode:
"parent_node_id",
"team_lead_node_id",
"root_execution_id",
+ # The model's unmerged arguments for an LLM-invoked tool
+ # call; routes ToolNodes through execute_as_tool in the
+ # legacy handler so split-schema ToolInput validation
+ # applies on the Temporal path too.
+ "tool_args",
):
if key in context:
extras[key] = context[key]
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index 7426902a..7fd53744 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -2005,10 +2005,16 @@ async def compact_context(payload: Dict[str, Any]) -> Dict[str, Any]:
)
lines.append(line)
+ rendered = "\n\n".join(lines)
+ activity.logger.info(
+ f"Compacting agent context: {len(lines)} messages "
+ f"({len(rendered)} rendered chars) via "
+ f"{payload['provider']}/{payload['model']}"
+ )
result = await svc.compact_context(
session_id=str(payload.get("session_id") or "default"),
node_id=payload["node_id"],
- memory_content="\n\n".join(lines),
+ memory_content=rendered,
provider=payload["provider"],
api_key=await _resolve_activity_api_key(payload),
model=payload["model"],
@@ -2016,6 +2022,14 @@ async def compact_context(payload: Dict[str, Any]) -> Dict[str, Any]:
# request inside the activity or SDK.
explicit_max_retries=0,
)
+ if result.get("success") and result.get("summary"):
+ usage = result.get("usage") or {}
+ activity.logger.info(
+ f"Agent context compacted: summary {len(result['summary'])} "
+ f"chars (summarizer usage: "
+ f"in={usage.get('input_tokens', 0)} "
+ f"out={usage.get('output_tokens', 0)})"
+ )
if not result.get("success") or not result.get("summary"):
# Compaction is the run's pressure-relief valve. Raising (retryable)
# gives transient summarizer failures the activity policy's retry
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index 77bf183a..fd588b6e 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -1662,6 +1662,13 @@ class AgentWorkflow:
"node_id": tool_info["tool_node_id"],
"node_type": tool_info["node_type"],
"node_data": tool_node_data,
+ # The model's arguments, unmerged. ToolNodes with a split
+ # ToolInput schema must validate these on their own — the
+ # merged node_data above validates against Params
+ # (extra="ignore"), which silently DROPS model arguments
+ # like Simple Memory's operation/content and degrades the
+ # call to a no-op.
+ "tool_args": call_args,
"inputs": {},
"workflow_id": payload.get("workflow_id"),
"session_id": payload.get("session_id", "default"),
@@ -2058,7 +2065,11 @@ class AgentWorkflow:
)
)
if compaction_threshold and token_total >= compaction_threshold:
- workflow.logger.info(f"AgentWorkflow compaction triggered: {token_total} tokens")
+ workflow.logger.info(
+ f"AgentWorkflow compaction triggered at iteration "
+ f"{iteration + 1}: {token_total} tokens >= threshold "
+ f"{compaction_threshold} ({len(messages)} live messages)"
+ )
compact_payload = {
"session_id": payload.get("session_id", "default"),
"node_id": payload["node_id"],
@@ -2135,25 +2146,54 @@ class AgentWorkflow:
# The activity raises on any failure, so a result here
# always carries a non-empty summary.
summary = compact_result.get("summary", "")
- # Replace the running messages with the summary plus the
- # last user prompt — same pattern ``CompactionService``
- # uses today in services/ai.py.
- compacted_content = f"## Compacted summary:\n{summary}"
+ dropped_count = len(messages)
+ # Rebuild as: the ORIGINAL system prompt, verbatim, plus ONE
+ # user message carrying the summary and the live request.
+ #
+ # The system prompt must never be modified or duplicated by
+ # compaction: (1) it is the agent's contract (personality +
+ # tool/delegation guidance) and must stay byte-stable for
+ # provider prompt caching and behavioral consistency; (2) the
+ # next firing's seeding drops stored system messages so
+ # policy changes take effect — anything compaction stores
+ # under the system role silently vanishes on the next
+ # firing, which is how a summary once survived only until
+ # the next chat message while the noisy tool tail outlived
+ # it.
+ #
+ # The summary rides a USER message for the same reason: user
+ # wires persist through seeding, so the compacted knowledge
+ # crosses firings with the conversation it summarizes.
+ compacted_content = (
+ "## Compacted conversation summary\n"
+ "The conversation so far was compacted to stay within "
+ "the model's context window. Treat this summary as the "
+ "authoritative record of prior work; do not repeat "
+ "completed steps.\n\n"
+ f"{summary}"
+ )
+ if user_prompt:
+ compacted_content += (
+ f"\n\n## Current request\n{user_prompt}"
+ )
messages = [
_native_message(
role="system",
content=system,
),
- _native_message(
- role="system",
- content=compacted_content,
- ),
_native_message(
role="user",
- content=user_prompt,
+ content=compacted_content,
),
]
context_usage_total = {}
+ workflow.logger.info(
+ f"AgentWorkflow compaction applied at iteration "
+ f"{iteration + 1}: {dropped_count} messages -> "
+ f"{len(messages)} (summary {len(summary)} chars; prior "
+ "tool calls/results now live only inside the summary; "
+ "system prompt preserved verbatim)"
+ )
# ---- Continue-as-new -------------------------------------
# Only at a clean turn boundary, and never while a delegation
diff --git a/server/tests/nodes/test_context_handlers.py b/server/tests/nodes/test_context_handlers.py
new file mode 100644
index 00000000..75cff7a7
--- /dev/null
+++ b/server/tests/nodes/test_context_handlers.py
@@ -0,0 +1,213 @@
+"""Contract for the Context panel WS handlers over the plain store.
+
+The panel shows the agent's CURRENT context only — rows from the newest
+stored generation. Prior generations stay in the store as inert history
+but are deliberately not browsable from the panel.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+import uuid
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from services.agent_context import save_conversation
+
+
+async def handler_database():
+ # Root conftest stubs core.database; load the real module privately.
+ module_name = f"tests._context_handler_database_{uuid.uuid4().hex}"
+ spec = importlib.util.spec_from_file_location(
+ module_name,
+ Path(__file__).resolve().parents[2] / "core" / "database.py",
+ )
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+
+ db_path = Path.cwd() / f".context-handler-{uuid.uuid4().hex}.db"
+ database = module.Database(
+ SimpleNamespace(
+ database_url=f"sqlite+aiosqlite:///{db_path.as_posix()}",
+ database_echo=False,
+ database_pool_size=5,
+ database_max_overflow=5,
+ )
+ )
+ await database.startup()
+ try:
+ yield database
+ finally:
+ await database.shutdown()
+ sys.modules.pop(module_name, None)
+ for candidate in (
+ db_path,
+ Path(f"{db_path}-wal"),
+ Path(f"{db_path}-shm"),
+ ):
+ candidate.unlink(missing_ok=True)
+
+
+class _Socket:
+ """Authenticated external socket double."""
+
+ state = SimpleNamespace(user_id="owner")
+ scope = {"path": "/ws/status", "user_id": "owner"}
+
+
+def _graph() -> dict:
+ return {
+ "owner_id": "owner",
+ "nodes": [
+ {"id": "ctx-1", "type": "context"},
+ {"id": "agent-a", "type": "aiAgent"},
+ ],
+ "edges": [],
+ }
+
+
+async def test_get_agent_context_returns_the_live_generation_only(
+ handler_database, monkeypatch
+):
+ from nodes.context import _handlers
+
+ database = handler_database
+ assert await database.save_workflow("wf-1", "WF", "wf", _graph())
+ for generation, content in ((1, "old"), (2, "live")):
+ await save_conversation(
+ database,
+ workflow_id="wf-1",
+ generation=generation,
+ agent_node_id="agent-a",
+ messages=[{"role": "user", "content": content}],
+ )
+ await save_conversation(
+ database,
+ workflow_id="wf-1",
+ generation=2,
+ agent_node_id="agent-b",
+ messages=[{"role": "user", "content": "sibling"}],
+ )
+ monkeypatch.setattr(_handlers, "_database", lambda: database)
+
+ result = await _handlers.handle_get_agent_context(
+ {"workflow_id": "wf-1", "context_node_id": "ctx-1"},
+ _Socket(),
+ )
+
+ assert result["success"] is True
+ context = result["context"]
+ # Only the newest generation's agents are listed.
+ assert {row["generation"] for row in context["conversations"]} == {2}
+ assert {row["agent_node_id"] for row in context["conversations"]} == {
+ "agent-a",
+ "agent-b",
+ }
+ # Default selection is the newest row; its transcript is the live one.
+ assert context["generation"] == 2
+ assert [m["content"] for m in context["messages"]] in (
+ ["live"],
+ ["sibling"],
+ )
+
+ # Selecting a specific agent narrows within the live generation.
+ narrowed = await _handlers.handle_get_agent_context(
+ {
+ "workflow_id": "wf-1",
+ "context_node_id": "ctx-1",
+ "agent_node_id": "agent-a",
+ },
+ _Socket(),
+ )
+ assert narrowed["context"]["agent_node_id"] == "agent-a"
+ assert [m["content"] for m in narrowed["context"]["messages"]] == ["live"]
+
+
+async def test_workflow_reset_clears_the_stored_conversations(
+ handler_database, monkeypatch
+):
+ """Reset must actually wipe: the panel shows the newest STORED
+ generation, so surviving rows would keep rendering the pre-Reset
+ conversation as the live context and Reset would look like a no-op."""
+
+ from nodes.context import AgentContextNode
+ from services.agent_context import list_conversations
+
+ database = handler_database
+ for generation in (1, 2):
+ await save_conversation(
+ database,
+ workflow_id="wf-1",
+ generation=generation,
+ agent_node_id="agent-a",
+ messages=[{"role": "user", "content": "before reset"}],
+ )
+
+ broadcasts: list[dict] = []
+
+ async def capture(**kwargs):
+ broadcasts.append(kwargs)
+
+ from nodes.context import _events
+
+ monkeypatch.setattr(_events, "dispatch_context_updated", capture)
+
+ result = await AgentContextNode.reset_execution_state(
+ node_id="ctx-1",
+ workflow_id="wf-1",
+ execution_id="exec-1",
+ generation=2,
+ graph={},
+ database=database,
+ )
+
+ assert result["reset"] is True
+ assert result["cleared_conversations"] == 2
+ assert await list_conversations(database, workflow_id="wf-1") == []
+ # An open panel refreshes off the broadcast rather than waiting for a
+ # manual refresh.
+ assert broadcasts and broadcasts[0]["workflow_id"] == "wf-1"
+
+
+async def test_reset_without_an_admitted_generation_is_a_no_op(
+ handler_database,
+):
+ from nodes.context import AgentContextNode
+
+ result = await AgentContextNode.reset_execution_state(
+ node_id="ctx-1",
+ workflow_id="wf-1",
+ execution_id="exec-1",
+ generation=0,
+ graph={},
+ database=handler_database,
+ )
+ assert result == {"reset": False, "cleared_conversations": 0}
+
+
+async def test_get_agent_context_empty_store_is_an_empty_context(
+ handler_database, monkeypatch
+):
+ from nodes.context import _handlers
+
+ database = handler_database
+ assert await database.save_workflow("wf-1", "WF", "wf", _graph())
+ monkeypatch.setattr(_handlers, "_database", lambda: database)
+
+ result = await _handlers.handle_get_agent_context(
+ {"workflow_id": "wf-1", "context_node_id": "ctx-1"},
+ _Socket(),
+ )
+ assert result["success"] is True
+ assert result["context"]["conversations"] == []
+ assert result["context"]["messages"] == []
diff --git a/server/tests/nodes/test_tool_call_dispatch.py b/server/tests/nodes/test_tool_call_dispatch.py
new file mode 100644
index 00000000..c1b4b048
--- /dev/null
+++ b/server/tests/nodes/test_tool_call_dispatch.py
@@ -0,0 +1,256 @@
+"""LLM tool calls must reach ToolNodes through execute_as_tool everywhere.
+
+The Temporal AgentWorkflow schedules each tool call as the tool's own
+per-type activity, which executes through the plugin's legacy handler.
+That handler used to call plain ``execute``, validating the merged
+params+args dict against ``Params`` — and for a split-schema ToolNode like
+Simple Memory (``Params`` is ``extra="ignore"``), the model's ``operation``
+and ``content`` were silently dropped and every ``remember`` degraded to a
+harmless ``list``. The activity reported success, the agent believed it
+had remembered, and the store stayed empty.
+
+The fix threads the model's unmerged arguments as ``context["tool_args"]``
+(agent_workflow payload → as_activity extras → legacy handler), which
+routes ToolNodes through ``execute_as_tool`` with real ToolInput
+validation.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+import uuid
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import ANY, AsyncMock, patch
+
+import pytest
+
+from nodes.tool.simple_memory import SimpleMemoryNode
+
+
+async def memory_database():
+ # Root conftest stubs core.database for fast unit tests; load the real
+ # implementation privately (same pattern as tests/services/memory/).
+ module_name = f"tests._tool_dispatch_database_{uuid.uuid4().hex}"
+ spec = importlib.util.spec_from_file_location(
+ module_name,
+ Path(__file__).resolve().parents[2] / "core" / "database.py",
+ )
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+
+ db_path = Path.cwd() / f".tool-dispatch-{uuid.uuid4().hex}.db"
+ database = module.Database(
+ SimpleNamespace(
+ database_url=f"sqlite+aiosqlite:///{db_path.as_posix()}",
+ database_echo=False,
+ database_pool_size=5,
+ database_max_overflow=5,
+ )
+ )
+ await database.startup()
+ try:
+ yield database
+ finally:
+ await database.shutdown()
+ sys.modules.pop(module_name, None)
+ for candidate in (
+ db_path,
+ Path(f"{db_path}-wal"),
+ Path(f"{db_path}-shm"),
+ ):
+ candidate.unlink(missing_ok=True)
+
+
+def _context(**extra):
+ return {
+ "workflow_id": "wf-1",
+ "user_id": "owner",
+ "session_id": "default",
+ "execution_id": "run-1",
+ **extra,
+ }
+
+
+async def test_tool_args_route_toolnodes_through_execute_as_tool():
+ handler = SimpleMemoryNode._make_legacy_handler()
+ tool_args = {"operation": "remember", "content": "launch is Tuesday"}
+ with patch.object(
+ SimpleMemoryNode,
+ "execute_as_tool",
+ AsyncMock(return_value={"operation": "remember"}),
+ ) as as_tool:
+ result = await handler(
+ "mem-1",
+ "simpleMemory",
+ {"reset_policy": "preserve", **tool_args},
+ _context(tool_args=tool_args),
+ )
+ as_tool.assert_awaited_once_with(
+ tool_args,
+ {"reset_policy": "preserve", **tool_args},
+ ANY,
+ )
+ assert result == {"operation": "remember"}
+
+
+async def test_plain_execution_without_tool_args_is_unchanged():
+ """A canvas Run of a tool node (no tool_args) keeps the execute path."""
+ handler = SimpleMemoryNode._make_legacy_handler()
+ with patch.object(
+ SimpleMemoryNode,
+ "execute",
+ AsyncMock(return_value={"operation": "list", "items": []}),
+ ) as execute, patch.object(
+ SimpleMemoryNode,
+ "execute_as_tool",
+ AsyncMock(),
+ ) as as_tool:
+ await handler(
+ "mem-1",
+ "simpleMemory",
+ {"reset_policy": "preserve"},
+ _context(),
+ )
+ execute.assert_awaited_once()
+ as_tool.assert_not_awaited()
+
+
+async def test_remember_through_the_activity_path_actually_stores(
+ memory_database, monkeypatch
+):
+ """The regression, end to end: the merged dict alone stored nothing."""
+ import nodes.tool.simple_memory as simple_memory_module
+
+ monkeypatch.setattr(
+ simple_memory_module, "get_database", lambda: memory_database
+ )
+ handler = SimpleMemoryNode._make_legacy_handler()
+ tool_args = {"operation": "remember", "content": "the launch is Tuesday"}
+ # node_data is the merged params+args dict exactly as the AgentWorkflow
+ # builds it; tool_args rides alongside, unmerged.
+ result = await handler(
+ "1:simpleMemory:1",
+ "simpleMemory",
+ {"reset_policy": "preserve", **tool_args},
+ _context(tool_args=tool_args, tool_call_id="call-1"),
+ )
+ assert result.get("operation") == "remember"
+ assert result.get("memory", {}).get("content") == "the launch is Tuesday"
+
+ from services.memory.tool_store import MemoryScope, MemoryToolStore
+
+ listing = await MemoryToolStore(memory_database).list(
+ MemoryScope(
+ owner_id="owner",
+ workflow_id="wf-1",
+ memory_node_id="1:simpleMemory:1",
+ )
+ )
+ assert [item["content"] for item in listing["items"]] == [
+ "the launch is Tuesday"
+ ]
+
+
+def test_agent_workflow_payload_carries_unmerged_tool_args():
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ source = inspect.getsource(AgentWorkflow.run)
+ assert '"tool_args": call_args' in source, (
+ "the per-type tool activity payload must carry the model's unmerged "
+ "arguments or split-schema ToolNodes silently drop them"
+ )
+
+
+def test_as_activity_forwards_tool_args_into_context():
+ import inspect
+
+ from services.plugin.base import BaseNode
+
+ source = inspect.getsource(BaseNode.as_activity.__func__)
+ assert '"tool_args"' in source, (
+ "as_activity must forward tool_args through extras so the legacy "
+ "handler can route ToolNodes through execute_as_tool"
+ )
+
+
+async def test_memory_mutations_broadcast_a_panel_refresh(monkeypatch):
+ """Both writers announce durable mutations so the panel stays live."""
+ from nodes.tool.simple_memory import _events
+
+ sent: list[dict] = []
+
+ async def capture(**kwargs):
+ sent.append(kwargs)
+
+ monkeypatch.setattr(_events, "dispatch_memory_updated", capture)
+ import nodes.tool.simple_memory as plugin_module
+
+ monkeypatch.setattr(
+ plugin_module, "dispatch_memory_updated", capture, raising=False
+ )
+
+ class _Store:
+ async def remember(self, scope, **kwargs):
+ return {"operation": "remember", "memory": {"id": "m1"}}
+
+ with patch.object(
+ plugin_module, "MemoryToolStore", lambda _db: _Store()
+ ), patch.object(plugin_module, "get_database", lambda: object()):
+ node = SimpleMemoryNode()
+ from services.plugin.context import NodeContext
+
+ ctx = NodeContext(
+ node_id="1:simpleMemory:1",
+ node_type="simpleMemory",
+ raw={"workflow_id": "wf-1", "user_id": "owner"},
+ )
+ from nodes.tool.simple_memory import SimpleMemoryToolInput
+
+ await node.memory(
+ ctx,
+ SimpleMemoryToolInput(operation="remember", content="x"),
+ )
+ assert sent == [
+ {
+ "workflow_id": "wf-1",
+ "memory_node_id": "1:simpleMemory:1",
+ "operation": "remember",
+ }
+ ]
+
+
+def test_frontend_handles_the_memory_wire_key():
+ """Same direction as the context.updated lock: the backend owns the
+ wire key, and renaming it would silently stop the Memory panel
+ refreshing with no test failing anywhere."""
+ import inspect
+ import re
+
+ from nodes.tool.simple_memory import _events
+
+ source = inspect.getsource(_events)
+ emitted = set(re.findall(r'"type": "([a-z.]+)"', source))
+ assert "memory.updated" in emitted
+
+ ws_context = (
+ Path(__file__).resolve().parents[3]
+ / "client"
+ / "src"
+ / "contexts"
+ / "WebSocketContext.tsx"
+ )
+ if not ws_context.exists(): # server-only checkouts
+ pytest.skip("client sources not present")
+ consumed = ws_context.read_text(encoding="utf-8")
+ assert "case 'memory.updated'" in consumed
diff --git a/server/tests/services/agent_context/test_conversation.py b/server/tests/services/agent_context/test_conversation.py
index 58806a5a..a689f8d4 100644
--- a/server/tests/services/agent_context/test_conversation.py
+++ b/server/tests/services/agent_context/test_conversation.py
@@ -95,6 +95,10 @@ _KEY = {
}
+def _sans_ts(messages: list[dict]) -> list[dict]:
+ return [{k: v for k, v in m.items() if k != "ts"} for m in messages]
+
+
@pytest.mark.asyncio
async def test_load_returns_exactly_what_save_committed(
conversation_database, isolated_listeners
@@ -103,7 +107,10 @@ async def test_load_returns_exactly_what_save_committed(
await save_conversation(
conversation_database, **_KEY, messages=messages
)
- assert await load_conversation(conversation_database, **_KEY) == messages
+ stored = await load_conversation(conversation_database, **_KEY)
+ # Content round-trips exactly; the store adds a view-only `ts` stamp.
+ assert _sans_ts(stored) == messages
+ assert all(m.get("ts") for m in stored)
@pytest.mark.asyncio
@@ -126,7 +133,10 @@ async def test_save_is_an_upsert_replacing_the_whole_list(
await save_conversation(
conversation_database, **_KEY, messages=replacement
)
- assert await load_conversation(conversation_database, **_KEY) == replacement
+ assert (
+ _sans_ts(await load_conversation(conversation_database, **_KEY))
+ == replacement
+ )
rows = await list_conversations(
conversation_database, workflow_id=_KEY["workflow_id"]
)
@@ -134,6 +144,33 @@ async def test_save_is_an_upsert_replacing_the_whole_list(
assert rows[0]["message_count"] == 3
+async def test_timestamps_stamp_new_messages_and_preserve_old_ones(
+ conversation_database, isolated_listeners
+):
+ """Callers regenerate wires each turn (no stamps of their own), so the
+ store keeps the original ``ts`` for the unchanged prefix and stamps
+ only the appended turn — a message's time is when it first persisted,
+ not when the conversation last saved."""
+
+ first_turn = [_wire("user", "one"), _wire("assistant", "two")]
+ await save_conversation(
+ conversation_database, **_KEY, messages=first_turn
+ )
+ first_stored = await load_conversation(conversation_database, **_KEY)
+ original_stamps = [m["ts"] for m in first_stored]
+
+ # Next turn re-sends the SAME prefix (fresh wires, no ts) + new tail.
+ second_turn = [*first_turn, _wire("user", "three")]
+ await save_conversation(
+ conversation_database, **_KEY, messages=second_turn
+ )
+ second_stored = await load_conversation(conversation_database, **_KEY)
+ assert [m["ts"] for m in second_stored[:2]] == original_stamps
+ assert second_stored[2]["ts"]
+ assert _sans_ts(second_stored) == second_turn
+
+
@pytest.mark.asyncio
async def test_keys_are_isolated_across_generation_and_agent(
conversation_database, isolated_listeners
diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.py
index 64bd502f..7f9813a9 100644
--- a/server/tests/temporal/test_agent_workflow.py
+++ b/server/tests/temporal/test_agent_workflow.py
@@ -160,6 +160,43 @@ class TestConversationIdentity:
f"runtime): {offenders}"
)
+ def test_compaction_preserves_the_system_prompt_and_summary_survival(
+ self,
+ ):
+ """Compaction rebuilds as [original system, user(summary+request)].
+
+ Two rules are locked. (1) The system prompt is never modified or
+ duplicated: it is the agent's contract and must stay byte-stable
+ (provider prompt caching, behavioral consistency). (2) The summary
+ must NOT ride ``role="system"`` — the next firing's seeding drops
+ stored system messages so policy changes take effect, which once
+ made the summary vanish on the next chat message while the noisy
+ tool tail (non-system) survived it. As a user message, the
+ compacted knowledge crosses firings with the conversation.
+ """
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ source = inspect.getsource(AgentWorkflow.run)
+ assert "## Compacted summary:" not in source, (
+ "the old system-role summary marker is retired"
+ )
+ start = source.index('summary = compact_result.get("summary"')
+ end = source.index("context_usage_total = {}", start)
+ rebuild = source[start:end]
+ assert rebuild.count('role="system"') == 1, (
+ "compaction must keep exactly ONE system message — the "
+ "original, verbatim"
+ )
+ assert 'role="user"' in rebuild, (
+ "the summary must ride a user message so it survives the next "
+ "firing's stored-system filter"
+ )
+ # Observability: both the trigger and the applied swap are logged.
+ assert "compaction triggered at iteration" in source
+ assert "compaction applied at iteration" in source
+
def test_resumed_run_continues_from_the_carried_transcript(self):
"""continue_as_new carries the live transcript itself.