Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat: scope runtime state and canonical identities
trohitgeb44bdaf3593
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 915df733..b60f6cd0 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -247,7 +247,7 @@ const DashboardContent: React.FC = () => {const isCurrentWorkflowLocked = workflowLock.locked &&workflowLock.workflow_id === currentWorkflow?.id;const [globalModelDefaults, setGlobalModelDefaults] = React.useState<{ provider: string; model: string } | null>(null);- const { onDragOver, onDrop, handleComponentDragStart } = useDragAndDrop({ nodes, setNodes, saveNodeParameters, globalModelDefaults });+ const { onDragOver, onDrop, handleComponentDragStart } = useDragAndDrop({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId: currentWorkflow?.id ?? 'new' });const { onConnect: baseOnConnect, onNodesDelete, onEdgesDelete: baseOnEdgesDelete } = useReactFlowNodes({ setNodes, setEdges });const { onConnect, onEdgesDelete } = useAutoSkillEdges({baseOnConnect,@@ -260,7 +260,7 @@ const DashboardContent: React.FC = () => {// Apply runtime canvas mutations pushed from the backend (e.g.,// Agent Builder tools called by the LLM mid-execution).useWorkflowOpsListener({ nodes, edges, setNodes, setEdges });- const { copySelectedNodes, pasteNodes } = useCopyPaste({ nodes, edges, setNodes, setEdges, saveNodeParameters });+ const { copySelectedNodes, pasteNodes } = useCopyPaste({ nodes, edges, setNodes, setEdges, saveNodeParameters, workflowId: currentWorkflow?.id ?? 'new' });// Override all agent nodes to use the global model. Agent membership is// derived at call time from the backend-served `group` field — by thediff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 45947b15..9c9b3f19 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -1231,6 +1231,12 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chidelete next[workflowId];return next;});+ setAllCompactionStats((previous) => {+ const next = { ...previous };+ delete next[workflowId];+ return next;+ });+ queryClient.removeQueries({ queryKey: queryKeys.compactionStats._def });if (useAppStore.getState().currentWorkflow?.id === workflowId) {setConsoleLogs([]);setChatMessages([]);@@ -2422,6 +2428,12 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chidelete next[workflowId];return next;});+ setAllCompactionStats((previous) => {+ const next = { ...previous };+ delete next[workflowId];+ return next;+ });+ queryClient.removeQueries({ queryKey: queryKeys.compactionStats._def });if (useAppStore.getState().currentWorkflow?.id === workflowId) {setConsoleLogs([]);setChatMessages([]);diff --git a/client/src/hooks/useAutoSkillEdges.ts b/client/src/hooks/useAutoSkillEdges.tsindex 15efa631..28299b7c 100644--- a/client/src/hooks/useAutoSkillEdges.ts+++ b/client/src/hooks/useAutoSkillEdges.ts@@ -23,6 +23,7 @@*/import { useCallback } from 'react';+import { useAppStore } from '../store/useAppStore';import type { Node, Edge, Connection } from 'reactflow';import { useWebSocket } from '../contexts/WebSocketContext';import { useUserSettingsQuery } from './useUserSettingsQuery';@@ -103,6 +104,7 @@ export function useAutoSkillEdges({if (!result?.operations?.length) return;await applyOperations(result.operations, {+ workflowId: useAppStore.getState().currentWorkflow?.id,nodes,edges,setNodes,diff --git a/client/src/hooks/useCopyPaste.ts b/client/src/hooks/useCopyPaste.tsindex 987bbf60..fef412a3 100644--- a/client/src/hooks/useCopyPaste.ts+++ b/client/src/hooks/useCopyPaste.ts@@ -2,12 +2,14 @@ import { useCallback, useRef } from 'react';import { Node, Edge } from 'reactflow';import { generateUniqueLabel } from './useDragAndDrop';import { resolveNodeDescription } from '../lib/nodeSpec';+import { nextNodeInstanceId } from '../utils/workflow';interface UseCopyPasteProps {nodes: Node[];edges: Edge[];setNodes: (nodes: Node[] | ((nodes: Node[]) => Node[])) => void;setEdges: (edges: Edge[] | ((edges: Edge[]) => Edge[])) => void;saveNodeParameters?: (nodeId: string, parameters: Record<string, any>) => Promise<boolean>;+ workflowId: string;}interface ClipboardData {@@ -28,7 +30,8 @@ export const useCopyPaste = ({edges,setNodes,setEdges,- saveNodeParameters+ saveNodeParameters,+ workflowId,}: UseCopyPasteProps) => {// In-memory clipboard (simpler than browser clipboard API)const clipboardRef = useRef<ClipboardData | null>(null);@@ -70,11 +73,11 @@ export const useCopyPaste = ({// Generate ID mapping (old ID -> new ID)const idMap = new Map<string, string>();- const now = Date.now();-- copiedNodes.forEach((node, index) => {- // Use timestamp + index to ensure unique IDs- idMap.set(node.id, `${node.type}-${now + index}`);+ const allocatedNodes = [...nodes];+ copiedNodes.forEach((node) => {+ const newId = nextNodeInstanceId(workflowId, node.type!, allocatedNodes);+ idMap.set(node.id, newId);+ allocatedNodes.push({ ...node, id: newId });});// Offset for pasted nodes to avoid stacking on original@@ -139,7 +142,7 @@ export const useCopyPaste = ({setEdges(eds => [...eds, ...newEdges]);console.log(`[CopyPaste] Pasted ${newNodes.length} nodes and ${newEdges.length} edges`);- }, [nodes, setNodes, setEdges, saveNodeParameters]);+ }, [nodes, setNodes, setEdges, saveNodeParameters, workflowId]);/*** Check if clipboard has content.diff --git a/client/src/hooks/useDragAndDrop.ts b/client/src/hooks/useDragAndDrop.tsindex a614cffa..501e2036 100644--- a/client/src/hooks/useDragAndDrop.ts+++ b/client/src/hooks/useDragAndDrop.ts@@ -1,6 +1,6 @@import { useCallback } from 'react';import { Node } from 'reactflow';-import { snapToGrid, getDefaultNodePosition } from '../utils/workflow';+import { snapToGrid, getDefaultNodePosition, nextNodeInstanceId } from '../utils/workflow';import { theme } from '../styles/theme';import { getCachedNodeSpec } from '../lib/nodeSpec';@@ -19,6 +19,7 @@ interface UseDragAndDropProps {setNodes: (nodes: Node[] | ((nodes: Node[]) => Node[])) => void;saveNodeParameters?: (nodeId: string, parameters: Record<string, any>) => Promise<boolean>;globalModelDefaults?: { provider: string; model: string } | null;+ workflowId: string;}/**@@ -47,7 +48,7 @@ export const generateUniqueLabel = (displayName: string, nodeType: string, existreturn `${displayName} ${suffix}`;};-export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModelDefaults }: UseDragAndDropProps) => {+export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModelDefaults, workflowId }: UseDragAndDropProps) => {const onDragOver = useCallback((event: React.DragEvent) => {event.preventDefault();event.dataTransfer.dropEffect = 'move';@@ -86,7 +87,7 @@ export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModeconst uniqueLabel = generateUniqueLabel(displayName, nodeData.type, nodes);const newNode: Node = {- id: `${nodeData.type}-${Date.now()}`,+ id: nextNodeInstanceId(workflowId, nodeData.type, nodes),type: nodeData.type,position,data: {@@ -117,7 +118,7 @@ export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModeconsole.error('Error dropping node:', error);}},- [setNodes, nodes, saveNodeParameters, globalModelDefaults]+ [setNodes, nodes, saveNodeParameters, globalModelDefaults, workflowId]);const handleComponentDragStart = useCallback((event: React.DragEvent, definition: any) => {@@ -139,4 +140,4 @@ export const useDragAndDrop = ({ nodes, setNodes, saveNodeParameters, globalModeonDrop,handleComponentDragStart,};-};\ No newline at end of file+};diff --git a/client/src/hooks/useWorkflowManagement.ts b/client/src/hooks/useWorkflowManagement.tsindex 6baf4616..f59915db 100644--- a/client/src/hooks/useWorkflowManagement.ts+++ b/client/src/hooks/useWorkflowManagement.ts@@ -20,8 +20,8 @@ export const useWorkflowManagement = () => {saveWorkflow();}, [saveWorkflow]);- const handleNew = useCallback(() => {- createNewWorkflow();+ const handleNew = useCallback(async () => {+ await createNewWorkflow();}, [createNewWorkflow]);const handleOpen = useCallback(() => {diff --git a/client/src/hooks/useWorkflowOpsListener.ts b/client/src/hooks/useWorkflowOpsListener.tsindex fad83f0c..20201767 100644--- a/client/src/hooks/useWorkflowOpsListener.ts+++ b/client/src/hooks/useWorkflowOpsListener.ts@@ -70,6 +70,7 @@ export function useWorkflowOpsListener({if (ops.length === 0) return;void applyOperations(ops, {+ workflowId: currentWorkflowId,nodes,edges,setNodes,diff --git a/client/src/lib/workflowOps.ts b/client/src/lib/workflowOps.tsindex 6252395b..9d515025 100644--- a/client/src/lib/workflowOps.ts+++ b/client/src/lib/workflowOps.ts@@ -18,6 +18,7 @@*/import type { Node, Edge } from 'reactflow';+import { NEW_WORKFLOW_ID, nextNodeInstanceId } from '../utils/workflow';// ---------------------------------------------------------------------------// Wire types -- mirror server/services/workflow_ops.py 1:1@@ -104,6 +105,8 @@ export type WorkflowOperation =// ---------------------------------------------------------------------------export interface ApplyContext {+ /** Canonical workflow identity used when minting plugin node instances. */+ workflowId?: string;/** Current React Flow nodes (read-only -- used for anchor resolution). */nodes: Node[];/** Current React Flow edges (read-only -- used for delete-cascade). */@@ -132,10 +135,6 @@ export interface ApplyResult {// Internal helpers// ----------------------------------------------------------------------------function newId(nodeType: string): string {- return `${nodeType}-${Date.now()}-${Math.floor(Math.random() * 1000)}`;-}-function resolveNodeRef(ref: NodeRef, refMap: Record<string, string>): string | null {if (typeof ref === 'string') return ref;return refMap[ref.client_ref] ?? null;@@ -188,7 +187,11 @@ export async function applyOperations(// Prefer the BE-minted id when present (agentBuilder hot-spawn// path) so status broadcasts dispatched against the same id// land on this React Flow node and the canvas glows.- const id = op.minted_id || newId(op.node_type);+ const id = op.minted_id || nextNodeInstanceId(+ ctx.workflowId ?? NEW_WORKFLOW_ID,+ op.node_type,+ liveNodes,+ );result.refMap[op.client_ref] = id;const position = resolvePosition(op.position, ctx, liveNodes);const label = op.label ?? op.parameters?.label ?? op.node_type;@@ -252,7 +255,11 @@ export async function applyOperations(case 'replace_node': {const existing = liveNodes.find(n => n.id === op.node_id);if (!existing) throw new Error(`replace_node: node ${op.node_id} not found`);- const newNodeId = newId(op.node_type);+ const newNodeId = nextNodeInstanceId(+ ctx.workflowId ?? NEW_WORKFLOW_ID,+ op.node_type,+ liveNodes,+ );const label = op.label ?? op.parameters?.label ?? op.node_type;const replacement: Node = {id: newNodeId,diff --git a/client/src/services/workflowApi.ts b/client/src/services/workflowApi.tsindex 035b27af..d91643f8 100644--- a/client/src/services/workflowApi.ts+++ b/client/src/services/workflowApi.ts@@ -30,8 +30,11 @@ export interface WorkflowData {export interface SaveWorkflowResult {success: boolean;+ /** Backend-allocated canonical decimal id (also returned for updates). */+ id: string;slug?: string;name?: string;+ nodeIdAliases?: Record<string, string>;}export const workflowApi = {@@ -45,7 +48,15 @@ export const workflowApi = {});const result = await response.json();if (!result.success) return null;- return { success: true, slug: result.slug, name: result.name };+ const canonicalId = result.id ?? result.workflow_id;+ if (!canonicalId && workflowId === 'new') return null;+ return {+ success: true,+ id: canonicalId ?? workflowId,+ slug: result.slug,+ name: result.name,+ nodeIdAliases: result.node_id_aliases ?? {},+ };} catch (error) {console.error('Failed to save workflow:', error);return null;diff --git a/client/src/store/useAppStore.ts b/client/src/store/useAppStore.tsindex 2bc7c511..e1d4b7f2 100644--- a/client/src/store/useAppStore.ts+++ b/client/src/store/useAppStore.ts@@ -1,7 +1,7 @@import { create } from 'zustand';import { Node, Edge } from 'reactflow';import { toast } from 'sonner';-import { generateWorkflowId } from '../utils/workflow';+import { NEW_WORKFLOW_ID } from '../utils/workflow';import { theme } from '../styles/theme';import {exportWorkflowToJSON as exportToJSON,@@ -23,7 +23,7 @@ export interface WorkflowData {nodes: Node[];edges: Edge[];name: string;- /** Stable UUID — backend system identity. Never changes on rename. */+ /** Stable backend-allocated decimal identity. Never changes on rename. */id: string;/** Human-readable slug derived from name (e.g. "AI_Assistant_1").* Backend recomputes on every name change and rotates the on-disk@@ -72,7 +72,7 @@ interface AppStore {// Workflow actionssetCurrentWorkflow: (workflow: WorkflowData) => void;updateWorkflow: (updates: Partial<Omit<WorkflowData, 'id' | 'createdAt'>>) => void;- createNewWorkflow: () => void;+ createNewWorkflow: () => Promise<void>;saveWorkflow: () => Promise<void>;loadWorkflow: (id: string) => Promise<void>;deleteWorkflow: (id: string) => Promise<boolean>;@@ -123,7 +123,7 @@ interface AppStore {// Helper functionsconst createDefaultWorkflow = (): WorkflowData => ({- id: generateWorkflowId(),+ id: NEW_WORKFLOW_ID,name: theme.constants.defaultWorkflowName,slug: '', // Server allocates on first save.nodes: [],@@ -227,13 +227,29 @@ export const useAppStore = create<AppStore>((set, get) => ({});},- createNewWorkflow: () => {+ createNewWorkflow: async () => {const newWorkflow = createDefaultWorkflow();- set({- currentWorkflow: newWorkflow,+ // The database owns the cross-client sequence. Persist the empty draft to+ // reserve its id before any node parameters are written against the graph.+ const result = await workflowApi.saveWorkflow(+ NEW_WORKFLOW_ID,+ newWorkflow.name,+ { nodes: [], edges: [] },+ );+ if (!result?.id) {+ console.error('Failed to allocate workflow identity');+ return;+ }+ set({+ currentWorkflow: {+ ...newWorkflow,+ id: result.id,+ slug: result.slug ?? newWorkflow.slug,+ },hasUnsavedChanges: false,selectedNode: null,});+ invalidateWorkflowsList();},saveWorkflow: async () => {@@ -255,12 +271,29 @@ export const useAppStore = create<AppStore>((set, get) => ({return;}+ const aliases = result.nodeIdAliases ?? {};+ const nodes = currentWorkflow.nodes.map(node => {+ const canonicalId = aliases[node.id];+ return canonicalId ? { ...node, id: canonicalId } : node;+ });+ const edges = currentWorkflow.edges.map(edge => ({+ ...edge,+ source: aliases[edge.source] ?? edge.source,+ target: aliases[edge.target] ?? edge.target,+ }));+set({currentWorkflow: {...currentWorkflow,+ id: result.id,+ nodes,+ edges,slug: result.slug ?? currentWorkflow.slug,lastModified: new Date(),},+ selectedNode: get().selectedNode && aliases[get().selectedNode!.id]+ ? { ...get().selectedNode!, id: aliases[get().selectedNode!.id] }+ : get().selectedNode,hasUnsavedChanges: false,});invalidateWorkflowsList();@@ -302,12 +335,7 @@ export const useAppStore = create<AppStore>((set, get) => ({// If deleting current workflow, create a new oneif (currentWorkflow?.id === id) {- const newWorkflow = createDefaultWorkflow();- set({- currentWorkflow: newWorkflow,- hasUnsavedChanges: false,- selectedNode: null,- });+ await get().createNewWorkflow();}invalidateWorkflowsList();diff --git a/client/src/utils/__tests__/workflowIdentity.test.ts b/client/src/utils/__tests__/workflowIdentity.test.tsnew file mode 100644index 00000000..bcb03e77--- /dev/null+++ b/client/src/utils/__tests__/workflowIdentity.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';+import type { Node } from 'reactflow';++import { nextNodeInstanceId } from '../workflow';++const node = (id: string, type: string): Pick<Node, 'id' | 'type'> => ({ id, type });++describe('nextNodeInstanceId', () => {+ it('uses the workflow and fixed plugin type with a one-based ordinal', () => {+ expect(nextNodeInstanceId('7', 'aiAgent', [])).toBe('7:aiAgent:1');+ });++ it('allows multiple instances and never reuses a lower ordinal', () => {+ const nodes = [+ node('7:aiAgent:1', 'aiAgent'),+ node('7:aiAgent:4', 'aiAgent'),+ node('7:taskManager:1', 'taskManager'),+ ];+ expect(nextNodeInstanceId('7', 'aiAgent', nodes)).toBe('7:aiAgent:5');+ expect(nextNodeInstanceId('7', 'taskManager', nodes)).toBe('7:taskManager:2');+ });++ it('accounts for legacy instances while a workflow is being migrated', () => {+ const nodes = [node('aiAgent-old-a', 'aiAgent'), node('aiAgent-old-b', 'aiAgent')];+ expect(nextNodeInstanceId('9', 'aiAgent', nodes)).toBe('9:aiAgent:3');+ });+});diff --git a/client/src/utils/workflow.ts b/client/src/utils/workflow.tsindex 7c7cf609..5462d050 100644--- a/client/src/utils/workflow.ts+++ b/client/src/utils/workflow.ts@@ -1,7 +1,36 @@import { Node, Edge } from 'reactflow';-export const generateWorkflowId = (): string =>- `workflow-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;+/** Marker used until the backend atomically allocates the next workflow id. */+export const NEW_WORKFLOW_ID = 'new';++/**+ * Allocate the next stable instance id for a plugin node in a workflow.+ *+ * Plugin `type` is the fixed metadata identity. The final ordinal keeps+ * multiple instances of that plugin distinct without timestamps/randomness.+ * The server repeats this validation while saving/importing, so this helper is+ * primarily what keeps live canvas operations canonical before persistence.+ */+export const nextNodeInstanceId = (+ workflowId: string,+ nodeType: string,+ existingNodes: Pick<Node, 'id' | 'type'>[],+): string => {+ const scope = workflowId || NEW_WORKFLOW_ID;+ const prefix = `${scope}:${nodeType}:`;+ let largest = 0;++ for (const node of existingNodes) {+ if (node.type !== nodeType || !node.id.startsWith(prefix)) continue;+ const ordinal = Number.parseInt(node.id.slice(prefix.length), 10);+ if (Number.isSafeInteger(ordinal) && ordinal > largest) largest = ordinal;+ }++ // Legacy ids do not contain an ordinal. Counting them prevents a migrated+ // canvas from issuing `:1` for what is visibly a later plugin instance.+ const sameTypeCount = existingNodes.filter(node => node.type === nodeType).length;+ return `${prefix}${Math.max(largest, sameTypeCount) + 1}`;+};export const sanitizeNodesForComparison = (nodes: Node[]): Node[] =>nodes.map(n => ({ ...n, selected: undefined, dragging: undefined }));@@ -33,4 +62,4 @@ export const getDefaultNodePosition = (nodeCount: number): { x: number; y: numbe// ``server/services/workflow_import.py::remap_node_ids`` — the import// path is now backend-authoritative (``import_workflow`` WS handler),// so there's no need for a duplicate frontend implementation. The-// in-canvas copy/paste path uses its own id scheme in ``useCopyPaste``.\ No newline at end of file+// in-canvas copy/paste path uses its own id scheme in ``useCopyPaste``.diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex 30f23b31..310f6949 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -112,7 +112,7 @@ Each node receives an immutable context snapshot:```pythoncontext = {- "node_id": "aiAgent-123",+ "node_id": "1:aiAgent:1","node_type": "aiAgent","node_data": {"model": "gpt-4",@@ -120,15 +120,13 @@ context = {"systemMessage": "You are a helpful assistant"},"inputs": { # Outputs from upstream nodes- "chatTrigger-456": {"message": "Hello", "timestamp": "..."},+ "1:chatTrigger:1": {"message": "Hello", "timestamp": "..."},},- "workflow_id": "6868cbbf4a36409fbd07ca24999f8b66", # 32-hex UUID, stable across rename+ "workflow_id": "1", # Backend-allocated application identity"workflow_slug": "AI_Assistant_1", # Human-readable, used for Temporal child IDs"session_id": "session-xyz",- "execution_id": "AI_Assistant_1-a1b2c3d4", # Stable per run (= the MachinaWorkflow Temporal id);- # threaded into AgentWorkflow tool payloads + delegate- # children so session-keyed nodes (browser) reuse one- # instance per run instead of minting a uuid per call+ "execution_id": "1:execution:1", # Application execution identity; distinct from+ # Temporal Workflow ID and Temporal Run ID"nodes": [...], # Full list for tool/memory detection"edges": [...], # Full list for tool/memory detection}diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.mdindex 603af932..e0bc593d 100644--- a/docs-internal/frontend_architecture.md+++ b/docs-internal/frontend_architecture.md@@ -396,13 +396,14 @@ See [ui_migration_plan.md](./ui_migration_plan.md) Phase 6.The older `deployment_snapshot` and binary deployment status remain migrationadapters for legacy deployments and must not override a resolved controllergeneration. See [Temporal Execution Engine RFC](temporal-execution-engine-rfc.md).-- **Runtime Reset clears projections, not durable memory.** The+- **Runtime Reset clears execution and conversation projections.** The`workflow_runtime_reset` broadcast drops the workflow's node-status slot,variables, and current console/chat arrays; `Dashboard` remounts theparameter panel so local output reducers cannot leak the previous run.- Simple Memory node-parameter queries and `compactionStats` are intentionally- retained. Only the memory panel's explicit Clear Memory mutation may reset- those stores. See [Memory Lifecycle](memory_lifecycle.md#workflow-reset-is-not-memory-clear).+ Simple Memory parameters are refreshed from the backend's cleared-row+ broadcast, and `compactionStats` caches are evicted. The old transcript stays+ available only through the archived generation. See+ [Memory Lifecycle](memory_lifecycle.md#workflow-reset-archives-then-clears-memory).- **`currentWorkflowId` lives in `useAppStore` only.** Non-React listeners (WS handlers) read it via `useAppStore.getState().currentWorkflow?.id` -- the documented Zustand escape hatch (https://github.com/pmndrs/zustand#read-state-without-subscription). The previous `currentWorkflowIdRef` mirror inside WebSocketContext was a one-render-late copy that misrouted broadcasts during workflow switches. The push to `nodeStatusStore.setCurrentWorkflowId` is driven from a single `useEffect` in `Dashboard.tsx`.## Ownership boundary: TanStack Query vs Zustand vs WebSocketContextdiff --git a/docs-internal/memory_lifecycle.md b/docs-internal/memory_lifecycle.mdindex c7d6aaad..294dceba 100644--- a/docs-internal/memory_lifecycle.md+++ b/docs-internal/memory_lifecycle.md@@ -96,27 +96,26 @@ Three stores are cleared in one call:Frontend `clear_memory` WS handler ([`routers/websocket.py:2167`](../server/routers/websocket.py)) calls this; UI presents a Reset Memory button on the simpleMemory parameter panel.-### Workflow Reset is not Memory Clear+### Workflow Reset archives then clears MemoryTemporal workflow **Reset** and the Simple Memory panel's **Clear Memory** areseparate lifecycle operations:| Operation | `memory_content` / `memory_jsonl` | session metadata | vector cache | compaction/token state ||---|---|---|---|---|-| Workflow Reset | preserved | preserved | preserved | preserved |+| Workflow Reset | archived, then reset | cleared | cleared | reset for connected sessions || Clear Memory | reset | cleared | optional (`clear_long_term`) | cleared for the selected session |-`workflow_runtime_reset` removes only the editor's disposable execution-projection: node statuses and outputs, variables, and current console/chat-views. It must not evict the Simple Memory query, compaction projection, or-node-parameter row. The next Temporal generation reads the same durable-`simpleMemory` parameters through `edge_walker._build_memory_entry`, so agent-conversation continuity survives a workflow Reset.--The archived workflow-generation snapshot may contain the memory-node values-admitted for that historical run. That is an immutable historical copy, not a-move of the authoritative memory row: `node_parameters` remains live and is-still the source of truth for the next Start.+`workflow_runtime_reset` removes the editor's disposable execution projection+and invalidates memory/compaction projections. Before clearing, Reset copies+the authoritative Simple Memory parameters into the archived generation's+`runtime_data.simple_memory` map. It then resets the live memory-node fields,+connected agent sessions, vector caches, direct memory-store sessions,+conversation rows, and token counters. The next Temporal generation therefore+starts with the empty conversation placeholder.++The archived copy is immutable history; the live `node_parameters` row remains+the source of truth and is reset to the empty-state value for the next Start.## 6. claude_code_agent native session resume bridgediff --git a/docs-internal/node-logic-flows/ai_agents/simpleMemory.md b/docs-internal/node-logic-flows/ai_agents/simpleMemory.mdindex 35d36d1b..34b17e05 100644--- a/docs-internal/node-logic-flows/ai_agents/simpleMemory.md+++ b/docs-internal/node-logic-flows/ai_agents/simpleMemory.md@@ -29,21 +29,24 @@ agents**. See "Edge cases" below.## Workflow Reset semantics-`simpleMemory` is durable workflow configuration and is deliberately excluded-from generation cleanup. Resetting the Temporal workflow:--- does not modify `memory_content`, `memory_jsonl`, `session_id`,- `last_session_id`, window settings, or long-term-memory settings;-- does not evict the memory node's compaction/token projection in the UI;-- does not clear either in-memory vector-store cache;-- may retain an immutable copy of the admitted memory values in the archived- generation snapshot, while the authoritative `node_parameters` row remains- active;-- makes the next workflow generation load the current memory-node parameters.--Only the explicit **Clear Memory** action calls-`clear_agent_session_state`. Workflow Reset must never call that service or-simulate it by clearing memory-related frontend queries.+`simpleMemory` configuration is durable, but its conversation state follows the+workflow generation. Resetting the Temporal workflow:++- archives the current memory parameters under the old generation;+- resets `memory_content`, `memory_jsonl`, `last_session_id`, and provider+ continuation identifiers while preserving configuration such as window size;+- clears connected agent sessions, long-term vector caches, direct memory-store+ sessions, conversation rows, and token/compaction counters;+- broadcasts the cleared node parameters so the open panel updates immediately;+- makes the next workflow generation start from an empty conversation.++The explicit **Clear Memory** action remains available for clearing memory+without resetting the whole workflow. Workflow Reset invokes the same+cross-store clear contract only after its archival write succeeds.++Implementation is plugin-owned: `SimpleMemoryNode.reset_execution_state`+implements the generic `BaseNode` lifecycle hook. The deployment/reset service+does not recognize the `simpleMemory` type or know its session topology.## Inputs (handles)diff --git a/docs-internal/temporal-execution-engine-rfc.md b/docs-internal/temporal-execution-engine-rfc.mdindex 922138ad..3c3dc3fe 100644--- a/docs-internal/temporal-execution-engine-rfc.md+++ b/docs-internal/temporal-execution-engine-rfc.md@@ -166,12 +166,23 @@ flowchart TBIdentity rules:+- New workflow IDs are backend-allocated positive integers (`1`, `2`, ...).+ Existing legacy records remain exactly as stored; the server does not run an+ identity migration or rewrite historical Temporal links.+- Application execution IDs are workflow-scoped sequences+ (`<workflow_id>:execution:<sequence>`). They are not Temporal Run IDs.+- Node instance IDs are `<workflow_id>:<plugin_type>:<ordinal>`. The plugin+ type is the fixed metadata identity; the ordinal distinguishes multiple+ instances, including multiple `aiAgent` nodes.- Browser and model callers never choose a Temporal workflow/run ID for traceaccess. The server resolves it from an authorized task attempt.- Workflow IDs and Run IDs are distinct. Resume signals the existing workflow;it does not manufacture a replacement Run ID.- A Reset archives the current generation and returns control state `ready`.The next Start creates generation `N + 1`.+- Random IDs remain appropriate only for correlation, idempotency, events,+ leases, and provider-owned identities. They are not application workflow,+ execution, or node identities.## 6. Deployment control plane@@ -505,12 +516,11 @@ Reset archives the scope rather than deleting it. A later Start creates a newscope and therefore a fresh node-data namespace, while archived task, output,trace, and graph-snapshot records remain available for historical inspection.-Durable configuration nodes are not owned by that disposable namespace.-In particular, `simpleMemory` remains authoritative in `node_parameters`:-workflow Reset preserves its transcript, JSONL/session metadata, long-term-cache, and compaction/token state. The archived scope contains only the-historical value admitted by that generation. The next Start reads the current-memory row; memory is cleared only by the explicit Clear Memory contract.+`simpleMemory` settings remain durable, but its conversation state is+generation-bound. Reset first writes the final memory parameters to the+archived scope's `runtime_data.simple_memory`, then clears the live transcript,+continuation metadata, connected sessions, vector/direct-memory caches,+conversation rows, and token counters. The next Start reads the reset live row.| State class | Reset behavior | Current source after Reset ||---|---|---|@@ -518,7 +528,28 @@ memory row; memory is cleared only by the explicit Clear Memory contract.| Console and chat-trigger run rows | archived by root execution | new generation scope || Team tasks, attempts, and traces | archived and queryable | selected execution history || Node parameters and canvas configuration | preserved | `node_parameters` / `workflows` |-| `simpleMemory` transcript and session state | preserved | `node_parameters` + memory services |+| `simpleMemory` transcript and session state | archived, then cleared | reset `node_parameters` + memory services |++### 11.2 Generic node runtime lifecycle++Reset orchestration must not contain node-type branches. The framework archives+every admitted node under `WorkflowRunDataScope.runtime_data.nodes`, keyed by+node ID and therefore transitively by `{workflow_id, execution_id, node_id}`.+Each entry contains the node type, admitted canvas data, and final parameter+snapshot.++After the generic archive succeeds, the coordinator resolves each node through+the node registry and calls `BaseNode.reset_execution_state(...)`. The default+implementation is a no-op for stateless nodes. A stateful plugin overrides the+hook to clear stores it owns and returns refreshed parameters for the standard+`node_parameters_updated` broadcast. Adding another stateful node therefore+requires a plugin lifecycle declaration, not a deployment-manager condition.++Normal execution output remains isolated by the generation's `data_scope_id`+session namespace. Console/chat rows, teams, tasks, attempts, and traces carry+the root execution ID explicitly. Together these identities prevent a current+run from reading another generation's mutable data while keeping archived runs+inspectable.```mermaiderDiagramdiff --git a/docs-internal/temporal-workflow-control.md b/docs-internal/temporal-workflow-control.mdindex 6cbde13c..e1ca9def 100644--- a/docs-internal/temporal-workflow-control.md+++ b/docs-internal/temporal-workflow-control.md@@ -54,11 +54,18 @@ execution ID; current-run reads filter by that ID while archived rows remain inthe database. Node parameters are canvas configuration and intentionally remainunchanged across Reset.-`simpleMemory` is explicitly outside the disposable generation projection.-Its `memory_content`, JSONL, configured session, long-term store, and compaction-statistics remain attached to the durable memory node across Reset. Resetting a-workflow must not behave like the memory panel's explicit **Clear Memory**-operation.+`simpleMemory` configuration survives, but conversation state does not leak+across generations. Reset snapshots current memory parameters into the archived+scope, then clears the live transcript, continuation metadata, connected+sessions, vector/direct-memory caches, conversation rows, and token/compaction+state. The explicit **Clear Memory** action performs the same clear without+resetting the workflow.++This is a framework contract, not a Reset special case. The runtime coordinator+archives every node's canvas data and parameters under the current execution,+then invokes the registered node class's `reset_execution_state` hook. Stateless+nodes inherit the no-op base implementation; stateful plugins own cleanup of+their external stores. Deployment control never switches on node type.On server restart, active controlled deployments are excluded from the legacystartup termination sweep. `TEMPORAL_TERMINATE_RUNNING_ON_STARTUP` defaults todiff --git a/docs-internal/workflow-schema.md b/docs-internal/workflow-schema.mdindex 2118ca24..ded877f8 100644--- a/docs-internal/workflow-schema.md+++ b/docs-internal/workflow-schema.md@@ -28,8 +28,8 @@ A workflow JSON document contains:"properties": {"id": {"type": "string",- "description": "Stable system UUID — 32 lowercase hex chars (uuid.uuid4().hex). Never changes on rename. FK target for cross-table refs + Temporal Search Attributes + CloudEvents extension + log context.",- "pattern": "^[0-9a-f]{32}$"+ "description": "Stable positive decimal application identity allocated atomically by the backend for new workflows. Existing legacy records are not migrated.",+ "pattern": "^[1-9][0-9]*$"},"name": {"type": "string",@@ -638,9 +638,9 @@ This resolves to the `message` property from the Start node's output data.## Validation Rules1. Workflow must have required fields: id, name, slug, nodes, edges, createdAt, lastModified-2. Workflow ID must be a 32-char lowercase hex UUID (`^[0-9a-f]{32}$`) — stable for the lifetime of the workflow, never changes on rename+2. New workflow IDs must be positive decimal strings (`^[1-9][0-9]*$`) allocated by the backend — stable for the workflow lifetime and never changed on rename. Pre-cutover records retain their stored IDs.3. Workflow slug must be `<Sanitized_Name>_<N>` (`^[A-Za-z0-9]+(_[0-9]+)?$`) — derived from `name` via `services.workflow_naming.next_available_slug`; unique across active workflows; mutable on rename-4. Each node must have: id, type, position (with x and y)+4. Each node must have `id`, `type`, and `position`; canonical node IDs are `<workflow_id>:<plugin_type>:<ordinal>`, where plugin type comes from fixed plugin metadata and the ordinal permits repeated instances5. Each edge must have: id, source, target6. Edge source and target must reference existing nodes7. Node types must be one of the supported typesdiff --git a/server/core/database.py b/server/core/database.pyindex eb098f5c..30c5bcf5 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -16,6 +16,7 @@ from core.config import Settingsfrom models.database import (NodeParameter,RuntimeMutation,+ IdentitySequence,Workflow,Execution,APIKey,@@ -117,6 +118,51 @@ class Database:logger.error("Database startup failed", error=str(e))raise+ async def allocate_identity(self, namespace: str) -> int:+ """Atomically allocate the next positive integer in ``namespace``."""+ if not namespace or len(namespace) > 512:+ raise ValueError("invalid_identity_namespace")+ # A compare-and-swap update is portable and prevents duplicate values+ # when multiple API/Temporal worker processes allocate concurrently.+ for _ in range(20):+ async with self.get_session() as session:+ row = await session.get(IdentitySequence, namespace)+ if row is None:+ session.add(IdentitySequence(namespace=namespace, next_value=2))+ try:+ await session.commit()+ return 1+ except IntegrityError:+ await session.rollback()+ continue+ current = row.next_value+ result = await session.execute(+ update(IdentitySequence)+ .where(+ IdentitySequence.namespace == namespace,+ IdentitySequence.next_value == current,+ )+ .values(next_value=current + 1, updated_at=datetime.now(timezone.utc))+ )+ if result.rowcount == 1:+ await session.commit()+ return current+ await session.rollback()+ raise RuntimeError("identity_allocation_conflict")++ async def allocate_workflow_id(self) -> str:+ """Return the next canonical workflow ID: ``1``, ``2``, ..."""+ return str(await self.allocate_identity("workflow"))++ async def allocate_execution_id(self, workflow_id: str) -> str:+ """Return a workflow-scoped application execution identity.++ The canonical workflow alias is used in the visible ID. This method+ never manufactures or replaces a Temporal Run ID.+ """+ value = await self.allocate_identity(f"workflow-execution:{workflow_id}")+ return f"{workflow_id}:execution:{value}"+async def _migrate_user_settings(self):"""Add missing columns to user_settings table."""try:@@ -627,7 +673,8 @@ class Database:) -> bool:"""Save or update workflow.- ``slug`` is required for new rows and is updated on every save+ ``workflow_id`` accepts either the canonical decimal identity or a+ retained legacy alias. ``slug`` is required for new rows and is updated on every savefor existing rows (so a rename routed through this path staysconsistent). Callers compute the slug via:func:`services.workflow_naming.next_available_slug` before@@ -698,11 +745,10 @@ class Database:return []async def rename_workflow(self, workflow_id: str, new_name: str, new_slug: str) -> bool:- """Atomically update display name + slug. ``id`` (PK) never moves.+ """Atomically update display name + slug. The storage PK never moves.- Cross-table FK references (``Execution.workflow_id``) and soft- refs (``ConsoleLog`` / ``TokenUsageMetric`` / etc.) all key on- the UUID, so renaming is a single-row UPDATE — no cascade+ Cross-table FK references and retained Temporal history may still key+ on a legacy storage identity, so renaming is a single-row UPDATE — no cascadeneeded. The unique constraint on ``slug`` is the collisionguard; the caller must pre-allocate a free slug via:func:`services.workflow_naming.next_available_slug`.@@ -2514,6 +2560,28 @@ class Database:session.add(control)scope_id = control.data_scope_id or control.execution_idcontrol.data_scope_id = scope_id+ graph_nodes = [+ node for node in control.graph_snapshot.get("nodes", [])+ if node.get("id")+ ]+ node_ids = [str(node["id"]) for node in graph_nodes]+ parameter_rows = []+ if node_ids:+ parameter_result = await session.execute(+ select(NodeParameter).where(NodeParameter.node_id.in_(node_ids))+ )+ parameter_rows = list(parameter_result.scalars().all())+ parameters_by_id = {+ row.node_id: dict(row.parameters or {}) for row in parameter_rows+ }+ runtime_nodes = {+ str(node["id"]): {+ "type": node.get("type"),+ "canvas_data": dict(node.get("data") or {}),+ "parameters": parameters_by_id.get(str(node["id"]), {}),+ }+ for node in graph_nodes+ }session.add(WorkflowRunDataScope(id=scope_id,control_id=control.id,@@ -2533,6 +2601,7 @@ class Database:for node in control.graph_snapshot.get("nodes", [])if node.get("id")},+ runtime_data={"nodes": runtime_nodes},))await session.commit()await session.refresh(control)@@ -2541,6 +2610,7 @@ class Database:async def update_workflow_run_data_scope(self, scope_id: str, *, temporal_run_id: Optional[str] = None,status: Optional[str] = None, archived_at: Optional[datetime] = None,+ runtime_data: Optional[Dict[str, Any]] = None,) -> bool:"""Update the execution link/lifecycle without mutating its node snapshot."""from models.database import WorkflowRunDataScope@@ -2552,6 +2622,8 @@ class Database:values["status"] = statusif archived_at is not None:values["archived_at"] = archived_at+ if runtime_data is not None:+ values["runtime_data"] = runtime_dataif not values:return Trueasync with self.get_session() as session:diff --git a/server/models/database.py b/server/models/database.pyindex 88940715..3d24b43b 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -52,7 +52,8 @@ class Workflow(SQLModel, table=True):Three identity carriers (Wave 14 split):- * ``id`` — opaque UUID, stable for the lifetime of the workflow.+ * ``id`` — positive decimal application identity for new workflows.+ Existing legacy rows remain unchanged; no automatic migration runs.FK target for every cross-table reference (``Execution.workflow_id``,soft refs on ``ConsoleLog`` / ``TokenUsageMetric`` / etc.), TemporalSearch Attributes, log context. Never changes on rename.@@ -468,6 +469,7 @@ class WorkflowControlExecution(SQLModel, table=True):UniqueConstraint("workflow_id", "idempotency_key", name="uq_workflow_control_idempotency"),)+id: str = Field(primary_key=True, max_length=255)workflow_id: str = Field(index=True, max_length=255)generation: int = Field(index=True)@@ -489,6 +491,23 @@ class WorkflowControlExecution(SQLModel, table=True):completed_at: Optional[datetime] = Field(default=None)+class IdentitySequence(SQLModel, table=True):+ """Atomic counters for application-owned, human-readable identities.++ Temporal Run IDs and transport correlation IDs deliberately do not use+ this table: those identities are owned by Temporal/the transport layer.+ """++ __tablename__ = "identity_sequences"++ namespace: str = Field(primary_key=True, max_length=512)+ next_value: int = Field(default=1)+ updated_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), onupdate=func.now()),+ )++class WorkflowRunDataScope(SQLModel, table=True):"""Immutable graph snapshot and isolated runtime namespace for one generation.diff --git a/server/nodes/skill/simple_memory/__init__.py b/server/nodes/skill/simple_memory/__init__.pyindex 89c5566b..e7d23509 100644--- a/server/nodes/skill/simple_memory/__init__.py+++ b/server/nodes/skill/simple_memory/__init__.py@@ -104,6 +104,45 @@ class SimpleMemoryNode(ActionNode):Params = SimpleMemoryParamsOutput = SimpleMemoryOutput+ @classmethod+ async def reset_execution_state(+ cls, *, node_id: str, workflow_id: str, execution_id: str,+ graph: dict[str, Any], database: Any,+ ) -> dict[str, Any]:+ """Clear this plugin's mutable state after the execution is archived."""+ from services.memory import clear_agent_session_state+ from services.memory_store import clear_session as clear_direct_session++ params = await database.get_node_parameters(node_id) or {}+ configured = str(params.get("session_id") or "").strip()+ if configured and configured != "default":+ sessions = [configured]+ else:+ sessions = [+ str(edge.get("target"))+ for edge in graph.get("edges", [])+ if edge.get("source") == node_id+ and (edge.get("targetHandle") or edge.get("target_handle")) == "input-memory"+ and edge.get("target")+ ]+ sessions.append("default")+ sessions = list(dict.fromkeys(sessions))+ for index, session_id in enumerate(sessions):+ await clear_agent_session_state(+ session_id=session_id,+ workflow_id=workflow_id,+ clear_long_term=True,+ memory_node_id=node_id if index == 0 else None,+ )+ clear_direct_session(session_id)+ await database.clear_conversation(session_id)+ await database.reset_session_token_state(session_id)+ return {+ "reset": True,+ "parameters": await database.get_node_parameters(node_id) or {},+ "sessions": sessions,+ }+@Operation("read")async def read(self, ctx: NodeContext, params: SimpleMemoryParams) -> SimpleMemoryOutput:"""Return the current message log for the session.diff --git a/server/nodes/tool/agent_builder/__init__.py b/server/nodes/tool/agent_builder/__init__.pyindex 106bd06d..e0ec0762 100644--- a/server/nodes/tool/agent_builder/__init__.py+++ b/server/nodes/tool/agent_builder/__init__.py@@ -33,7 +33,6 @@ from __future__ import annotationsimport hashlibimport inspectimport json-import uuidfrom pathlib import Pathfrom typing import Any, Dict, List, Literal, Optional@@ -43,7 +42,7 @@ from core.logging import get_loggerfrom services import workflow_opsfrom services.node_registry import registered_node_classesfrom services.plugin import NodeContext, Operation, TaskQueue, ToolNode-from services.workflow_naming import new_workflow_id, next_available_slug+from services.workflow_naming import next_available_sluglogger = get_logger(__name__)@@ -1227,9 +1226,9 @@ class AgentBuilderNode(ToolNode):from services.plugin.deps import get_databasedatabase = get_database()- workflow_id = new_workflow_id()+ workflow_id = await database.allocate_workflow_id()slug = await next_available_slug(name, database)- start_node_id = f"start-{uuid.uuid4().hex[:8]}"+ start_node_id = f"{workflow_id}:start:1"description = (params.workflow_description or "").strip()workflow_data = {"id": workflow_id,diff --git a/server/services/deployment/control.py b/server/services/deployment/control.pyindex e24b14a0..2cea0500 100644--- a/server/services/deployment/control.py+++ b/server/services/deployment/control.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport hashlibimport json-import uuidfrom datetime import datetime, timezonefrom typing import Any, Dict, Optional@@ -65,7 +64,7 @@ class WorkflowControlService:if latest and latest.status != "reset" and not reset:raise ValueError("workflow_already_started")generation = (latest.generation + 1) if latest else 1- execution_id = f"{workflow_id}:g{generation}:{uuid.uuid4().hex[:12]}"+ execution_id = await self.database.allocate_execution_id(workflow_id)control = WorkflowControlExecution(id=f"workflow-control:{workflow_id}:{generation}", workflow_id=workflow_id,generation=generation, execution_id=execution_id, root_execution_id=execution_id,diff --git a/server/services/deployment/handlers.py b/server/services/deployment/handlers.pyindex e8125edb..619071f7 100644--- a/server/services/deployment/handlers.py+++ b/server/services/deployment/handlers.py@@ -645,14 +645,27 @@ async def handle_reset_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dstatus="archived", archived_at=datetime.now(timezone.utc),)from services.status_broadcaster import get_status_broadcaster- await get_status_broadcaster().broadcast({+ from services.deployment.runtime_state import archive_and_reset_node_state+ broadcaster = get_status_broadcaster()+ node_state = await archive_and_reset_node_state(+ current, service.database, broadcaster,+ )+ await broadcaster.broadcast({"type": "workflow_runtime_reset","workflow_id": workflow_id,"generation": current.generation,"data_scope_id": current.data_scope_id or current.execution_id,+ "archived_nodes": node_state["archived_nodes"],+ "reset_nodes": node_state["reset_nodes"],})return await _with_runtime_counts(- {"success": True, "terminated_executions": terminated, **serialize_control(current)},+ {+ "success": True,+ "terminated_executions": terminated,+ "archived_nodes": node_state["archived_nodes"],+ "reset_nodes": node_state["reset_nodes"],+ **serialize_control(current),+ },workflow_id,)diff --git a/server/services/deployment/runtime_state.py b/server/services/deployment/runtime_state.pynew file mode 100644index 00000000..f4e7fe3d--- /dev/null+++ b/server/services/deployment/runtime_state.py@@ -0,0 +1,56 @@+"""Generic execution-scoped node-state archival and reset coordination."""++from __future__ import annotations++from typing import Any, Dict+++async def archive_and_reset_node_state(control: Any, database: Any, broadcaster: Any) -> Dict[str, Any]:+ """Archive every node's current data, then invoke its lifecycle contract.++ Deployment orchestration never branches on node type. Each registered node+ class owns any external mutable state through ``reset_execution_state``.+ """+ from services.node_registry import get_node_class++ graph = control.graph_snapshot or {}+ archived_nodes: Dict[str, Any] = {}+ reset_nodes: list[str] = []+ for node in graph.get("nodes", []):+ node_id = node.get("id")+ if not node_id:+ continue+ params = await database.get_node_parameters(str(node_id)) or {}+ archived_nodes[str(node_id)] = {+ "type": node.get("type"),+ "canvas_data": dict(node.get("data") or {}),+ "parameters": dict(params),+ }++ scope_id = control.data_scope_id or control.execution_id+ scope = await database.get_workflow_run_data_scope(scope_id)+ runtime_data = dict(getattr(scope, "runtime_data", None) or {})+ runtime_data["nodes"] = archived_nodes+ await database.update_workflow_run_data_scope(scope_id, runtime_data=runtime_data)++ for node in graph.get("nodes", []):+ node_id = node.get("id")+ node_class = get_node_class(str(node.get("type") or ""))+ if not node_id or node_class is None:+ continue+ result = await node_class.reset_execution_state(+ node_id=str(node_id), workflow_id=control.workflow_id,+ execution_id=control.execution_id, graph=graph, database=database,+ )+ if not result.get("reset"):+ continue+ reset_nodes.append(str(node_id))+ if "parameters" in result:+ await broadcaster.broadcast_node_parameters_updated(+ str(node_id), parameters=result["parameters"],+ workflow_id=control.workflow_id, source_hint="workflow_reset",+ )+ return {"archived_nodes": len(archived_nodes), "reset_nodes": reset_nodes}+++__all__ = ["archive_and_reset_node_state"]diff --git a/server/services/example_loader.py b/server/services/example_loader.pyindex 170bf022..503a2b2a 100644--- a/server/services/example_loader.py+++ b/server/services/example_loader.py@@ -54,18 +54,16 @@ async def import_examples_for_user(database) -> int:Returns the count of workflows imported."""from services.workflow_import import remap_node_ids- from services.workflow_naming import new_workflow_id, next_available_slug+ from services.workflow_naming import canonicalize_node_ids, next_available_slugfrom services.workflow_validator import validate_workflowexamples = get_example_workflows()imported = 0for example in examples:- # Fresh UUID for each example (pre-Wave-14 used "example_"- # prefix + JSON id which produced ugly "example_example_workflow-..."- # double-prefixed strings). Slug comes from the seed's display- # name via the standard helper.- workflow_id = new_workflow_id()+ # Examples use the same incremental identity allocator as user-created+ # and imported workflows.+ workflow_id = await database.allocate_workflow_id()example_name = example.get("name", "Example Workflow")slug = await next_available_slug(example_name, database)@@ -76,7 +74,11 @@ async def import_examples_for_user(database) -> int:example.get("edges", []),example.get("nodeParameters", {}),)-+ nodes, edges, node_aliases = canonicalize_node_ids(workflow_id, nodes, edges)+ node_parameters = {+ node_aliases.get(node_id, node_id): params+ for node_id, params in node_parameters.items()+ }# Pre-save validation. parameters_by_id is the freshly-remapped# map so INVALID_PARAM check sees the configured defaults instead# of empty dicts.diff --git a/server/services/plugin/base.py b/server/services/plugin/base.pyindex 44ba89ae..1da0cb69 100644--- a/server/services/plugin/base.py+++ b/server/services/plugin/base.py@@ -118,6 +118,21 @@ class BaseNode:call the sole operation regardless of the ``operation`` field."""+ # Mutable state owned by a node belongs to an execution scope, never to+ # deployment orchestration. Plugins that keep state outside normal node+ # outputs override this hook; stateless nodes inherit the no-op contract.+ @classmethod+ async def reset_execution_state(+ cls,+ *,+ node_id: str,+ workflow_id: str,+ execution_id: str,+ graph: Dict[str, Any],+ database: Any,+ ) -> Dict[str, Any]:+ return {"reset": False}+# ---- declaration (override in subclass) -------------------------------type: ClassVar[str] = ""version: ClassVar[int] = 1diff --git a/server/services/workflow_import.py b/server/services/workflow_import.pyindex 85ca53ad..b884a535 100644--- a/server/services/workflow_import.py+++ b/server/services/workflow_import.py@@ -36,7 +36,7 @@ from typing import Any, Dict, List, Optional, Tuplefrom core.logging import get_loggerfrom services.node_registry import get_node_classfrom services.workflow_migrations import normalize_legacy_android_toolkit-from services.workflow_naming import new_workflow_id, next_available_slug+from services.workflow_naming import canonicalize_node_ids, next_available_slugfrom services.workflow_validator import validate_workflowlogger = get_logger(__name__)@@ -311,9 +311,16 @@ async def import_workflow(node_parameters,)- # 7. Save. UUID-based system identity + name-derived slug for+ # 7. Save. Incremental system identity + name-derived slug for# human-visible surfaces (folder names, Temporal Web UI).- workflow_id = new_workflow_id()+ workflow_id = await database.allocate_workflow_id()+ remapped_nodes, remapped_edges, canonical_aliases = canonicalize_node_ids(+ workflow_id, remapped_nodes, remapped_edges+ )+ remapped_params = {+ canonical_aliases.get(node_id, node_id): params+ for node_id, params in remapped_params.items()+ }slug = await next_available_slug(proposed_name, database)saved = await database.save_workflow(workflow_id=workflow_id,diff --git a/server/services/workflow_naming.py b/server/services/workflow_naming.pyindex d330224a..6443bc6c 100644--- a/server/services/workflow_naming.py+++ b/server/services/workflow_naming.py@@ -2,7 +2,7 @@Separates two concerns the system used to conflate:-* ``Workflow.id`` (UUID) — stable system identity. Never changes on+* ``Workflow.id`` (positive decimal string) — stable system identity. Never changes onrename. Used for FK references (``Execution.workflow_id``), TemporalSearch Attributes, CloudEvents extensions, log context, cache keys,in-memory ``DeploymentManager._deployments`` dict keys, frontend@@ -28,7 +28,6 @@ Temporal-safe up to 1000 chars).from __future__ import annotationsimport re-import uuidfrom typing import Any, Dict, Setfrom core.logging import get_logger@@ -133,24 +132,51 @@ async def next_available_slug(return f"{base}_{n}"-def new_workflow_id() -> str:- """Canonical workflow UUID: 32 lowercase hex chars, no prefix.+def canonicalize_node_ids(+ workflow_id: str, nodes: list[dict], edges: list[dict]+) -> tuple[list[dict], list[dict], dict[str, str]]:+ """Give node instances stable IDs derived from plugin metadata.- Replaces the three pre-Wave-14 generation conventions- (``wf_<12hex>`` from agent_builder, ``workflow-<ms>-<8hex>`` from- workflow_import, ``example_<original_id>`` from example_loader)- with a single stable form. The id never appears in human-readable- surfaces — it's pure system identity — so a bare UUID is the right- shape. Stays on stdlib to avoid adding a dep for marginal benefit- (ULID/UUIDv7 would gain sortability but every consumer treats the- id as opaque).+ Plugin ``type`` is the fixed identity while the per-type ordinal permits+ repeatable plugins such as ``aiAgent``. List order is the stable migration+ order used for legacy graphs. The function is pure and idempotent."""- return uuid.uuid4().hex+ prefix = f"{workflow_id}:"+ counts: dict[str, int] = {}+ mapping: dict[str, str] = {}+ normalized_nodes: list[dict] = []+ for node in nodes:+ item = dict(node)+ plugin_type = str(item.get("type") or (item.get("data") or {}).get("type") or "node")+ plugin_type = re.sub(r"[^A-Za-z0-9_-]+", "-", plugin_type).strip("-") or "node"+ counts[plugin_type] = counts.get(plugin_type, 0) + 1+ old_id = str(item.get("id") or "")+ expected = f"{prefix}{plugin_type}:{counts[plugin_type]}"+ # Already canonical graphs retain their ordinals even if nodes were+ # reordered by a later layout/save operation.+ match = re.fullmatch(re.escape(prefix + plugin_type) + r":([1-9]\d*)", old_id)+ if match:+ counts[plugin_type] = max(counts[plugin_type], int(match.group(1)))+ expected = old_id+ if old_id and old_id != expected:+ mapping[old_id] = expected+ item["id"] = expected+ normalized_nodes.append(item)++ normalized_edges: list[dict] = []+ for edge in edges:+ item = dict(edge)+ for key in ("source", "target", "sourceNode", "targetNode"):+ value = item.get(key)+ if isinstance(value, str) and value in mapping:+ item[key] = mapping[value]+ normalized_edges.append(item)+ return normalized_nodes, normalized_edges, mapping__all__ = ["slugify_name","node_label_slug","next_available_slug",- "new_workflow_id",+ "canonicalize_node_ids",]diff --git a/server/services/workflow_storage/handlers.py b/server/services/workflow_storage/handlers.pyindex 2838dded..1e2cd77e 100644--- a/server/services/workflow_storage/handlers.py+++ b/server/services/workflow_storage/handlers.py@@ -62,12 +62,20 @@ async def handle_save_workflow(data: Dict[str, Any], websocket: WebSocket) -> Di``updateWorkflow({name})`` -> debounced save) flows through thishandler, so renaming happens here — no dedicated rename endpoint."""- from services.workflow_naming import next_available_slug+ from services.workflow_naming import canonicalize_node_ids, next_available_slugdatabase = container.database()- workflow_id = data["workflow_id"]+ requested_id = str(data.get("workflow_id") or "").strip()+ is_new_marker = requested_id.lower() in {"", "new"}+ existing = await database.get_workflow(requested_id) if requested_id and not is_new_marker else None+ if is_new_marker:+ workflow_id = await database.allocate_workflow_id()+ elif existing is None:+ return {"success": False, "error": "workflow_not_found"}+ else:+ workflow_id = requested_idname = data["name"]- existing = await database.get_workflow(workflow_id)+ storage_id = existing.id if existing is not None else workflow_idif existing and existing.name == name and existing.slug:slug = existing.slug@@ -80,9 +88,16 @@ async def handle_save_workflow(data: Dict[str, Any], websocket: WebSocket) -> Dinodes, edges, _, migration_warnings = normalize_legacy_android_toolkit(workflow_data.get("nodes") or [], workflow_data.get("edges") or [])+ # New workflows use canonical IDs from their first persistence boundary.+ # Existing legacy workflows are deliberately left byte-for-byte compatible;+ # there is no startup or save-time migration.+ if is_new_marker:+ nodes, edges, node_id_aliases = canonicalize_node_ids(workflow_id, nodes, edges)+ else:+ node_id_aliases = {}normalized_data = {**workflow_data, "nodes": nodes, "edges": edges}success = await database.save_workflow(- workflow_id=workflow_id,+ workflow_id=storage_id,name=name,slug=slug,data=normalized_data,@@ -98,6 +113,7 @@ async def handle_save_workflow(data: Dict[str, Any], websocket: WebSocket) -> Di"name": name,"slug": slug,"migration_warnings": migration_warnings,+ "node_id_aliases": node_id_aliases,}diff --git a/server/tests/services/test_identity_allocation.py b/server/tests/services/test_identity_allocation.pynew file mode 100644index 00000000..be1052d0--- /dev/null+++ b/server/tests/services/test_identity_allocation.py@@ -0,0 +1,60 @@+import asyncio+import importlib.util+import sys+import uuid+from pathlib import Path+from types import SimpleNamespace++import pytest++from services.workflow_naming import canonicalize_node_ids+++def _load_database(db_path: Path):+ module_name = f"tests._identity_database_{uuid.uuid4().hex}"+ spec = importlib.util.spec_from_file_location(+ module_name, Path(__file__).resolve().parents[2] / "core" / "database.py"+ )+ assert spec and spec.loader+ module = importlib.util.module_from_spec(spec)+ sys.modules[module_name] = module+ spec.loader.exec_module(module)+ return module.Database(SimpleNamespace(+ database_url=f"sqlite+aiosqlite:///{db_path.as_posix()}",+ database_echo=False, database_pool_size=5, database_max_overflow=5,+ ))+++def test_node_ids_are_plugin_derived_repeatable_and_idempotent():+ nodes = [+ {"id": "old-a", "type": "aiAgent"},+ {"id": "old-b", "type": "aiAgent"},+ {"id": "old-start", "type": "start"},+ ]+ edges = [{"id": "edge", "source": "old-start", "target": "old-a"}]+ migrated_nodes, migrated_edges, aliases = canonicalize_node_ids("7", nodes, edges)+ assert [node["id"] for node in migrated_nodes] == [+ "7:aiAgent:1", "7:aiAgent:2", "7:start:1",+ ]+ assert migrated_edges[0]["source"] == "7:start:1"+ assert migrated_edges[0]["target"] == "7:aiAgent:1"+ assert canonicalize_node_ids("7", migrated_nodes, migrated_edges)[2] == {}+ assert aliases["old-b"] == "7:aiAgent:2"+++async def test_allocators_are_atomic_and_execution_ids_are_workflow_scoped():+ path = Path.cwd() / f".identity-{uuid.uuid4().hex}.db"+ database = _load_database(path)+ await database.startup()+ try:+ allocated = await asyncio.gather(*(database.allocate_workflow_id() for _ in range(12)))+ assert sorted(map(int, allocated)) == list(range(1, 13))+ executions = await asyncio.gather(*(database.allocate_execution_id("3") for _ in range(4)))+ assert sorted(executions) == [+ "3:execution:1", "3:execution:2", "3:execution:3", "3:execution:4",+ ]+ finally:+ await database.shutdown()+ for candidate in (path, Path(f"{path}-wal"), Path(f"{path}-shm")):+ candidate.unlink(missing_ok=True)diff --git a/server/tests/services/test_workflow_control.py b/server/tests/services/test_workflow_control.pyindex 79f5bf78..5881cb0b 100644--- a/server/tests/services/test_workflow_control.py+++ b/server/tests/services/test_workflow_control.py@@ -9,6 +9,7 @@ import pytestfrom sqlalchemy.exc import IntegrityErrorfrom services.deployment.control import WorkflowControlService, serialize_control+from services.deployment.runtime_state import archive_and_reset_node_state@pytest.fixture@@ -69,6 +70,11 @@ async def test_generation_atomically_creates_and_archives_isolated_data_scope(coassert scope.execution_id == control.execution_idassert scope.source_session_id == "browser-session"assert scope.node_data["agent-1"]["data"]["label"] == "Researcher"+ assert scope.runtime_data["nodes"]["agent-1"] == {+ "type": "aiAgent",+ "canvas_data": {"label": "Researcher"},+ "parameters": {},+ }assert scope.status == "active"await control_database.update_workflow_run_data_scope(@@ -100,6 +106,44 @@ async def test_generation_atomically_creates_and_archives_isolated_data_scope(coassert [item["formatted"] for item in current_logs] == ["new"]+async def test_reset_archives_every_node_then_calls_plugin_lifecycle(monkeypatch):+ database = AsyncMock()+ database.get_node_parameters.side_effect = [+ {"configured": True},+ ]+ database.get_workflow_run_data_scope.return_value = SimpleNamespace(+ runtime_data={"existing": True},+ )+ broadcaster = SimpleNamespace(+ broadcast_node_parameters_updated=AsyncMock(),+ )+ lifecycle = AsyncMock(return_value={+ "reset": True, "parameters": {"configured": True, "runtime": "empty"},+ })+ node_class = SimpleNamespace(reset_execution_state=lifecycle)+ monkeypatch.setattr("services.node_registry.get_node_class", lambda _node_type: node_class)+ control = SimpleNamespace(+ workflow_id="wf",+ execution_id="execution-1",+ data_scope_id="scope-1",+ graph_snapshot={+ "nodes": [+ {"id": "stateful-1", "type": "statefulPlugin", "data": {"label": "Node"}},+ ],+ "edges": [],+ },+ )++ result = await archive_and_reset_node_state(control, database, broadcaster)++ assert result == {"archived_nodes": 1, "reset_nodes": ["stateful-1"]}+ archived = database.update_workflow_run_data_scope.await_args.kwargs["runtime_data"]+ assert archived["nodes"]["stateful-1"]["parameters"] == {"configured": True}+ lifecycle.assert_awaited_once()+ broadcaster.broadcast_node_parameters_updated.assert_awaited_once()++@pytest.mark.asyncioasync def test_concurrent_insert_rereads_idempotent_winner():db = AsyncMock()diff --git a/server/tests/services/test_workflow_naming.py b/server/tests/services/test_workflow_naming.pyindex a41ade0c..0aee8408 100644--- a/server/tests/services/test_workflow_naming.py+++ b/server/tests/services/test_workflow_naming.py@@ -15,7 +15,6 @@ from typing import List, Tupleimport pytestfrom services.workflow_naming import (- new_workflow_id,next_available_slug,slugify_name,)@@ -166,28 +165,3 @@ async def test_next_available_slug_empty_name_uses_fallback_base() -> None:async def test_next_available_slug_special_chars_in_name() -> None:db = _fake_db([])assert await next_available_slug("Test/Workflow:Beta!", db) == "Test_Workflow_Beta_1"---# ----------------------------------------------------------------------------# new_workflow_id — UUID shape-# ------------------------------------------------------------------------------def test_new_workflow_id_is_32_hex_chars() -> None:- wid = new_workflow_id()- assert len(wid) == 32- assert all(c in "0123456789abcdef" for c in wid)---def test_new_workflow_id_is_unique() -> None:- ids = {new_workflow_id() for _ in range(1000)}- assert len(ids) == 1000---def test_new_workflow_id_no_prefix() -> None:- # Wave 14 dropped the per-site prefixes (wf_, workflow-, example_).- wid = new_workflow_id()- assert not wid.startswith("wf_")- assert not wid.startswith("workflow-")- assert not wid.startswith("example_")- assert "-" not in wid # bare hex, no separators