Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(events): wrap node_parameters_updated + agent_progress in CloudEvents envelopes
trohitg7c9e87314f8d
diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex ed772d08..4f5d09e4 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -159,10 +159,12 @@ async def handle_save_node_parameters(data: Dict[str, Any], websocket: WebSocketlogger.debug(f"[SAVE_PARAMS] Node ID: {node_id}, has_code: {'code' in parameters}, code_len: {len(parameters.get('code', '')) if 'code' in parameters else 0}")await database.save_node_parameters(node_id, parameters)- await broadcaster.broadcast({- "type": "node_parameters_updated", "node_id": node_id,- "parameters": parameters, "version": 1, "timestamp": time.time()- })+ # CloudEvents v1.0 envelope (RFC §6.4) — type is+ # ``com.machinaos.node.parameters.updated``; ``source_hint="user"``+ # because this handler fires from the parameter-panel save flow.+ await broadcaster.broadcast_node_parameters_updated(+ node_id, parameters=parameters, source_hint="user",+ )return {"node_id": node_id, "parameters": parameters, "version": 1, "timestamp": time.time()}diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.pyindex 86709693..3bb2adfe 100644--- a/server/services/cli_agent/service.py+++ b/server/services/cli_agent/service.py@@ -430,19 +430,17 @@ class AICliService:# Broadcast `node_parameters_updated` so the simpleMemory's# parameter panel + memory editor refetch live without a page- # reload. Mirrors the pattern in- # `routers/websocket.py:handle_save_node_parameters`. Without- # this the DB has the latest conversation but the UI keeps- # showing the stale snapshot it loaded at workflow open.+ # reload. CloudEvents v1.0 envelope (RFC §6.4) — type is+ # ``com.machinaos.node.parameters.updated``; ``source_hint="cli"``+ # distinguishes this Claude-CLI autonomous write from a user+ # parameter-panel save.if broadcaster is not None:try:- await broadcaster.broadcast({- "type": "node_parameters_updated",- "node_id": memory_node_id,- "parameters": params,- "version": 1,- "timestamp": time.time(),- })+ await broadcaster.broadcast_node_parameters_updated(+ memory_node_id,+ parameters=params,+ source_hint="cli",+ )except Exception as exc:logger.warning("[CC-Agent _persist_memory] broadcast failed: %s", exc,diff --git a/server/services/events/envelope.py b/server/services/events/envelope.pyindex 9290a97b..e0c09877 100644--- a/server/services/events/envelope.py+++ b/server/services/events/envelope.py@@ -243,6 +243,45 @@ class WorkflowEvent(BaseModel):},)+ @classmethod+ def node_parameters_updated(+ cls,+ node_id: str,+ *,+ parameters: Mapping[str, Any],+ workflow_id: Optional[str] = None,+ version: int = 1,+ source_hint: str = "user",+ ) -> "WorkflowEvent":+ """Server-pushed notification that a node's parameters changed.++ Three emission sites today:+ - ``routers/websocket.py:handle_save_node_parameters`` — user+ edited the parameter panel.+ - ``services/cli_agent/service.py:_persist_memory`` — Claude+ Code CLI memory bridge appended a turn to ``simpleMemory``.+ - ``services/temporal/agent_activities.py:persist_agent_turn``+ — F4.B AgentWorkflow's per-turn memory append.++ ``subject`` is the node_id so the FE routes the refetch to the+ right parameter panel. ``source_hint`` distinguishes user edits+ (``"user"``) from autonomous writes (``"agent"`` / ``"cli"``)+ so the panel can choose whether to confirm a re-render against+ the user's in-progress local edits.+ """+ return cls(+ source="machinaos://services/parameters",+ type=f"{_TYPE_PREFIX}node.parameters.updated",+ subject=node_id,+ workflow_id=workflow_id,+ data={+ "node_id": node_id,+ "parameters": dict(parameters),+ "version": version,+ "source": source_hint,+ },+ )+@classmethoddef deployment_snapshot(cls,diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.pyindex cbfe9128..06da8cb0 100644--- a/server/services/status_broadcaster.py+++ b/server/services/status_broadcaster.py@@ -318,6 +318,46 @@ class StatusBroadcaster:"data": event.model_dump(mode="json"),})+ async def broadcast_node_parameters_updated(+ self,+ node_id: str,+ *,+ parameters: Dict[str, Any],+ workflow_id: Optional[str] = None,+ version: int = 1,+ source_hint: str = "user",+ ) -> None:+ """Emit a CloudEvents-typed ``node.parameters.updated`` event.++ Replaces three legacy raw-dict broadcast sites with one typed+ envelope (RFC §6.4 CloudEvents discipline). Wire-format key+ ``node_parameters_updated`` stays the same for FE back-compat;+ only the inner payload becomes the typed envelope.++ Callers:+ - ``routers/websocket.py:handle_save_node_parameters`` (user+ edited the parameter panel — ``source_hint="user"``).+ - ``services/cli_agent/service.py:_persist_memory`` (Claude+ Code CLI memory bridge appended a turn —+ ``source_hint="cli"``).+ - ``services/temporal/agent_activities.py:persist_agent_turn``+ (F4.B AgentWorkflow per-turn memory append —+ ``source_hint="agent"``).+ """+ from services.events import WorkflowEvent++ event = WorkflowEvent.node_parameters_updated(+ node_id,+ parameters=parameters,+ workflow_id=workflow_id,+ version=version,+ source_hint=source_hint,+ )+ await self.broadcast({+ "type": "node_parameters_updated",+ "data": event.model_dump(mode="json"),+ })+async def broadcast_agent_progress(self,node_id: str,diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.pyindex 2606c0f5..3c9f085e 100644--- a/server/services/temporal/agent_activities.py+++ b/server/services/temporal/agent_activities.py@@ -270,13 +270,14 @@ async def persist_agent_turn(payload: Dict[str, Any]) -> Dict[str, Any]:await database.save_node_parameters(memory_node_id, params)# Broadcast so the parameter panel auto-refetches mid-run.+ # CloudEvents v1.0 envelope (RFC §6.4) — type is+ # ``com.machinaos.node.parameters.updated``; ``source_hint="agent"``+ # distinguishes this autonomous write from a user-edited save.broadcaster = container.status_broadcaster()- await broadcaster.broadcast(- {- "type": "node_parameters_updated",- "node_id": memory_node_id,- "parameters": params,- }+ await broadcaster.broadcast_node_parameters_updated(+ memory_node_id,+ parameters=params,+ source_hint="agent",)return {"appended": True, "trimmed_count": len(trimmed_pairs)}@@ -320,6 +321,49 @@ async def compact_agent_memory(payload: Dict[str, Any]) -> Dict[str, Any]:return result[email protected](name="agent.broadcast_progress.v1")+async def broadcast_agent_progress(payload: Dict[str, Any]) -> Dict[str, Any]:+ """Emit a CloudEvents-shaped ``agent_progress`` broadcast per turn.++ Wraps :meth:`services.status_broadcaster.StatusBroadcaster.broadcast_agent_progress`+ so ``AgentWorkflow`` can schedule it deterministically (workflows+ cannot call broadcaster methods directly — they have to go through+ an activity).++ Wire-format key ``agent_progress`` is the same channel the legacy+ LangGraph path uses (services/ai.py:execute_agent), and the inner+ payload is a CloudEvents v1.0 ``WorkflowEvent`` with+ ``type="com.machinaos.agent.progress"``. The FE routes+ ``data.iteration`` / ``data.max_iterations`` into+ ``nodeStatusStore`` so the "N / max" badge on the canvas updates+ in real time.++ ``payload`` shape::++ {+ "node_id": str,+ "workflow_id": Optional[str],+ "iteration": int,+ "max_iterations": int,+ "phase": Optional[str], # e.g. "llm_step", "tool_dispatch"+ }++ Returns ``{"emitted": True}`` for completeness — callers don't+ typically inspect the result.+ """+ from core.container import container++ broadcaster = container.status_broadcaster()+ await broadcaster.broadcast_agent_progress(+ payload["node_id"],+ workflow_id=payload.get("workflow_id"),+ iteration=int(payload.get("iteration", 0)),+ max_iterations=int(payload.get("max_iterations", 0)),+ phase=payload.get("phase"),+ )+ return {"emitted": True}++@activity.defn(name="agent.prepare_payload.v1")async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:"""Resolve everything ``AgentWorkflow`` needs from the canvas + DB.@@ -564,17 +608,18 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:def collect_agent_activities() -> List[Any]:- """Return the four F4.B agent activities for worker registration.+ """Return the five F4.B agent activities for worker registration.Mirrors :func:`services.temporal.plugin_activities.collect_plugin_activities`for the workflow-orchestrated agent loop. Workers register these so- ``AgentWorkflow`` can schedule them; ``MachinaWorkflow`` invokes- only :func:`prepare_agent_payload` directly (to build the- AgentWorkflow input payload before scheduling the child workflow).+ ``AgentWorkflow`` can schedule them; ``MachinaWorkflow`` doesn't+ invoke any of them directly — AgentWorkflow.run() owns the entire+ setup + execution + observation pipeline."""return [execute_llm_step,persist_agent_turn,compact_agent_memory,prepare_agent_payload,+ broadcast_agent_progress,]diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex 0f94af00..afd03421 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -200,6 +200,9 @@ class AgentWorkflow:final_content: Optional[str] = Noneusage_total: Dict[str, int] = {}+ agent_node_id = payload["node_id"]+ agent_workflow_id = payload.get("workflow_id")+# ---- Main loop --------------------------------------------------for iteration in range(max_iterations):workflow.logger.info(@@ -207,6 +210,23 @@ class AgentWorkflow:f"(messages={len(messages)} tools={len(tools)})")+ # CloudEvents-shaped agent_progress per LLM turn. Mirrors the+ # legacy LangGraph path's super-step broadcast (RFC §6.4).+ # FE consumes the typed envelope and updates the canvas+ # node's "N / max" iteration badge live.+ await workflow.execute_activity(+ "agent.broadcast_progress.v1",+ args=[{+ "node_id": agent_node_id,+ "workflow_id": agent_workflow_id,+ "iteration": iteration,+ "max_iterations": max_iterations,+ "phase": "llm_step",+ }],+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,+ retry_policy=AGENT_ACTIVITY_RETRY,+ )+# Strip per-turn fields the activity doesn't need.llm_payload = {"provider": payload["provider"],diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.pyindex 0ae834b6..7258cd87 100644--- a/server/tests/temporal/test_agent_workflow.py+++ b/server/tests/temporal/test_agent_workflow.py@@ -67,10 +67,11 @@ class TestAgentActivities:defn = getattr(compact_agent_memory, "__temporal_activity_definition")assert defn.name == "agent.compact_memory.v1"- def test_collect_returns_all_four(self):- """F4.B canary wiring added ``agent.prepare_payload.v1``. The- collector must surface all four so the worker registration covers- the orchestrator's prep + the workflow's loop activities."""+ def test_collect_returns_all_five(self):+ """Each successive sprint added one F4.B agent activity:+ infra (3) → per-agent-wiring +prepare_payload (4) → CloudEvents+ cleanup +broadcast_progress (5). All five must register so the+ AgentWorkflow loop can schedule them by name."""from services.temporal.agent_activities import collect_agent_activitiesactivities = collect_agent_activities()@@ -78,6 +79,7 @@ class TestAgentActivities:getattr(a, "__temporal_activity_definition").name for a in activities)assert names == [+ "agent.broadcast_progress.v1","agent.compact_memory.v1","agent.execute_llm_step.v1","agent.persist_turn.v1",@@ -90,6 +92,12 @@ class TestAgentActivities:defn = getattr(prepare_agent_payload, "__temporal_activity_definition")assert defn.name == "agent.prepare_payload.v1"+ def test_broadcast_progress_registered(self):+ from services.temporal.agent_activities import broadcast_agent_progress++ defn = getattr(broadcast_agent_progress, "__temporal_activity_definition")+ assert defn.name == "agent.broadcast_progress.v1"+class TestWorkerWiring:"""Worker registration must include AgentWorkflow + activities so thediff --git a/server/tests/test_cloudevents_node_parameters.py b/server/tests/test_cloudevents_node_parameters.pynew file mode 100644index 00000000..f6065cb4--- /dev/null+++ b/server/tests/test_cloudevents_node_parameters.py@@ -0,0 +1,135 @@+"""Lock the CloudEvents contract for ``node_parameters_updated`` broadcasts.++Pre-CloudEvents-cleanup three sites emitted ``node_parameters_updated``+as raw dicts (``routers/websocket.py:handle_save_node_parameters``,+``services/cli_agent/service.py:_persist_memory``, and F4.B's+``services/temporal/agent_activities.py:persist_agent_turn``). Per RFC+§6.4 these are NEW broadcasts and must use ``WorkflowEvent`` envelopes+— raw-dict is reserved for telemetry-high-frequency carve-outs only.++This invariant pins:++- ``WorkflowEvent.node_parameters_updated(...)`` factory exists with the+ canonical reverse-DNS type ``com.machinaos.node.parameters.updated``.+- ``StatusBroadcaster.broadcast_node_parameters_updated(...)`` wrapper+ exists and routes through the factory.+- The three legacy emission sites all call the broadcaster wrapper, not+ ``broadcaster.broadcast({...})`` directly.++Same ``inspect.getsource`` introspection pattern as+``test_credential_broadcasts.py`` + ``test_status_broadcasts.py``.+"""++from __future__ import annotations++import inspect++import pytest+++class TestFactoryShape:+ def test_factory_exists_and_returns_workflow_event(self):+ from services.events import WorkflowEvent++ event = WorkflowEvent.node_parameters_updated(+ "test_node_id",+ parameters={"foo": "bar"},+ workflow_id="wf_abc",+ source_hint="agent",+ )+ # CloudEvents envelope shape.+ assert event.source == "machinaos://services/parameters"+ assert event.type == "com.machinaos.node.parameters.updated"+ assert event.subject == "test_node_id"+ # workflow_id extension is preserved.+ assert event.workflow_id == "wf_abc"+ # data carries the inner payload.+ assert event.data["node_id"] == "test_node_id"+ assert event.data["parameters"] == {"foo": "bar"}+ assert event.data["source"] == "agent"++ def test_factory_defaults(self):+ from services.events import WorkflowEvent++ event = WorkflowEvent.node_parameters_updated(+ "test_node_id",+ parameters={},+ )+ assert event.data["version"] == 1+ assert event.data["source"] == "user"+ assert event.workflow_id is None+++class TestBroadcasterWrapper:+ def test_wrapper_method_exists(self):+ from services.status_broadcaster import StatusBroadcaster++ assert hasattr(StatusBroadcaster, "broadcast_node_parameters_updated"), (+ "StatusBroadcaster must expose broadcast_node_parameters_updated "+ "(RFC §6.4 cross-cutting broadcaster wrapper for the factory)."+ )++ def test_wrapper_routes_through_factory(self):+ """The wrapper must build a WorkflowEvent (not raw dict). Source+ introspection prevents accidental regression to raw-dict+ broadcasts when this method is rewritten."""+ from services.status_broadcaster import StatusBroadcaster++ src = inspect.getsource(+ StatusBroadcaster.broadcast_node_parameters_updated+ )+ assert "WorkflowEvent" in src, (+ "broadcast_node_parameters_updated must build a "+ "WorkflowEvent envelope; raw-dict broadcasts violate RFC §6.4."+ )+ assert "node_parameters_updated" in src, (+ "Wire-format key node_parameters_updated must stay in "+ "the broadcast payload (FE back-compat)."+ )+++class TestEmissionSites:+ """No new raw-dict ``node_parameters_updated`` emissions. All three+ callers route through the broadcaster wrapper."""++ EMISSION_SITES = [+ ("routers.websocket", "handle_save_node_parameters"),+ ("services.cli_agent.service", "AICliService._persist_memory"),+ ("services.temporal.agent_activities", "persist_agent_turn"),+ ]++ def test_all_sites_use_broadcaster_wrapper(self):+ import importlib++ for module_name, attr in self.EMISSION_SITES:+ module = importlib.import_module(module_name)+ # Resolve the attribute — could be a function or a method on+ # a class (``_persist_memory`` is a method on AICliService).+ target = module+ for part in attr.split("."):+ target = getattr(target, part)++ src = inspect.getsource(target)+ assert "broadcast_node_parameters_updated" in src, (+ f"{module_name}.{attr} must call "+ f"broadcaster.broadcast_node_parameters_updated, not the "+ f"raw broadcast({{type: 'node_parameters_updated', ...}}) "+ f"pattern. Raw-dict emissions violate RFC §6.4 CloudEvents "+ f"discipline."+ )++ def test_no_raw_dict_node_parameters_in_source(self):+ """Defensive grep: search the three module sources for the raw-dict+ pattern. Catches future regressions where someone copy-pastes the+ old emission style."""+ import importlib++ bad_pattern = '"type": "node_parameters_updated"'+ for module_name, _ in self.EMISSION_SITES:+ module = importlib.import_module(module_name)+ src = inspect.getsource(module)+ assert bad_pattern not in src, (+ f"{module_name} contains a raw-dict node_parameters_updated "+ f"emission. Use broadcaster.broadcast_node_parameters_updated "+ f"so the wire payload is a WorkflowEvent envelope."+ )