Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(workflows): add Jev flow optimizer

Rahman769fe495f7ff
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
index 57bf713b..56cbb451 100644
--- a/app/api/v1/workflows/route.ts
+++ b/app/api/v1/workflows/route.ts
@@ -24,6 +24,8 @@ import { resolveProjectHint } from "@/lib/host/projects-api";
import { listAutomationScripts, readAutomationScript } from "@/lib/orchestration/repo-memory-artifacts";
import { listLearnedRecipes, recipeMaturity } from "@/lib/workflow";
import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";
+import { optimizeWorkflowGraph } from "@/lib/workflow/graph-optimizer";
+import { createJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-optimizer";
export const runtime="nodejs";export const dynamic="force-dynamic";const headers={"Cache-Control":"no-store, private"};
const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceof Error?error.message.slice(0,500):String(error).slice(0,500)||"workflow request failed"},{status,headers});
async function auth(minimum:"viewer"|"operator"|"owner"="viewer"){const context=await getSessionContext();if(!context?.session.device_id||!roleAtLeast(context.role,minimum))return null;return{context,principal:`web:${context.session.device_id}`};}
@@ -60,6 +62,23 @@ export async function POST(req:NextRequest){const session=await auth("operator")
if(action==="restore_version"){const id=String(body.graph_id??""),snapshot=await readWorkflowGraphVersion(workflowGraphOwner(session.principal),id,String(body.revision??""));if(!snapshot)throw new Error("workflow version not found");return NextResponse.json({graph:await updateWorkflowGraph(session.principal,id,String(body.expected_revision??""),definition(snapshot.graph),"restore",{remember:true})},{headers});}
if(action==="variable_set"||action==="variable_delete"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);return NextResponse.json(action==="variable_set"?await setWorkflowVariable(session.principal,String(body.key??""),body.value,body.secret===true):await deleteWorkflowVariable(session.principal,String(body.key??"")),{headers});}
if(action==="ai_suggest"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);return NextResponse.json({definition:await suggestWorkflowGraph(String(body.prompt??""))},{headers});}
+ if(action==="optimize_preview"||action==="optimize_clone"){
+ const graph=await getWorkflowGraph(session.principal,String(body.graph_id??""));if(!graph)throw new Error("workflow graph not found");
+ if(action==="optimize_clone"&&String(body.expected_revision??"")!==graph.revision)throw new Error("workflow graph revision changed; refresh before optimizing");
+ const mode=body.mode==="jev"?"jev" as const:"deterministic" as const;let evaluator;
+ if(mode==="jev"){
+ if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);
+ const jev=body.jev;if(!jev||typeof jev!=="object"||Array.isArray(jev))throw new Error("jev connection reference is required");
+ const ref=jev as Record<string,unknown>;if(typeof ref.user!=="string"||typeof ref.connection!=="string")throw new Error("jev user and connection are required");
+ evaluator=createJevWorkflowOptimizerEvaluator({user:ref.user,connection:ref.connection,...(typeof ref.tool==="string"?{tool:ref.tool}:{}),...(typeof ref.model==="string"?{model:ref.model}:{})});
+ }
+ const optimized=await optimizeWorkflowGraph(graph,{mode,threshold:Number(body.threshold)||undefined,applyReview:body.apply_review===true,evaluator,resolveTool:name=>TOOLS_BY_NAME.get(name)});
+ if(action==="optimize_preview")return NextResponse.json({optimization:optimized.preview},{headers});
+ if(optimized.preview.summary.selectedCount<1)throw new Error("no optimization candidate selected; analyze first or enable review transformations");
+ const next=optimized.definition as Record<string,unknown>,meta=next.metadata&&typeof next.metadata==="object"&&!Array.isArray(next.metadata)?next.metadata as Record<string,unknown>:{},tags=Array.isArray(meta.tags)?meta.tags.filter((value):value is string=>typeof value==="string"):[];
+ next.name=typeof body.name==="string"&&body.name.trim()?body.name.trim().slice(0,160):`${graph.name} · Optimized`.slice(0,160);next.status="draft";next.metadata={...meta,provenance:"ai-assisted",fingerprint:undefined,tags:[...new Set([...tags,"optimized",optimized.preview.provider==="jev"?"jev":"deterministic"])].slice(0,32)};
+ return NextResponse.json({graph:await createWorkflowGraph(session.principal,next,"create",{remember:true}),optimization:optimized.preview},{headers});
+ }
if(action==="data_table_create")return NextResponse.json({table:await createWorkflowDataTable(session.principal,body.name,body.columns)},{headers});
if(action==="data_table_delete")return NextResponse.json(await deleteWorkflowDataTable(session.principal,body.table_id),{headers});
if(action==="data_table_row_upsert")return NextResponse.json({row:await upsertWorkflowDataTableRow(session.principal,body.table_id,body.row_id,body.values)},{headers});
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index 07d9ae55..4d0fbfe3 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -218,8 +218,11 @@ mso integrations execute '{"user":"rahman","provider":"dokploy","connection":"pr
source-aware setup instructions. `integration_manage` performs confirmed user,
connection, folder-binding, credential-deletion or hosted-authorization actions.
`integration_execute` takes explicit user/provider/connection and returns a route,
-verifies that connection, performs supported bounded direct operations, or executes
-a toolkit-matching Composio tool using its exact connected account.
+verifies that connection, performs supported bounded direct operations, executes
+a toolkit-matching Composio tool using its exact connected account, or calls one exact
+tool on a named direct `mcp` connection through `mcp.tool`. `mcp.tools.list` exposes the
+downstream tool catalog after the connection allowlist is applied. The bearer credential
+is resolved inside the transport and never appears in model/tool arguments.
`integration_setup_open` requires `user`, `provider` and `connection`; optional `method`
must match the connection. Its private grant exists only in result `_meta` for the UI.
@@ -241,6 +244,8 @@ This release does **not** add every service's entire API or replace provider-own
OAuth clients. Explicit direct execution covers Dokploy project listing/ensure,
Cloudflare zone listing/DNS upsert, and Hostinger DNS upsert. Composio tool execution
is generic but restricted to the selected toolkit, active account and exec permission.
+Named direct MCP execution is likewise restricted to the selected endpoint/token and its
+optional exact `allowedTools` list; it is not an arbitrary URL/request escape hatch.
## Existing-data migration and concurrency
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index d767e2bc..6a3d2df9 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -213,10 +213,31 @@ MSO deliberately keeps this capability behind one compact MCP tool to preserve t
Actions:
-`list`, `search`, `get`, `create`, `update`, `delete`, `clone`, `run`, `status`, `runs`, `stop`, `retry`, `run_delete`, `versions`, `restore`, `catalog`, `scripts`, `templates`, `create_from_template`, `variables`, `variable_set`, `variable_delete`, `data_tables`, `data_table_get`, `data_table_create`, `data_table_delete`, `data_table_row_upsert`, `data_table_row_delete`. `list` and `search` accept the same workflow query/filter semantics used by the UI; `scripts` returns safe RASMIC manifest summaries for an exact project without exposing raw script files or credentials.
+`list`, `search`, `get`, `create`, `update`, `delete`, `clone`, `optimize_preview`, `optimize_clone`, `run`, `status`, `runs`, `stop`, `retry`, `run_delete`, `versions`, `restore`, `catalog`, `scripts`, `templates`, `create_from_template`, `variables`, `variable_set`, `variable_delete`, `data_tables`, `data_table_get`, `data_table_create`, `data_table_delete`, `data_table_row_upsert`, `data_table_row_delete`. `list` and `search` accept the same workflow query/filter semantics used by the UI; `scripts` returns safe RASMIC manifest summaries for an exact project without exposing raw script files or credentials.
The linear `flow_catalog`, `flow_manage`, `flow_run` and `flow_status` tools remain compatible for small deterministic project-owned sequences.
+## Flow Optimizer
+
+Flow Optimizer is a review-first compiler pass over an existing Workflow Graph. It does not replace the graph engine, planner, capability catalog, permissions or confirmation policy.
+
+`optimize_preview` analyzes an exact saved graph revision and returns bounded candidate transformations, per-candidate probability, risk class, before/after counts and whether deterministic fallback was used. It never mutates the graph. `optimize_clone` repeats the analysis against the exact current revision and creates a new **draft** graph; the source graph is never overwritten.
+
+Two candidate classes exist in v1:
+
+- **Safe / presentation-only** — consecutive action/context nodes may be wrapped in a collapsed `metadata.customNodes` group. Original executable nodes, edges, arguments and run receipts stay unchanged.
+- **Review / structural** — three or more consecutive calls to the same read-only MSO tool may be compacted into one sequential `loop` node containing the exact already-prepared argument objects. This changes the output shape and therefore requires `apply_review=true`. Write/exec tools are not eligible.
+
+Decision modes:
+
+- `deterministic` is always available and uses local policy scores.
+- `jev` sends only the compact workflow summary plus host-generated candidate descriptions to a named generic MCP Integration. The graph arguments themselves, credentials and capability authority stay in MSO. Jev can score the candidates; it cannot invent a new tool call, alter arguments, authorize an action, or execute anything. The preview also computes a deterministic shadow baseline and reports agreement/disagreement so rollout can be measured before relying more heavily on Jev.
+- If the Jev call fails or returns no usable probability, the preview records `provider: fallback` and uses the deterministic scores.
+
+For Jev, create a normal **Integrations → Project MCP** named connection to the reviewed Jev MCP endpoint, keep the bearer key in the private Integrations form, and optionally pin `allowedTools` to the exact decision tool (for example `jev_decide`). The workflow stores only the non-secret Integration user/connection reference supplied at optimization time.
+
+The native Workflows UI exposes **Optimize** and a Flow Optimizer detail panel. Dirty graph edits are saved before opening the optimizer so preview/clone always operate on the revision the user can see.
+
## Automatic learning
`workflow_start` still checks reusable automation before performing exploratory work. Successful `workflow_finish` learns a sanitized route, updates private procedural memory and creates/deduplicates a private draft graph candidate. Learned workflows never auto-activate or bypass normal scope/authz checks.
diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsx
index 9fd95e4c..d49afb70 100644
--- a/frontend/slices/workflows/app.tsx
+++ b/frontend/slices/workflows/app.tsx
@@ -2,7 +2,7 @@
import { pruneGraphCustomNodes } from "@/lib/contracts/graph-custom-nodes";
import { useEffect, useMemo, useState } from "react";
-import { Activity, Copy, Download, PanelLeft, PanelRight, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
+import { Activity, Copy, Download, PanelLeft, PanelRight, Play, RefreshCw, Save, Sparkles, Trash2, Workflow } from "lucide-react";
import type { AppProps, ToolbarItem } from "@/features/appshell";
import type { SessionGraphView } from "@/lib/contracts/session-monitor";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
@@ -70,6 +70,7 @@ export default function WorkflowsApp(props: AppProps) {
const exportCurrent = () => { if (!graph) return; const blob = new Blob([JSON.stringify(buildWorkflowPackage(graph), null, 2)], { type: "application/json" }); saveAs(URL.createObjectURL(blob), workflowPackageFilename(graph.name)); setMessage("Exported portable workflow package"); };
const remove = () => graph && wrap(async () => { await deleteGraph(graph); setSelected(null); setRun(null); const list = await listGraphs(); setGraphs(list); setGraph(list[0] ? await getGraph(list[0].id) : null); setDirty(false); });
const execute = () => graph && wrap(async () => { const saved = await saveCurrent(); setRun(await runGraph(saved.id)); setPanel("run"); if (overlayPane) setDetailsOpen(true); });
+ const openOptimizer = () => graph && wrap(async () => { await saveCurrent(); setPanel("optimizer"); if (overlayPane) setDetailsOpen(true); else setShowDetails(true); });
const updateNode = (next: WorkflowGraphNode) => graph && mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === next.id ? next : item) });
const deleteNodes = (ids: string[]) => { if (!graph || !ids.length) return; const removed = new Set(ids); mutate({ ...graph, nodes: graph.nodes.filter((item) => !removed.has(item.id)), edges: graph.edges.filter((edge) => !removed.has(edge.source) && !removed.has(edge.target)), metadata: { ...graph.metadata, ...(graph.metadata.customNodes ? { customNodes: pruneGraphCustomNodes(graph.metadata.customNodes, new Set(graph.nodes.filter((n) => !removed.has(n.id)).map((n) => n.id))) } : {}) } }); if (selected && removed.has(selected)) setSelected(null); };
const deleteEdges = (ids: string[]) => { if (!graph || !ids.length) return; const removed = new Set(ids); mutate({ ...graph, edges: graph.edges.filter((edge) => !removed.has(edge.id)) }); };
@@ -101,13 +102,14 @@ export default function WorkflowsApp(props: AppProps) {
const automationLibrary = <WorkflowLibrary graphs={graphs} activeId={graph?.id} search={search} onSearch={setSearch} onSelect={(id) => void wrap(() => selectGraph(id))} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }} onImport={async (definition) => { await createImported(definition); }}/>;
const library = <div className="flex h-full min-h-0 flex-col"><div className="grid grid-cols-2 gap-1 border-b p-2">{(["automations", "sessions"] as const).map((mode) => <button key={mode} type="button" className={`rounded-md px-2 py-1.5 text-xs capitalize ${libraryMode === mode ? "bg-accent font-semibold" : "text-muted-foreground hover:bg-accent/60"}`} onClick={() => setLibraryMode(mode)}>{mode}</button>)}</div><div className="min-h-0 flex-1">{libraryMode === "automations" ? automationLibrary : <WorkflowSessionLibrary activeId={sessionView?.session.id} onSelect={(id) => void wrap(() => selectSession(id))}/>}</div></div>;
- const details = libraryMode === "sessions" && sessionView ? <WorkflowSessionDetails view={sessionView} node={sessionNode} onOpenTerminal={openSessionTerminal} onOpenCode={openSessionCode} onSaveDraft={saveSessionDraft} savingDraft={busy} learning={learning}/> : graph ? <WorkflowDetails graph={graph} graphs={graphs} node={node} run={run} panel={panel} onPanel={setPanel} onNode={updateNode} onDeleteNode={(id) => deleteNodes([id])} onGraph={mutate} onRunSelect={(selectedRun) => { setRun(selectedRun); setPanel("run"); }} onRestored={(next) => { setGraph(next); setDirty(false); void listGraphs().then(setGraphs); }}/> : null;
+ const details = libraryMode === "sessions" && sessionView ? <WorkflowSessionDetails view={sessionView} node={sessionNode} onOpenTerminal={openSessionTerminal} onOpenCode={openSessionCode} onSaveDraft={saveSessionDraft} savingDraft={busy} learning={learning}/> : graph ? <WorkflowDetails graph={graph} graphs={graphs} node={node} run={run} panel={panel} onPanel={(next) => next === "optimizer" && dirty ? void openOptimizer() : setPanel(next)} onNode={updateNode} onDeleteNode={(id) => deleteNodes([id])} onGraph={mutate} onRunSelect={(selectedRun) => { setRun(selectedRun); setPanel("run"); }} onRestored={(next) => { setGraph(next); setDirty(false); void listGraphs().then(setGraphs); }} onOptimizerCloned={(next) => { setGraph(next); setSelected(null); setRun(null); setDirty(false); setPanel("optimizer"); void listGraphs(true).then(setGraphs); }}/> : null;
const toolbarItems: ToolbarItem[] = [
{ id: "library", label: "Workflow library", icon: PanelLeft, onClick: toggleLibrary, primary: true },
{ id: "refresh", label: "Refresh", icon: RefreshCw, onClick: () => void wrap(async () => { if (libraryMode === "sessions") await refreshSession(); else await load(undefined, true); }), disabled: busy },
...(libraryMode === "automations" && graph ? [
{ id: "duplicate", label: "Duplicate", icon: Copy, onClick: () => void duplicate(), disabled: busy },
{ id: "export", label: "Export", icon: Download, onClick: exportCurrent, disabled: busy },
+ { id: "optimize", label: "Optimize", icon: Sparkles, onClick: () => void openOptimizer(), disabled: busy },
{ id: "save", label: "Save", icon: Save, onClick: () => void save(), disabled: busy || !dirty, primary: true },
{ id: "run", label: "Run", icon: Play, onClick: () => void execute(), disabled: busy, primary: true },
{ id: "details", label: "Details", icon: PanelRight, onClick: toggleDetails },
diff --git a/frontend/slices/workflows/components/workflow-details.tsx b/frontend/slices/workflows/components/workflow-details.tsx
index c55933b0..9a91adf4 100644
--- a/frontend/slices/workflows/components/workflow-details.tsx
+++ b/frontend/slices/workflows/components/workflow-details.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Activity, BookOpen, Braces, Clock3, Database, History, SlidersHorizontal } from "lucide-react";
+import { Activity, BookOpen, Braces, Clock3, Database, History, SlidersHorizontal, Sparkles } from "lucide-react";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
import { ScrollArea } from "@/components/ui/scroll-area";
import { WorkflowInspector } from "./workflow-inspector";
@@ -10,11 +10,13 @@ import { WorkflowVariablePanel } from "./workflow-variable-panel";
import { WorkflowVersionPanel } from "./workflow-version-panel";
import { WorkflowDirectoryPanel } from "./workflow-directory-panel";
import { WorkflowDataTablePanel } from "./workflow-data-table-panel";
+import { WorkflowOptimizerPanel } from "./workflow-optimizer-panel";
-export type WorkflowPanel = "inspector" | "run" | "history" | "versions" | "variables" | "data" | "directory";
+export type WorkflowPanel = "inspector" | "optimizer" | "run" | "history" | "versions" | "variables" | "data" | "directory";
const PANELS = [
["inspector", "Builder", SlidersHorizontal],
+ ["optimizer", "Flow optimizer", Sparkles],
["run", "Current run", Activity],
["history", "Executions", History],
["versions", "Versions", Clock3],
@@ -23,7 +25,7 @@ const PANELS = [
["directory", "Directory", BookOpen],
] as const satisfies ReadonlyArray<readonly [WorkflowPanel, string, typeof SlidersHorizontal]>;
-export function WorkflowDetails({ graph, graphs, node, run, panel, onPanel, onNode, onDeleteNode, onGraph, onRunSelect, onRestored }: {
+export function WorkflowDetails({ graph, graphs, node, run, panel, onPanel, onNode, onDeleteNode, onGraph, onRunSelect, onRestored, onOptimizerCloned }: {
graph: WorkflowGraph;
graphs: WorkflowGraph[];
node: WorkflowGraphNode | null;
@@ -35,6 +37,7 @@ export function WorkflowDetails({ graph, graphs, node, run, panel, onPanel, onNo
onGraph: (graph: WorkflowGraph) => void;
onRunSelect: (run: WorkflowGraphRun) => void;
onRestored: (graph: WorkflowGraph) => void;
+ onOptimizerCloned: (graph: WorkflowGraph) => void;
}) {
return <div className="flex h-full min-h-0 bg-card/20">
<nav aria-label="Workflow details" className="flex w-11 shrink-0 flex-col items-center gap-1 border-r bg-card/30 p-1.5">
@@ -50,6 +53,7 @@ export function WorkflowDetails({ graph, graphs, node, run, panel, onPanel, onNo
</nav>
<div className="min-h-0 min-w-0 flex-1">
{panel === "inspector" ? <ScrollArea className="h-full"><WorkflowInspector key={node?.id ?? `graph-${graph.id}`} graph={graph} graphs={graphs} node={node} onNode={onNode} onDeleteNode={onDeleteNode} onGraph={onGraph}/></ScrollArea> : null}
+ {panel === "optimizer" ? <WorkflowOptimizerPanel graph={graph} onCloned={onOptimizerCloned}/> : null}
{panel === "run" ? <WorkflowRunPanel run={run}/> : null}
{panel === "history" ? <WorkflowRunHistory graph={graph} onSelect={onRunSelect}/> : null}
{panel === "versions" ? <WorkflowVersionPanel graph={graph} onRestored={onRestored}/> : null}
diff --git a/frontend/slices/workflows/components/workflow-optimizer-panel.tsx b/frontend/slices/workflows/components/workflow-optimizer-panel.tsx
new file mode 100644
index 00000000..890da885
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-optimizer-panel.tsx
@@ -0,0 +1,104 @@
+"use client";
+
+import { useState } from "react";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import type { WorkflowOptimizationPreview } from "@/lib/workflow/graph-optimizer";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { optimizeGraphClone, optimizeGraphPreview, type WorkflowOptimizeOptions } from "../lib/api";
+
+const inputClass = "h-8 text-xs";
+
+export function WorkflowOptimizerPanel({ graph, onCloned }: {
+ graph: WorkflowGraph;
+ onCloned: (graph: WorkflowGraph) => void;
+}) {
+ const [mode, setMode] = useState<"deterministic" | "jev">("deterministic");
+ const [user, setUser] = useState("");
+ const [connection, setConnection] = useState("");
+ const [applyReview, setApplyReview] = useState(false);
+ const [preview, setPreview] = useState<WorkflowOptimizationPreview | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [message, setMessage] = useState("");
+
+ const options = (): WorkflowOptimizeOptions => ({
+ mode,
+ applyReview,
+ ...(mode === "jev" ? { jev: { user: user.trim(), connection: connection.trim() } } : {}),
+ });
+
+ const valid = mode === "deterministic" || Boolean(user.trim() && connection.trim());
+ const analyze = async () => {
+ setBusy(true); setMessage("");
+ try { setPreview(await optimizeGraphPreview(graph, options())); }
+ catch (error) { setMessage(error instanceof Error ? error.message : "Optimization failed"); }
+ finally { setBusy(false); }
+ };
+ const createDraft = async () => {
+ setBusy(true); setMessage("");
+ try {
+ const result = await optimizeGraphClone(graph, options());
+ setPreview(result.optimization);
+ onCloned(result.graph);
+ } catch (error) { setMessage(error instanceof Error ? error.message : "Could not create optimized draft"); }
+ finally { setBusy(false); }
+ };
+
+ return <div className="flex h-full min-h-0 flex-col overflow-y-auto p-3 text-sm">
+ <div className="space-y-1">
+ <div className="font-semibold">Flow Optimizer</div>
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ Analyze first. The source workflow is never overwritten; Apply creates a new draft.
+ </p>
+ </div>
+
+ <div className="mt-4 space-y-3 rounded-lg border bg-card/40 p-3">
+ <label className="grid gap-1 text-xs font-medium">
+ Decision mode
+ <select className="h-8 rounded-md border bg-background px-2 text-xs" value={mode} onChange={(event) => { setMode(event.target.value as "deterministic" | "jev"); setPreview(null); }}>
+ <option value="deterministic">MSO deterministic</option>
+ <option value="jev">Jev decision kernel</option>
+ </select>
+ </label>
+ {mode === "jev" ? <div className="grid gap-2">
+ <p className="text-[11px] leading-relaxed text-muted-foreground">Use a named Integrations → Project MCP connection. Endpoint/token remain in Integrations and never enter the workflow graph.</p>
+ <Input className={inputClass} value={user} onChange={(event) => setUser(event.target.value)} placeholder="Credential user ID"/>
+ <Input className={inputClass} value={connection} onChange={(event) => setConnection(event.target.value)} placeholder="MCP connection ID, e.g. jev"/>
+ </div> : null}
+ <label className="flex items-start gap-2 text-xs">
+ <input className="mt-0.5" type="checkbox" checked={applyReview} onChange={(event) => { setApplyReview(event.target.checked); setPreview(null); }}/>
+ <span><b>Include review transformations</b><span className="mt-0.5 block font-normal text-muted-foreground">Allows structural compaction such as repeated read-only calls → one sequential Loop node. Safe presentation-only groups do not need this.</span></span>
+ </label>
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" variant="outline" disabled={busy || !valid} onClick={() => void analyze()}>{busy ? "Analyzing…" : "Analyze"}</Button>
+ <Button size="sm" disabled={busy || !valid} onClick={() => void createDraft()}>Create optimized draft</Button>
+ </div>
+ {message ? <p className="text-xs text-destructive">{message}</p> : null}
+ </div>
+
+ {preview ? <div className="mt-4 space-y-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <Badge variant="outline">{preview.provider}</Badge>
+ <Badge variant="outline">{preview.summary.selectedCount}/{preview.summary.candidateCount} selected</Badge>
+ <Badge variant="outline">{preview.summary.nodeReduction} node reduction</Badge>
+ </div>
+ {preview.fallbackReason ? <div className="rounded-md border border-dashed p-2 text-xs text-muted-foreground">Jev unavailable; deterministic fallback used: {preview.fallbackReason}</div> : null}
+ {preview.shadow ? <div className="rounded-md border border-dashed p-2 text-xs text-muted-foreground">Shadow agreement vs deterministic baseline: <b className="text-foreground">{Math.round(preview.shadow.agreement * 100)}%</b>{preview.shadow.disagreements.length ? ` · disagreements: ${preview.shadow.disagreements.join(", ")}` : " · no decision disagreement"}</div> : null}
+ <div className="grid grid-cols-2 gap-2 text-xs">
+ <div className="rounded-md border p-2"><div className="text-muted-foreground">Nodes</div><div className="mt-1 font-medium">{preview.summary.beforeNodes} → {preview.summary.afterNodes}</div></div>
+ <div className="rounded-md border p-2"><div className="text-muted-foreground">Visual groups</div><div className="mt-1 font-medium">+{preview.summary.visualGroupsAdded}</div></div>
+ </div>
+ <div className="space-y-2">
+ {preview.candidates.length ? preview.candidates.map((candidate) => <div key={candidate.id} className="rounded-md border p-2">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0 font-medium">{candidate.title}</div>
+ <div className="flex shrink-0 gap-1"><Badge variant="outline">{candidate.risk}</Badge>{candidate.probability !== undefined ? <Badge variant="outline">{Math.round(candidate.probability * 100)}%</Badge> : null}</div>
+ </div>
+ <p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">{candidate.description}</p>
+ <p className="mt-1 text-[11px]">{candidate.selected ? "Selected" : candidate.reason ?? "Not selected"}</p>
+ </div>) : <p className="text-xs text-muted-foreground">No safe compaction candidate found for this graph.</p>}
+ </div>
+ </div> : null}
+ </div>;
+}
diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.ts
index b66ce785..3259f62e 100644
--- a/frontend/slices/workflows/lib/api.ts
+++ b/frontend/slices/workflows/lib/api.ts
@@ -1,6 +1,7 @@
import type { SessionGraphView, SessionPage } from "@/lib/contracts/session-monitor";
import type { WorkflowGraph, WorkflowGraphRun, WorkflowGraphStatus } from "@/lib/contracts/workflow-graph";
import type { WorkflowNodeCatalogItem } from "@/lib/workflow/node-catalog";
+import type { WorkflowOptimizationPreview } from "@/lib/workflow/graph-optimizer";
import { cachedWorkflowResource, invalidateWorkflowResources, seedWorkflowResource } from "./resource-cache";
async function json<T>(input:RequestInfo,init?:RequestInit):Promise<T>{const response=await fetch(input,{...init,cache:"no-store",headers:{"Content-Type":"application/json",...(init?.headers??{})}}),body=await response.json().catch(()=>({}));if(!response.ok)throw new Error(typeof body.error==="string"?body.error:`request failed (${response.status})`);return body as T;}
const post=<T>(body:Record<string,unknown>)=>json<T>("/api/v1/workflows",{method:"POST",body:JSON.stringify(body)});
@@ -34,6 +35,9 @@ export async function deleteDataTable(id:string){return post<{id:string;deleted:
export async function upsertDataTableRow(tableId:string,values:Record<string,unknown>,rowId?:string){return(await post<{row:WorkflowDataTableRow}>({action:"data_table_row_upsert",table_id:tableId,...(rowId?{row_id:rowId}:{}),values})).row;}
export async function deleteDataTableRow(tableId:string,rowId:string){return post<{tableId:string;rowId:string;deleted:boolean}>({action:"data_table_row_delete",table_id:tableId,row_id:rowId});}
export async function aiSuggest(prompt:string){return(await post<{definition:Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">}>({action:"ai_suggest",prompt})).definition;}
+export type WorkflowOptimizeOptions={mode?:"deterministic"|"jev";threshold?:number;applyReview?:boolean;jev?:{user:string;connection:string;tool?:string;model?:string}};
+export async function optimizeGraphPreview(graph:WorkflowGraph,options:WorkflowOptimizeOptions={}){return(await post<{optimization:WorkflowOptimizationPreview}>({action:"optimize_preview",graph_id:graph.id,mode:options.mode??"deterministic",threshold:options.threshold,apply_review:options.applyReview===true,...(options.jev?{jev:options.jev}:{})})).optimization;}
+export async function optimizeGraphClone(graph:WorkflowGraph,options:WorkflowOptimizeOptions={}){const result=await post<{graph:WorkflowGraph;optimization:WorkflowOptimizationPreview}>({action:"optimize_clone",graph_id:graph.id,expected_revision:graph.revision,mode:options.mode??"deterministic",threshold:options.threshold,apply_review:options.applyReview===true,...(options.jev?{jev:options.jev}:{})});invalidateWorkflowResources("graphs");seedWorkflowResource(`graph:${result.graph.id}`,result.graph,8000);return result;}
export async function resolveNode(graphId:string,nodeId:string){return json<{project:string;name:string;path:string;relativePath:string}>(`/api/v1/workflows?graph_id=${encodeURIComponent(graphId)}&node_id=${encodeURIComponent(nodeId)}&resolve=target`);}
export async function listWorkflowSessions(page=1,query=""){const q=new URLSearchParams({view:"monitor",includeOffline:"1",page:String(page)});if(query.trim())q.set("q",query.trim());return json<SessionPage>(`/api/v1/agent-sessions?${q}`);}
diff --git a/lib/infra/connection-dispatch-mcp.test.ts b/lib/infra/connection-dispatch-mcp.test.ts
new file mode 100644
index 00000000..e0a2ba55
--- /dev/null
+++ b/lib/infra/connection-dispatch-mcp.test.ts
@@ -0,0 +1,66 @@
+import { afterAll, beforeAll, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+const callNamedMcpConnectionTool = vi.fn(async (_selection, name, args) => ({ name, args, ok: true }));
+const listNamedMcpConnectionTools = vi.fn(async () => [{ name: "jev_decide", inputSchema: { type: "object", properties: {} } }]);
+vi.mock("./mcp-connection", () => ({ callNamedMcpConnectionTool, listNamedMcpConnectionTools }));
+
+let root = "";
+let executeIntegrationAction: typeof import("./connection-dispatch").executeIntegrationAction;
+
+beforeAll(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-mcp-dispatch-"));
+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");
+ process.env.VITEST = "1";
+
+ const { integrationManage } = await import("./connection-manage");
+ const service = await import("./connection-service");
+ await integrationManage({ action: "user.create", confirm: true, user: "owner" });
+ await integrationManage({ action: "connection.create", confirm: true, user: "owner", provider: "mcp", connection: "jev", source: "direct", authMethod: "direct" });
+ const snapshot = await service.credentialSnapshot("mcp", { user: "owner", connection: "jev" });
+ await service.saveConnectionValues("mcp", { user: "owner", connection: "jev" }, {
+ endpoint: "https://jev.example.test/mcp",
+ accessToken: "synthetic_mcp_token_123456789",
+ allowedTools: "jev_decide",
+ }, snapshot.connection, true);
+ executeIntegrationAction = (await import("./connection-dispatch")).executeIntegrationAction;
+});
+
+afterAll(async () => {
+ delete process.env.OS_INFRA_STORE;
+ delete process.env.VITEST;
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+it("keeps generic MCP connection execution behind confirmation and metadata-only arguments", async () => {
+ await expect(executeIntegrationAction({
+ user: "owner", provider: "mcp", connection: "jev", operation: "mcp.tool",
+ arguments: { name: "jev_decide", arguments: { state: "safe" } },
+ })).rejects.toMatchObject({ code: "confirmation_required" });
+
+ await expect(executeIntegrationAction({
+ user: "owner", provider: "mcp", connection: "jev", operation: "mcp.tool", confirm: true,
+ arguments: { name: "jev_decide", arguments: { token: "must-not-enter-tool-json" } },
+ })).rejects.toMatchObject({ code: "secret_input_forbidden" });
+
+ await expect(executeIntegrationAction({
+ user: "owner", provider: "mcp", connection: "jev", operation: "mcp.tool", confirm: true,
+ arguments: { name: "jev_decide", arguments: { state: { task: "compact" }, questions: {} } },
+ })).resolves.toMatchObject({ result: { name: "jev_decide", ok: true } });
+
+ expect(callNamedMcpConnectionTool).toHaveBeenCalledWith(
+ { user: "owner", connection: "jev" },
+ "jev_decide",
+ { state: { task: "compact" }, questions: {} },
+ );
+});
+
+it("lists tools only through the exact selected MCP connection", async () => {
+ await expect(executeIntegrationAction({
+ user: "owner", provider: "mcp", connection: "jev", operation: "mcp.tools.list", confirm: true, arguments: {},
+ })).resolves.toMatchObject({ result: [{ name: "jev_decide" }] });
+ expect(listNamedMcpConnectionTools).toHaveBeenCalledWith({ user: "owner", connection: "jev" });
+});
diff --git a/lib/infra/connection-dispatch.ts b/lib/infra/connection-dispatch.ts
index 7aad1b77..d95a4b61 100644
--- a/lib/infra/connection-dispatch.ts
+++ b/lib/infra/connection-dispatch.ts
@@ -6,6 +6,7 @@ import { importConvexCliPersonalConnection } from "./convex-cli-import";
import { listConvexCustomDomains, ensureConvexCustomDomain, getConvexCanonicalUrls, setConvexCanonicalUrl, getConvexEnvPresence, deployConvexCloudProject, importConvexCloudSnapshot } from "./convex-cloud";
import { doctorInfraProvider, ensureDokployProject, listDokployApplications, listDokployDeployments, readDokployDeploymentLogs, listDokployGitProviders, listDokployGithubRepositories, ensureDokployGithubApplication, ensureDokployApplicationDomain, recoverDokployPublicGithubToHttpsGit, deployDokployApplication, configureDokployDockerfileBuild, listDokployProjects, listCloudflareZones, upsertCloudflareDns, upsertDokployPublicBuildEnv, upsertHostingerDns, listHostingerMailOrders, getHostingerMailPlan, listHostingerMail, listHostingerMailLogs, mutateHostingerMail } from "./clients";
import { isInfraProviderId } from "./catalog";
+import { callNamedMcpConnectionTool, listNamedMcpConnectionTools } from "./mcp-connection";
export const safeActionInput=(input:Record<string,unknown>)=>Object.fromEntries(Object.entries(input).filter(([key])=>key!=="workflow_id"));
export const selectionFrom=(a:Record<string,unknown>):ConnectionSelector=>({user:typeof a.user==="string"?a.user:undefined,connection:typeof a.connection==="string"?a.connection:undefined,cwd:typeof a.cwd==="string"?a.cwd:undefined});
export async function manageIntegrationAction(raw:Record<string,unknown>){
@@ -65,6 +66,8 @@ export async function executeIntegrationAction(raw:Record<string,unknown>){
"hostinger.mail.list":{provider:"hostinger",fields:["orderId","resource","page"],run:()=>listHostingerMail((args as Record<string,unknown>).orderId,(args as Record<string,unknown>).resource,(args as Record<string,unknown>).page as number)},
"hostinger.mail.logs.list":{provider:"hostinger",fields:["orderId","kind","page"],run:()=>listHostingerMailLogs((args as Record<string,unknown>).orderId,(args as Record<string,unknown>).kind,(args as Record<string,unknown>).page as number)},
"hostinger.mail.mutate":{provider:"hostinger",fields:["orderId","mailboxId","aliasId","forwarderId","autoreplyId","catchallId","localPart","destination","keepCopy","subject","body","displayName","startsAt","endsAt","action"],run:()=>mutateHostingerMail(String((args as Record<string,unknown>).action),args as Record<string,unknown>)},
+ "mcp.tools.list":{provider:"mcp",fields:[],run:()=>listNamedMcpConnectionTools(selection)},
+ "mcp.tool":{provider:"mcp",fields:["name","arguments"],run:()=>callNamedMcpConnectionTool(selection,String((args as Record<string,unknown>).name??""),((args as Record<string,unknown>).arguments&&typeof (args as Record<string,unknown>).arguments==="object"&&!Array.isArray((args as Record<string,unknown>).arguments)?(args as Record<string,unknown>).arguments:{} ) as Record<string,unknown>)},
};
const verb=verbs[operation];if(!verb||verb.provider!==provider)throw new IntegrationError("provider_operation_mismatch");
diff --git a/lib/infra/mcp-connection.test.ts b/lib/infra/mcp-connection.test.ts
new file mode 100644
index 00000000..1b046298
--- /dev/null
+++ b/lib/infra/mcp-connection.test.ts
@@ -0,0 +1,57 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+const call = vi.fn();
+const list = vi.fn();
+vi.mock("@/lib/host/project-mcp-client", () => ({ callMcpServerTool: call, listMcpServerTools: list }));
+
+let root = "";
+let callNamedMcpConnectionTool: typeof import("./mcp-connection").callNamedMcpConnectionTool;
+let listNamedMcpConnectionTools: typeof import("./mcp-connection").listNamedMcpConnectionTools;
+
+beforeAll(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-mcp-connection-"));
+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");
+ process.env.VITEST = "1";
+ const { integrationManage } = await import("./connection-manage");
+ const service = await import("./connection-service");
+ await integrationManage({ action: "user.create", confirm: true, user: "owner" });
+ await integrationManage({ action: "connection.create", confirm: true, user: "owner", provider: "mcp", connection: "jev", source: "direct", authMethod: "direct" });
+ const snapshot = await service.credentialSnapshot("mcp", { user: "owner", connection: "jev" });
+ await service.saveConnectionValues("mcp", { user: "owner", connection: "jev" }, {
+ endpoint: "https://www.jevai.org/api/mcp",
+ accessToken: "opaque-private-token-123456",
+ allowedTools: "jev_decide, jev_route_task",
+ }, snapshot.connection, true);
+ const module = await import("./mcp-connection");
+ callNamedMcpConnectionTool = module.callNamedMcpConnectionTool;
+ listNamedMcpConnectionTools = module.listNamedMcpConnectionTools;
+});
+
+afterAll(async () => {
+ delete process.env.OS_INFRA_STORE;
+ delete process.env.VITEST;
+ await fs.rm(root, { recursive: true, force: true });
+});
+
+describe("named MCP integration execution", () => {
+ it("uses the stored bearer only inside the transport and honors the allowlist", async () => {
+ list.mockResolvedValue([{ name: "jev_decide" }, { name: "jev_route_task" }, { name: "other" }]);
+ call.mockResolvedValue({ structuredContent: { answers: {} } });
+
+ const listed = await listNamedMcpConnectionTools({ user: "owner", connection: "jev" });
+ expect(listed.map((row: { name: string }) => row.name)).toEqual(["jev_decide", "jev_route_task"]);
+
+ await callNamedMcpConnectionTool({ user: "owner", connection: "jev" }, "jev_decide", { state: { task: "route" }, questions: {} });
+ expect(call).toHaveBeenCalledTimes(1);
+ const [server, name] = call.mock.calls[0]!;
+ expect(name).toBe("jev_decide");
+ expect(server.url).toBe("https://www.jevai.org/api/mcp");
+ expect(server.headers.Authorization).toBe("Bearer opaque-private-token-123456");
+
+ await expect(callNamedMcpConnectionTool({ user: "owner", connection: "jev" }, "other", {})).rejects.toMatchObject({ code: "mcp_tool_not_allowed" });
+ });
+});
diff --git a/lib/infra/mcp-connection.ts b/lib/infra/mcp-connection.ts
new file mode 100644
index 00000000..aac5b778
--- /dev/null
+++ b/lib/infra/mcp-connection.ts
@@ -0,0 +1,35 @@
+import { callMcpServerTool, listMcpServerTools } from "@/lib/host/project-mcp-client";
+import type { ProjectMcpServer } from "@/lib/host/project-mcp-config";
+import { IntegrationError, type ConnectionSelector } from "./identity";
+import { normalizeMcpEndpoint, parseMcpToolAllowlist } from "./mcp-policy";
+import { directConnectionValues } from "./connection-service";
+
+function serverFrom(values: Record<string, string>): ProjectMcpServer {
+ if (!values.endpoint || !values.accessToken) throw new IntegrationError("required_fields_missing");
+ return {
+ name: "integration-mcp",
+ transport: "http",
+ url: normalizeMcpEndpoint(values.endpoint),
+ headers: { Authorization: `Bearer ${values.accessToken}` },
+ oauthConfigured: false,
+ };
+}
+
+function allowedTool(values: Record<string, string>, tool: string): void {
+ if (!/^[A-Za-z0-9_.-]{1,128}$/.test(tool)) throw new IntegrationError("invalid_tool_arguments");
+ const allowed = parseMcpToolAllowlist(values.allowedTools);
+ if (allowed && !allowed.includes(tool)) throw new IntegrationError("mcp_tool_not_allowed", 403);
+}
+
+export async function listNamedMcpConnectionTools(selector: ConnectionSelector) {
+ const values = await directConnectionValues("mcp", selector);
+ const tools = await listMcpServerTools(serverFrom(values));
+ const allowed = parseMcpToolAllowlist(values.allowedTools);
+ return allowed ? tools.filter((tool) => allowed.includes(tool.name)) : tools;
+}
+
+export async function callNamedMcpConnectionTool(selector: ConnectionSelector, tool: string, args: Record<string, unknown>) {
+ const values = await directConnectionValues("mcp", selector);
+ allowedTool(values, tool);
+ return callMcpServerTool(serverFrom(values), tool, args);
+}
diff --git a/lib/mcp/tools-flows-optimizer.test.ts b/lib/mcp/tools-flows-optimizer.test.ts
new file mode 100644
index 00000000..0c489c21
--- /dev/null
+++ b/lib/mcp/tools-flows-optimizer.test.ts
@@ -0,0 +1,79 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+
+const f = vi.hoisted(() => ({
+ get: vi.fn(),
+ create: vi.fn(),
+ optimize: vi.fn(),
+}));
+
+vi.mock("@/lib/workflow/graph-store", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/workflow/graph-store")>();
+ return { ...actual, getWorkflowGraph: f.get, createWorkflowGraph: f.create };
+});
+vi.mock("@/lib/workflow/graph-optimizer", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/workflow/graph-optimizer")>();
+ return { ...actual, optimizeWorkflowGraph: f.optimize };
+});
+vi.mock("./tools", () => ({ TOOLS_BY_NAME: new Map() }));
+
+const { FLOW_TOOLS } = await import("./tools-flows");
+const tool = FLOW_TOOLS.find((row) => row.name === "workflow_graph")!;
+
+const graph: WorkflowGraph = {
+ version: 2,
+ id: "graph-1",
+ name: "Source",
+ description: "",
+ status: "draft",
+ inputs: {},
+ nodes: [{ id: "manual", name: "Manual", type: "manual", position: { x: 0, y: 0 }, config: {} }],
+ edges: [],
+ metadata: {},
+ createdAt: "2026-09-24T00:00:00.000Z",
+ updatedAt: "2026-09-24T00:00:00.000Z",
+ revision: "rev-1",
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ f.get.mockResolvedValue(graph);
+ f.optimize.mockResolvedValue({
+ preview: {
+ version: 1,
+ source: { id: graph.id, revision: graph.revision, name: graph.name, nodeCount: 1, edgeCount: 0 },
+ mode: "deterministic",
+ provider: "deterministic",
+ threshold: 0.72,
+ candidates: [{ id: "presentation:1", kind: "presentation-group", title: "Group", description: "safe", nodeIds: ["manual"], risk: "safe", estimatedNodeDelta: 0, hostEligible: true, probability: 0.96, selected: true }],
+ selectedCandidateIds: ["presentation:1"],
+ reviewCandidateIds: [],
+ summary: { candidateCount: 1, selectedCount: 1, reviewCount: 0, beforeNodes: 1, afterNodes: 1, beforeEdges: 0, afterEdges: 0, visualGroupsAdded: 1, nodeReduction: 0, edgeReduction: 0 },
+ },
+ definition: { name: graph.name, description: graph.description, status: graph.status, inputs: {}, nodes: graph.nodes, edges: [], metadata: {} },
+ });
+ f.create.mockImplementation(async (_principal, definition) => ({ ...graph, ...definition, id: "clone-1", revision: "rev-2" }));
+});
+
+describe("workflow_graph optimizer actions", () => {
+ it("previews without creating or updating a graph", async () => {
+ const result = await tool.run({ action: "optimize_preview", id: graph.id }, { actor: "test", scope: "exec" });
+ expect(result).toMatchObject({ optimization: { source: { id: graph.id }, summary: { selectedCount: 1 } } });
+ expect(f.create).not.toHaveBeenCalled();
+ });
+
+ it("creates a new draft from the exact source revision", async () => {
+ const result = await tool.run({ action: "optimize_clone", id: graph.id, data: { revision: "rev-1" } }, { actor: "test", scope: "exec" });
+ expect(result).toMatchObject({ graph: { id: "clone-1", status: "draft" }, optimization: { summary: { selectedCount: 1 } } });
+ expect(f.create).toHaveBeenCalledTimes(1);
+ const definition = f.create.mock.calls[0]?.[1] as Record<string, unknown>;
+ expect(definition.name).toBe("Source · Optimized");
+ expect(definition.metadata).toMatchObject({ provenance: "ai-assisted", tags: ["optimized", "deterministic"] });
+ });
+
+ it("refuses a stale source revision", async () => {
+ await expect(tool.run({ action: "optimize_clone", id: graph.id, data: { revision: "stale" } }, { actor: "test", scope: "exec" }))
+ .rejects.toThrow("revision changed");
+ expect(f.optimize).not.toHaveBeenCalled();
+ });
+});
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
index 00a0d102..a09e2ed6 100644
--- a/lib/mcp/tools-flows.ts
+++ b/lib/mcp/tools-flows.ts
@@ -14,6 +14,8 @@ import { workflowMatchesQuery } from "@/lib/workflow/search";
import { resolveProjectHint } from "@/lib/host/projects-api";
import { listAutomationScripts } from "@/lib/orchestration/repo-memory-artifacts";
import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";
+import { optimizeWorkflowGraph } from "@/lib/workflow/graph-optimizer";
+import { createJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-optimizer";
const project = { type: "string", maxLength: 4096 };
const flow = { type: "string", maxLength: 64 };
@@ -62,8 +64,8 @@ export const FLOW_TOOLS: McpTool[] = [
return manageProjectFlow(catalog.project.path, { action: a.action, id, flow: a.definition, revision: str(a, "revision") });
} },
{ name: "workflow_graph", title: "Workflow Graph", scope: "exec", limit: { key: "workflow.graph", max: 20, windowMs: 60_000 },
- description: "Private workflow graph CRUD/run plus execution controls, history, versions, templates, catalog, variables and data tables. Definitions reject embedded secrets. metadata.customNodes supports named collapsible groups [{id,name,nodeIds,collapsed}]; original nodes/edges and execution stay unchanged. Update with the current revision.",
- chatgptDescription: "CRUD/run workflows; read node logs.",
+ description: "Private workflow graph CRUD/run/optimization plus execution controls, history, versions, templates, catalog, variables and data tables. optimize_preview is read-only; optimize_clone creates a new review-first draft and never overwrites the source. Definitions reject embedded secrets. metadata.customNodes supports named collapsible groups [{id,name,nodeIds,collapsed}]; original nodes/edges and execution stay unchanged. Update with the current revision.",
+ chatgptDescription: "CRUD/run/optimize workflows; preview before creating an optimized draft.",
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, audit: { action: "exec.run", targetArg: "id" },
inputSchema: S({ action: { type: "string", minLength: 1, maxLength: 32 }, id: { type: "string", maxLength: 96 }, data: { type: "object", additionalProperties: true }, wait_ms: { type: "integer", minimum: 0, maximum: 25_000 } }, ["action"]),
run: async (a, context) => {
@@ -90,6 +92,31 @@ export const FLOW_TOOLS: McpTool[] = [
if (action === "create_from_template") { const row = workflowTemplate(String(data.template_id ?? "")); if (!row) throw new Error("workflow template not found"); return { graph: await createWorkflowGraph(principal, row.definition, "template", { remember: true }) }; }
if (action === "create") return { graph: await createWorkflowGraph(principal, data.definition ?? data, "create", { remember: true }) };
const id = str(a, "id");
+ if (action === "optimize_preview" || action === "optimize_clone") {
+ const graph = await getWorkflowGraph(principal, id); if (!graph) throw new Error("workflow graph not found");
+ if (action === "optimize_clone" && String(data.revision ?? "") !== graph.revision) throw new Error("workflow graph revision changed; refresh before optimizing");
+ const mode = data.mode === "jev" ? "jev" as const : "deterministic" as const;
+ let evaluator;
+ if (mode === "jev") {
+ const jev = data.jev;
+ if (!jev || typeof jev !== "object" || Array.isArray(jev)) throw new Error("data.jev with user and connection is required for Jev optimization");
+ const ref = jev as Record<string, unknown>;
+ if (typeof ref.user !== "string" || typeof ref.connection !== "string") throw new Error("Jev optimizer requires integration user and connection");
+ evaluator = createJevWorkflowOptimizerEvaluator({ user: ref.user, connection: ref.connection, ...(typeof ref.tool === "string" ? { tool: ref.tool } : {}), ...(typeof ref.model === "string" ? { model: ref.model } : {}) });
+ }
+ const { TOOLS_BY_NAME } = await import("./tools");
+ const optimized = await optimizeWorkflowGraph(graph, { mode, threshold: Number(data.threshold) || undefined, applyReview: data.apply_review === true, evaluator, resolveTool: name => TOOLS_BY_NAME.get(name) });
+ if (action === "optimize_preview") return { optimization: optimized.preview };
+ if (optimized.preview.summary.selectedCount < 1) throw new Error("no optimization candidate selected; preview first or enable review transformations");
+ const definition = optimized.definition as Record<string, unknown>;
+ const metadata = definition.metadata && typeof definition.metadata === "object" && !Array.isArray(definition.metadata) ? definition.metadata as Record<string, unknown> : {};
+ const tags = Array.isArray(metadata.tags) ? metadata.tags.filter((value): value is string => typeof value === "string") : [];
+ definition.name = typeof data.name === "string" && data.name.trim() ? data.name.trim().slice(0, 160) : `${graph.name} · Optimized`.slice(0, 160);
+ definition.status = "draft";
+ definition.metadata = { ...metadata, provenance: "ai-assisted", fingerprint: undefined, tags: [...new Set([...tags, "optimized", optimized.preview.provider === "jev" ? "jev" : "deterministic"])].slice(0, 32) };
+ const clone = await createWorkflowGraph(principal, definition, "create", { remember: true });
+ return { graph: clone, optimization: optimized.preview };
+ }
if (action === "get") { const graph = await getWorkflowGraph(principal, id); if (!graph) throw new Error("workflow graph not found"); return { graph }; }
if (action === "versions") return { versions: await listWorkflowGraphVersions(workflowGraphOwner(principal), id) };
if (action === "restore") { const current = await getWorkflowGraph(principal, id), snapshot = await readWorkflowGraphVersion(workflowGraphOwner(principal), id, String(data.version ?? "")); if (!current || !snapshot) throw new Error("workflow graph/version not found"); const { revision: _r, createdAt: _c, updatedAt: _u, version: _v, ...definition } = snapshot.graph; return { graph: await updateWorkflowGraph(principal, id, String(data.revision ?? current.revision), definition, "restore", { remember: true }) }; }
diff --git a/lib/workflow/graph-optimizer-candidates.ts b/lib/workflow/graph-optimizer-candidates.ts
new file mode 100644
index 00000000..c4f04af0
--- /dev/null
+++ b/lib/workflow/graph-optimizer-candidates.ts
@@ -0,0 +1,173 @@
+import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";
+import type { WorkflowGraph, WorkflowGraphEdge, WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
+import type { CapabilityTool } from "@/lib/capabilities/tool";
+import type { WorkflowOptimizerCandidate } from "./graph-optimizer";
+
+export type InternalOptimizerCandidate = WorkflowOptimizerCandidate & {
+ apply: (graph: WorkflowGraph) => WorkflowGraph;
+};
+
+const ACTION_TYPES = new Set<WorkflowGraphNode["type"]>([
+ "tool", "project_function", "project_mcp", "integration", "channel_send", "script", "agent", "subflow",
+ "project", "folder", "skill", "knowledge", "cache", "data_table", "memory", "session", "directory",
+]);
+
+const cloneGraph = (graph: WorkflowGraph): WorkflowGraph => structuredClone(graph);
+
+function referencedNodeIds(value: unknown, out = new Set<string>()): Set<string> {
+ if (Array.isArray(value)) {
+ for (const child of value) referencedNodeIds(child, out);
+ return out;
+ }
+ if (!value || typeof value !== "object") return out;
+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
+ if (key === "$ref" && typeof child === "string") {
+ const match = /^nodes\.([A-Za-z0-9_.:-]+)(?:\.|$)/.exec(child);
+ if (match) out.add(match[1]!);
+ } else referencedNodeIds(child, out);
+ }
+ return out;
+}
+
+function allReferencedNodeIds(graph: WorkflowGraph): Set<string> {
+ const out = new Set<string>();
+ for (const node of graph.nodes) referencedNodeIds(node.config, out);
+ return out;
+}
+
+function simpleChain(graph: WorkflowGraph): WorkflowGraphNode[] | null {
+ const enabledEdges = graph.edges.filter((edge) => !edge.disabled);
+ const incoming = new Map<string, WorkflowGraphEdge[]>();
+ const outgoing = new Map<string, WorkflowGraphEdge[]>();
+ for (const node of graph.nodes) {
+ incoming.set(node.id, []);
+ outgoing.set(node.id, []);
+ }
+ for (const edge of enabledEdges) {
+ incoming.get(edge.target)?.push(edge);
+ outgoing.get(edge.source)?.push(edge);
+ }
+ const roots = graph.nodes.filter((node) => (incoming.get(node.id)?.length ?? 0) === 0);
+ if (roots.length !== 1) return null;
+ const ordered: WorkflowGraphNode[] = [], visited = new Set<string>();
+ let current: WorkflowGraphNode | undefined = roots[0];
+ while (current) {
+ if (visited.has(current.id)) return null;
+ visited.add(current.id); ordered.push(current);
+ const edges: WorkflowGraphEdge[] = outgoing.get(current.id) ?? [];
+ if (edges.length > 1 || edges.some((edge) => edge.sourceHandle || edge.targetHandle)) return null;
+ if (!edges.length) break;
+ const next: WorkflowGraphNode | undefined = graph.nodes.find((node) => node.id === edges[0]!.target);
+ if (!next || (incoming.get(next.id)?.length ?? 0) !== 1) return null;
+ current = next;
+ }
+ return visited.size === graph.nodes.length ? ordered : null;
+}
+
+function addPresentationGroup(graph: WorkflowGraph, group: GraphCustomNode): WorkflowGraph {
+ const next = cloneGraph(graph), groups = next.metadata.customNodes ?? [];
+ const assigned = new Set(groups.flatMap((row) => row.nodeIds));
+ const members = group.nodeIds.filter((id) => next.nodes.some((node) => node.id === id) && !assigned.has(id));
+ if (members.length < 3) return next;
+ next.metadata.customNodes = [...groups, { ...group, nodeIds: members }];
+ return next;
+}
+
+function presentationCandidates(graph: WorkflowGraph): InternalOptimizerCandidate[] {
+ const chain = simpleChain(graph);
+ if (!chain) return [];
+ const assigned = new Set((graph.metadata.customNodes ?? []).flatMap((group) => group.nodeIds));
+ if (chain.filter((node) => ACTION_TYPES.has(node.type) && !assigned.has(node.id)).length < 4) return [];
+ const chunks: WorkflowGraphNode[][] = [];
+ let chunk: WorkflowGraphNode[] = [];
+ for (const node of chain) {
+ if (ACTION_TYPES.has(node.type) && !assigned.has(node.id)) { chunk.push(node); continue; }
+ if (chunk.length >= 4) chunks.push(chunk);
+ chunk = [];
+ }
+ if (chunk.length >= 4) chunks.push(chunk);
+ return chunks.slice(0, 12).map((nodes, index) => {
+ const id = `group-${index + 1}-${nodes[0]!.id}`.slice(0, 96);
+ const group: GraphCustomNode = {
+ id: `optimized:${id}`.slice(0, 96),
+ name: nodes.length > 6 ? `Action block · ${nodes.length} steps` : nodes.map((node) => node.name).join(" → ").slice(0, 120),
+ nodeIds: nodes.map((node) => node.id),
+ collapsed: true,
+ };
+ return {
+ id: `presentation:${index + 1}`, kind: "presentation-group", title: `Collapse ${nodes.length} related steps`,
+ description: "Presentation-only grouping. Execution nodes, edges, arguments and receipts remain unchanged.",
+ nodeIds: group.nodeIds, risk: "safe", estimatedNodeDelta: 0, hostEligible: true,
+ apply: (current: WorkflowGraph) => addPresentationGroup(current, group),
+ };
+ });
+}
+
+const isPlainArguments = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value && typeof value === "object" && !Array.isArray(value));
+
+function exactToolConfig(node: WorkflowGraphNode): { tool: string; arguments: Record<string, unknown> } | null {
+ if (node.type !== "tool" || node.disabled) return null;
+ if (Object.keys(node.config).some((key) => !["tool", "arguments"].includes(key))) return null;
+ if (typeof node.config.tool !== "string" || !node.config.tool) return null;
+ const args = node.config.arguments ?? {};
+ if (!isPlainArguments(args) || referencedNodeIds(node.config).size) return null;
+ return { tool: node.config.tool, arguments: structuredClone(args) };
+}
+
+function replaceRunWithLoop(graph: WorkflowGraph, nodes: WorkflowGraphNode[], tool: string): WorkflowGraph {
+ const next = cloneGraph(graph), ids = new Set(nodes.map((node) => node.id));
+ const firstId = nodes[0]!.id, lastId = nodes.at(-1)!.id;
+ const configs = nodes.map((node) => exactToolConfig(node)!.arguments);
+ next.nodes = next.nodes
+ .filter((node) => !ids.has(node.id) || node.id === firstId)
+ .map((node) => node.id === firstId ? {
+ ...node, name: `Loop · ${tool} × ${configs.length}`.slice(0, 120), type: "loop" as const,
+ config: { tool, items: configs, arguments: { $item: true }, concurrency: 1 },
+ } : node);
+ next.edges = next.edges
+ .filter((edge) => !(ids.has(edge.source) && ids.has(edge.target)))
+ .filter((edge) => !ids.has(edge.target) || edge.target === firstId)
+ .filter((edge) => !ids.has(edge.source) || edge.source === firstId || edge.source === lastId)
+ .map((edge) => edge.source === lastId ? { ...edge, source: firstId } : edge);
+ if (next.metadata.customNodes) next.metadata.customNodes = next.metadata.customNodes
+ .map((group) => ({ ...group, nodeIds: group.nodeIds.filter((id) => !ids.has(id) || id === firstId) }))
+ .filter((group) => group.nodeIds.length > 0);
+ return next;
+}
+
+function loopCandidates(graph: WorkflowGraph, resolveTool?: (name: string) => CapabilityTool | undefined): InternalOptimizerCandidate[] {
+ const chain = simpleChain(graph);
+ if (!chain) return [];
+ const referenced = allReferencedNodeIds(graph), result: InternalOptimizerCandidate[] = [];
+ for (let i = 0; i < chain.length;) {
+ const first = exactToolConfig(chain[i]!);
+ if (!first) { i += 1; continue; }
+ const tool = resolveTool?.(first.tool);
+ if (resolveTool && (!tool || tool.annotations?.readOnlyHint !== true)) { i += 1; continue; }
+ let end = i + 1;
+ while (end < chain.length) {
+ const config = exactToolConfig(chain[end]!);
+ if (!config || config.tool !== first.tool) break;
+ end += 1;
+ }
+ const nodes = chain.slice(i, end);
+ if (nodes.length >= 3 && nodes.every((node) => !referenced.has(node.id))) {
+ result.push({
+ id: `loop:${result.length + 1}`, kind: "loop-compaction", title: `Compact ${nodes.length} × ${first.tool} into one loop`,
+ description: "Preserves call order with concurrency=1 and exact prepared arguments. Runtime result shape changes from per-node outputs to one loop result, so review is required.",
+ nodeIds: nodes.map((node) => node.id), risk: "review", estimatedNodeDelta: 1 - nodes.length, hostEligible: true,
+ apply: (current: WorkflowGraph) => replaceRunWithLoop(current, nodes, first.tool),
+ });
+ }
+ i = Math.max(end, i + 1);
+ }
+ return result.slice(0, 12);
+}
+
+export function workflowOptimizerCandidates(
+ graph: WorkflowGraph,
+ resolveTool?: (name: string) => CapabilityTool | undefined,
+): InternalOptimizerCandidate[] {
+ return [...presentationCandidates(graph), ...loopCandidates(graph, resolveTool)];
+}
diff --git a/lib/workflow/graph-optimizer.test.ts b/lib/workflow/graph-optimizer.test.ts
new file mode 100644
index 00000000..b746172d
--- /dev/null
+++ b/lib/workflow/graph-optimizer.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import type { CapabilityTool } from "@/lib/capabilities/tool";
+import { optimizeWorkflowGraph } from "./graph-optimizer";
+
+function graph(nodes: WorkflowGraph["nodes"], edges: WorkflowGraph["edges"]): WorkflowGraph {
+ return {
+ version: 2,
+ id: "graph-1",
+ name: "Optimizer fixture",
+ description: "fixture",
+ status: "draft",
+ inputs: {},
+ nodes,
+ edges,
+ metadata: { provenance: "user" },
+ createdAt: "2026-09-24T00:00:00.000Z",
+ updatedAt: "2026-09-24T00:00:00.000Z",
+ revision: "r1",
+ };
+}
+
+const pos = (x: number) => ({ x, y: 100 });
+const manual = { id: "manual", name: "Manual", type: "manual" as const, position: pos(0), config: {} };
+const output = { id: "output", name: "Output", type: "output" as const, position: pos(1000), config: {} };
+
+describe("workflow graph optimizer", () => {
+ it("adds presentation-only grouping without changing executable topology", async () => {
+ const nodes: WorkflowGraph["nodes"] = [
+ manual,
+ { id: "a", name: "A", type: "project" as const, position: pos(100), config: { project: "mso" } },
+ { id: "b", name: "B", type: "skill" as const, position: pos(200), config: { query: "workflow" } },
+ { id: "c", name: "C", type: "knowledge" as const, position: pos(300), config: { query: "graph" } },
+ { id: "d", name: "D", type: "directory" as const, position: pos(400), config: { source: "tools" } },
+ output,
+ ];
+ const edges = nodes.slice(1).map((node, index) => ({ id: `e${index}`, source: nodes[index]!.id, target: node.id }));
+ const result = await optimizeWorkflowGraph(graph(nodes, edges));
+ expect(result.preview.summary.visualGroupsAdded).toBe(1);
+ expect(result.preview.summary.nodeReduction).toBe(0);
+ expect((result.definition.metadata as WorkflowGraph["metadata"]).customNodes?.[0]?.nodeIds).toEqual(["a", "b", "c", "d"]);
+ expect(result.definition.edges).toEqual(edges);
+ });
+
+ it("suggests repeated prepared read calls as review-only loop compaction", async () => {
+ const nodes: WorkflowGraph["nodes"] = [
+ manual,
+ ...[1, 2, 3].map((n, index) => ({
+ id: `read-${n}`,
+ name: `Read ${n}`,
+ type: "tool" as const,
+ position: pos(100 + index * 100),
+ config: { tool: "fs_read", arguments: { path: `/tmp/file-${n}.txt` } },
+ })),
+ output,
+ ];
+ const edges = nodes.slice(1).map((node, index) => ({ id: `e${index}`, source: nodes[index]!.id, target: node.id }));
+ const resolveTool = (name: string) => name === "fs_read" ? ({ name, description: "read", scope: "read", inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true }, run: async () => ({}) } as CapabilityTool) : undefined;
+ const preview = await optimizeWorkflowGraph(graph(nodes, edges), { resolveTool });
+ expect(preview.preview.reviewCandidateIds).toEqual(["loop:1"]);
+ expect(preview.preview.selectedCandidateIds).toEqual([]);
+ expect(preview.preview.summary.nodeReduction).toBe(0);
+
+ const applied = await optimizeWorkflowGraph(graph(nodes, edges), { resolveTool, applyReview: true });
+ expect(applied.preview.selectedCandidateIds).toEqual(["loop:1"]);
+ expect(applied.preview.summary.nodeReduction).toBe(2);
+ const loop = applied.definition.nodes.find((node) => node.id === "read-1");
+ expect(loop?.type).toBe("loop");
+ expect(loop?.config).toMatchObject({ tool: "fs_read", concurrency: 1 });
+ expect((loop?.config.items as unknown[]).length).toBe(3);
+ });
+
+ it("uses Jev probabilities only as an optimization signal and falls back deterministically", async () => {
+ const nodes: WorkflowGraph["nodes"] = [
+ manual,
+ { id: "a", name: "A", type: "project" as const, position: pos(100), config: { project: "mso" } },
+ { id: "b", name: "B", type: "skill" as const, position: pos(200), config: { query: "workflow" } },
+ { id: "c", name: "C", type: "knowledge" as const, position: pos(300), config: { query: "graph" } },
+ { id: "d", name: "D", type: "directory" as const, position: pos(400), config: { source: "tools" } },
+ output,
+ ];
+ const edges = nodes.slice(1).map((node, index) => ({ id: `e${index}`, source: nodes[index]!.id, target: node.id }));
+ const source = graph(nodes, edges);
+
+ const rejected = await optimizeWorkflowGraph(source, {
+ mode: "jev",
+ evaluator: async (_state, candidates) => ({ provider: "jev", probabilities: Object.fromEntries(candidates.map((candidate) => [candidate.id, 0.2])) }),
+ });
+ expect(rejected.preview.provider).toBe("jev");
+ expect(rejected.preview.selectedCandidateIds).toEqual([]);
+ expect(rejected.preview.shadow?.agreement).toBe(0);
+ expect(rejected.preview.shadow?.disagreements).toEqual(["presentation:1"]);
+
+ const fallback = await optimizeWorkflowGraph(source, {
+ mode: "jev",
+ evaluator: async () => { throw new Error("upstream unavailable"); },
+ });
+ expect(fallback.preview.provider).toBe("fallback");
+ expect(fallback.preview.fallbackReason).toContain("upstream unavailable");
+ expect(fallback.preview.selectedCandidateIds.length).toBeGreaterThan(0);
+ });
+});
diff --git a/lib/workflow/graph-optimizer.ts b/lib/workflow/graph-optimizer.ts
new file mode 100644
index 00000000..47f3930b
--- /dev/null
+++ b/lib/workflow/graph-optimizer.ts
@@ -0,0 +1,177 @@
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import type { CapabilityTool } from "@/lib/capabilities/tool";
+import { workflowOptimizerCandidates } from "./graph-optimizer-candidates";
+
+export type WorkflowOptimizerRisk = "safe" | "review";
+export type WorkflowOptimizerCandidateKind = "presentation-group" | "loop-compaction";
+export type WorkflowOptimizerCandidate = {
+ id: string;
+ kind: WorkflowOptimizerCandidateKind;
+ title: string;
+ description: string;
+ nodeIds: string[];
+ risk: WorkflowOptimizerRisk;
+ estimatedNodeDelta: number;
+ hostEligible: true;
+ probability?: number;
+ selected?: boolean;
+ reason?: string;
+};
+export type WorkflowOptimizerDecisionMode = "deterministic" | "jev";
+export type WorkflowOptimizerEvaluation = {
+ provider: "deterministic" | "jev" | "fallback";
+ probabilities: Record<string, number>;
+ fallbackReason?: string;
+};
+export type WorkflowOptimizerEvaluator = (
+ state: Record<string, unknown>,
+ candidates: WorkflowOptimizerCandidate[],
+) => Promise<WorkflowOptimizerEvaluation>;
+
+export type WorkflowOptimizationPreview = {
+ version: 1;
+ source: { id: string; revision: string; name: string; nodeCount: number; edgeCount: number };
+ mode: WorkflowOptimizerDecisionMode;
+ provider: WorkflowOptimizerEvaluation["provider"];
+ threshold: number;
+ candidates: WorkflowOptimizerCandidate[];
+ selectedCandidateIds: string[];
+ reviewCandidateIds: string[];
+ summary: {
+ candidateCount: number;
+ selectedCount: number;
+ reviewCount: number;
+ beforeNodes: number;
+ afterNodes: number;
+ beforeEdges: number;
+ afterEdges: number;
+ visualGroupsAdded: number;
+ nodeReduction: number;
+ edgeReduction: number;
+ };
+ fallbackReason?: string;
+ shadow?: { baseline: "deterministic"; compared: "jev"; agreement: number; disagreements: string[] };
+};
+
+function optimizerState(graph: WorkflowGraph, candidates: WorkflowOptimizerCandidate[]): Record<string, unknown> {
+ return {
+ objective: "Compact the workflow while preserving semantics, bounded execution, permissions, and debuggability.",
+ workflow: {
+ name: graph.name,
+ description: graph.description.slice(0, 400),
+ status: graph.status,
+ provenance: graph.metadata.provenance ?? "user",
+ nodeCount: graph.nodes.length,
+ edgeCount: graph.edges.length,
+ nodeTypes: graph.nodes.map((node) => node.type),
+ },
+ candidates: candidates.map((candidate) => ({
+ id: candidate.id,
+ kind: candidate.kind,
+ risk: candidate.risk,
+ title: candidate.title,
+ description: candidate.description,
+ affectedNodeCount: candidate.nodeIds.length,
+ estimatedNodeDelta: candidate.estimatedNodeDelta,
+ })),
+ policy: {
+ safeCandidatesMayAutoApply: true,
+ reviewCandidatesRequireExplicitApplyReview: true,
+ jevCannotCreateCallsOrBypassMsoPolicy: true,
+ },
+ };
+}
+
+function deterministicEvaluation(candidates: WorkflowOptimizerCandidate[]): WorkflowOptimizerEvaluation {
+ return {
+ provider: "deterministic",
+ probabilities: Object.fromEntries(candidates.map((candidate) => [candidate.id, candidate.risk === "safe" ? 0.96 : 0.72])),
+ };
+}
+
+function withoutRuntimeFields(graph: WorkflowGraph) {
+ const { version: _version, id: _id, revision: _revision, createdAt: _createdAt, updatedAt: _updatedAt, ...definition } = graph;
+ return definition;
+}
+
+function shadowEvaluation(
+ mode: WorkflowOptimizerDecisionMode,
+ evaluation: WorkflowOptimizerEvaluation,
+ baseline: WorkflowOptimizerEvaluation,
+ candidates: WorkflowOptimizerCandidate[],
+ threshold: number,
+): WorkflowOptimizationPreview["shadow"] {
+ if (mode !== "jev" || evaluation.provider !== "jev") return undefined;
+ const disagreements = candidates.filter((candidate) => {
+ const base = (baseline.probabilities[candidate.id] ?? 0) >= threshold;
+ const jev = (evaluation.probabilities[candidate.id] ?? 0) >= threshold;
+ return base !== jev;
+ }).map((candidate) => candidate.id);
+ const agreement = candidates.length ? (candidates.length - disagreements.length) / candidates.length : 1;
+ return { baseline: "deterministic", compared: "jev", agreement: Math.round(agreement * 1000) / 1000, disagreements };
+}
+
+export async function optimizeWorkflowGraph(graph: WorkflowGraph, options: {
+ mode?: WorkflowOptimizerDecisionMode;
+ threshold?: number;
+ applyReview?: boolean;
+ evaluator?: WorkflowOptimizerEvaluator;
+ resolveTool?: (name: string) => CapabilityTool | undefined;
+} = {}) {
+ const mode = options.mode ?? "deterministic";
+ const threshold = Math.max(0.5, Math.min(0.99, Number(options.threshold) || 0.72));
+ const internal = workflowOptimizerCandidates(graph, options.resolveTool);
+ const publicCandidates: WorkflowOptimizerCandidate[] = internal.map(({ apply: _apply, ...candidate }) => candidate);
+ const baseline = deterministicEvaluation(publicCandidates);
+ let evaluation = baseline;
+ if (mode === "jev" && options.evaluator && publicCandidates.length) {
+ try {
+ evaluation = await options.evaluator(optimizerState(graph, publicCandidates), publicCandidates);
+ } catch (error) {
+ evaluation = {
+ provider: "fallback",
+ probabilities: baseline.probabilities,
+ fallbackReason: error instanceof Error ? error.message.slice(0, 240) : "Jev evaluation failed",
+ };
+ }
+ }
+ const shadow = shadowEvaluation(mode, evaluation, baseline, publicCandidates, threshold);
+ const selected = internal.filter((candidate) => {
+ const probability = evaluation.probabilities[candidate.id] ?? (candidate.risk === "safe" ? 0.96 : 0.72);
+ return probability >= threshold && (candidate.risk === "safe" || options.applyReview === true);
+ });
+ let optimized = structuredClone(graph);
+ for (const candidate of selected.filter((row) => row.kind === "loop-compaction")) optimized = candidate.apply(optimized);
+ for (const candidate of selected.filter((row) => row.kind === "presentation-group")) optimized = candidate.apply(optimized);
+ const candidates = publicCandidates.map((candidate) => ({
+ ...candidate,
+ probability: Math.round((evaluation.probabilities[candidate.id] ?? 0) * 1000) / 1000,
+ selected: selected.some((row) => row.id === candidate.id),
+ reason: candidate.risk === "review" && options.applyReview !== true ? "Requires explicit apply_review=true." : undefined,
+ }));
+ const preview: WorkflowOptimizationPreview = {
+ version: 1,
+ source: { id: graph.id, revision: graph.revision, name: graph.name, nodeCount: graph.nodes.length, edgeCount: graph.edges.length },
+ mode,
+ provider: evaluation.provider,
+ threshold,
+ candidates,
+ selectedCandidateIds: selected.map((candidate) => candidate.id),
+ reviewCandidateIds: candidates.filter((candidate) => candidate.risk === "review").map((candidate) => candidate.id),
+ summary: {
+ candidateCount: candidates.length,
+ selectedCount: selected.length,
+ reviewCount: candidates.filter((candidate) => candidate.risk === "review").length,
+ beforeNodes: graph.nodes.length,
+ afterNodes: optimized.nodes.length,
+ beforeEdges: graph.edges.length,
+ afterEdges: optimized.edges.length,
+ visualGroupsAdded: Math.max(0, (optimized.metadata.customNodes?.length ?? 0) - (graph.metadata.customNodes?.length ?? 0)),
+ nodeReduction: graph.nodes.length - optimized.nodes.length,
+ edgeReduction: graph.edges.length - optimized.edges.length,
+ },
+ ...(evaluation.fallbackReason ? { fallbackReason: evaluation.fallbackReason } : {}),
+ ...(shadow ? { shadow } : {}),
+ };
+ return { preview, definition: withoutRuntimeFields(optimized) };
+}
diff --git a/lib/workflow/jev-optimizer.test.ts b/lib/workflow/jev-optimizer.test.ts
new file mode 100644
index 00000000..7287cbb9
--- /dev/null
+++ b/lib/workflow/jev-optimizer.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { WorkflowOptimizerCandidate } from "./graph-optimizer";
+
+const executeIntegrationAction = vi.fn();
+vi.mock("@/lib/infra/connection-dispatch", () => ({ executeIntegrationAction }));
+
+const { createJevWorkflowOptimizerEvaluator } = await import("./jev-optimizer");
+
+const candidate = (id: string): WorkflowOptimizerCandidate => ({
+ id,
+ kind: "presentation-group",
+ title: `Candidate ${id}`,
+ description: "Compact a reviewed workflow segment without changing authority.",
+ nodeIds: ["a", "b", "c"],
+ risk: "safe",
+ estimatedNodeDelta: 0,
+ hostEligible: true,
+});
+
+beforeEach(() => executeIntegrationAction.mockReset());
+
+describe("Jev workflow optimizer adapter", () => {
+ it("adapts to state/questions typed evaluate schemas", async () => {
+ executeIntegrationAction
+ .mockResolvedValueOnce({ result: [{ name: "evaluate", inputSchema: { type: "object", properties: { state: {}, questions: {}, model: {} } } }] })
+ .mockResolvedValueOnce({ result: { content: [{ type: "text", text: JSON.stringify({ answers: { q1: { type: "noul", noul: 0.91 } } }) }] } });
+ const evaluate = createJevWorkflowOptimizerEvaluator({ user: "owner", connection: "jev", model: "jev-1.13.0" });
+ const result = await evaluate({ workflow: { nodeCount: 8 } }, [candidate("safe-1")]);
+
+ expect(result).toEqual({ provider: "jev", probabilities: { "safe-1": 0.91 } });
+ expect(executeIntegrationAction).toHaveBeenCalledTimes(2);
+ expect(executeIntegrationAction.mock.calls[1]?.[0]).toMatchObject({
+ provider: "mcp",
+ connection: "jev",
+ operation: "mcp.tool",
+ arguments: { name: "evaluate", arguments: { model: "jev-1.13.0" } },
+ });
+ });
+
+ it("adapts to jev_decide bounded-alternative schemas", async () => {
+ executeIntegrationAction
+ .mockResolvedValueOnce({ result: [{ name: "jev_decide", inputSchema: { type: "object", properties: { decision: {}, evidence: {}, priorities: {}, candidates: {}, requirements: {} } } }] })
+ .mockResolvedValueOnce({ result: { content: [{ type: "text", text: JSON.stringify({ recommendation: { selected: "apply", confidence: 0.88, probabilities: { apply: 0.84, skip: 0.16 } } }) }] } });
+ const evaluate = createJevWorkflowOptimizerEvaluator({ user: "owner", connection: "jev" });
+ const result = await evaluate({ workflow: { nodeCount: 8 } }, [candidate("safe-1")]);
+
+ expect(result.probabilities["safe-1"]).toBe(0.84);
+ expect(executeIntegrationAction.mock.calls[1]?.[0]).toMatchObject({
+ operation: "mcp.tool",
+ arguments: {
+ name: "jev_decide",
+ arguments: {
+ candidates: [
+ { id: "apply", description: expect.any(String) },
+ { id: "skip", description: expect.any(String) },
+ ],
+ requirements: expect.any(Array),
+ },
+ },
+ });
+ });
+
+ it("fails closed on an unsupported advertised decision schema so the core can fallback", async () => {
+ executeIntegrationAction.mockResolvedValueOnce({
+ result: [{ name: "jev_decide", inputSchema: { type: "object", properties: { prompt: {} } } }],
+ });
+ const evaluate = createJevWorkflowOptimizerEvaluator({ user: "owner", connection: "jev" });
+ await expect(evaluate({}, [candidate("safe-1")])).rejects.toThrow("Unsupported Jev tool schema");
+ });
+});
diff --git a/lib/workflow/jev-optimizer.ts b/lib/workflow/jev-optimizer.ts
new file mode 100644
index 00000000..bcaf66e3
--- /dev/null
+++ b/lib/workflow/jev-optimizer.ts
@@ -0,0 +1,174 @@
+import { executeIntegrationAction } from "@/lib/infra/connection-dispatch";
+import type { WorkflowOptimizerCandidate, WorkflowOptimizerEvaluation } from "./graph-optimizer";
+
+type JevOptimizerConnection = {
+ user: string;
+ connection: string;
+ tool?: string;
+ model?: string;
+};
+
+type ToolDescriptor = { name: string; inputSchema: Record<string, unknown> };
+
+function object(value: unknown): value is Record<string, unknown> {
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
+}
+
+function parseJsonText(value: unknown): unknown {
+ if (!object(value) || !Array.isArray(value.content)) return null;
+ const text = value.content
+ .filter((item): item is Record<string, unknown> => object(item) && item.type === "text" && typeof item.text === "string")
+ .map((item) => String(item.text))
+ .join("\n");
+ if (!text) return null;
+ try { return JSON.parse(text); } catch { return null; }
+}
+
+function structured(value: unknown): Record<string, unknown> {
+ let current: unknown = value;
+ for (let depth = 0; depth < 6; depth += 1) {
+ if (!object(current)) break;
+ if (object(current.structuredContent)) return current.structuredContent;
+ const parsed = parseJsonText(current);
+ if (object(parsed)) return parsed;
+ if (object(current.data)) current = current.data;
+ else if (object(current.result)) current = current.result;
+ else break;
+ }
+ if (object(current)) return current;
+ throw new Error("Jev MCP returned no structured decision payload");
+}
+
+function listedTools(value: unknown): ToolDescriptor[] {
+ if (!object(value)) return [];
+ const result = value.result;
+ const rows = Array.isArray(result) ? result : Array.isArray(value.tools) ? value.tools : [];
+ return rows.filter((row): row is ToolDescriptor =>
+ object(row) && typeof row.name === "string" && object(row.inputSchema),
+ );
+}
+
+function schemaProperties(tool: ToolDescriptor): Record<string, unknown> {
+ return object(tool.inputSchema.properties) ? tool.inputSchema.properties : {};
+}
+
+function probability(answer: unknown): number | null {
+ if (!object(answer)) return null;
+ for (const key of ["noul", "probability", "confidence", "certainty"]) {
+ const value = Number(answer[key]);
+ if (Number.isFinite(value) && value >= 0 && value <= 1) return value;
+ }
+ return null;
+}
+
+async function mcpCall(config: JevOptimizerConnection, tool: string, args: Record<string, unknown>) {
+ return executeIntegrationAction({
+ user: config.user,
+ provider: "mcp",
+ connection: config.connection,
+ operation: "mcp.tool",
+ confirm: true,
+ arguments: { name: tool, arguments: args },
+ });
+}
+
+async function evaluateTypedQuestions(
+ config: JevOptimizerConnection,
+ tool: ToolDescriptor,
+ state: Record<string, unknown>,
+ candidates: WorkflowOptimizerCandidate[],
+): Promise<Record<string, number>> {
+ const mapping = new Map<string, string>();
+ const questions = Object.fromEntries(candidates.slice(0, 16).map((candidate, index) => {
+ const key = `q${index + 1}`;
+ mapping.set(key, candidate.id);
+ return [key, {
+ type: "noul",
+ instructions: `Should MSO apply candidate "${candidate.title}"? Answer yes only when it meaningfully compacts this workflow while preserving declared semantics, bounded execution, permissions and debuggability. Candidate risk: ${candidate.risk}.`,
+ }];
+ }));
+ const props = schemaProperties(tool);
+ const payload = structured(await mcpCall(config, tool.name, {
+ state,
+ questions,
+ ...(config.model && Object.hasOwn(props, "model") ? { model: config.model } : {}),
+ }));
+ const answers = object(payload.answers) ? payload.answers : object(payload.data) && object(payload.data.answers) ? payload.data.answers : null;
+ if (!answers) throw new Error("Jev typed response did not contain answers");
+ const probabilities: Record<string, number> = {};
+ for (const [question, candidateId] of mapping) {
+ const p = probability(answers[question]);
+ if (p !== null) probabilities[candidateId] = p;
+ }
+ return probabilities;
+}
+
+async function evaluateBoundedDecisions(
+ config: JevOptimizerConnection,
+ tool: ToolDescriptor,
+ state: Record<string, unknown>,
+ candidates: WorkflowOptimizerCandidate[],
+): Promise<Record<string, number>> {
+ const probabilities: Record<string, number> = {};
+ const evidence = JSON.stringify(state).slice(0, 12_000);
+ const props = schemaProperties(tool);
+ for (const candidate of candidates.slice(0, 12)) {
+ const payload = structured(await mcpCall(config, tool.name, {
+ decision: `Should MSO apply this workflow optimization: ${candidate.title}?`,
+ evidence: `${evidence}\nCandidate: ${candidate.description}\nAffected nodes: ${candidate.nodeIds.length}. Estimated node delta: ${candidate.estimatedNodeDelta}.`,
+ priorities: "Preserve workflow semantics, permission boundaries, bounded execution and debuggability. Prefer compaction only when evidence supports it. Review-risk transformations must be treated conservatively.",
+ candidates: [
+ { id: "apply", description: "Apply this exact host-generated optimization candidate." },
+ { id: "skip", description: "Keep the current workflow unchanged for this candidate." },
+ ],
+ requirements: [
+ "The candidate must not create a new tool call or new arguments.",
+ "The candidate must not weaken MSO authorization, confirmation, retry, idempotency or audit boundaries.",
+ "The candidate should meaningfully reduce visual or structural workflow complexity.",
+ ],
+ ...(config.model && Object.hasOwn(props, "model") ? { model: config.model } : {}),
+ }));
+ const recommendation = object(payload.recommendation) ? payload.recommendation : payload;
+ const distribution = object(recommendation.probabilities) ? recommendation.probabilities : {};
+ const apply = Number(distribution.apply);
+ if (Number.isFinite(apply) && apply >= 0 && apply <= 1) probabilities[candidate.id] = apply;
+ else if (recommendation.selected === "apply") probabilities[candidate.id] = probability(recommendation) ?? 1;
+ else if (recommendation.selected === "skip") probabilities[candidate.id] = 1 - (probability(recommendation) ?? 1);
+ }
+ return probabilities;
+}
+
+export function createJevWorkflowOptimizerEvaluator(config: JevOptimizerConnection) {
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(config.user)) throw new Error("invalid Jev integration user");
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(config.connection)) throw new Error("invalid Jev integration connection");
+ if (config.tool && !/^[A-Za-z0-9_.-]{1,128}$/.test(config.tool)) throw new Error("invalid Jev MCP tool");
+
+ return async (state: Record<string, unknown>, candidates: WorkflowOptimizerCandidate[]): Promise<WorkflowOptimizerEvaluation> => {
+ if (!candidates.length) return { provider: "jev", probabilities: {} };
+ const catalog = await executeIntegrationAction({
+ user: config.user,
+ provider: "mcp",
+ connection: config.connection,
+ operation: "mcp.tools.list",
+ confirm: true,
+ arguments: {},
+ });
+ const tools = listedTools(catalog);
+ const tool = config.tool
+ ? tools.find((row) => row.name === config.tool)
+ : tools.find((row) => row.name === "jev_decide") ?? tools.find((row) => row.name === "evaluate") ?? tools.find((row) => /(?:jev_)?(?:decide|evaluate)$/i.test(row.name));
+ if (!tool) throw new Error(config.tool ? `Configured Jev MCP tool "${config.tool}" was not advertised` : "Jev MCP advertised no supported decision tool");
+
+ const props = schemaProperties(tool);
+ let probabilities: Record<string, number>;
+ if (Object.hasOwn(props, "questions") && Object.hasOwn(props, "state")) {
+ probabilities = await evaluateTypedQuestions(config, tool, state, candidates);
+ } else if (Object.hasOwn(props, "decision") && Object.hasOwn(props, "candidates")) {
+ probabilities = await evaluateBoundedDecisions(config, tool, state, candidates);
+ } else {
+ throw new Error(`Unsupported Jev tool schema for ${tool.name}`);
+ }
+ if (!Object.keys(probabilities).length) throw new Error("Jev MCP response contained no usable probabilities");
+ return { provider: "jev", probabilities };
+ };
+}