Skip to content

Self-improving AI Employees for everyone

fix(context): let the user delete a Context node

trohitg3364d7674d6b
diff --git a/CLAUDE.md b/CLAUDE.md
index b6bad32c..c68f2d16 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1376,7 +1376,7 @@ A new chat-model provider is one self-contained folder under `server/nodes/model
Two different things, deliberately separated. Read [RFC-0002](./RFC-0002-AGENT-CONTEXT-AND-MEMORY.md) before touching either.
-**Context** is the plain conversation store — what the agent actually sent and received, as JSON messages. One table (`agent_conversations`, [models/agent_context.py](./server/models/agent_context.py)) keyed by **`(workflow_id, generation, agent_node_id)`** → `messages` (MessageWire list) + `updated_at`; the service is four functions in [`services/agent_context/conversation.py`](./server/services/agent_context/conversation.py) (`load_conversation` / `save_conversation` (per-key lock, whole-list upsert, post-commit notify) / `clear_conversation` / `list_conversations`). Every firing of an agent — chat message or taskTrigger review — loads the row at run start and saves the live message list back per turn, so the one conversation continues across firings; Reset admits a new generation = new key = fresh conversation, AND the Context node's `reset_execution_state` clears the workflow's stored rows + fences warm claude subprocesses + broadcasts `context.updated` — the generation bump alone is not enough because the panel shows the newest STORED generation, so surviving rows would render the pre-Reset conversation as the live context and Reset would look like a no-op. (A plain Stop→Start leaves prior generations as inert, non-browsable history until workflow delete or Reset.) The `context` node (`server/nodes/context/`, `input-context` handle) is the **opt-in switch and viewing panel**, nothing more — it declares no parameters. This is the LangGraph `thread_id` / OpenAI `conversation_id` pattern; the previous hash-chained journal (threads, epochs, checkpoints, blobs, provider bindings, session/task/execution thread routing) is deleted.
+**Context** is the plain conversation store — what the agent actually sent and received, as JSON messages. One table (`agent_conversations`, [models/agent_context.py](./server/models/agent_context.py)) keyed by **`(workflow_id, generation, agent_node_id)`** → `messages` (MessageWire list) + `updated_at`; the service is four functions in [`services/agent_context/conversation.py`](./server/services/agent_context/conversation.py) (`load_conversation` / `save_conversation` (per-key lock, whole-list upsert, post-commit notify) / `clear_conversation` / `list_conversations`). Every firing of an agent — chat message or taskTrigger review — loads the row at run start and saves the live message list back per turn, so the one conversation continues across firings; Reset admits a new generation = new key = fresh conversation, AND the Context node's `reset_execution_state` clears the workflow's stored rows + fences warm claude subprocesses + broadcasts `context.updated` — the generation bump alone is not enough because the panel shows the newest STORED generation, so surviving rows would render the pre-Reset conversation as the live context and Reset would look like a no-op. (A plain Stop→Start leaves prior generations as inert, non-browsable history until workflow delete or Reset.) The `context` node (`server/nodes/context/`, `input-context` handle) is the **opt-in switch and viewing panel**, nothing more — it declares no parameters. It is an ordinary canvas node the user deletes like any other: `normalize_workflow_graph` never creates, reconnects or deletes one (rewriting a legacy `simpleMemory -> input-memory` edge is the one exception), save never restores a deleted one, and `workflow_validator` does not require one — `INVALID_CONTEXT_EDGE` / `MULTIPLE_CONTEXTS` / `SHARED_CONTEXT` still reject ambiguous wiring. Deleting it opts the agent out, and the save's archive outbox then clears the workflow's stored conversations. The palette does not offer it (`uiHints.systemManaged`), so a deleted Context cannot be re-added from there. This is the LangGraph `thread_id` / OpenAI `conversation_id` pattern; the previous hash-chained journal (threads, epochs, checkpoints, blobs, provider bindings, session/task/execution thread routing) is deleted.
Load-bearing invariants, learned the hard way: (1) *attaching a Context node must never change what the agent sends* — requests are always built from `messages`; `conversation_key` only says where to save. (2) *The store records what was sent, after it was sent* — `agent.execute_llm_step` saves `[...sent, assistant]` immediately after `ChatUnifier.chat` returns; nothing writes before a request exists (the retired `prepare_context` activity did, and journalled fabricated requests). (3) **Loads are LOUD, saves are best-effort** — `agent.prepare_payload` raises `ApplicationError("ConversationLoadFailed")` (retryable) / `ApplicationError("ConversationTooLarge")` (non-retryable, 1 MB cap) rather than silently running an amnesiac agent that burns tokens on an empty prompt; the save runs post-billing and swallows failures with a WARN. (4) Seeding precedence is **carried rollover transcript > stored conversation > bare build** — a `continue_as_new` resume carries the live transcript in its resume marker (size-guarded ≤ 1 MB) and must win over the store. Locked by `tests/temporal/test_agent_workflow.py::TestConversationIdentity`.
diff --git a/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md b/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md
index 58fde214..6ebb77d2 100644
--- a/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md
+++ b/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md
@@ -33,8 +33,11 @@ the journal, provider bindings, tenant scope, mutation rules, compaction
algorithm, or durable Memory items. Those responsibilities live in backend
services and are reached through the plugin and tool registries.
-Each agent that declares the `requiresContext` capability has exactly one
-system-managed Context companion. A Context owns multiple isolated threads:
+An agent that declares the `requiresContext` capability accepts at most one
+Context node, which the user adds and deletes on the canvas. (Superseded,
+September 2026: this originally gave every such agent exactly one
+system-managed Context companion that the backend created and restored; see
+§11.) A Context owns multiple isolated threads:
1. an explicit chat/session ID selects a persistent session thread;
2. otherwise a delegated task ID selects a task thread;
@@ -70,7 +73,8 @@ The backend NodeSpec is the source of truth.
### 3.1 Context node
-The `context` plugin is a passive, system-managed configuration node:
+The `context` plugin is a passive, optional configuration node that the user
+adds and deletes on the canvas:
```text
context.output-context -> agent.input-context
@@ -79,9 +83,10 @@ context.output-context -> agent.input-context
It declares no parameters; the connection is the whole configuration
(`AgentContextParams` is empty).
-Its NodeSpec advertises `isContextPanel` and `systemManaged`. The frontend
-renders the panel and calls backend handlers; it does not create journals,
-choose thread IDs, calculate pressure, compact messages, or mutate epochs.
+Its NodeSpec advertises `isContextPanel` and `systemManaged`; the latter only
+keeps the node out of the component palette. The frontend renders the panel
+and calls backend handlers; it does not create journals, choose thread IDs,
+calculate pressure, compact messages, or mutate epochs.
### 3.2 Memory node
@@ -303,13 +308,24 @@ frontend replaces its draft rather than reproducing migration rules.
Backend lifecycle rules:
-- create/copy/hot-spawn/Agent-Builder add a fresh Context companion;
-- copying never copies a journal;
-- deleting an agent archives its Context;
-- deleting a required system edge is rejected or repaired;
-- a Context cannot attach to two agents;
-- capability discovery uses `requiresContext`, never renderer kind or a
- hardcoded agent type list.
+**Superseded (September 2026).** The original rules made the Context a
+system-managed companion. Normalization created one for every agent that
+declared `requiresContext`, repaired its edge and deleted it along with its
+agent, and save put back one the user had deleted, so the node could not be
+deleted at all. The Context is now optional and user-owned:
+
+- normalization never creates, reconnects or deletes a Context outside the
+ legacy rewrite above, and save never restores one;
+- the validator does not require a Context. It still rejects a Context edge
+ into a node without `requiresContext`, two Contexts on one agent, and one
+ Context on two agents;
+- Agent Builder's `add_subagent` still wires a fresh Context to the teammate
+ it spawns; creating or copying an agent on the canvas adds none;
+- deleting an agent leaves its Context node in place. Removing a Context
+ node from a saved graph enqueues the archive that clears the workflow's
+ stored conversations;
+- capability discovery still uses `requiresContext`, never renderer kind or
+ a hardcoded agent type list.
## 12. Reset
diff --git a/docs-internal/agent_context_flow.md b/docs-internal/agent_context_flow.md
index 04c6e66e..edc886d4 100644
--- a/docs-internal/agent_context_flow.md
+++ b/docs-internal/agent_context_flow.md
@@ -175,6 +175,13 @@ registered save listener; payload is identity + count only — the panel
refetches through the authorized handler). The node declares **no
parameters**; the connection is the whole configuration.
+The node is optional and user-owned. `normalize_workflow_graph` never
+creates, reconnects or deletes one; rewriting a legacy
+`simpleMemory -> input-memory` edge is the one exception. Save never restores
+a deleted Context, and `workflow_validator` accepts an agent without one: it
+checks only the Context edges that exist (`INVALID_CONTEXT_EDGE`,
+`MULTIPLE_CONTEXTS`, `SHARED_CONTEXT`). Deleting the node is the opt-out.
+
The panel ([`ContextPanel.tsx`](../client/src/components/parameterPanel/ContextPanel.tsx))
renders role-tinted message cards with per-message `ts` timestamps, routes
JSON-shaped payloads (tool calls, tool results) through the themed JSON
@@ -192,9 +199,11 @@ 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. A plain Stop → Start (new generation without Reset) leaves prior
rows in the store as inert history — deliberately **not browsable from
-the panel**, which shows only the agent's current context — until the
-workflow is deleted (the archive-outbox drain in
-`services/workflow_storage/handlers.py`) or Reset runs.
+the panel**, which shows only the agent's current context — until Reset
+runs or the archive-outbox drain in `services/workflow_storage/handlers.py`
+clears them. The drain runs when the workflow is deleted AND when a save
+removes a Context node, and it clears every stored conversation of the
+workflow, not only the removed Context's agent.
## Invariants (do not break)
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index 40b010ee..af3826f5 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -508,8 +508,8 @@ Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts]
| `isMemoryToolPanel` | `MiddleSection` | Render the durable Memory item browser (search, edit, forget, clear). Declared by `simpleMemory`, and selected *before* `isMemoryPanel` |
| `isContextPanel` | `MiddleSection` | Render the Context inspector (journal, active replay, fork/export/clear). Read-only: it observes the agent's journal and must never alter execution |
| `isDataPanel` | `MiddleSection` | Render the Data node's mounts + read-only file browser (`DataPanel`). Declared by `dataSource`. |
-| `requiresContext` | backend graph normalization | Declared in `STD_AGENT_HINTS`. Not a rendering flag — `normalize_workflow_graph` pairs every plugin carrying it with a Context companion, and `workflow_validator` enforces the topology |
-| `systemManaged` | canvas | Marks the auto-created Context companion. The backend owns its lifecycle; the user does not add or delete it directly |
+| `requiresContext` | backend graph validation | Declared in `STD_AGENT_HINTS`. Not a rendering flag — `workflow_validator` accepts a Context edge only into a node carrying it. The Context itself is optional: nothing pairs one with the agent, and an agent without one is valid |
+| `systemManaged` | `ComponentPalette` | Declared by the Context node; keeps it out of the component palette. It does not protect the node — the user can delete it, and neither normalization nor save re-creates or restores it |
| `isMonitorPanel` | `MiddleSection`, `ParameterPanel` | Render the team-monitor panel |
| `isTodoEditor` | `MiddleSection` | Render the editable Current Todos manager (`writeTodos`) instead of the plain params list |
| `isTaskManagerPanel` | `MiddleSection` | Render the execution-scoped team task control panel |
diff --git a/docs-internal/node-logic-flows/ai_agents/context.md b/docs-internal/node-logic-flows/ai_agents/context.md
index d8f0eb12..ab8f7211 100644
--- a/docs-internal/node-logic-flows/ai_agents/context.md
+++ b/docs-internal/node-logic-flows/ai_agents/context.md
@@ -40,10 +40,19 @@ Class facts: `component_kind = "model"`, `group = ("memory",)` (so
`@Operation("policy")` ignores its inputs and returns `AgentContextOutput`
(`{configured: true}`, `extra="forbid"`); conversations stay in the store.
`ui_hints`: `isContextPanel`, `systemManaged`, `hideInputSection`,
-`hideOutputSection`, `hideRunButton` — all `True`.
+`hideOutputSection`, `hideRunButton` — all `True`. `systemManaged` only
+keeps the node out of the component palette; it does not protect it.
## Behavior
+- **Lifecycle**: an ordinary canvas node the user deletes like any other.
+ `normalize_workflow_graph` never creates, reconnects or deletes one; the
+ single exception is rewriting a legacy `simpleMemory -> input-memory`
+ edge, which adds a Context for an agent that has none. Save never restores
+ a deleted Context, and `workflow_validator` does not require one (no
+ `MISSING_CONTEXT`). It still rejects `INVALID_CONTEXT_EDGE`,
+ `MULTIPLE_CONTEXTS` and `SHARED_CONTEXT`. Agent Builder's `add_subagent`
+ wires a Context to the teammate it spawns.
- **Descriptor** ([`_descriptor.py`](../../../server/nodes/context/_descriptor.py)):
registered via `register_agent_context_builder`; emits `kind: "context"` +
workflow/generation identity. Returns `None` for `generation <= 0`
@@ -75,8 +84,17 @@ Class facts: `component_kind = "model"`, `group = ("memory",)` (so
## Edge cases & known limits
+- Deleting the node opts its agent out of persistence. The save's archive
+ outbox (`Database.save_workflow` enqueues it for every Context id that
+ leaves the graph) then clears ALL of the workflow's stored conversations,
+ not just that agent's.
+- Deleting an agent leaves its Context node on the canvas, unconnected;
+ nothing cascades.
+- The palette does not offer the node (`systemManaged`), so a deleted
+ Context cannot be re-added from there.
- Two agents on one Context node keep separate conversations (the key is
- per agent node); the panel offers a selector.
+ per agent node); the panel offers a selector. The validator nevertheless
+ rejects that wiring as `SHARED_CONTEXT` at save, Run and Start.
- A plain Stop → Start starts a fresh conversation (new generation) and
leaves prior rows as inert, non-browsable history until Reset or
workflow delete.
diff --git a/server/services/workflow_migrations.py b/server/services/workflow_migrations.py
index 8daf4f3f..3dd6d5c0 100644
--- a/server/services/workflow_migrations.py
+++ b/server/services/workflow_migrations.py
@@ -49,20 +49,6 @@ def _source_handle(edge: Mapping[str, Any]) -> Optional[str]:
return str(value) if value else None
-def _requires_context(node_type: str) -> bool:
- """Read the declared plugin capability without type-name heuristics."""
- from services.node_registry import get_node_class
-
- node_cls = get_node_class(node_type)
- if node_cls is None:
- return False
- if bool(getattr(node_cls, "requires_context", False)):
- return True
- # Transitional support for plugins which shipped the capability as a
- # NodeSpec hint before gaining the BaseNode ClassVar.
- return bool((getattr(node_cls, "ui_hints", {}) or {}).get("requiresContext"))
-
-
def _context_node_for(agent: Mapping[str, Any], node_id: str) -> Dict[str, Any]:
position = dict(agent.get("position") or {})
x = position.get("x")
@@ -76,11 +62,7 @@ def _context_node_for(agent: Mapping[str, Any], node_id: str) -> Dict[str, Any]:
"id": node_id,
"type": "context",
"position": context_position,
- "data": {
- "label": "Context",
- "systemManaged": True,
- "agentNodeId": str(agent.get("id") or ""),
- },
+ "data": {"label": "Context"},
}
@@ -184,10 +166,16 @@ def normalize_workflow_graph(
1. canonicalize legacy handle field names;
2. migrate the retired Android toolkit;
- 3. convert every legacy Memory continuity edge into a Context edge plus
- an ordinary Memory tool edge;
- 4. pair every plugin declaring ``requires_context`` with a fresh Context;
- 5. assign canonical node IDs and return aliases/import receipts.
+ 3. convert every legacy Memory continuity edge into an ordinary Memory
+ tool edge plus a Context edge, adding a Context node for an agent
+ that has none;
+ 4. assign canonical node IDs and return aliases/import receipts.
+
+ Context nodes are otherwise left exactly as the user placed them. A
+ Context is an opt-in the user adds and removes on the canvas, so this
+ never creates, reconnects or deletes one. The legacy edge in stage 3 is
+ the one exception, because it was itself an explicit continuity
+ declaration.
Raw legacy Markdown is returned only in ``state_imports``. It is never
copied into the Context node or workflow graph.
@@ -237,224 +225,38 @@ def normalize_workflow_graph(
)
tool_pairs.add((memory_id, agent_id))
- required_agent_ids = {node_id for node_id, node in node_by_id.items() if _requires_context(str(node.get("type") or ""))}
- # A legacy edge is itself an explicit continuity declaration. It remains
- # migratable even if an optional plugin is not installed on this host.
- required_agent_ids.update(legacy_by_agent)
-
- # Resolve system companion ownership before repairing edges. This prevents
- # a stale Context whose owner was deleted from being silently adopted by a
- # different agent merely because an unrelated edge still points at it.
- context_targets: Dict[str, List[str]] = {}
- for edge in normalized_edges:
- source = str(edge.get("source") or "")
- target = str(edge.get("target") or "")
- if (
- source in context_ids
- and _source_handle(edge) == "output-context"
- and _target_handle(edge) == "input-context"
- and target in required_agent_ids
- ):
- context_targets.setdefault(source, []).append(target)
-
- declared_owners: Dict[str, str] = {}
- resolved_system_owners: Dict[str, str] = {}
- orphaned_system_contexts: set[str] = set()
- for context_id in sorted(context_ids):
- context_node = node_by_id[context_id]
- data = dict(context_node.get("data") or {})
- if data.get("systemManaged") is not True:
- continue
- declared_owner = str(data.get("agentNodeId") or "")
- if declared_owner:
- if declared_owner not in required_agent_ids:
- orphaned_system_contexts.add(context_id)
- warnings.append(f"Removed orphaned system Context {context_id!r}")
- continue
- declared_owners[context_id] = declared_owner
- resolved_system_owners[context_id] = declared_owner
- continue
-
- inferred = sorted(set(context_targets.get(context_id, [])))
- if len(inferred) == 1:
- resolved_system_owners[context_id] = inferred[0]
- elif not inferred:
- orphaned_system_contexts.add(context_id)
- warnings.append(f"Removed orphaned system Context {context_id!r}")
- # A shared system Context without ownership metadata is ambiguous.
- # Preserve it so the validation boundary rejects the graph instead of
- # guessing which agent owns provider state.
-
- # If retries or an older client produced two system companions for one
- # agent, retain one deterministically and archive the rest after save.
- contexts_by_owner: Dict[str, List[str]] = {}
- for context_id, owner_id in resolved_system_owners.items():
- if context_id not in orphaned_system_contexts:
- contexts_by_owner.setdefault(owner_id, []).append(context_id)
- for owner_id, candidates in sorted(contexts_by_owner.items()):
- if len(candidates) < 2:
- continue
- keeper = min(
- candidates,
- key=lambda context_id: (
- context_id not in declared_owners,
- owner_id not in context_targets.get(context_id, []),
- context_id,
- ),
- )
- for context_id in sorted(candidates):
- if context_id == keeper:
- continue
- orphaned_system_contexts.add(context_id)
- resolved_system_owners.pop(context_id, None)
- warnings.append(f"Removed duplicate system Context {context_id!r} for agent {owner_id!r}; retained {keeper!r}")
-
- if orphaned_system_contexts:
- normalized_nodes = [node for node in normalized_nodes if str(node.get("id") or "") not in orphaned_system_contexts]
- normalized_edges = [
- edge
- for edge in normalized_edges
- if str(edge.get("source") or "") not in orphaned_system_contexts
- and str(edge.get("target") or "") not in orphaned_system_contexts
- ]
- for context_id in orphaned_system_contexts:
- params.pop(context_id, None)
- node_by_id.pop(context_id, None)
- context_ids.discard(context_id)
-
- # A system-owned Context may only point at its recorded owner. Repair
- # stale/shared system edges, but leave ambiguous user-authored topology
- # untouched so validation can reject it.
- repaired_edges: List[Dict[str, Any]] = []
- owner_pairs: set[tuple[str, str]] = set()
+ # Stage 3, second half: the legacy edge declared continuity, so its agent
+ # keeps it. Reuse a Context the agent is already connected to, otherwise
+ # add one. A legacy edge stays migratable even when the destination
+ # plugin is not installed on this host.
+ connected_contexts: Dict[str, str] = {}
for edge in normalized_edges:
source = str(edge.get("source") or "")
- target = str(edge.get("target") or "")
- owner_id = resolved_system_owners.get(source)
- is_context_edge = _source_handle(edge) == "output-context" and _target_handle(edge) == "input-context"
- if owner_id and is_context_edge:
- if target != owner_id:
- warnings.append(f"Removed stale system Context edge {source!r} -> {target!r}; owner is {owner_id!r}")
- continue
- owner_pairs.add((source, target))
- repaired_edges.append(edge)
- normalized_edges = repaired_edges
- for context_id, owner_id in sorted(resolved_system_owners.items()):
- if (context_id, owner_id) in owner_pairs:
- continue
- normalized_edges.append(
- {
- "id": _edge_id("context", context_id, owner_id),
- "source": context_id,
- "target": owner_id,
- "sourceHandle": "output-context",
- "targetHandle": "input-context",
- "data": {"systemManaged": True},
- }
- )
-
- existing_contexts: Dict[str, List[str]] = {}
- for edge in normalized_edges:
- source = str(edge.get("source") or "")
- target = str(edge.get("target") or "")
if source in context_ids and _source_handle(edge) == "output-context" and _target_handle(edge) == "input-context":
- existing_contexts.setdefault(target, []).append(source)
-
- # A required system edge removed in the editor is repaired by the
- # backend. The companion records its owner as non-runtime UI metadata so
- # repair does not rely on geometry or agent type-name heuristics.
- existing_pairs = {(source, target) for target, sources in existing_contexts.items() for source in sources}
- for context_id in sorted(context_ids):
- context_node = node_by_id[context_id]
- data = context_node.get("data") or {}
- owner_id = str(data.get("agentNodeId") or "")
- if (
- data.get("systemManaged") is True
- and owner_id in node_by_id
- and _requires_context(str((node_by_id.get(owner_id) or {}).get("type") or ""))
- and (context_id, owner_id) not in existing_pairs
- ):
- normalized_edges.append(
- {
- "id": _edge_id("context", context_id, owner_id),
- "source": context_id,
- "target": owner_id,
- "sourceHandle": "output-context",
- "targetHandle": "input-context",
- "data": {"systemManaged": True},
- }
- )
- existing_contexts.setdefault(owner_id, []).append(context_id)
- existing_pairs.add((context_id, owner_id))
+ connected_contexts.setdefault(str(edge.get("target") or ""), source)
occupied_ids = set(node_by_id)
- for ordinal, agent_id in enumerate(sorted(required_agent_ids), start=1):
- if existing_contexts.get(agent_id):
+ for ordinal, agent_id in enumerate(sorted(legacy_by_agent), start=1):
+ if agent_id in connected_contexts:
continue
- temporary_id = f"__context__:{ordinal}:{agent_id}"
+ context_id = f"__context__:{ordinal}:{agent_id}"
suffix = 1
- while temporary_id in occupied_ids:
+ while context_id in occupied_ids:
suffix += 1
- temporary_id = f"__context__:{ordinal}:{agent_id}:{suffix}"
- occupied_ids.add(temporary_id)
- context_node = _context_node_for(node_by_id[agent_id], temporary_id)
- normalized_nodes.append(context_node)
- node_by_id[temporary_id] = context_node
- context_ids.add(temporary_id)
- existing_contexts[agent_id] = [temporary_id]
+ context_id = f"__context__:{ordinal}:{agent_id}:{suffix}"
+ occupied_ids.add(context_id)
+ normalized_nodes.append(_context_node_for(node_by_id[agent_id], context_id))
+ connected_contexts[agent_id] = context_id
normalized_edges.append(
{
- "id": _edge_id("context", temporary_id, agent_id),
- "source": temporary_id,
+ "id": _edge_id("context", context_id, agent_id),
+ "source": context_id,
"target": agent_id,
"sourceHandle": "output-context",
"targetHandle": "input-context",
- "data": {"systemManaged": True},
}
)
- # Persist the ownership marker for backend edge repair/cascade semantics.
- # It is UI metadata only; runtime state lives in the conversation store.
- agents_for_context: Dict[str, List[str]] = {}
- for agent_id, sources in existing_contexts.items():
- for source_id in dict.fromkeys(sources):
- agents_for_context.setdefault(source_id, []).append(agent_id)
- for agent_id, sources in existing_contexts.items():
- unique_sources = list(dict.fromkeys(sources))
- if len(unique_sources) != 1:
- continue
- source_id = unique_sources[0]
- if len(set(agents_for_context.get(source_id, []))) != 1:
- continue
- context_node = node_by_id.get(source_id)
- if context_node is None:
- continue
- context_node["data"] = {
- **dict(context_node.get("data") or {}),
- "systemManaged": True,
- "agentNodeId": agent_id,
- }
-
- # Cascade-delete an orphaned system companion when its owning agent is
- # absent. User-authored/unowned Context nodes are left for validation.
- claimed_context_ids = {source_id for sources in existing_contexts.values() for source_id in sources}
- unclaimed_system_contexts = {
- node_id
- for node_id, node in node_by_id.items()
- if node.get("type") == "context" and (node.get("data") or {}).get("systemManaged") is True and node_id not in claimed_context_ids
- }
- if unclaimed_system_contexts:
- normalized_nodes = [node for node in normalized_nodes if str(node.get("id") or "") not in unclaimed_system_contexts]
- normalized_edges = [
- edge
- for edge in normalized_edges
- if str(edge.get("source") or "") not in unclaimed_system_contexts
- and str(edge.get("target") or "") not in unclaimed_system_contexts
- ]
- for context_id in unclaimed_system_contexts:
- params.pop(context_id, None)
- warnings.append(f"Removed orphaned system Context {context_id!r}")
-
aliases: Dict[str, str] = {}
if canonicalize_ids and workflow_id:
from services.workflow_naming import canonicalize_node_ids
diff --git a/server/services/workflow_storage/handlers.py b/server/services/workflow_storage/handlers.py
index bed78465..4bd77546 100644
--- a/server/services/workflow_storage/handlers.py
+++ b/server/services/workflow_storage/handlers.py
@@ -23,7 +23,6 @@ logger = get_logger(__name__)
_CONTEXT_TOPOLOGY_ERROR_CODES = frozenset(
{
"INVALID_CONTEXT_EDGE",
- "MISSING_CONTEXT",
"MULTIPLE_CONTEXTS",
"SHARED_CONTEXT",
}
@@ -71,200 +70,6 @@ def _trusted_owner_id(websocket: WebSocket, existing: Any) -> str:
return "owner"
-def _reconcile_context_submission(
- workflow_data: Dict[str, Any],
- existing: Any,
-) -> tuple[list[Dict[str, Any]], list[Dict[str, Any]], list[str]]:
- """Restore backend-owned Context companions before normalization.
-
- Client graph data may preserve ownership metadata for round-tripping, but
- it is never authoritative. Existing companions survive while their owner
- agent remains, and client-created/replacement Context nodes are discarded
- so normalization creates fresh backend companions where needed.
- """
-
- submitted_nodes = [
- dict(node)
- for node in workflow_data.get("nodes") or []
- if isinstance(node, dict)
- ]
- submitted_edges = [
- dict(edge)
- for edge in workflow_data.get("edges") or []
- if isinstance(edge, dict)
- ]
- existing_graph = getattr(existing, "data", None)
- if not isinstance(existing_graph, dict):
- existing_graph = {}
- stored_nodes = {
- str(node.get("id")): dict(node)
- for node in existing_graph.get("nodes") or []
- if isinstance(node, dict) and node.get("id")
- }
- stored_contexts = {
- node_id: node
- for node_id, node in stored_nodes.items()
- if node.get("type") == "context"
- }
- submitted_context_targets: Dict[str, set[str]] = {}
- for edge in submitted_edges:
- source = str(edge.get("source") or "")
- target = str(edge.get("target") or "")
- source_handle = edge.get("sourceHandle") or edge.get(
- "source_handle"
- )
- target_handle = edge.get("targetHandle") or edge.get(
- "target_handle"
- )
- if (
- source
- and target
- and source_handle == "output-context"
- and target_handle == "input-context"
- ):
- submitted_context_targets.setdefault(source, set()).add(
- target
- )
-
- edge_owners: Dict[str, set[str]] = {}
- for edge in existing_graph.get("edges") or []:
- if not isinstance(edge, dict):
- continue
- source = str(edge.get("source") or "")
- target = str(edge.get("target") or "")
- source_handle = edge.get("sourceHandle") or edge.get(
- "source_handle"
- )
- target_handle = edge.get("targetHandle") or edge.get(
- "target_handle"
- )
- if (
- source in stored_contexts
- and source_handle == "output-context"
- and target_handle == "input-context"
- and target
- ):
- edge_owners.setdefault(source, set()).add(target)
-
- protected_owners: Dict[str, str] = {}
- for context_id, node in stored_contexts.items():
- data = dict(node.get("data") or {})
- declared = str(data.get("agentNodeId") or "")
- if (
- data.get("systemManaged") is True
- and declared in stored_nodes
- ):
- protected_owners[context_id] = declared
- continue
- inferred = sorted(edge_owners.get(context_id, set()))
- if len(inferred) == 1:
- protected_owners[context_id] = inferred[0]
-
- submitted_owner_ids = {
- str(node.get("id"))
- for node in submitted_nodes
- if node.get("id")
- and node.get("type") != "context"
- and str(node.get("id")) not in stored_contexts
- }
- retained_context_ids = {
- context_id
- for context_id, owner_id in protected_owners.items()
- if owner_id in submitted_owner_ids
- }
- warnings: list[str] = []
- reconciled_nodes: list[Dict[str, Any]] = []
- seen_context_ids: set[str] = set()
- rejected_context_ids: set[str] = set()
- for node in submitted_nodes:
- node_id = str(node.get("id") or "")
- is_context_submission = (
- node.get("type") == "context"
- or node_id in stored_contexts
- )
- if not is_context_submission:
- reconciled_nodes.append(node)
- continue
- if node_id not in stored_contexts and not stored_contexts:
- # A new/legacy graph has no protected companion to replace.
- # Ignore client ownership claims and derive ownership only from
- # an unambiguous submitted topology. Ambiguous topology is left
- # intact so the shared validator rejects it.
- submitted_data = dict(node.get("data") or {})
- submitted_data.pop("systemManaged", None)
- submitted_data.pop("agentNodeId", None)
- targets = sorted(
- submitted_context_targets.get(node_id, set())
- )
- if len(targets) == 1:
- submitted_data["systemManaged"] = True
- submitted_data["agentNodeId"] = targets[0]
- reconciled_nodes.append(
- {
- **node,
- "type": "context",
- "data": submitted_data,
- }
- )
- continue
- if node_id not in retained_context_ids:
- if node_id:
- rejected_context_ids.add(node_id)
- warnings.append(
- f"Ignored untrusted Context companion {node_id!r}"
- )
- continue
-
- stored = stored_contexts[node_id]
- owner_id = protected_owners[node_id]
- submitted_data = dict(node.get("data") or {})
- stored_data = dict(stored.get("data") or {})
- item = {
- **stored,
- **node,
- "id": node_id,
- "type": "context",
- "data": {
- **stored_data,
- **{
- key: submitted_data[key]
- for key in ("label", "disabled")
- if key in submitted_data
- },
- "systemManaged": True,
- "agentNodeId": owner_id,
- },
- }
- reconciled_nodes.append(item)
- seen_context_ids.add(node_id)
-
- for context_id in sorted(retained_context_ids - seen_context_ids):
- stored = stored_contexts[context_id]
- owner_id = protected_owners[context_id]
- reconciled_nodes.append(
- {
- **stored,
- "type": "context",
- "data": {
- **dict(stored.get("data") or {}),
- "systemManaged": True,
- "agentNodeId": owner_id,
- },
- }
- )
- warnings.append(
- f"Restored protected Context companion {context_id!r}"
- )
-
- reconciled_edges = [
- edge
- for edge in submitted_edges
- if str(edge.get("source") or "") not in rejected_context_ids
- and str(edge.get("target") or "") not in rejected_context_ids
- ]
- return reconciled_nodes, reconciled_edges, warnings
-
-
def _supports_context_archive_outbox(database: Any) -> bool:
return callable(
getattr(
@@ -403,12 +208,10 @@ async def handle_save_workflow(data: Dict[str, Any], websocket: WebSocket) -> Di
)
from services.workflow_migrations import normalize_workflow_graph
- source_nodes, source_edges, ownership_warnings = (
- _reconcile_context_submission(
- workflow_data,
- existing,
- )
- )
+ # The submitted graph is authoritative for Context nodes: one the user
+ # deleted stays deleted, and one the user added is kept.
+ source_nodes = [node for node in workflow_data.get("nodes") or [] if isinstance(node, dict)]
+ source_edges = [edge for edge in workflow_data.get("edges") or [] if isinstance(edge, dict)]
source_params = await load_node_parameters(database, source_nodes)
normalization = normalize_workflow_graph(
workflow_id,
@@ -416,10 +219,7 @@ async def handle_save_workflow(data: Dict[str, Any], websocket: WebSocket) -> Di
source_edges,
source_params,
)
- migration_warnings = [
- *ownership_warnings,
- *normalization.warnings,
- ]
+ migration_warnings = list(normalization.warnings)
context_errors = await _context_topology_errors(
normalization.nodes,
normalization.edges,
diff --git a/server/services/workflow_validator.py b/server/services/workflow_validator.py
index 50d58cf8..ce13c551 100644
--- a/server/services/workflow_validator.py
+++ b/server/services/workflow_validator.py
@@ -166,19 +166,13 @@ async def validate_workflow(
valid_contexts_by_agent.setdefault(target_id, []).append(source_id)
agents_by_context.setdefault(source_id, []).append(target_id)
+ # A Context is optional: the user adds and deletes it on the canvas, so an
+ # agent without one is valid. Only ambiguous wiring is rejected.
for node_id in sorted(node_by_id):
if not requires_context(node_id):
continue
context_ids = list(dict.fromkeys(valid_contexts_by_agent.get(node_id, [])))
- if not context_ids:
- errors.append(
- {
- "code": "MISSING_CONTEXT",
- "node_id": node_id,
- "message": "This agent requires exactly one Context node",
- }
- )
- elif len(context_ids) > 1:
+ if len(context_ids) > 1:
errors.append(
{
"code": "MULTIPLE_CONTEXTS",
diff --git a/server/tests/test_context_graph_migration.py b/server/tests/test_context_graph_migration.py
index e8aa75e5..56daf458 100644
--- a/server/tests/test_context_graph_migration.py
+++ b/server/tests/test_context_graph_migration.py
@@ -18,11 +18,7 @@ def _node(node_id: str, node_type: str, x: int = 0):
}
-def test_legacy_memory_becomes_isolated_context_and_shared_tool(monkeypatch):
- monkeypatch.setattr(
- "services.workflow_migrations._requires_context",
- lambda node_type: node_type == "agent",
- )
+def test_legacy_memory_becomes_isolated_context_and_shared_tool():
nodes = [
_node("memory", "simpleMemory"),
_node("first", "agent", 400),
@@ -62,11 +58,7 @@ def test_legacy_memory_becomes_isolated_context_and_shared_tool(monkeypatch):
assert all("memory_content" not in node.get("data", {}) for node in contexts)
-def test_context_graph_normalization_is_idempotent(monkeypatch):
- monkeypatch.setattr(
- "services.workflow_migrations._requires_context",
- lambda node_type: node_type == "agent",
- )
+def test_context_graph_normalization_is_idempotent():
first = normalize_workflow_graph(
"7",
[_node("agent", "agent")],
@@ -83,157 +75,55 @@ def test_context_graph_normalization_is_idempotent(monkeypatch):
assert second.aliases == {}
-def test_backend_repairs_required_edge_and_removes_deleted_agent_context(
- monkeypatch,
-):
- monkeypatch.setattr(
- "services.workflow_migrations._requires_context",
- lambda node_type: node_type == "agent",
- )
- nodes = [
- {
- **_node("agent", "agent"),
- "data": {"label": "Agent"},
- },
- {
- **_node("ctx", "context"),
- "data": {
- "label": "Context",
- "systemManaged": True,
- "agentNodeId": "agent",
- },
- },
- ]
- repaired = normalize_workflow_graph("3", nodes, [])
- assert [edge for edge in repaired.edges if edge.get("targetHandle") == "input-context"]
- context = next(node for node in repaired.nodes if node["type"] == "context")
- assert context["data"]["agentNodeId"] == "3:agent:1"
-
- deleted = normalize_workflow_graph(
+def test_normalization_never_recreates_a_deleted_context():
+ # The user deleted the agent's Context on the canvas; saving must not
+ # bring it back. Stale companion metadata on the remaining nodes changes
+ # nothing either.
+ result = normalize_workflow_graph(
"3",
- [node for node in repaired.nodes if node["type"] != "agent"],
+ [
+ {
+ **_node("agent", "agent"),
+ "data": {"label": "Agent"},
+ },
+ ],
[],
)
- assert not [node for node in deleted.nodes if node["type"] == "context"]
-
-def test_normalization_removes_duplicate_system_context_deterministically(
- monkeypatch,
-):
- monkeypatch.setattr(
- "services.workflow_migrations._requires_context",
- lambda node_type: node_type == "agent",
- )
- nodes = [
- _node("agent", "agent"),
- {
- **_node("ctx-a", "context"),
- "data": {
- "label": "ctx-a",
- "systemManaged": True,
- "agentNodeId": "agent",
- },
- },
- {
- **_node("ctx-b", "context"),
- "data": {
- "label": "ctx-b",
- "systemManaged": True,
- "agentNodeId": "agent",
- },
- },
- ]
- edges = [
- {
- "source": "ctx-b",
- "target": "agent",
- "sourceHandle": "output-context",
- "targetHandle": "input-context",
- }
- ]
-
- result = normalize_workflow_graph("5", nodes, edges)
-
- contexts = [node for node in result.nodes if node["type"] == "context"]
- assert len(contexts) == 1
- assert contexts[0]["data"]["label"] == "ctx-b"
- assert contexts[0]["data"]["agentNodeId"] == "5:agent:1"
- assert any("Removed duplicate system Context" in warning for warning in result.warnings)
+ assert not [node for node in result.nodes if node["type"] == "context"]
+ assert not [edge for edge in result.edges if edge.get("targetHandle") == "input-context"]
+ assert result.warnings == []
-def test_stale_system_context_owner_is_removed_instead_of_reassigned(
- monkeypatch,
-):
- monkeypatch.setattr(
- "services.workflow_migrations._requires_context",
- lambda node_type: node_type == "agent",
- )
+def test_normalization_leaves_user_context_topology_alone():
+ # A Context left without its agent, and a Context whose edge the user
+ # removed, stay exactly as placed: no cascade delete, no edge repair.
nodes = [
_node("agent", "agent"),
{
- **_node("ctx", "context"),
+ **_node("orphan", "context"),
"data": {
- "label": "stale",
+ "label": "orphan",
"systemManaged": True,
"agentNodeId": "deleted-agent",
},
},
- ]
- edges = [
- {
- "source": "ctx",
- "target": "agent",
- "sourceHandle": "output-context",
- "targetHandle": "input-context",
- }
- ]
-
- result = normalize_workflow_graph("6", nodes, edges)
-
- contexts = [node for node in result.nodes if node["type"] == "context"]
- assert len(contexts) == 1
- assert contexts[0]["data"]["label"] == "Context"
- assert contexts[0]["data"]["agentNodeId"] == "6:agent:1"
- assert any("Removed orphaned system Context 'ctx'" == warning for warning in result.warnings)
-
-
-def test_system_context_shared_edge_is_repaired_to_recorded_owner(
- monkeypatch,
-):
- monkeypatch.setattr(
- "services.workflow_migrations._requires_context",
- lambda node_type: node_type == "agent",
- )
- nodes = [
- _node("a", "agent"),
- _node("b", "agent"),
{
- **_node("ctx", "context"),
+ **_node("unwired", "context"),
"data": {
- "label": "existing",
+ "label": "unwired",
"systemManaged": True,
- "agentNodeId": "a",
+ "agentNodeId": "agent",
},
},
]
- edges = [
- {
- "source": "ctx",
- "target": target,
- "sourceHandle": "output-context",
- "targetHandle": "input-context",
- }
- for target in ("a", "b")
- ]
- result = normalize_workflow_graph("8", nodes, edges)
+ result = normalize_workflow_graph("5", nodes, [])
- context_edges = [edge for edge in result.edges if edge.get("targetHandle") == "input-context"]
- assert len(context_edges) == 2
- assert len({edge["source"] for edge in context_edges}) == 2
- existing = next(node for node in result.nodes if node["type"] == "context" and node["data"]["label"] == "existing")
- assert existing["data"]["agentNodeId"] == "8:agent:1"
- assert next(edge["target"] for edge in context_edges if edge["source"] == existing["id"]) == "8:agent:1"
+ contexts = [node for node in result.nodes if node["type"] == "context"]
+ assert [node["data"]["label"] for node in contexts] == ["orphan", "unwired"]
+ assert result.edges == []
+ assert result.warnings == []
class _Params(BaseModel):
@@ -255,7 +145,7 @@ class _ContextNode:
@pytest.mark.asyncio
-async def test_validator_rejects_missing_multiple_and_shared_contexts(monkeypatch):
+async def test_validator_rejects_multiple_and_shared_contexts_not_missing(monkeypatch):
from services.workflow_validator import validate_workflow
monkeypatch.setattr(
@@ -296,8 +186,9 @@ async def test_validator_rejects_missing_multiple_and_shared_contexts(monkeypatc
assert "MULTIPLE_CONTEXTS" in codes
assert "SHARED_CONTEXT" in codes
+ # A Context is optional: an agent without one is a valid graph.
missing = await validate_workflow([_node("a", "agent")], [])
- assert "MISSING_CONTEXT" in {issue["code"] for issue in missing["errors"]}
+ assert missing["errors"] == []
@pytest.mark.asyncio
@@ -306,10 +197,6 @@ async def test_save_rejects_ambiguous_shared_context_before_persistence(
):
from services.workflow_storage import handlers
- monkeypatch.setattr(
- "services.workflow_migrations._requires_context",
- lambda node_type: node_type == "agent",
- )
monkeypatch.setattr(
"services.workflow_validator.get_node_class",
lambda node_type: {
@@ -391,15 +278,11 @@ async def test_save_uses_authenticated_owner_and_ignores_client_owner(
@pytest.mark.asyncio
-async def test_save_cannot_replace_backend_owned_context(
+async def test_save_keeps_a_deleted_context_deleted(
monkeypatch,
):
from services.workflow_storage import handlers
- monkeypatch.setattr(
- "services.workflow_migrations._requires_context",
- lambda node_type: node_type == "agent",
- )
monkeypatch.setattr(
"services.workflow_validator.get_node_class",
lambda node_type: {
@@ -442,49 +325,25 @@ async def test_save_cannot_replace_backend_owned_context(
database.save_workflow = AsyncMock(return_value=True)
monkeypatch.setattr(handlers.container, "database", lambda: database)
+ # The user deleted the Context node (and with it, its edge).
result = await handlers.handle_save_workflow(
{
"workflow_id": "1",
"name": "Owned",
"data": {
- "nodes": [
- _node("1:agent:1", "agent"),
- {
- **_node("1:context:99", "context"),
- "data": {
- "label": "Forged",
- "systemManaged": True,
- "agentNodeId": "1:agent:1",
- },
- },
- ],
- "edges": [
- {
- "source": "1:context:99",
- "target": "1:agent:1",
- "sourceHandle": "output-context",
- "targetHandle": "input-context",
- }
- ],
- "owner_id": "forged-owner",
+ "nodes": [_node("1:agent:1", "agent")],
+ "edges": [],
},
},
websocket=None,
)
- contexts = [
- node
- for node in result["data"]["nodes"]
- if node["type"] == "context"
- ]
- assert [node["id"] for node in contexts] == ["1:context:1"]
- assert contexts[0]["data"]["agentNodeId"] == "1:agent:1"
- assert result["data"]["owner_id"] == "owner"
- assert any(
- "Ignored untrusted Context companion '1:context:99'"
- == warning
- for warning in result["migration_warnings"]
- )
+ assert result["success"] is True
+ assert [node["id"] for node in result["data"]["nodes"]] == ["1:agent:1"]
+ assert result["data"]["edges"] == []
+ assert result["migration_warnings"] == []
+ saved = database.save_workflow.await_args.kwargs["data"]
+ assert [node["id"] for node in saved["nodes"]] == ["1:agent:1"]
def test_save_owner_resolution_preserves_existing_backend_owner():