Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(workflows): retain teammate configuration in trigger runs
trohitg2c0d8dcb0da1
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex eb568a26..8cea5bc5 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -797,6 +797,20 @@ reconcile; one that never reported ends `failed` with an unknown outcome. See## Config Node Filtering+Trigger-run graph construction first preserves the complete configuration+dependency graph through `services/run_graph.py`. After collecting downstream+work, it follows incoming configuration handles to a fixed point, including+each teammate's Context, Skills, model and tools regardless of edge order.+Configuration-only additions do not bring their unrelated outgoing main+branches into the run, and sibling triggers remain independent listeners.+Push, polling and cron runs share this selection with local deployments.+The configuration nodes remain available for capability and conversation+discovery; executable-node filtering below still excludes them from scheduling.++This selection changes child-workflow inputs only, preserving parent command+order and child identities. Existing children keep their recorded graph;+future firings use the corrected selection after the worker is upgraded.+Certain nodes provide configuration rather than executing:```pythondiff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.pyindex eb37a45c..540a5c26 100644--- a/server/services/deployment/manager.py+++ b/server/services/deployment/manager.py@@ -18,6 +18,7 @@ from core.logging import get_loggerfrom constants import POLLING_TRIGGER_TYPES, WORKFLOW_TRIGGER_TYPESfrom services import event_waiterfrom services.events.envelope import equivalent_event_types+from services.run_graph import collect_downstream_node_idsfrom .state import DeploymentState, TriggerInfofrom .triggers import TriggerManager@@ -1364,61 +1365,8 @@ class DeploymentManager:return resultdef _get_downstream_nodes(self, node_id: str, nodes: List[Dict], edges: List[Dict]) -> List[Dict]:- """Get all downstream nodes from a trigger."""- downstream_ids = set()- node_types = {n["id"]: n.get("type", "") for n in nodes}- def collect(current_id: str):- for edge in edges:- if edge.get("source") != current_id:- continue- target_id = edge.get("target")- if not target_id or target_id in downstream_ids:- continue-- target_type = node_types.get(target_id, "")- is_trigger = target_type in WORKFLOW_TRIGGER_TYPES-- # Stop at trigger nodes — they are independent event listeners,- # not regular execution nodes. Each trigger spawns its own- # execution run when its event fires (n8n pattern).- if is_trigger:- continue-- downstream_ids.add(target_id)- collect(target_id)-- collect(node_id)-- # Include config nodes connected to downstream nodes- for edge in edges:- target = edge.get("target")- source = edge.get("source")- handle = edge.get("targetHandle") or edge.get("target_handle") or ""-- is_config = handle and handle.startswith("input-") and handle != "input-main"- if is_config and target in downstream_ids and source not in downstream_ids:- # Never include trigger nodes as config dependencies -- # they are event listeners, not configuration providers- source_type = node_types.get(source, "")- if source_type in WORKFLOW_TRIGGER_TYPES:- continue- downstream_ids.add(source)-- # Include tool nodes connected to AI Agent nodes (for capability discovery)- # When a child agent is included, we need its connected tools so the parent- # can discover what capabilities the child has- from constants import AI_AGENT_TYPES-- agent_node_ids = {n["id"] for n in nodes if n.get("type") in AI_AGENT_TYPES and n["id"] in downstream_ids}- for edge in edges:- target = edge.get("target")- source = edge.get("source")- target_handle = edge.get("targetHandle") or edge.get("target_handle") or ""- # Include tool nodes connected to agent's input-tools handle- if target in agent_node_ids and target_handle == "input-tools" and source not in downstream_ids:- downstream_ids.add(source)- logger.debug(f"[Deployment] Including tool node {source} connected to agent {target}")-+ """Get downstream work with all connected configuration dependencies."""+ downstream_ids = collect_downstream_node_ids(node_id, nodes, edges)return [n for n in nodes if n["id"] in downstream_ids]# =========================================================================diff --git a/server/services/run_graph.py b/server/services/run_graph.pynew file mode 100644index 00000000..52d37dac--- /dev/null+++ b/server/services/run_graph.py@@ -0,0 +1,61 @@+"""Pure dependency collection for a trigger's execution graph.++Keep main-flow reachability separate from configuration dependencies: a+teammate, tool, or Context belongs in the run, but its unrelated outgoing+main flow does not. Both Temporal and local deployments use this collector.+"""++from typing import Any++from constants import WORKFLOW_TRIGGER_TYPES+++def collect_downstream_node_ids(+ node_id: str,+ nodes: list[dict[str, Any]],+ edges: list[dict[str, Any]],+) -> set[str]:+ """Collect downstream work and its transitive configuration dependencies.++ An agent discovered through ``input-teammates`` or ``input-tools`` can+ have its own Context, Skills, model, and tools. Follow those incoming+ configuration edges to a fixed point, regardless of their source order.+ Other triggers remain independent listeners, even on config handles.+ The firing node itself is excluded from the returned set.+ """+ node_types = {node["id"]: node.get("type", "") for node in nodes}+ outgoing: dict[str, list[str]] = {}+ dependencies: dict[str, list[str]] = {}+ for edge in edges:+ source, target = edge.get("source"), edge.get("target")+ if source not in node_types or target not in node_types:+ continue+ outgoing.setdefault(source, []).append(target)+ handle = edge.get("targetHandle") or edge.get("target_handle") or ""+ if handle.startswith("input-") and handle != "input-main":+ dependencies.setdefault(target, []).append(source)++ downstream: set[str] = set()+ pending = [node_id]+ while pending:+ for target in outgoing.get(pending.pop(), ()):+ if target == node_id or target in downstream:+ continue+ if node_types[target] in WORKFLOW_TRIGGER_TYPES:+ continue+ downstream.add(target)+ pending.append(target)++ # Do not resume forward traversal from configuration-only additions.+ # They supply capabilities, not another main branch to execute.+ pending = [node["id"] for node in nodes if node["id"] in downstream]+ while pending:+ for source in dependencies.get(pending.pop(), ()):+ if source == node_id or source in downstream:+ continue+ if node_types[source] in WORKFLOW_TRIGGER_TYPES:+ continue+ downstream.add(source)+ pending.append(source)++ return downstreamdiff --git a/server/services/temporal/trigger_listener_workflow.py b/server/services/temporal/trigger_listener_workflow.pyindex 19abe260..01d69dd1 100644--- a/server/services/temporal/trigger_listener_workflow.py+++ b/server/services/temporal/trigger_listener_workflow.py@@ -43,6 +43,8 @@ from temporalio.common import ()from temporalio.workflow import ParentClosePolicy+from services.run_graph import collect_downstream_node_ids+from .workflow import TEMPORAL_ROUTING_INPUT_KEY@@ -591,11 +593,10 @@ async def _broadcast_trigger_waiting(# ----------------------------------------------------------------------------# Pure graph builder — kept in this module on purpose: the only consumer is-# this workflow class, and inlining keeps the import surface deterministic-# (workflow.defn(sandboxed=False) still benefits from minimal imports).-# Mirrors the logic in DeploymentManager._execute_from_trigger + ._get_downstream_nodes-# but specialised for the listener's "trigger fires once, spawn run" path.+# Pure graph builder shared by push, polling, cron, and controlled runs.+# Dependency collection is shared with local deployments; trigger-output+# decoration stays here. Changes to the selected graph affect child input+# only, preserving parent command order and child workflow identities.# ---------------------------------------------------------------------------@@ -612,50 +613,9 @@ def _build_run_graph(marks sibling triggers ``_pre_executed=True`` with ``{not_triggered:True}`` so MachinaWorkflow doesn't try to wait on them."""- from constants import (- AI_AGENT_TYPES,- WORKFLOW_TRIGGER_TYPES,- )-- node_types = {n["id"]: n.get("type", "") for n in nodes}-- downstream_ids: Set[str] = set()+ from constants import WORKFLOW_TRIGGER_TYPES- def _collect(current_id: str) -> None:- for edge in edges:- if edge.get("source") != current_id:- continue- target_id = edge.get("target")- if not target_id or target_id in downstream_ids:- continue- target_type = node_types.get(target_id, "")- if target_type in WORKFLOW_TRIGGER_TYPES:- # Stop at trigger nodes — independent event listeners.- continue- downstream_ids.add(target_id)- _collect(target_id)-- _collect(trigger_node_id)-- # Config nodes (memory, tools, etc.) connected to downstream nodes.- for edge in edges:- target = edge.get("target")- source = edge.get("source")- handle = edge.get("targetHandle") or edge.get("target_handle") or ""- is_config = handle and handle.startswith("input-") and handle != "input-main"- if is_config and target in downstream_ids and source not in downstream_ids:- if node_types.get(source, "") in WORKFLOW_TRIGGER_TYPES:- continue- downstream_ids.add(source)-- # Tool nodes connected to AI Agent's input-tools handle.- agent_ids = {n["id"] for n in nodes if n.get("type") in AI_AGENT_TYPES and n["id"] in downstream_ids}- for edge in edges:- target = edge.get("target")- source = edge.get("source")- handle = edge.get("targetHandle") or edge.get("target_handle") or ""- if target in agent_ids and handle == "input-tools" and source not in downstream_ids:- downstream_ids.add(source)+ downstream_ids = collect_downstream_node_ids(trigger_node_id, nodes, edges)run_filter = {trigger_node_id} | downstream_idsfiltered_nodes: List[Dict[str, Any]] = []diff --git a/server/tests/temporal/test_run_graph_replay.py b/server/tests/temporal/test_run_graph_replay.pynew file mode 100644index 00000000..c4f6fdbf--- /dev/null+++ b/server/tests/temporal/test_run_graph_replay.py@@ -0,0 +1,293 @@+"""Native replay and same-controller worker upgrade for graph dependencies.++Run in a clean subprocess: the shared pytest fixtures stub Temporal and core+services. This gate uses an isolated native dev server and no application DB,+providers, or browser processes.+"""+from __future__ import annotations++import asyncio+import importlib+import os+import subprocess+import sys+import types+from pathlib import Path+from uuid import uuid4++import pytest+from temporalio import activity, workflow+from temporalio.api.enums.v1 import EventType, IndexedValueType+from temporalio.api.operatorservice.v1 import AddSearchAttributesRequest+from temporalio.service import RPCError, RPCStatusCode+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import Replayer, Worker+++# Pin the actual worker before this fix; HEAD will move after it is committed.+_PRE_FIX_COMMIT = "41bca81aad25430803bc1de02e6205d094123a1c"+_MODULES = ("trigger_listener_workflow", "polling_trigger_workflow", "workflow_control_workflow")+_poll_events: list[dict] = []++[email protected](name="poll.googleGmailReceive.v1")+async def poll(payload: dict) -> dict:+ events = list(_poll_events)+ _poll_events.clear()+ return {"events": events, "seen_ids": [*payload["seen_ids"], *(event["id"] for event in events)]}++[email protected](name="broadcast_trigger_status_activity")+async def broadcast(_payload: dict) -> None:+ pass++[email protected](name="evaluate_trigger_filter_activity")+async def evaluate_filter(_payload: dict) -> bool:+ return True++[email protected](name="MachinaWorkflow", sandboxed=False)+class GraphProbe:+ @workflow.run+ async def run(self, payload: dict) -> dict:+ # Observe the native child's recorded input without running any nodes.+ return payload+++def _load_old(stem: str):+ package = importlib.import_module("services.temporal")+ name = "services.temporal." + stem+ source = subprocess.check_output(+ ["git", "show", f"{_PRE_FIX_COMMIT}:server/services/temporal/{stem}.py"],+ cwd=Path(__file__).parents[3], encoding="utf-8",+ )+ module = types.ModuleType(name)+ module.__package__ = "services.temporal"+ module.__file__ = f"git:{_PRE_FIX_COMMIT}:{stem}"+ sys.modules[name] = module+ setattr(package, stem, module)+ exec(compile(source, module.__file__, "exec"), module.__dict__)+ return module+++def _restore(modules: dict) -> None:+ package = importlib.import_module("services.temporal")+ for stem, module in modules.items():+ sys.modules[module.__name__] = module+ setattr(package, stem, module)+++def _registration(trigger: str, slug: str) -> dict:+ nodes = [+ {"id": "push", "type": "webhookTrigger"},+ {"id": "poll", "type": "googleGmailReceive"},+ {"id": "lead", "type": "aiAgent"},+ {"id": "browser", "type": "browser_agent"},+ {"id": "context", "type": "context"},+ {"id": "skill", "type": "skill"},+ {"id": "nested-context", "type": "context"},+ {"id": "tool", "type": "browser"},+ {"id": "unrelated", "type": "aiAgent"},+ ]+ # The dependency edges precede the edge discovering their teammate. The+ # previous single pass drops Context and Skill, then restores only tools.+ edges = [+ {"source": "context", "target": "browser", "targetHandle": "input-context"},+ {"source": "nested-context", "target": "skill", "targetHandle": "input-context"},+ {"source": "skill", "target": "browser", "targetHandle": "input-skill"},+ {"source": "browser", "target": "lead", "targetHandle": "input-teammates"},+ {"source": "tool", "target": "browser", "targetHandle": "input-tools"},+ {"source": "push", "target": "lead", "targetHandle": "input-main"},+ {"source": "poll", "target": "lead", "targetHandle": "input-main"},+ ]+ polling = trigger == "poll"+ event_type = "com.opencompany.graph-replay.received"+ return {+ "listener_id": trigger,+ "workflow_type": "PollingTriggerWorkflow" if polling else "TriggerListenerWorkflow",+ "trigger_node_id": trigger,+ "event_type": event_type,+ "listener_args": {+ "trigger_node_id": trigger, "trigger_label": trigger,+ "node_type": "googleGmailReceive" if polling else "webhookTrigger",+ "workflow_slug": slug, "workflow_id": None, "data_scope_id": "test-scope",+ "graphVersion": 2, "generation": 1,+ "event_type": event_type,+ "filter_params": {"poll_interval": 1} if polling else {},+ "nodes": nodes, "edges": edges,+ },+ }+++def _assert_graph(payload: dict, trigger: str, *, fixed: bool) -> None:+ identifiers = {trigger, "lead", "browser", "tool"}+ if fixed:+ identifiers.update({"context", "skill", "nested-context"})+ assert {node["id"] for node in payload["nodes"]} == identifiers+ expected = _registration(trigger, payload["workflow_slug"])["listener_args"]+ assert payload["edges"] == [+ edge for edge in expected["edges"] if edge["source"] in identifiers and edge["target"] in identifiers+ ]+ assert payload["graphVersion"] == 2+ assert payload["generation"] == 1+ assert payload["data_scope_id"] == "test-scope"+ firing_node = next(node for node in payload["nodes"] if node["id"] == trigger)+ assert firing_node["_pre_executed"] is True+ assert firing_node["_trigger_output"]["body"] == trigger + " payload"+++async def _child_result(client, identifier: str) -> dict:+ async def wait():+ while True:+ handle = client.get_workflow_handle(identifier)+ try:+ await handle.describe()+ except RPCError as exc:+ if exc.status != RPCStatusCode.NOT_FOUND:+ raise+ await asyncio.sleep(0.025)+ else:+ return await handle.result()+ return await asyncio.wait_for(wait(), timeout=20)+++async def _wait_registered(handle) -> None:+ async def wait():+ while set((await handle.query("status"))["triggers"]) != {"push", "poll"}:+ await asyncio.sleep(0.025)+ await asyncio.wait_for(wait(), timeout=10)+++def _starts(history) -> list:+ return [+ event.start_child_workflow_execution_initiated_event_attributes+ for event in history.events+ if event.event_type == EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED+ ]+++async def gate(cli: str, control_version: int) -> None:+ current = {stem: importlib.import_module("services.temporal." + stem) for stem in _MODULES}+ old = {stem: _load_old(stem) for stem in _MODULES}+ # Exercise real poll timers quickly; the same test-only floor applies to+ # both workers so upgrading changes only the graph construction code.+ for modules in (old, current):+ modules["workflow_control_workflow"]._MIN_POLL_INTERVAL_S = 1+ modules["polling_trigger_workflow"]._MIN_POLL_INTERVAL_S = 1+ token = uuid4().hex+ controller_id, slug, queue = "graph-controller-" + token, "graph-" + token, "graph-replay-" + token+ triggers = {trigger: _registration(trigger, slug) for trigger in ("push", "poll")}+ activities = [poll, broadcast, evaluate_filter]+ definitions = [current["workflow_control_workflow"].WorkflowControlWorkflow, GraphProbe]+ old_outputs, old_child_histories = {}, {}+ try:+ async with await WorkflowEnvironment.start_local(dev_server_existing_path=cli, ip="127.0.0.1", port=None) as env:+ client = env.client+ await client.operator_service.add_search_attributes(AddSearchAttributesRequest(+ namespace=client.namespace,+ search_attributes={"ControlEventTypes": IndexedValueType.INDEXED_VALUE_TYPE_KEYWORD_LIST},+ ))+ async with Worker(+ client, task_queue=queue,+ workflows=[old["workflow_control_workflow"].WorkflowControlWorkflow, GraphProbe],+ activities=activities, max_cached_workflows=0,+ ):+ handle = await client.start_workflow(+ "WorkflowControlWorkflow", {+ "triggers": triggers, "execution_control_version": control_version,+ "controller_workflow_id": controller_id, "generation": 1,+ }, id=controller_id, task_queue=queue,+ )+ original_run = handle.first_execution_run_id+ await _wait_registered(handle)+ await handle.signal("on_event", {+ "id": "push-before", "type": triggers["push"]["event_type"], "data": {"body": "push payload"},+ })+ _poll_events.append({"id": "poll-before", "body": "poll payload"})+ for trigger in triggers:+ identifier = f"{slug}-{trigger}-{trigger}-before"+ output = await _child_result(client, identifier)+ _assert_graph(output, trigger, fixed=False)+ old_outputs[identifier] = output+ old_child_histories[identifier] = await client.get_workflow_handle(identifier).fetch_history()+ await handle.execute_update("set_control_state", {+ "state": "paused", "revision": 1, "generation": 1,+ } if control_version else "paused")+ old_history = await handle.fetch_history()++ # Genuine pre-fix native history must replay with the new builder;+ # no patch marker is required for changing child input alone.+ _restore(current)+ replay = await Replayer(workflows=definitions).replay_workflow(old_history)+ assert replay.replay_failure is None+ async with Worker(+ client, task_queue=queue, workflows=definitions,+ activities=activities, max_cached_workflows=0,+ ):+ assert (await handle.describe()).run_id == original_run+ await handle.execute_update("set_control_state", {+ "state": "running", "revision": 2, "generation": 1,+ } if control_version else "running")+ await handle.signal("on_event", {+ "id": "push-after", "type": triggers["push"]["event_type"], "data": {"body": "push payload"},+ })+ _poll_events.append({"id": "poll-after", "body": "poll payload"})+ child_histories = list(old_child_histories.values())+ for trigger in triggers:+ identifier = f"{slug}-{trigger}-{trigger}-after"+ output = await _child_result(client, identifier)+ _assert_graph(output, trigger, fixed=True)+ assert output["context_execution_id"] == identifier+ if control_version:+ assert output["execution_control_version"] == 1+ assert output["controller_workflow_id"] == controller_id+ child_histories.append(await client.get_workflow_handle(identifier).fetch_history())+ # Upgrade must neither rewrite old children nor change the+ # controller run. Reset is used only for final test cleanup.+ assert (await handle.describe()).run_id == original_run+ for identifier, expected in old_outputs.items():+ assert await client.get_workflow_handle(identifier).result() == expected+ history = await client.get_workflow_handle(identifier).fetch_history()+ assert history.to_json() == old_child_histories[identifier].to_json()+ await handle.signal("reset")+ await asyncio.wait_for(handle.result(), timeout=10)+ final_history = await handle.fetch_history()++ assert len(_starts(old_history)) == 2+ starts = _starts(final_history)+ assert len(starts) == 4+ assert all(start.workflow_type.name == "MachinaWorkflow" for start in starts)+ for trigger in triggers:+ assert [start.workflow_id for start in starts if start.workflow_id.startswith(f"{slug}-{trigger}-")] == [+ f"{slug}-{trigger}-{trigger}-before", f"{slug}-{trigger}-{trigger}-after",+ ]+ assert not any(+ event.event_type in (+ EventType.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW,+ EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED,+ ) for event in final_history.events+ )+ for history in [final_history, *child_histories]:+ replay = await Replayer(workflows=definitions).replay_workflow(history)+ assert replay.replay_failure is None+ finally:+ _poll_events.clear()+ _restore(current)++[email protected]("control_version", [0, 1], ids=["legacy", "execution-control-v1"])+def test_native_graph_old_history_and_same_controller_upgrade(control_version):+ cli = os.environ.get("TEMPORAL_TEST_CLI")+ if not cli or not Path(cli).is_file():+ pytest.skip("Set TEMPORAL_TEST_CLI to an existing native Temporal CLI binary")+ completed = subprocess.run(+ [sys.executable, "-X", "utf8", "-m", "tests.temporal.test_run_graph_replay", cli, str(control_version)],+ cwd=Path(__file__).parents[2], stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=180, check=False,+ )+ assert completed.returncode == 0, completed.stdout.decode(errors="replace")[-16000:]+++if __name__ == "__main__":+ asyncio.run(gate(sys.argv[1], int(sys.argv[2])))diff --git a/server/tests/test_run_graph_dependencies.py b/server/tests/test_run_graph_dependencies.pynew file mode 100644index 00000000..cb3cc948--- /dev/null+++ b/server/tests/test_run_graph_dependencies.py@@ -0,0 +1,170 @@+"""Triggered runs retain the full configuration of connected teammate agents.++Both event-listener and in-process deployment runs must select the same graph,+regardless of the order in which canvas edges were saved. These tests use only+in-memory graphs; no database, Temporal server, browser, or provider is needed.+"""++from __future__ import annotations++from copy import deepcopy+from itertools import permutations+from pathlib import Path+from unittest.mock import MagicMock++import pytest+++def _node(node_id: str, node_type: str = "aiAgent") -> dict:+ return {"id": node_id, "type": node_type, "data": {"label": node_id}}+++def _edge(source: str, target: str, handle: str = "input-main", *, key: str = "targetHandle") -> dict:+ return {"id": f"{source}-{target}-{handle}", "source": source, "target": target, key: handle}+++def graph_builders(monkeypatch):+ # services.temporal imports the supervisor's dependency-free cli.tcp module.+ # Make the project root available without constructing any runtime services.+ monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2]))+ from temporalio import workflow+ from services.deployment.manager import DeploymentManager+ from services.temporal.trigger_listener_workflow import _build_run_graph++ monkeypatch.setattr(workflow, "logger", MagicMock())+ monkeypatch.setattr(workflow, "patched", lambda _patch_id: True)+ manager = object.__new__(DeploymentManager)+ return _build_run_graph, manager._get_downstream_nodes++[email protected](params=["listener", "deployment"])+def select_nodes(graph_builders, request):+ listener_builder, deployment_builder = graph_builders++ def select(nodes, edges):+ if request.param == "listener":+ run_nodes, _ = listener_builder(+ trigger_node_id="trigger", trigger_output={"message": "test"}, nodes=nodes, edges=edges,+ )+ return {node["id"] for node in run_nodes} - {"trigger"}+ return {node["id"] for node in deployment_builder("trigger", nodes, edges)}++ return select++[email protected]("handle_key", ["targetHandle", "target_handle"])[email protected]("edge_order", list(permutations(range(4))))+def test_teammate_context_and_skills_survive_every_edge_order(select_nodes, handle_key, edge_order):+ nodes = [+ _node("trigger", "taskTrigger"), _node("lead", "orchestrator_agent"), _node("browser"),+ _node("context", "context"), _node("skill", "masterSkill"), _node("tool", "browser"),+ ]+ critical_edges = [+ _edge("context", "browser", "input-context", key=handle_key),+ _edge("skill", "browser", "input-skill", key=handle_key),+ _edge("browser", "lead", "input-teammates", key=handle_key),+ _edge("trigger", "lead", "input-task", key=handle_key),+ ]+ # The previous tools-only recovery pass preserved this tool while silently+ # dropping the earlier Context and Master Skill connections.+ edges = [critical_edges[index] for index in edge_order] + [+ _edge("tool", "browser", "input-tools", key=handle_key),+ ]++ assert select_nodes(nodes, edges) == {"lead", "browser", "context", "skill", "tool"}+++def test_nested_teammates_and_tool_configuration_are_closed_transitively(select_nodes):+ nodes = [+ _node("trigger", "webhookTrigger"), _node("lead", "orchestrator_agent"), _node("browser"),+ _node("researcher"), _node("tool", "browser"), _node("context", "context"),+ _node("skill", "masterSkill"), _node("model", "geminiModel"), _node("memory", "simpleMemory"),+ ]+ # Dependencies occur before their consumers, including configuration for a+ # tool and a teammate of a teammate. A fixed number of recovery passes loses+ # some of these nodes as the team grows.+ edges = [+ _edge("memory", "model", "input-memory"),+ _edge("model", "tool", "input-model", key="target_handle"),+ _edge("skill", "researcher", "input-skill"),+ _edge("context", "researcher", "input-context", key="target_handle"),+ _edge("tool", "researcher", "input-tools"),+ _edge("researcher", "browser", "input-teammates", key="target_handle"),+ _edge("browser", "lead", "input-teammates"),+ _edge("trigger", "lead"),+ ]++ assert select_nodes(nodes, edges) == {node["id"] for node in nodes} - {"trigger"}+++def test_configuration_and_runtime_cycles_terminate(select_nodes):+ nodes = [+ _node("trigger", "webhookTrigger"), _node("lead"), _node("output", "console"),+ _node("browser"), _node("context", "context"),+ ]+ edges = [+ _edge("context", "browser", "input-context"),+ _edge("browser", "context", "input-tools"),+ _edge("browser", "lead", "input-teammates"),+ _edge("trigger", "lead"), _edge("lead", "output"), _edge("output", "lead"),+ ]++ assert select_nodes(nodes, edges) == {"lead", "output", "browser", "context"}+++def test_config_closure_preserves_trigger_and_component_boundaries(select_nodes):+ nodes = [+ _node("trigger", "webhookTrigger"), _node("lead"), _node("output", "console"),+ _node("browser"), _node("context", "context"),+ _node("sibling", "taskTrigger"), _node("sibling-output", "console"),+ _node("unrelated-agent"), _node("unrelated-output", "console"),+ _node("config-only-output", "console"), _node("ordinary-upstream", "console"),+ ]+ edges = [+ _edge("context", "browser", "input-context"),+ _edge("sibling", "browser", "input-tools"),+ _edge("sibling", "browser", "input-context"),+ _edge("browser", "lead", "input-teammates"),+ _edge("trigger", "lead"), _edge("lead", "output"),+ _edge("lead", "sibling"), _edge("sibling", "sibling-output"),+ _edge("unrelated-agent", "unrelated-output"),+ _edge("browser", "config-only-output"),+ _edge("ordinary-upstream", "lead"),+ ]++ # Configuration discovery must not execute a teammate's separate main-flow+ # branch or cross an independent trigger, even through input-tools.+ assert select_nodes(nodes, edges) == {"lead", "output", "browser", "context"}+++def test_both_builders_preserve_source_order_and_inputs(graph_builders):+ listener_builder, deployment_builder = graph_builders+ nodes = [+ _node("context", "context"), _node("orphan"), _node("browser"),+ _node("trigger", "taskTrigger"), _node("lead", "orchestrator_agent"), _node("skill", "masterSkill"),+ ]+ edges = [+ _edge("context", "browser", "input-context"), _edge("skill", "browser", "input-skill"),+ _edge("browser", "lead", "input-teammates"), _edge("trigger", "lead", "input-task"),+ _edge("orphan", "orphan"),+ ]+ original_nodes, original_edges = deepcopy(nodes), deepcopy(edges)+ trigger_output = {"message": "do the task", "metadata": {"source": "test"}}+ original_output = deepcopy(trigger_output)++ run_nodes, run_edges = listener_builder(+ trigger_node_id="trigger", trigger_output=trigger_output, nodes=nodes, edges=edges,+ )+ deployment_nodes = deployment_builder("trigger", nodes, edges)++ assert [node["id"] for node in run_nodes] == ["context", "browser", "trigger", "lead", "skill"]+ assert [node["id"] for node in deployment_nodes] == ["context", "browser", "lead", "skill"]+ assert run_edges == edges[:-1]+ trigger = next(node for node in run_nodes if node["id"] == "trigger")+ assert trigger["_pre_executed"] is True+ assert trigger["_trigger_output"] == original_output+ assert nodes == original_nodes+ assert edges == original_edges+ assert trigger_output == original_output+ assert all(node is not original for node in run_nodes for original in nodes)