Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(context): record the real request, and stop the Context node steering the agent
trohitgb3c84f442524
diff --git a/client/src/components/parameterPanel/ContextPanel.tsx b/client/src/components/parameterPanel/ContextPanel.tsxindex 2935b47b..0351a482 100644--- a/client/src/components/parameterPanel/ContextPanel.tsx+++ b/client/src/components/parameterPanel/ContextPanel.tsx@@ -178,7 +178,10 @@ const ContextPanel: React.FC<ContextPanelProps> = ({ nodeId, workflowId }) => {onError: () => toast.error('Failed to export Context'),});- const pressurePercent = useMemo(() => {+ // ``null`` means the server could not compute pressure — it has no context+ // window for this thread. Rendering that as 0% would claim an empty context+ // window, which reads as healthy; the bar is hidden instead.+ const pressurePercent = useMemo<number | null>(() => {if (typeof snapshot.pressure_ratio === 'number') {return Math.max(0, Math.min(100, snapshot.pressure_ratio * 100));}@@ -188,7 +191,7 @@ const ContextPanel: React.FC<ContextPanelProps> = ({ nodeId, workflowId }) => {Math.min(100, (snapshot.active_token_count / snapshot.context_window) * 100),);}- return 0;+ return null;}, [snapshot.active_token_count,snapshot.context_window,@@ -269,7 +272,14 @@ const ContextPanel: React.FC<ContextPanelProps> = ({ nodeId, workflowId }) => {<div className="rounded-md border border-border bg-card p-3"><div className="text-xs text-muted-foreground">Replay fidelity</div><div className="mt-1 flex flex-wrap gap-1">- <Badge variant={snapshot.resumable === false ? 'warning' : 'success'}>+ {/* Success is claimed only when the server actually reported both+ a fidelity and resumability. Defaulting an absent verdict to+ green asserted a guarantee the server never made. */}+ <Badge+ variant={+ !snapshot.fidelity || snapshot.resumable !== true ? 'warning' : 'success'+ }+ >{snapshot.fidelity || 'unknown'}</Badge>{snapshot.resumable === false && <Badge variant="outline">non-resumable</Badge>}@@ -279,7 +289,9 @@ const ContextPanel: React.FC<ContextPanelProps> = ({ nodeId, workflowId }) => {<div className="text-xs text-muted-foreground">Provider</div><div className="text-sm font-medium">{snapshot.provider || '—'}</div><div className="text-xs text-muted-foreground">- Binding {snapshot.provider_binding_status || 'unbound'}+ {/* "unbound" is a real server verdict, so it must not double as+ the placeholder for "the server said nothing". */}+ Binding {snapshot.provider_binding_status || '—'}</div></div><div className="rounded-md border border-border bg-card p-3">@@ -288,7 +300,13 @@ const ContextPanel: React.FC<ContextPanelProps> = ({ nodeId, workflowId }) => {{snapshot.active_token_count ?? 0}{snapshot.context_window ? ` / ${snapshot.context_window}` : ' tokens'}</div>- <Progress value={pressurePercent} />+ {pressurePercent === null ? (+ <div className="text-xs text-muted-foreground">+ Set a context window to track pressure+ </div>+ ) : (+ <Progress value={pressurePercent} />+ )}</div></div>diff --git a/client/src/components/parameterPanel/MemoryToolPanel.tsx b/client/src/components/parameterPanel/MemoryToolPanel.tsxindex 60e9b134..5f371a84 100644--- a/client/src/components/parameterPanel/MemoryToolPanel.tsx+++ b/client/src/components/parameterPanel/MemoryToolPanel.tsx@@ -367,6 +367,12 @@ const MemoryToolPanel: React.FC<MemoryToolPanelProps> = ({</section><section className="min-h-0 overflow-y-auto p-4">+ {/* This panel replaces the generic parameter list, so it has to render+ `reset_policy` itself — the options below duplicate the backend+ Literal in `simple_memory/__init__.py` and must be kept in step+ with it. (`server_controlled_fields` marks the field so the MODEL+ cannot override it through tool arguments; the operator still+ sets it here.) */}<div className="mb-4 grid gap-3 rounded-md border border-border bg-card p-3 sm:grid-cols-2"><label className="text-xs font-medium text-muted-foreground">Workflow Reset policy@@ -403,7 +409,11 @@ const MemoryToolPanel: React.FC<MemoryToolPanelProps> = ({<h4 className="font-medium">{selected ? 'Edit Memory item' : 'Remember something'}</h4>{selected && (<Badge variant="outline">- {selected.indexing_state || 'indexed'} · v{selected.version}+ {/* 'indexed' is not a member of the backend enum+ (lexical | embedding_ready | embedding_failed), so+ defaulting to it rendered an embedding failure — or an+ absent verdict — as success. */}+ {selected.indexing_state || 'unknown'} · v{selected.version}</Badge>)}</div>diff --git a/server/nodes/context/_descriptor.py b/server/nodes/context/_descriptor.pyindex d28c0b2f..92033253 100644--- a/server/nodes/context/_descriptor.py+++ b/server/nodes/context/_descriptor.py@@ -62,7 +62,20 @@ async def build_agent_context_descriptor(if generation <= 0:return None- policy = await database.get_node_parameters(source_node_id) or {}+ # Only this node's DECLARED policy travels in the descriptor. Reading the+ # stored row verbatim shipped whatever else happened to be saved against+ # the node — migrated graphs still carry the legacy ``memory_content``+ # markdown here — which then landed in the runtime snapshot, was persisted+ # into the journal, and was rendered to the operator as though it were+ # part of the model's context.+ from . import AgentContextParams++ stored = await database.get_node_parameters(source_node_id) or {}+ policy = {+ name: stored[name]+ for name in AgentContextParams.model_fields+ if name in stored+ }delegated_task_id = (context.get("delegated_task_id")or context.get("parent_task_id")diff --git a/server/nodes/context/_handlers.py b/server/nodes/context/_handlers.pyindex 9d05f6b0..98e0995b 100644--- a/server/nodes/context/_handlers.py+++ b/server/nodes/context/_handlers.py@@ -287,10 +287,15 @@ async def _snapshot(base["next_cursor"] = Nonereturn base+ # Scope the journal to the live epoch. Workflow Reset (and Clear epoch)+ # rotate the thread to a fresh epoch and leave the prior events in place+ # as archived history; reading every epoch made a reset look like it had+ # done nothing, because the panel still listed every pre-reset turn.events, next_after = await store.load_journal_page(active.ref,after_sequence=_decode_cursor(cursor),limit=limit,+ epoch=active.ref.epoch,)base["events"] = [await _event_view(store, event, hydrate_payload=True)diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.pyindex 7307bc02..a0983133 100644--- a/server/services/temporal/agent_activities.py+++ b/server/services/temporal/agent_activities.py@@ -315,6 +315,16 @@ async def _execute_native_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:assistant_wire = message_to_wire(assistant)usage = asdict(response.usage)+ # Record the turn exactly as it happened: the message list this activity+ # just sent to the provider, and the reply it got back. ``messages`` above+ # IS the argument handed to ``ChatUnifier.chat`` — nothing is rebuilt,+ # inferred, or re-typed, so the journal cannot drift from the request.+ await _journal_llm_turn(+ payload,+ sent=[dict(message_to_wire(message)) for message in messages],+ assistant_wire=dict(assistant_wire),+ )+if response.tool_calls:calls = []for tool_call in response.tool_calls:@@ -352,14 +362,53 @@ async def _execute_native_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:return result+async def _journal_llm_turn(+ payload: Dict[str, Any],+ *,+ sent: List[Dict[str, Any]],+ assistant_wire: Dict[str, Any],+) -> None:+ """Append this turn to the Context journal, when one is attached.++ Observation only: it never influences the request. ``request.snapshot``+ carries the exact list sent, which is what+ :func:`services.agent_context.runtime.reconstruct_message_wire_v2`+ documents that event to be — the render boundary that later assistant and+ tool transitions are applied on top of.+ """+ ref_data = payload.get("context_ref")+ operation_id = str(payload.get("journal_operation_id") or "")+ if not ref_data or not operation_id:+ return+ store = _context_store()+ ref = _context_ref(ref_data)+ provider = str(payload.get("provider") or "")+ ref = await _append_event(+ store,+ ref,+ event_type="request.snapshot",+ operation_id=f"{operation_id}:request",+ provider=provider,+ payload_ref=await store.put_blob({"messages": sent}),+ )+ await _append_event(+ store,+ ref,+ event_type="message.assistant",+ operation_id=f"{operation_id}:assistant",+ provider=provider,+ message_wire_v2=assistant_wire,+ )++@activity.defn(name="agent.execute_llm_step")async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:"""Run one LLM turn with bound tools and return the structured response.- The single LLM-step activity. A ``context_ref`` in the payload selects- the journal-backed path (transcript reconstructed from the Context- store rather than carried in the payload); everything else is- identical, so callers do not pick an implementation.+ The single LLM-step activity. There is exactly one implementation: the+ request is always built from ``payload["messages"]``. A ``context_ref``+ only asks for the turn to be journalled afterwards — attaching a Context+ node observes the agent, it never changes what the agent sends.``payload`` shape::@@ -389,9 +438,6 @@ async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:``heartbeat_timeout``."""- if payload.get("context_ref"):- return await _execute_context_llm_step(payload)-activity.logger.info(f"Agent LLM step: provider={payload.get('provider')} " f"model={payload.get('model')} messages={len(payload.get('messages', []))}")@@ -885,7 +931,16 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:)# ---- Edge walking ---------------------------------------------------+ # Carry the execution context through rather than rebuilding it from a+ # fixed key list. Connected nodes decide what they need from it: the+ # Context descriptor requires ``generation`` and refuses to build without+ # one, then reads ``session_id`` / ``explicit_session_id`` /+ # ``delegated_task_id`` to pick its thread. A four-key rebuild dropped all+ # of them, so every Temporal run walked edges as if it had no admitted+ # generation and the agent journalled nothing — while the in-process path+ # (nodes/agent/_inline.py) passed the context whole and worked.walk_context = {+ **context,"nodes": context.get("nodes") or [],"edges": context.get("edges") or [],"workflow_id": workflow_id,@@ -2167,28 +2222,22 @@ async def prepare_context(payload: Dict[str, Any]) -> Dict[str, Any]:generation=generation,**_thread_inputs(context),)+ # The runtime configuration is machinery, not context: it carries the+ # whole canvas graph, node positions, execution/team identifiers and+ # routing flags. It stays addressable through ``runtime_config_ref``,+ # which the LLM and append activities receive directly — it is NOT a+ # journal event. Pointing ``request.snapshot`` at it put several hundred+ # lines of scaffolding into the operator's view of the conversation, and+ # broke reconstruction as well: that reader expects a snapshot payload to+ # contain ``messages`` (services/agent_context/runtime.py), found a config+ # blob instead, and silently skipped the boundary.runtime_config_ref = await store.put_blob(runtime_snapshot)- thread = await _append_event(- store,- thread,- event_type="request.snapshot",- operation_id=f"{operation_id}:snapshot",- provider=str(prepared.get("provider") or ""),- payload_ref=runtime_config_ref,- )-- prompt = str(prepared.get("user_prompt") or "")- if prompt:- thread = await _append_event(- store,- thread,- event_type="message.user",- operation_id=f"{operation_id}:user",- provider=str(prepared.get("provider") or ""),- message_wire_v2=message_to_wire(- Message(role="user", content=prompt)- ),- )+ # Nothing is journalled here. This activity runs BEFORE the request exists,+ # so anything it wrote would be a reconstruction from configuration rather+ # than a record of what was sent — which is how the journal came to hold a+ # fabricated request, the system prompt typed as a tool result, and the+ # user's prompt twice. ``agent.execute_llm_step`` journals each turn from+ # the exact message list it hands to ``ChatUnifier.chat``.return {"context_ref": _ref_dict(thread),@@ -2231,158 +2280,6 @@ def _pending_tool_identities(})return pending-async def _execute_context_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:- """Journal-backed variant: load checkpoint-plus-tail, call once, commit.-- Not an activity of its own — ``execute_llm_step`` dispatches here when- the payload carries a ``context_ref``, so there is exactly one LLM-step- activity regardless of whether the agent is journal-backed.- """-- from services.agent_context import (- ContextCompactionPolicy,- provider_context_request_options,- reconstruct_message_wire_v2,- )- from services.llm.protocol import Message, message_to_wire-- store = _context_store()- ref = _context_ref(payload["context_ref"])- config = await _runtime_config(- store,- str(payload["runtime_config_ref"]),- )- prepared = dict(config["prepared"])- provider = str(prepared.get("provider") or "")- policy = ContextCompactionPolicy.from_mapping(- dict(config.get("context_policy") or {})- )- operation_id = str(payload["operation_id"])- iteration = int(payload.get("iteration") or 1)-- current_ref, wires = await reconstruct_message_wire_v2(store, ref)- system_message = str(prepared.get("system_message") or "")- messages = list(wires)- if system_message:- messages.insert(- 0,- message_to_wire(- Message(role="system", content=system_message)- ),- )- llm_payload = {- "node_id": prepared.get("node_id"),- "provider": provider,- "model": prepared.get("model"),- "messages": messages,- "tools": [- tool.get("definition") or {}- for tool in prepared.get("tools") or []- if not tool.get("llm_hidden")- ],- "temperature": prepared.get("temperature", 0.7),- "max_tokens": prepared.get("max_tokens", 4096),- "thinking_config": prepared.get("thinking_config"),- "message_wire_version": prepared.get("message_wire_version", 2),- "include_finish_reason": True,- "context_management": provider_context_request_options(- provider=provider,- model=str(prepared.get("model") or ""),- policy=policy,- ),- }-- activity.heartbeat(- f"Context V2 LLM step starting: {prepared.get('model')}"- )- try:- result = dict(await _execute_native_llm_step(llm_payload))- except BaseException as exc:- # The provider may have accepted a request even though the caller did- # not receive a response. Record the ambiguity and let the one-shot- # Temporal policy surface it; never silently rebill.- ambiguous_ref = await store.put_blob(- {- "iteration": iteration,- "error_type": type(exc).__name__,- "ambiguous": True,- }- )- try:- await _append_event(- store,- current_ref,- event_type="provider.outcome_ambiguous",- operation_id=f"{operation_id}:ambiguous",- provider=provider,- payload_ref=ambiguous_ref,- )- except Exception:- activity.logger.exception(- "Could not persist ambiguous Context V2 provider outcome"- )- raise-- response_ref = await store.put_blob(- {- "kind": result.get("kind"),- "assistant_message": result.get("assistant_message"),- "calls": result.get("calls") or [],- "content": result.get("content") or "",- "thinking": result.get("thinking"),- "usage": result.get("usage") or {},- "finish_reason": result.get("finish_reason"),- "iteration": iteration,- }- )- current_ref = await _append_event(- store,- current_ref,- event_type="message.assistant",- operation_id=f"{operation_id}:assistant",- provider=provider,- message_wire_v2=dict(result["assistant_message"]),- payload_ref=response_ref,- )- finish_reason = str(result.get("finish_reason") or "").strip().lower()- if finish_reason == "compaction":- current_ref = await _append_event(- store,- current_ref,- event_type="provider.compaction_paused",- operation_id=f"{operation_id}:compaction-pause",- provider=provider,- payload_ref=response_ref,- )-- usage = dict(result.get("usage") or {})- pending = _pending_tool_identities(- result.get("calls") or [],- prepared.get("tools") or [],- )- return {- "context_ref": _ref_dict(current_ref),- "response_ref": response_ref,- "response_hash": _hash_from_ref(response_ref),- "iteration": iteration,- "status": (- "compaction_pause"- if finish_reason == "compaction"- else (- "tool_calls"- if result.get("kind") == "tool_calls"- else "final"- )- ),- "pending_tools": pending,- # Delegation builds its child prompt from candidate["args"] in the- # workflow; pending_tools is identity-only and cannot carry them.- "calls": list(result.get("calls") or []),- "assistant_message": result.get("assistant_message"),- "kind": result.get("kind"),- "active_input_tokens": int(usage.get("input_tokens") or 0),- "output_tokens": int(usage.get("output_tokens") or 0),- }def _find_call(response: Mapping[str, Any],pending: Mapping[str, Any],diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex 2e97ba45..3d806d93 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -655,6 +655,16 @@ class AgentWorkflow:task_scope_execution_id = str(payload.get("team_execution_id") or execution_id)+ # Journal operation ids must be unique per FIRING, not per generation.+ # ``execution_id`` is generation-scoped (``1:execution:10``), so every+ # chat message within one generation minted identical operation ids+ # and the store's idempotency guard discarded turns 2..N as replays —+ # only the first message a generation ever saw was recorded. The+ # trigger listener already plumbs a per-firing ``context_execution_id``+ # (the child workflow id) for exactly this purpose.+ journal_operation_id = (+ str(context.get("context_execution_id") or "") or execution_id+ )# Needed by every terminal result, including agents that never make a# tool call (for example downstream taskTrigger automation). It was# previously initialized only inside the tool-call branch.@@ -717,12 +727,16 @@ class AgentWorkflow:# only references.context_ref: Optional[Dict[str, Any]] = Noneruntime_config_ref = ""- journalled = 0if payload.get("context_descriptor"):await self._wait_until_resumed()prepared_context = await workflow.execute_activity("agent.prepare_context",- args=[{"context": context, "operation_id": f"{execution_id}:prepare"}],+ args=[+ {+ "context": context,+ "operation_id": f"{journal_operation_id}:prepare",+ }+ ],activity_id="prepare-context",start_to_close_timeout=PERSIST_TURN_TIMEOUT * 2,retry_policy=AGENT_ACTIVITY_RETRY,@@ -813,28 +827,6 @@ class AgentWorkflow:# delegation paths, which never touch the journal, so without# this the next reconstruction replays an assistant turn whose# tool calls have no answers.- if context_ref and len(messages) > journalled:- pending_messages = messages[journalled:]- appended = await workflow.execute_activity(- "agent.append_context",- args=[- {- "action": "append_messages",- "context_ref": context_ref,- "runtime_config_ref": runtime_config_ref,- "messages": pending_messages,- "iteration": iteration,- "operation_id": (- f"{execution_id}:iter:{iteration}:append"- ),- }- ],- activity_id=f"append-context-{iteration + 1}",- start_to_close_timeout=PERSIST_TURN_TIMEOUT,- retry_policy=AGENT_ACTIVITY_RETRY,- )- context_ref = appended.get("context_ref") or context_ref- journalled = len(messages)# CloudEvents-shaped agent_progress per LLM turn. Mirrors the# the in-process agent loop's per-turn broadcast (RFC §6.4).@@ -871,13 +863,16 @@ class AgentWorkflow:"thinking_config": payload.get("thinking_config"),"llm_engine": NATIVE_LLM_ENGINE,"message_wire_version": message_wire_version,- # Present only for journal-backed agents; the activity- # reconstructs the transcript from the store instead of- # trusting `messages`.+ # Journalling only. The activity always builds its request+ # from ``messages`` above; these just tell it where to+ # record the turn it actually sent. A Context node observes+ # the agent, it never steers it.**({"context_ref": context_ref,- "runtime_config_ref": runtime_config_ref,+ "journal_operation_id": (+ f"{journal_operation_id}:iter:{iteration}"+ ),}if context_refelse {}@@ -1054,11 +1049,6 @@ class AgentWorkflow:assistant_message = step_result.get("assistant_message")if assistant_message:messages.append(assistant_message)- if context_ref and step_result.get("context_ref"):- # The step committed the assistant turn; nothing for the- # delta journaller below to re-append.- context_ref = step_result["context_ref"]- journalled = len(messages)# A provider that stops to compact has not answered. It carries# no tool calls, so it would otherwise be classified "final" and@@ -1088,6 +1078,9 @@ class AgentWorkflow:retry_policy=AGENT_ACTIVITY_RETRY,)await self._persist_turn(payload, human_text=user_prompt, assistant_text=final_content)+ # The delta journaller runs at the TOP of each iteration, so+ # the answer that ends the loop would never reach the journal+ # without a final flush here.breakif kind != "tool_calls":@@ -2433,6 +2426,7 @@ class AgentWorkflow:retry_policy=AGENT_ACTIVITY_RETRY,)+async def _persist_turn(self,payload: Dict[str, Any],diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.pyindex e73aa7ca..89fd6751 100644--- a/server/tests/temporal/test_agent_workflow.py+++ b/server/tests/temporal/test_agent_workflow.py@@ -92,6 +92,78 @@ class TestDurableTeamDelegationContract:assert '"team_id": payload.get("team_id") or context.get("team_id")' in sourceassert '"execution_id": context.get("execution_id")' in source++class TestContextJournalIdentity:+ """Every firing must journal, and journal each turn exactly once."""++ def test_journal_operation_ids_are_per_firing_not_per_generation(self):+ """``execution_id`` is generation-scoped, so reusing it for journal+ operation ids made every chat message in a generation mint identical+ ids. The store's idempotency guard then discarded turns 2..N as+ replays and only the generation's first message was ever recorded.+ """+ import inspect++ from services.temporal.agent_workflow import AgentWorkflow++ source = inspect.getsource(AgentWorkflow.run)+ assert 'context.get("context_execution_id")' in source, (+ "journal operation ids must derive from the per-firing "+ "context_execution_id"+ )+ for suffix in (":prepare", ":append", ":llm"):+ assert f"{{journal_operation_id}}" in source+ assert f"{{execution_id}}:iter" not in source+ assert f'f"{{execution_id}}{suffix}"' not in source++ def test_llm_step_has_a_single_implementation(self):+ """A Context node observes execution; it must not steer it.++ ``context_ref`` used to select a second, journal-backed LLM+ implementation that rebuilt the request from the store instead of+ sending ``messages``. That transcript did not carry the user's prompt,+ so merely connecting a Context node made the agent answer an empty+ question.+ """+ import inspect++ from services.temporal import agent_activities++ source = inspect.getsource(agent_activities)+ assert "_execute_context_llm_step" not in source, (+ "a second LLM implementation selected by context_ref is exactly "+ "how attaching a Context node changed the agent's request"+ )+ step = inspect.getsource(agent_activities.execute_llm_step)+ assert "if payload.get(\"context_ref\")" not in step++ def test_journal_records_the_exact_request_never_a_reconstruction(self):+ """The journal must record what was sent, not rebuild it.++ ``prepare_context`` runs before the request exists, so anything it+ wrote was assembled from configuration — that is how the journal came+ to hold a fabricated request, the system prompt typed as a tool+ result, and the user's prompt twice. The turn is journalled from the+ exact list handed to ``ChatUnifier.chat``.+ """+ import inspect++ from services.temporal import agent_activities++ prepare = inspect.getsource(agent_activities.prepare_context)+ assert "_append_event" not in prepare, (+ "prepare_context must not journal; it has no request yet"+ )++ native = inspect.getsource(agent_activities._execute_native_llm_step)+ sent = native.index("_journal_llm_turn")+ called = native.index("run_native_llm_step(")+ assert called < sent, "journal the request only after it was sent"+ assert "for message in messages" in native, (+ "the journalled request must be the same `messages` object passed "+ "to the unifier"+ )+def test_root_execution_identity_is_initialized_before_agent_loop(self):import inspect