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 server-native workflow graph

Rahman966a8247add4
diff --git a/README.md b/README.md
index 8a34b174..e2b8507d 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,7 @@
| **Understand a project** | Project context, trusted skills and task-specific tool discovery. |
| **Do the work** | Real PTY, bounded file tools, service controls and explicit approvals. |
| **Pick up where you left off** | Durable sessions, local memory, workflow evidence and agent handoffs. |
+| **Build server-native workflows** | Visual n8n-like workflow graphs, reusable scripts/subflows, per-node logs, dynamic project/folder bindings, and automatic private learning from successful sessions. |
**One runtime, three ways in:** use desktop/mobile windows, stay in your terminal, or connect an MCP client.
Code, image/video tools, a browser and native credential setup live beside your operational tools.
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
new file mode 100644
index 00000000..6d9e2625
--- /dev/null
+++ b/app/api/v1/workflows/route.ts
@@ -0,0 +1,57 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { roleAtLeast } from "@/lib/auth/roles";
+import { createAgentSession } from "@/lib/agent/session-store";
+import { readSetupJson } from "@/lib/infra/setup-http";
+import { maxScope } from "@/lib/mcp/scope";
+import { TOOLS_BY_NAME } from "@/lib/mcp/tools";
+import { cloneWorkflowGraph, createWorkflowGraph, deleteWorkflowGraph, getWorkflowGraph, listWorkflowGraphs, updateWorkflowGraph } from "@/lib/workflow/graph-store";
+import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";
+import { resolveWorkflowGraphNodeTarget } from "@/lib/workflow/graph-target";
+
+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) : "workflow request failed" }, { status, headers });
+
+async function auth(minimum: "viewer" | "operator" | "owner" = "viewer") {
+ const context = await getSessionContext();
+ if (!context?.session.device_id) return null;
+ if (!roleAtLeast(context.role, minimum)) return null;
+ return { context, principal: `web:${context.session.device_id}` };
+}
+
+export async function GET(req: NextRequest) {
+ const session = await auth("viewer"); if (!session) return fail("unauthorized", 401);
+ try {
+ const q = req.nextUrl.searchParams;
+ if (q.has("run_id")) return NextResponse.json(await workflowGraphRunStatus(session.principal, q.get("run_id")!, Number(q.get("wait_ms")) || 0), { headers });
+ if (q.has("graph_id") && q.has("node_id") && q.get("resolve") === "target") {
+ const graph = await getWorkflowGraph(session.principal, q.get("graph_id")!); if (!graph) throw new Error("workflow graph not found");
+ return NextResponse.json(await resolveWorkflowGraphNodeTarget(graph, q.get("node_id")!), { headers });
+ }
+ if (q.has("graph_id")) {
+ const graph = await getWorkflowGraph(session.principal, q.get("graph_id")!); if (!graph) return fail("workflow graph not found", 404);
+ return NextResponse.json({ graph }, { headers });
+ }
+ return NextResponse.json({ graphs: await listWorkflowGraphs(session.principal) }, { headers });
+ } catch (error) { return fail(error); }
+}
+
+export async function POST(req: NextRequest) {
+ const session = await auth("operator"); if (!session) return fail("operator_required", 403);
+ try {
+ const body = await readSetupJson(req), action = typeof body.action === "string" ? body.action : "";
+ if (action === "create") return NextResponse.json({ graph: await createWorkflowGraph(session.principal, body.graph) }, { headers });
+ if (action === "update") return NextResponse.json({ graph: await updateWorkflowGraph(session.principal, String(body.graph_id ?? ""), String(body.expected_revision ?? ""), body.graph) }, { headers });
+ if (action === "delete") return NextResponse.json(await deleteWorkflowGraph(session.principal, String(body.graph_id ?? ""), String(body.expected_revision ?? "")), { headers });
+ if (action === "clone") return NextResponse.json({ graph: await cloneWorkflowGraph(session.principal, String(body.graph_id ?? "")) }, { headers });
+ if (action === "run") {
+ const graph = await getWorkflowGraph(session.principal, String(body.graph_id ?? "")); if (!graph) throw new Error("workflow graph not found");
+ const agentSession = await createAgentSession(session.principal, "cli", { title: `Workflow: ${graph.name}`, titleSource: "auto" });
+ const context = { principal: session.principal, actor: session.principal, sessionId: agentSession.id, scope: maxScope() } as const;
+ return NextResponse.json(await startWorkflowGraph(graph, body.input ?? {}, String(body.idempotency_key ?? `${Date.now()}`), context, (name) => TOOLS_BY_NAME.get(name)), { headers });
+ }
+ throw new Error("unknown workflow action");
+ } catch (error) { return fail(error); }
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 47b2df43..305cb2e9 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -288,3 +288,7 @@ future archaeology task.
### ChatGPT MSO Page trust boundary
Each MSO connector/server scope owns its own Page app catalog. Core MSO Page code must not import project identities or trusted frame origins from another server scope. Portable source ships with an empty external-app catalog. An installation may opt into reviewed apps through the bounded owner-local `~/.mso/surface-apps.json` registry (or an explicit `MSO_SURFACE_APPS_JSON` override); MSO re-reads the registry when the Page resource is read and validates each exact HTTPS origin, approved start-path prefix, renderer, sandbox, and presentation before it can enter Page CSP. The dedicated widget origin is installation-derived from `OS_MCP_UI_ORIGIN` / `OS_PUBLIC_ORIGIN`. The Block resource has no frame domains.
+
+## Server-native workflow graph
+
+MSO now has a Workflow Graph v2 layer above the existing automation/lifecycle/RASMIC primitives. The graph is the automation-topology SSOT; canonical project paths are resolved dynamically from the project registry and are not copied into portable workflow definitions. Graph definitions/runs are isolated by authenticated principal, while tools/scripts/subflows retain normal capability scope, audit, connection and project guards. See [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md).
diff --git a/docs/AUTOMATION-FLOWS.md b/docs/AUTOMATION-FLOWS.md
index bc03a022..5193f9e5 100644
--- a/docs/AUTOMATION-FLOWS.md
+++ b/docs/AUTOMATION-FLOWS.md
@@ -139,3 +139,7 @@ of serializing learned recipes on every tool event. Snapshot ids prevent an old
from undoing a newer complete store. Back up both files together. Full learning writes
still atomically persist the complete store. This follows the existing single-process
workflow-store model; a multi-writer database is not introduced.
+
+## Workflow Graph v2
+
+For visual, branching, mixed-node workflows, see [WORKFLOW-GRAPH.md](./WORKFLOW-GRAPH.md). Graph v2 is private per authenticated principal, has per-node logs/error identity, resolves project/folder locations dynamically, and coexists with the linear flow format documented above. `workflow_start` checks matching private graphs before learned recipes; successful `workflow_finish` seeds private draft graphs automatically.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index afbdfe48..30f7d1d9 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -4,6 +4,16 @@
Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;
this is the *what*, and it is what Settings → About shows as “What's new”.
+## 2026-09-15
+
+**Added**
+
+- `workflows` add server-native workflow graph
+
+**Fixed**
+
+- `mcp` expose downstream project tool results (#43)
+
## 2026-09-14
**Added**
diff --git a/docs/README.md b/docs/README.md
index 2cf23411..12a948d9 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -35,6 +35,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`INTEGRATIONS.md`](./INTEGRATIONS.md) | Native temporary credential forms, direct HTTPS secret submission, CLI and ChatGPT Page |
| [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs |
| [`AUTOMATION-FLOWS.md`](./AUTOMATION-FLOWS.md) | Versioned project API/MCP flows, CLI, sessions, Add MCP, assets and limits |
+| [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md) | Private server-native Workflow Graph v2, visual editor, node runtime/logging, dynamic project/folder bindings and automatic learning |
| [`MCP-HOW-TO.md`](./MCP-HOW-TO.md) | Bahasa Indonesia onboarding: client connection, prompts, workflow, project MCP and troubleshooting |
| [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model |
| [`A2A.md`](./A2A.md) | A2A v1 peer discovery, delegation/task lifecycle, CLI/MCP surface and trust boundary |
diff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.md
index 4335ee86..5700d408 100644
--- a/docs/SLICE-CATALOG.md
+++ b/docs/SLICE-CATALOG.md
@@ -3,12 +3,12 @@
> **Current reference.** Counts are checked against the directory tree by
> `scripts/check-docs.mjs`; the directory remains the final authority.
-<!-- slice-catalog: slices=23 appshell-features=10 -->
+<!-- slice-catalog: slices=24 appshell-features=10 -->
Every application is a vertical slice under `frontend/slices/`. Host-facing slices use the
shared API/host seam rather than reaching arbitrary Node host APIs from client code.
-## Slices (23)
+## Slices (24)
| Slug | Purpose |
|---|---|
@@ -35,6 +35,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c
| `reel-editor` | Video/reel timeline editor |
| `shell-settings` | Shared shell settings UI primitives |
| `system-monitor` | Live metrics/processes plus service inventory/logs/allowlisted lifecycle and cache-only package updates |
+| `workflows` | Server-native visual workflow graph editor, private runs and node-level logs |
## AppShell feature directories (10)
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
new file mode 100644
index 00000000..87c408ba
--- /dev/null
+++ b/docs/WORKFLOW-GRAPH.md
@@ -0,0 +1,93 @@
+# Workflow Graph v2
+
+MSO Workflow Graph v2 is the private, server-native automation layer for reusable workflows. It extends the existing linear project flow engine rather than replacing it.
+
+## SSOT boundaries
+
+- **MSO Workflow Graph** owns automation topology, runtime node state, execution bindings and reusable workflow definitions.
+- **MSO project registry** resolves canonical projects and real server paths at runtime. Graph definitions store project ids/hints, not installation-specific absolute paths.
+- **Git** remains the code source of truth.
+- **Project `.mso/KNOWLEDGE.md` / repo memory** remain project knowledge sources.
+- External delivery systems may remain delivery/task SSOT when connected; MSO does not copy their task state into graph definitions.
+- No separate organizational-memory product is required for workflow execution.
+
+## Privacy and portability
+
+Private graphs and run receipts are keyed by an authenticated principal hash. Another principal cannot list, read or poll them. Source code and builtin templates contain no installation owner, private path, credential or user-specific workflow seed. Project/folder paths are resolved only at runtime after canonical-project containment checks.
+
+Secret-like fields (`token`, `password`, `apiKey`, authorization headers, cookies, etc.) are rejected recursively from stored graph definitions. Credentials continue to resolve through normal MSO integration/project authorities during execution.
+
+## Graph model
+
+A graph is a versioned DAG with revision conflict protection. MVP node types:
+
+- `manual`
+- `tool`
+- `project_function`
+- `project_mcp`
+- `script`
+- `agent`
+- `subflow`
+- `condition`
+- `project`
+- `folder`
+- `skill`
+- `knowledge`
+- `output`
+
+Cycles are rejected in v2 MVP. Condition nodes route `true` / `false` handles. Disabled or unselected branches become `skipped`.
+
+## Runtime receipts
+
+Each graph run persists a private receipt. Nodes expose:
+
+- queued / running / completed / failed / skipped / blocked
+- start/end/duration
+- bounded redacted output
+- error text
+- compact node log
+
+On failure, the receipt includes `failedNodeId` and `failedNodeName`; downstream queued nodes become `blocked`. Failed mutations are not replayed automatically.
+
+## Visual editor
+
+The native **Workflows** app (`/workflows`) provides:
+
+- private workflow list
+- draggable node canvas and edges
+- node/edge CRUD
+- JSON node config inspector
+- duplicate/archive/save/run controls
+- per-node run log
+- project/folder nodes that open the resolved real server directory in MSO Files/Finder
+
+The browser does not attempt to open a VPS desktop file manager.
+
+## Automatic learning
+
+`workflow_start` checks automation in this order:
+
+1. matching private Workflow Graph v2
+2. existing project/builtin linear flow
+3. learned recipe and deterministic script candidate
+4. normal bounded execution
+
+Successful `workflow_finish` automatically learns the sanitized route, updates private procedural memory and creates/deduplicates a private **draft** graph candidate. Learned drafts never auto-activate or auto-run; ordinary scope/authorization still applies.
+
+This makes repeated session history useful without requiring a separate manual memory write for every successful workflow. Manual user-test evidence still uses project memory because it has stronger authority semantics.
+
+## MCP tools
+
+- `workflow_graph_catalog`
+- `workflow_graph_manage`
+- `workflow_graph_run`
+- `workflow_graph_status`
+
+The existing v1 tools remain compatible:
+
+- `flow_catalog`
+- `flow_manage`
+- `flow_run`
+- `flow_status`
+
+Use v1 for compact deterministic ordered API/MCP sequences; use graph v2 for visual branching workflows, mixed node types and richer runtime observability.
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index c578461e..69d52d70 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,21 +4,21 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.14.4 version=2026.09.15.3 tools=105 read=50 write=34 exec=21 -->
+<!-- mcp-toolset: server=1.14.4 version=2026.09.15.3 tools=109 read=52 write=35 exec=22 -->
| Fact | Current source value |
|---|---:|
| MCP server | `1.14.4` |
| Toolset | `2026.09.15.3` |
| Toolset changed at | `2026-09-15T03:35:00+07:00` |
-| Transport tools | **107** |
-| Model/operator tools | **105** |
-| Read | **50** |
-| Write | **34** |
-| Exec | **21** |
+| Transport tools | **111** |
+| Model/operator tools | **109** |
+| Read | **52** |
+| Write | **35** |
+| Exec | **22** |
| App-only bridges | **2** |
-### Read (50)
+### Read (52)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -70,8 +70,10 @@
- `sys_stats`
- `tool_forge_candidates`
- `vps_status`
+- `workflow_graph_catalog`
+- `workflow_graph_status`
-### Write (34)
+### Write (35)
- `a2a_agent_register`
- `a2a_agent_remove`
@@ -106,9 +108,10 @@
- `tool_forge_propose`
- `workflow_cancel`
- `workflow_finish`
+- `workflow_graph_manage`
- `workflow_start`
-### Exec (21)
+### Exec (22)
- `a2a_handoff`
- `a2a_message_send`
@@ -131,6 +134,7 @@
- `project_mcp_tools`
- `tool_forge_evaluate`
- `tool_forge_promote`
+- `workflow_graph_run`
### App-only bridges (2)
@@ -139,20 +143,20 @@
## ChatGPT model profile
-<!-- mcp-chatgpt-profile: server=1.14.4 version=2026.09.15.3 tools=105 read=50 write=34 exec=21 app-only=2 total=107 -->
+<!-- mcp-chatgpt-profile: server=1.14.4 version=2026.09.15.3 tools=109 read=52 write=35 exec=22 app-only=2 total=111 -->
The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.
| Fact | Current source value |
|---|---:|
-| ChatGPT transport tools | **107** |
-| ChatGPT model/operator tools | **105** |
-| Read | **50** |
-| Write | **34** |
-| Exec | **21** |
+| ChatGPT transport tools | **111** |
+| ChatGPT model/operator tools | **109** |
+| Read | **52** |
+| Write | **35** |
+| Exec | **22** |
| App-only bridges | **2** |
-### ChatGPT read (50)
+### ChatGPT read (52)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -204,8 +208,10 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `sys_stats`
- `tool_forge_candidates`
- `vps_status`
+- `workflow_graph_catalog`
+- `workflow_graph_status`
-### ChatGPT write (34)
+### ChatGPT write (35)
- `a2a_agent_register`
- `a2a_agent_remove`
@@ -240,9 +246,10 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `tool_forge_propose`
- `workflow_cancel`
- `workflow_finish`
+- `workflow_graph_manage`
- `workflow_start`
-### ChatGPT exec (21)
+### ChatGPT exec (22)
- `a2a_handoff`
- `a2a_message_send`
@@ -265,6 +272,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `project_mcp_tools`
- `tool_forge_evaluate`
- `tool_forge_promote`
+- `workflow_graph_run`
### ChatGPT app-only bridges (2)
diff --git a/frontend/slices/os-shell/shell.manifest.ts b/frontend/slices/os-shell/shell.manifest.ts
index 2a16d6b5..f416454f 100644
--- a/frontend/slices/os-shell/shell.manifest.ts
+++ b/frontend/slices/os-shell/shell.manifest.ts
@@ -21,6 +21,7 @@ import { osSettingsApp } from "@/features/os-settings";
import { quicklinksApp } from "@/features/quicklinks";
import { docsApp } from "@/features/docs";
import { integrationsApp } from "@/features/integrations";
+import { workflowsApp } from "@/features/workflows";
import { cloudflareApp, dokployApp } from "@/features/infrastructure";
import { themeQuickPickerFeature } from "./theme-quick-picker";
import { serverConnectionStatusFeature } from "./server-connection-status";
@@ -67,6 +68,7 @@ export const BUILTIN_APPS: AppDescriptor[] = [
withSlug(withArtwork(openclawApp), "openclaw"),
withSlug(withArtwork(nineRouterApp), "9router"),
pin(withSlug(integrationsApp, "connections")),
+ pin(withSlug(withArtwork(workflowsApp), "workflows")),
withSlug(withArtwork(dokployApp), "dokploy"),
withSlug(withArtwork(cloudflareApp), "cloudflare"),
withSlug(withArtwork(quicklinksApp), "links"),
diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsx
new file mode 100644
index 00000000..ff631f2c
--- /dev/null
+++ b/frontend/slices/workflows/app.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { Copy, Play, Plus, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
+import type { AppProps } from "@/features/appshell";
+import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+import { AppFrame, openWindow } from "@/features/appshell";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { WorkflowCanvas } from "./components/workflow-canvas";
+import { WorkflowInspector } from "./components/workflow-inspector";
+import { WorkflowRunPanel } from "./components/workflow-run-panel";
+import { cloneGraph, createGraph, deleteGraph, getGraph, listGraphs, resolveNode, runGraph, runStatus, updateGraph } from "./lib/api";
+
+function starterGraph(name = "New Workflow") {
+ return {
+ name, description: "Private workflow graph.", status: "draft" as const, inputs: {}, metadata: { provenance: "user" as const },
+ nodes: [
+ { id: "manual", name: "Manual Trigger", type: "manual" as const, position: { x: 80, y: 160 }, config: {} },
+ { id: "output", name: "Output", type: "output" as const, position: { x: 420, y: 160 }, config: {} },
+ ],
+ edges: [{ id: "edge-start", source: "manual", target: "output" }],
+ };
+}
+
+export default function WorkflowsApp(_props: AppProps) {
+ const [graphs, setGraphs] = useState<WorkflowGraph[]>([]), [graph, setGraph] = useState<WorkflowGraph | null>(null);
+ const [selected, setSelected] = useState<string | null>(null), [run, setRun] = useState<WorkflowGraphRun | null>(null);
+ const [busy, setBusy] = useState(false), [message, setMessage] = useState(""), [panel, setPanel] = useState<"inspector" | "runs">("inspector");
+ const node = useMemo(() => graph?.nodes.find((item) => item.id === selected) ?? null, [graph, selected]);
+ const runStates = useMemo(() => new Map(run?.nodes.map((item) => [item.id, item.state]) ?? []), [run]);
+ const refresh = async (selectId?: string) => {
+ const list = await listGraphs(); setGraphs(list);
+ const id = selectId ?? graph?.id ?? list[0]?.id;
+ if (id) setGraph(await getGraph(id)); else setGraph(null);
+ };
+ useEffect(() => {
+ let cancelled = false;
+ void listGraphs().then(async (list) => {
+ if (cancelled) return;
+ setGraphs(list);
+ if (list[0]) setGraph(await getGraph(list[0].id));
+ }).catch((error: unknown) => { if (!cancelled) setMessage(error instanceof Error ? error.message : "Could not load workflows"); });
+ return () => { cancelled = true; };
+ }, []);
+ useEffect(() => {
+ if (!run || run.state !== "running") return;
+ const timer = setInterval(() => { void runStatus(run.id).then(setRun).catch(() => undefined); }, 1600); return () => clearInterval(timer);
+ }, [run]);
+ const wrap = async (fn: () => Promise<void>) => { setBusy(true); setMessage(""); try { await fn(); } catch (error) { setMessage(error instanceof Error ? error.message : "Action failed"); } finally { setBusy(false); } };
+ const create = () => wrap(async () => { const next = await createGraph(starterGraph()); await refresh(next.id); setSelected("manual"); });
+ const save = () => graph && wrap(async () => { const next = await updateGraph(graph); setGraph(next); setGraphs(await listGraphs()); setMessage("Saved"); });
+ const duplicate = () => graph && wrap(async () => { const next = await cloneGraph(graph.id); await refresh(next.id); });
+ 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); });
+ const execute = () => graph && wrap(async () => { const receipt = await runGraph(graph.id); setRun(receipt); setPanel("runs"); });
+ const updateNode = (next: WorkflowGraphNode) => graph && setGraph({ ...graph, nodes: graph.nodes.map((item) => item.id === next.id ? next : item) });
+ const deleteNode = (id: string) => { if (!graph) return; setGraph({ ...graph, nodes: graph.nodes.filter((item) => item.id !== id), edges: graph.edges.filter((edge) => edge.source !== id && edge.target !== id) }); setSelected(null); };
+ const openNode = async (id: string) => {
+ if (!graph) return;
+ const resolved = await resolveNode(graph.id, id);
+ openWindow("files-manager", resolved.name, undefined, { path: resolved.path }, { multi: true });
+ };
+ const addNode = (type: WorkflowGraphNodeType) => {
+ if (!graph) return; const id = `${type}-${crypto.randomUUID().slice(0, 8)}`;
+ const next: WorkflowGraphNode = { id, name: type.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase()), type, position: { x: 220 + graph.nodes.length * 32, y: 280 + (graph.nodes.length % 4) * 100 }, config: {} };
+ setGraph({ ...graph, nodes: [...graph.nodes, next] }); setSelected(id); setPanel("inspector");
+ };
+
+ return <AppFrame safeArea={false} className="h-full" toolbar={<div className="flex h-11 items-center gap-2 border-b px-3">
+ <Workflow className="size-4" /><span className="text-sm font-semibold">Workflows</span><div className="h-4 w-px bg-border" />
+ {graph && <Input className="h-8 max-w-56" value={graph.name} onChange={(e) => setGraph({ ...graph, name: e.target.value })} />}
+ <div className="ml-auto flex items-center gap-1"><Button size="sm" variant="ghost" onClick={() => void refresh()} disabled={busy}><RefreshCw className="size-3" /></Button><Button size="sm" variant="outline" onClick={() => void create()} disabled={busy}><Plus className="mr-1 size-3" />New</Button>{graph && <><Button size="sm" variant="outline" onClick={() => void duplicate()} disabled={busy}><Copy className="size-3" /></Button><Button size="sm" variant="outline" onClick={() => void save()} disabled={busy}><Save className="mr-1 size-3" />Save</Button><Button size="sm" onClick={() => void execute()} disabled={busy}><Play className="mr-1 size-3" />Run</Button><Button size="sm" variant="ghost" onClick={() => void remove()} disabled={busy}><Trash2 className="size-3" /></Button></>}</div>
+ </div>}>
+ <div className="grid h-full min-h-0 grid-cols-[220px_minmax(0,1fr)_300px]">
+ <aside className="min-h-0 border-r bg-muted/10"><div className="border-b p-2"><Button className="w-full" size="sm" onClick={() => void create()}><Plus className="mr-1 size-3" />Create workflow</Button></div><ScrollArea className="h-[calc(100%-49px)]"><div className="space-y-1 p-2">{graphs.length === 0 && <div className="p-3 text-xs text-muted-foreground">No private workflows yet. Successful repeated sessions can also create learned drafts.</div>}{graphs.map((item) => <button key={item.id} type="button" onClick={() => void wrap(async () => { setGraph(await getGraph(item.id)); setSelected(null); setRun(null); })} className={`w-full rounded-lg border p-2 text-left text-xs ${graph?.id === item.id ? "bg-accent" : "bg-card"}`}><div className="truncate font-medium">{item.name}</div><div className="mt-1 text-[10px] text-muted-foreground">{item.status} · {item.nodes.length} nodes{item.metadata.provenance === "learned-from-session" ? " · learned" : ""}</div></button>)}</div></ScrollArea></aside>
+ <main className="min-h-0 min-w-0 overflow-hidden">{graph ? <div className="flex h-full flex-col"><div className="flex h-10 items-center gap-2 border-b px-2"><select className="h-7 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(e) => setGraph({ ...graph, status: e.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><select className="h-7 rounded border bg-background px-2 text-xs" defaultValue="" onChange={(e) => { if (e.target.value) { addNode(e.target.value as WorkflowGraphNodeType); e.target.value = ""; } }}><option value="">+ Add node</option>{["tool","project_function","project_mcp","script","agent","subflow","condition","project","folder","skill","knowledge","output"].map((type) => <option key={type} value={type}>{type}</option>)}</select>{message && <span className="ml-auto truncate text-[11px] text-muted-foreground">{message}</span>}</div><div className="min-h-0 flex-1 overflow-auto"><WorkflowCanvas graph={graph} selectedId={selected} onSelect={setSelected} nodeStates={runStates} onOpen={(id) => void openNode(id)} onMove={(id, position) => setGraph({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} /></div></div> : <div className="flex h-full items-center justify-center text-sm text-muted-foreground">Create or select a workflow.</div>}</main>
+ <aside className="min-h-0 border-l"><div className="flex h-10 border-b"><button className={`flex-1 text-xs ${panel === "inspector" ? "font-semibold" : "text-muted-foreground"}`} onClick={() => setPanel("inspector")}>Inspector</button><button className={`flex-1 text-xs ${panel === "runs" ? "font-semibold" : "text-muted-foreground"}`} onClick={() => setPanel("runs")}>Run log</button></div><div className="h-[calc(100%-40px)]">{graph && panel === "inspector" ? <ScrollArea className="h-full"><WorkflowInspector key={node?.id ?? "none"} graph={graph} node={node} onNode={updateNode} onDeleteNode={deleteNode} onGraph={setGraph} /></ScrollArea> : <WorkflowRunPanel run={run} />}</div></aside>
+ </div>
+ </AppFrame>;
+}
diff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsx
new file mode 100644
index 00000000..4b43200c
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-canvas.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { useMemo, useRef } from "react";
+import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeState } from "@/lib/contracts/workflow-graph";
+import { cn } from "@/lib/utils";
+
+const W = 184, H = 76;
+
+export function WorkflowCanvas({ graph, selectedId, onSelect, onMove, nodeStates, onOpen }: {
+ graph: WorkflowGraph;
+ selectedId: string | null;
+ onSelect: (id: string | null) => void;
+ onMove: (id: string, position: { x: number; y: number }) => void;
+ nodeStates?: ReadonlyMap<string, WorkflowGraphNodeState>;
+ onOpen?: (id: string) => void;
+}) {
+ const drag = useRef<{ id: string; dx: number; dy: number } | null>(null);
+ const nodes = useMemo(() => new Map(graph.nodes.map((node) => [node.id, node])), [graph.nodes]);
+ const down = (event: React.PointerEvent, node: WorkflowGraphNode) => {
+ const box = event.currentTarget.getBoundingClientRect();
+ drag.current = { id: node.id, dx: event.clientX - box.left, dy: event.clientY - box.top };
+ event.currentTarget.setPointerCapture(event.pointerId); onSelect(node.id);
+ };
+ const move = (event: React.PointerEvent) => {
+ if (!drag.current) return;
+ const canvas = event.currentTarget.getBoundingClientRect();
+ onMove(drag.current.id, { x: Math.max(12, event.clientX - canvas.left - drag.current.dx), y: Math.max(12, event.clientY - canvas.top - drag.current.dy) });
+ };
+ return (
+ <div className="relative h-full min-h-[520px] min-w-[880px] overflow-auto bg-muted/20" onPointerMove={move} onPointerUp={() => { drag.current = null; }} onClick={(event) => { if (event.target === event.currentTarget) onSelect(null); }}>
+ <svg className="pointer-events-none absolute inset-0 h-[1400px] w-[2200px]" aria-hidden>
+ {graph.edges.map((edge) => {
+ const a = nodes.get(edge.source), b = nodes.get(edge.target); if (!a || !b) return null;
+ const x1 = a.position.x + W, y1 = a.position.y + H / 2, x2 = b.position.x, y2 = b.position.y + H / 2, c = Math.max(60, Math.abs(x2 - x1) / 2);
+ return <path key={edge.id} d={`M ${x1} ${y1} C ${x1 + c} ${y1}, ${x2 - c} ${y2}, ${x2} ${y2}`} fill="none" stroke="currentColor" strokeWidth="1.5" className="text-border" />;
+ })}
+ </svg>
+ <div className="relative h-[1400px] w-[2200px]">
+ {graph.nodes.map((node) => (
+ <button key={node.id} type="button" onPointerDown={(event) => down(event, node)} onClick={(event) => { event.stopPropagation(); onSelect(node.id); }}
+ onDoubleClick={() => { if ((node.type === "project" || node.type === "folder") && onOpen) onOpen(node.id); }}
+ className={cn("absolute flex h-[76px] w-[184px] cursor-grab flex-col items-start justify-center rounded-xl border bg-card px-3 text-left shadow-sm active:cursor-grabbing", selectedId === node.id && "ring-2 ring-ring", nodeStates?.get(node.id) === "failed" && "border-destructive ring-1 ring-destructive", nodeStates?.get(node.id) === "running" && "border-primary ring-1 ring-primary", ["skipped", "blocked"].includes(nodeStates?.get(node.id) ?? "") && "opacity-55", node.disabled && "opacity-50")}
+ style={{ transform: `translate(${node.position.x}px, ${node.position.y}px)` }}>
+ <span className="w-full truncate text-xs font-semibold">{node.name}</span>
+ <span className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">{node.type.replaceAll("_", " ")}{nodeStates?.get(node.id) ? ` · ${nodeStates.get(node.id)}` : ""}</span>
+ {node.type === "condition" && <span className="mt-1 text-[10px] text-muted-foreground">true / false</span>}
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsx
new file mode 100644
index 00000000..505a33b1
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-inspector.tsx
@@ -0,0 +1,41 @@
+"use client";
+import { useMemo, useState } from "react";
+import { FolderOpen, Link2, Trash2 } from "lucide-react";
+import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType } from "@/lib/contracts/workflow-graph";
+import { WORKFLOW_GRAPH_NODE_TYPES } from "@/lib/contracts/workflow-graph";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { openWindow } from "@/features/appshell";
+import { resolveNode } from "../lib/api";
+
+export function WorkflowInspector({ graph, node, onNode, onDeleteNode, onGraph }: {
+ graph: WorkflowGraph; node: WorkflowGraphNode | null;
+ onNode: (node: WorkflowGraphNode) => void; onDeleteNode: (id: string) => void; onGraph: (graph: WorkflowGraph) => void;
+}) {
+ const [configText, setConfigText] = useState(node ? JSON.stringify(node.config, null, 2) : "{}");
+ const [target, setTarget] = useState("");
+ const outgoing = useMemo(() => node ? graph.edges.filter((edge) => edge.source === node.id) : [], [graph.edges, node]);
+ if (!node) return <div className="p-4 text-xs text-muted-foreground">Select a node to edit config, edges, or open project folders.</div>;
+ const patch = (next: Partial<WorkflowGraphNode>) => onNode({ ...node, ...next });
+ const applyConfig = () => { try { patch({ config: JSON.parse(configText) as Record<string, unknown> }); } catch { /* keep draft text */ } };
+ const addEdge = () => {
+ if (!target || target === node.id) return;
+ const id = `edge-${crypto.randomUUID().slice(0, 8)}`;
+ onGraph({ ...graph, edges: [...graph.edges, { id, source: node.id, target }] }); setTarget("");
+ };
+ const openTarget = async () => {
+ const resolved = await resolveNode(graph.id, node.id);
+ openWindow("files-manager", resolved.name, undefined, { path: resolved.path }, { multi: true });
+ };
+ return <div className="space-y-4 p-3 text-xs">
+ <div><label className="mb-1 block text-muted-foreground">Name</label><Input value={node.name} onChange={(e) => patch({ name: e.target.value })} /></div>
+ <div><label className="mb-1 block text-muted-foreground">Type</label><select className="h-9 w-full rounded-md border bg-background px-2" value={node.type} onChange={(e) => patch({ type: e.target.value as WorkflowGraphNodeType })}>{WORKFLOW_GRAPH_NODE_TYPES.map((type) => <option key={type} value={type}>{type}</option>)}</select></div>
+ <div><label className="mb-1 block text-muted-foreground">Config JSON</label><Textarea className="min-h-36 font-mono text-[11px]" value={configText} onChange={(e) => setConfigText(e.target.value)} onBlur={applyConfig} /></div>
+ {(node.type === "project" || node.type === "folder") && <Button variant="secondary" size="sm" className="w-full" onClick={() => void openTarget()}><FolderOpen className="mr-2 size-3" />Open real folder</Button>}
+ <div className="space-y-2"><div className="font-medium">Outgoing edges</div>{outgoing.map((edge) => <div key={edge.id} className="flex items-center justify-between rounded border p-2"><span className="truncate">→ {graph.nodes.find((item) => item.id === edge.target)?.name ?? edge.target}</span><Button size="icon" variant="ghost" onClick={() => onGraph({ ...graph, edges: graph.edges.filter((item) => item.id !== edge.id) })}><Trash2 className="size-3" /></Button></div>)}
+ <div className="flex gap-1"><select className="h-8 min-w-0 flex-1 rounded-md border bg-background px-2" value={target} onChange={(e) => setTarget(e.target.value)}><option value="">Connect to…</option>{graph.nodes.filter((item) => item.id !== node.id).map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select><Button size="sm" variant="outline" onClick={addEdge}><Link2 className="size-3" /></Button></div>
+ </div>
+ <Button variant="destructive" size="sm" className="w-full" onClick={() => onDeleteNode(node.id)}><Trash2 className="mr-2 size-3" />Delete node</Button>
+ </div>;
+}
diff --git a/frontend/slices/workflows/components/workflow-run-panel.tsx b/frontend/slices/workflows/components/workflow-run-panel.tsx
new file mode 100644
index 00000000..36ab8c41
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-run-panel.tsx
@@ -0,0 +1,14 @@
+"use client";
+import type { WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+import { ScrollArea } from "@/components/ui/scroll-area";
+
+export function WorkflowRunPanel({ run }: { run: WorkflowGraphRun | null }) {
+ if (!run) return <div className="p-4 text-xs text-muted-foreground">Run a workflow to inspect node-by-node receipts.</div>;
+ return <ScrollArea className="h-full"><div className="space-y-2 p-3">
+ <div className="rounded-lg border p-3 text-xs"><div className="font-semibold">{run.graphName}</div><div className="mt-1 text-muted-foreground">{run.state}{run.failedNodeName ? ` · failed at ${run.failedNodeName}` : ""}</div></div>
+ {run.nodes.map((node) => <details key={node.id} className="rounded-lg border p-2" open={node.state === "failed"}>
+ <summary className="cursor-pointer text-xs font-medium">{node.name} <span className="text-muted-foreground">· {node.state}{node.durationMs != null ? ` · ${node.durationMs}ms` : ""}</span></summary>
+ <div className="mt-2 space-y-1 font-mono text-[10px] text-muted-foreground">{node.logs.map((log, i) => <div key={i}>{log}</div>)}{node.error && <div>{node.error}</div>}{node.output !== undefined && <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-muted p-2">{JSON.stringify(node.output, null, 2)}</pre>}</div>
+ </details>)}
+ </div></ScrollArea>;
+}
diff --git a/frontend/slices/workflows/index.ts b/frontend/slices/workflows/index.ts
new file mode 100644
index 00000000..4430cf16
--- /dev/null
+++ b/frontend/slices/workflows/index.ts
@@ -0,0 +1,11 @@
+import { Workflow } from "lucide-react";
+import type { AppDescriptor } from "@/features/appshell";
+
+export const workflowsApp: AppDescriptor = {
+ id: "workflows",
+ title: "Workflows",
+ icon: Workflow,
+ gradient: "var(--primary)",
+ load: () => import("./app"),
+ defaultSize: { w: 1180, h: 760 },
+};
diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.ts
new file mode 100644
index 00000000..4fb3adaf
--- /dev/null
+++ b/frontend/slices/workflows/lib/api.ts
@@ -0,0 +1,21 @@
+import type { WorkflowGraph, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+
+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 ?? {}) } });
+ const 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;
+}
+
+export async function listGraphs(): Promise<WorkflowGraph[]> { return (await json<{ graphs: WorkflowGraph[] }>("/api/v1/workflows")).graphs; }
+export async function getGraph(id: string): Promise<WorkflowGraph> { return (await json<{ graph: WorkflowGraph }>(`/api/v1/workflows?graph_id=${encodeURIComponent(id)}`)).graph; }
+export async function createGraph(graph: unknown): Promise<WorkflowGraph> { return (await json<{ graph: WorkflowGraph }>("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "create", graph }) })).graph; }
+export async function updateGraph(graph: WorkflowGraph): Promise<WorkflowGraph> {
+ const { revision, createdAt: _createdAt, updatedAt: _updatedAt, version: _version, ...definition } = graph;
+ return (await json<{ graph: WorkflowGraph }>("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "update", graph_id: graph.id, expected_revision: revision, graph: definition }) })).graph;
+}
+export async function deleteGraph(graph: WorkflowGraph): Promise<void> { await json("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "delete", graph_id: graph.id, expected_revision: graph.revision }) }); }
+export async function cloneGraph(id: string): Promise<WorkflowGraph> { return (await json<{ graph: WorkflowGraph }>("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "clone", graph_id: id }) })).graph; }
+export async function runGraph(id: string): Promise<WorkflowGraphRun & { pollAfterMs?: number }> { return json("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "run", graph_id: id, input: {}, idempotency_key: `ui-${Date.now()}-${Math.random().toString(36).slice(2, 8)}` }) }); }
+export async function runStatus(id: string): Promise<WorkflowGraphRun & { pollAfterMs?: number }> { return json(`/api/v1/workflows?run_id=${encodeURIComponent(id)}&wait_ms=1500`); }
+export async function resolveNode(graphId: string, nodeId: string): Promise<{ project: string; name: string; path: string; relativePath: string }> { return json(`/api/v1/workflows?graph_id=${encodeURIComponent(graphId)}&node_id=${encodeURIComponent(nodeId)}&resolve=target`); }
diff --git a/lib/contracts/workflow-graph.ts b/lib/contracts/workflow-graph.ts
new file mode 100644
index 00000000..89f46f33
--- /dev/null
+++ b/lib/contracts/workflow-graph.ts
@@ -0,0 +1,85 @@
+export const WORKFLOW_GRAPH_NODE_TYPES = [
+ "manual", "tool", "project_function", "project_mcp", "script", "agent", "subflow",
+ "condition", "project", "folder", "skill", "knowledge", "output",
+] as const;
+export type WorkflowGraphNodeType = (typeof WORKFLOW_GRAPH_NODE_TYPES)[number];
+export type WorkflowGraphStatus = "draft" | "active" | "archived";
+
+export type WorkflowGraphNode = {
+ id: string;
+ name: string;
+ type: WorkflowGraphNodeType;
+ position: { x: number; y: number };
+ config: Record<string, unknown>;
+ disabled?: boolean;
+};
+
+export type WorkflowGraphEdge = {
+ id: string;
+ source: string;
+ target: string;
+ sourceHandle?: string;
+ targetHandle?: string;
+};
+
+export type WorkflowGraphMetadata = {
+ intent?: string;
+ normalizedIntent?: string;
+ project?: string;
+ provenance?: "user" | "learned-from-session" | "clone" | "import";
+ fingerprint?: string;
+ sourceDigests?: string[];
+ tags?: string[];
+};
+
+export type WorkflowGraph = {
+ version: 2;
+ id: string;
+ name: string;
+ description: string;
+ status: WorkflowGraphStatus;
+ inputs: Record<string, unknown>;
+ nodes: WorkflowGraphNode[];
+ edges: WorkflowGraphEdge[];
+ metadata: WorkflowGraphMetadata;
+ createdAt: string;
+ updatedAt: string;
+ revision: string;
+};
+
+export type WorkflowGraphNodeState = "queued" | "running" | "completed" | "failed" | "skipped" | "blocked";
+export type WorkflowGraphRunNode = {
+ id: string;
+ name: string;
+ type: WorkflowGraphNodeType;
+ state: WorkflowGraphNodeState;
+ startedAt?: string;
+ finishedAt?: string;
+ durationMs?: number;
+ input?: unknown;
+ output?: unknown;
+ error?: string;
+ logs: string[];
+};
+
+export type WorkflowGraphRun = {
+ version: 1;
+ id: string;
+ owner: string;
+ sessionId: string;
+ graphId: string;
+ graphRevision: string;
+ graphName: string;
+ idempotencyKey: string;
+ fingerprint: string;
+ state: "running" | "completed" | "failed" | "interrupted";
+ startedAt: string;
+ updatedAt: string;
+ finishedAt?: string;
+ failedNodeId?: string;
+ failedNodeName?: string;
+ error?: string;
+ pid: number;
+ instance: string;
+ nodes: WorkflowGraphRunNode[];
+};
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index fa98f2e4..acc895ff 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -21,6 +21,10 @@ const ALFA_ONLY: Record<string, string> = {
};
const MCP_ONLY: Record<string, string> = {
+ "workflow.graph.catalog": "Native Workflows UI uses the private REST surface; MCP agents need a principal-scoped catalog without inheriting an unrelated Alfa browser-thread identity.",
+ "workflow.graph.manage": "Workflow graph CRUD is exposed natively by the Workflows app and separately to MCP principals; sharing Alfa thread identity would collapse the deliberate principal boundary.",
+ "workflow.graph.run": "Server-native graph execution is principal/idempotency scoped; Alfa uses the native Workflows app rather than claiming an external MCP workflow principal.",
+ "workflow.graph.status": "Per-node graph receipts belong to the exact workflow principal; the native Workflows app has its own authenticated receipt surface.",
"flow.catalog": "Project API/MCP automation belongs to the external/CLI session context; Alfa has its own browser workflow identity.",
"flow.run": "Provider mutations require the durable external principal, exact connection, and idempotency receipt; owner CLI shares this executor.",
"flow.status": "Flow receipts belong to their authenticated external/CLI principal; Alfa must not inherit that principal.",
@@ -165,7 +169,7 @@ describe("MCP rate limits mirror the routes", () => {
"fs.delete": 60, "fs.upload": 20, "exec": 60, "managed-app": 12, "camoufox": 12,
};
const MCP_NATIVE_LIMITS: Record<string, number> = {
- "flow.run": 20, "flow.manage": 20, "agent.session.open": 20, "project.mcp.manage": 20, "project.asset.attach": 20,
+ "flow.run": 20, "flow.manage": 20, "workflow.graph.manage": 30, "workflow.graph.run": 20, "agent.session.open": 20, "project.mcp.manage": 20, "project.asset.attach": 20,
// Native capabilities have independent bounded buckets (no matching HTTP route).
"screen.capture": 10,
"fs.export": 20,
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
index fe3c735a..ad741d9a 100644
--- a/lib/mcp/tools-flows.ts
+++ b/lib/mcp/tools-flows.ts
@@ -3,8 +3,16 @@ import { startFlow, flowStatus } from "@/lib/workflow/automation-engine";
import { BUILTIN_FLOWS } from "@/lib/workflow/automation-builtins";
import { manageProjectFlow } from "@/lib/host/project-flow-manifest";
import { type McpTool, S, str } from "./tool-kit";
+import { cloneWorkflowGraph, createWorkflowGraph, deleteWorkflowGraph, getWorkflowGraph, listWorkflowGraphs, updateWorkflowGraph } from "@/lib/workflow/graph-store";
+import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";
const project = { type: "string", maxLength: 4096, description: "Exact project id/path/name." };
const flow = { type: "string", maxLength: 64, description: "Flow id from flow_catalog." };
+
+function privateGraphPrincipal(context: Parameters<McpTool["run"]>[1]): string {
+ const principal = context.recipeActor ?? context.workflowActor ?? context.actor ?? context.principal;
+ if (!principal) throw new Error("workflow graph requires an authenticated principal");
+ return principal;
+}
export const FLOW_TOOLS: McpTool[] = [
{ name: "flow_catalog", title: "Discover Automation Flows", scope: "read",
description: "Discover reusable API/MCP flows for an exact project. Returns input schema, ordered steps, account context and required scope. Inspect a flow before flow_run; project flows live in .mso/flows.json.",
@@ -41,4 +49,46 @@ export const FLOW_TOOLS: McpTool[] = [
const catalog = await flowCatalog(str(a, "project"));
return manageProjectFlow(catalog.project.path, { action: a.action, id, flow: a.definition, revision: str(a, "revision") });
} },
+ { name: "workflow_graph_catalog", title: "Workflow Graph Catalog", scope: "read",
+ description: "List private Workflow Graph v2 definitions for this authenticated principal, or inspect one exact graph. Graphs are isolated per principal and never contain provider secrets.",
+ chatgptDescription: "List or inspect this user's private n8n-like workflow graphs before managing/running one.",
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
+ inputSchema: S({ graph_id: { type: "string", maxLength: 96 } }),
+ run: async (a, context) => {
+ const principal = privateGraphPrincipal(context);
+ if (typeof a.graph_id === "string" && a.graph_id) { const graph = await getWorkflowGraph(principal, a.graph_id); if (!graph) throw new Error("workflow graph not found"); return { graph }; }
+ const graphs = await listWorkflowGraphs(principal);
+ return { graphs: graphs.map(graph => ({ id: graph.id, name: graph.name, description: graph.description, status: graph.status, revision: graph.revision, nodeCount: graph.nodes.length, updatedAt: graph.updatedAt, provenance: graph.metadata.provenance, project: graph.metadata.project })) };
+ } },
+ { name: "workflow_graph_manage", title: "Manage Workflow Graph", scope: "write", limit: { key: "workflow.graph.manage", max: 30, windowMs: 60_000 },
+ description: "Create, update, clone or delete one private Workflow Graph v2 definition. Updates/deletes require expected_revision. Definitions are metadata-only; secret-like fields are rejected.",
+ chatgptDescription: "CRUD a private n8n-like workflow graph with revision conflict protection.",
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }, audit: { action: "fs.write", targetArg: "graph_id" },
+ inputSchema: S({ action: { type: "string", enum: ["create", "update", "delete", "clone"] }, graph_id: { type: "string", maxLength: 96 }, expected_revision: { type: "string", maxLength: 128 }, definition: { type: "object", additionalProperties: true } }, ["action"]),
+ run: async (a, context) => {
+ const principal = privateGraphPrincipal(context), action = str(a, "action");
+ if (action === "create") return { graph: await createWorkflowGraph(principal, a.definition) };
+ const id = str(a, "graph_id");
+ if (action === "clone") return { graph: await cloneWorkflowGraph(principal, id) };
+ if (action === "update") return { graph: await updateWorkflowGraph(principal, id, str(a, "expected_revision"), a.definition) };
+ if (action === "delete") return deleteWorkflowGraph(principal, id, str(a, "expected_revision"));
+ throw new Error("unsupported workflow graph action");
+ } },
+ { name: "workflow_graph_run", title: "Run Workflow Graph", scope: "exec", limit: { key: "workflow.graph.run", max: 20, windowMs: 60_000 },
+ description: "Run one inspected private Workflow Graph v2 with exact input/idempotency key. Execution remains bounded by normal capability scopes and returns a durable per-node receipt.",
+ chatgptDescription: "Run a private workflow graph and return the per-node run receipt id.",
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, audit: { action: "exec.run", targetArg: "graph_id" },
+ inputSchema: S({ graph_id: { type: "string", maxLength: 96 }, input: { type: "object", additionalProperties: true }, idempotency_key: { type: "string", minLength: 1, maxLength: 128 } }, ["graph_id", "input", "idempotency_key"]),
+ run: async (a, context) => {
+ const principal = privateGraphPrincipal(context), graph = await getWorkflowGraph(principal, str(a, "graph_id"));
+ if (!graph) throw new Error("workflow graph not found");
+ const { TOOLS_BY_NAME } = await import("./tools");
+ return startWorkflowGraph(graph, a.input, str(a, "idempotency_key"), context, name => TOOLS_BY_NAME.get(name), principal);
+ } },
+ { name: "workflow_graph_status", title: "Workflow Graph Run Status", scope: "read",
+ description: "Read a private Workflow Graph v2 run receipt with node states, logs, durations and failed-node identity. Optional wait_ms reduces polling.",
+ chatgptDescription: "Read node-by-node workflow graph status/logs and identify the failed node.",
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
+ inputSchema: S({ run_id: { type: "string", pattern: "^[a-f0-9]{32}$" }, wait_ms: { type: "integer", minimum: 0, maximum: 25_000 } }, ["run_id"]),
+ run: (a, context) => workflowGraphRunStatus(privateGraphPrincipal(context), str(a, "run_id"), Number(a.wait_ms) || 0) },
];
diff --git a/lib/mcp/tools-workflow-start.ts b/lib/mcp/tools-workflow-start.ts
index d257f273..8b2af407 100644
--- a/lib/mcp/tools-workflow-start.ts
+++ b/lib/mcp/tools-workflow-start.ts
@@ -1,6 +1,7 @@
import { ownedArtifactSession, prepareSessionArtifacts } from "@/lib/agent/artifact-session";
import { inspectProject, readProjectKnowledge, resolveProjectHint } from "@/lib/host/projects-api";
-import { markRecipeUsed, startWorkflow, summarizeProjectContention } from "@/lib/workflow";
+import { listLearnedRecipes, markRecipeUsed, startWorkflow, summarizeProjectContention } from "@/lib/workflow";
+import { ensureLearnedWorkflowGraph, findMatchingWorkflowGraph } from "@/lib/workflow/graph-store";
import { searchSkillMemory } from "@/lib/skills/search";
import { progressiveVerification } from "@/lib/orchestration/automation";
import { routeIntentText } from "@/lib/orchestration/capability-catalog.mjs";
@@ -49,10 +50,6 @@ export const WORKFLOW_START_TOOL: McpTool =
const routedTools = intentRoute.catalogMatched
? tools.filter((tool) => intentRoute.tools.includes(tool.name) || tool.name === "workflow_start")
: tools;
- // Complete every fallible read-only preflight before allocating the run id.
- // A catalog hit narrows tool discovery before semantic search, so known intents
- // do not pay to score/return the entire tool catalog. Skills and learned recipes
- // remain globally searchable because they are content, not model tool schemas.
const search = await searchSkillMemory(intent, {
topK: intentRoute.catalogMatched ? 5 : 7,
recipeAccess: { actor: recipeOwner, scope: context.scope },
@@ -84,6 +81,13 @@ export const WORKFLOW_START_TOOL: McpTool =
const reusableScript = project && search.recommendedRecipe
? await readAutomationScript(project.path, `script_${search.recommendedRecipe.id}`).catch(() => null)
: null;
+ const projectKeys = [project?.id, project?.path, project?.name, projectHint].filter((value): value is string => Boolean(value));
+ let graphAutomation = await findMatchingWorkflowGraph(recipeOwner, intent, projectKeys).catch(() => null);
+ if (!graphAutomation && search.recommendedRecipe) {
+ const fullRecipe = (await listLearnedRecipes({ actor: recipeOwner, scope: context.scope }))
+ .find((recipe) => recipe.id === search.recommendedRecipe?.id);
+ if (fullRecipe) graphAutomation = await ensureLearnedWorkflowGraph(fullRecipe).catch(() => null);
+ }
const recipePlan = search.recommendedRecipe ? {
id: search.recommendedRecipe.id,
attempts: search.recommendedRecipe.attempts ?? 0,
@@ -131,9 +135,6 @@ export const WORKFLOW_START_TOOL: McpTool =
createdAt: new Date().toISOString(),
};
const toolset = toolsetInfo(tools, context.scope, context.toolProfile);
- // Discovery incompleteness travels WITH the bootstrap. A model told "here is the
- // project and the trusted skills" will not re-check whether the scan covered the
- // whole box; if it did not, it has to be told in the same breath.
const discovery = {
catalog: search.catalog,
complete: !search.catalog.truncated,
@@ -146,8 +147,6 @@ export const WORKFLOW_START_TOOL: McpTool =
constraints: opt(a, "constraints"),
orchestration,
});
- // Recommendation telemetry is useful, but failure to persist lastUsedAt must
- // never turn a successfully-created workflow into an opaque tool failure.
if (search.recommendedRecipe) {
await markRecipeUsed(search.recommendedRecipe.id, { actor: recipeOwner, scope: context.scope }).catch(() => undefined);
}
@@ -167,12 +166,20 @@ export const WORKFLOW_START_TOOL: McpTool =
classification,
verificationPlan: progressiveVerification(classification.risk),
recipe: recipePlan,
- automation: reusableScript ? {
- scriptId: reusableScript.id, status: reusableScript.status,
- instruction: reusableScript.status === "tested"
- ? "Prefer project_script_run before replanning this deterministic repeated route."
- : "Run project_script_run once to verify this bounded candidate; success promotes it to tested.",
- } : undefined,
+ automation: {
+ ...(graphAutomation ? {
+ graph: { id: graphAutomation.id, name: graphAutomation.name, status: graphAutomation.status, revision: graphAutomation.revision, provenance: graphAutomation.metadata.provenance },
+ graphInstruction: graphAutomation.status === "active"
+ ? "A private workflow graph already matches this task. Prefer it before replanning when current evidence is compatible."
+ : "A private learned/user draft matches this task. Inspect it before activation/run; normal authorization still applies.",
+ } : {}),
+ ...(reusableScript ? {
+ scriptId: reusableScript.id, status: reusableScript.status,
+ instruction: reusableScript.status === "tested"
+ ? "Prefer project_script_run before replanning this deterministic repeated route."
+ : "Run project_script_run once to verify this bounded candidate; success promotes it to tested.",
+ } : {}),
+ },
memory: repoMemory.map((hit) => ({
id: hit.record.id, kind: hit.record.kind, title: hit.record.title, summary: hit.record.summary,
status: hit.record.status, score: hit.score, lastVerified: hit.record.lastVerified,
@@ -186,6 +193,7 @@ export const WORKFLOW_START_TOOL: McpTool =
`[Knowledge] ${projectKnowledge?.exists ? `${projectKnowledge.bytes} bytes always-on` : "not configured"}`,
`[Memory] ${repoMemory.length} repo-local hit(s) · ${search.recommendedRecipe ? "recipe available" : "no verified recipe selected"} · ~${contextEstimateTokens} context tokens`,
...(recipePlan ? [`[Recipe] ${recipePlan.attempts} attempts · ${recipePlan.successRate}% success · ${recipePlan.steps.length} reusable step(s)`] : []),
+ ...(graphAutomation ? [`[Workflow graph] ${graphAutomation.status} · ${graphAutomation.name} · ${graphAutomation.metadata.provenance ?? "private"}`] : [`[Workflow graph] no matching private graph; successful completion will seed a learned draft`]),
...(reusableScript ? [`[Automation] ${reusableScript.status} script ${reusableScript.id} available`] : []),
...(contention.conflictingWorkflowCount ? [`[Collision] ${contention.conflictingWorkflowCount} workflow(s) overlap declared paths/resources`] : []),
...(discovery.complete ? [] : [`[Discovery] partial scan — ${search.catalog.truncationReasons.join(", ")}; do not conclude something is absent`]),
diff --git a/lib/orchestration/capability-catalog.mjs b/lib/orchestration/capability-catalog.mjs
index fce71c58..c72621db 100644
--- a/lib/orchestration/capability-catalog.mjs
+++ b/lib/orchestration/capability-catalog.mjs
@@ -1,5 +1,5 @@
const ROUTES = [
- { id: "automation-flow", priority: 105, patterns: [/\b(automation flow|flow_catalog|flow_run|mso flow|reusable flow|alur otomatis|otomasi provider)\b/i], tools: ["flow_catalog", "flow_run", "flow_status", "flow_manage", "integration_query"], budget: 10_000 },
+ { id: "automation-flow", priority: 105, patterns: [/\b(automation flow|workflow graph|workflow|flow_catalog|flow_run|mso flow|reusable flow|alur otomatis|otomasi provider|n8n)\b/i], tools: ["workflow_graph_catalog", "workflow_graph_run", "workflow_graph_status", "workflow_graph_manage", "flow_catalog", "flow_run", "flow_status", "flow_manage", "integration_query"], budget: 12_000 },
{ id: "project-mcp-add", priority: 105, patterns: [/\b(add|connect|tambah|pasang)\b.{0,30}\bmcp\b/i], tools: ["project_mcp_manage", "project_mcp_tools", "integration_query", "integration_setup_open"], budget: 10_000 },
{ id: "project-asset", priority: 105, patterns: [/\b(attach|save|kirim|simpan)\b.{0,40}\b(asset|image|gambar)\b.{0,30}\b(project|proyek)\b/i], tools: ["session_artifacts", "project_asset_attach"], budget: 8_000 },
{ id: "managed-app-diagnostics", priority: 100, patterns: [/\b(hermes|openclaw|managed app|service)\b.*\b(down|error|crash|logs?|journal|status)\b/i, /\b(logs?|journal)\b.*\b(hermes|openclaw|service)\b/i], tools: ["apps_list", "apps_logs"], budget: 8_000 },
diff --git a/lib/workflow/graph-engine.test.ts b/lib/workflow/graph-engine.test.ts
new file mode 100644
index 00000000..11f465c9
--- /dev/null
+++ b/lib/workflow/graph-engine.test.ts
@@ -0,0 +1,49 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { CapabilityTool } from "@/lib/capabilities/tool";
+
+vi.mock("@/lib/capabilities/execute", () => ({ executeCapabilityCall: async ({ tool, args, context }: { tool: CapabilityTool; args: Record<string, unknown>; context: never }) => {
+ try { return { kind: "success", result: await tool.run(args, context) }; } catch (error) { return { kind: "error", message: error instanceof Error ? error.message : String(error) }; }
+} }));
+const dir = await mkdtemp(path.join(os.tmpdir(), "mso-graph-engine-"));
+process.env.OS_AGENT_SESSIONS_DIR = dir;
+const { createWorkflowGraph } = await import("./graph-store");
+const { startWorkflowGraph, workflowGraphRunStatus } = await import("./graph-engine");
+const context = { principal: "graph-owner", sessionId: "session", scope: "exec" as const, actor: "graph-owner" };
+afterAll(() => rm(dir, { recursive: true, force: true }));
+
+describe("workflow graph engine", () => {
+ it("routes a condition branch and marks the other branch skipped", async () => {
+ const graph = await createWorkflowGraph("graph-owner", { name: "Branch", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "check", name: "Check", type: "condition", position: { x: 100, y: 0 }, config: { path: "input.ok" } },
+ { id: "yes", name: "Yes", type: "output", position: { x: 200, y: 0 }, config: { value: "yes" } },
+ { id: "no", name: "No", type: "output", position: { x: 200, y: 100 }, config: { value: "no" } },
+ ], edges: [
+ { id: "a", source: "start", target: "check" }, { id: "b", source: "check", target: "yes", sourceHandle: "true" }, { id: "c", source: "check", target: "no", sourceHandle: "false" },
+ ] });
+ const started = await startWorkflowGraph(graph, { ok: true }, "branch-once", context, () => undefined);
+ const done = await workflowGraphRunStatus("graph-owner", started.id, 5000);
+ expect(done.state).toBe("completed");
+ expect(done.nodes.find((node) => node.id === "yes")?.state).toBe("completed");
+ expect(done.nodes.find((node) => node.id === "no")?.state).toBe("skipped");
+ });
+ it("pinpoints the failed node and blocks downstream nodes", async () => {
+ const graph = await createWorkflowGraph("graph-owner", { name: "Failure", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "start2", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "bad", name: "Broken tool", type: "tool", position: { x: 100, y: 0 }, config: { tool: "fixture_fail", arguments: {} } },
+ { id: "after", name: "After", type: "output", position: { x: 200, y: 0 }, config: {} },
+ ], edges: [{ id: "d", source: "start2", target: "bad" }, { id: "e", source: "bad", target: "after" }] });
+ const tool: CapabilityTool = { name: "fixture_fail", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: async () => { throw new Error("fixture exploded"); } };
+ const started = await startWorkflowGraph(graph, {}, "fail-once", context, (name) => name === tool.name ? tool : undefined);
+ const done = await workflowGraphRunStatus("graph-owner", started.id, 5000);
+ expect(done.state).toBe("failed"); expect(done.failedNodeId).toBe("bad"); expect(done.failedNodeName).toBe("Broken tool");
+ expect(done.nodes.find((node) => node.id === "after")?.state).toBe("blocked");
+ expect(done.nodes.find((node) => node.id === "bad")?.logs.join(" ")).toContain("fixture exploded");
+ });
+ it("keeps run receipts private to the principal", async () => {
+ await expect(workflowGraphRunStatus("another-owner", "0".repeat(32))).rejects.toThrow("not found");
+ });
+});
diff --git a/lib/workflow/graph-engine.ts b/lib/workflow/graph-engine.ts
new file mode 100644
index 00000000..7f8edb58
--- /dev/null
+++ b/lib/workflow/graph-engine.ts
@@ -0,0 +1,115 @@
+import { createHash, randomUUID } from "node:crypto";
+import type { CapabilityRunContext, CapabilityTool } from "@/lib/capabilities/tool";
+import type { WorkflowGraph, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+import { redactText } from "@/lib/security/redact-text";
+import { assertWorkflowMetadataOnly, graphObject } from "./graph-schema";
+import { workflowGraphOwner } from "./graph-store";
+import { compact, executeNode } from "./graph-runtime";
+import { lockWorkflowGraphRun, pruneWorkflowGraphRuns, publicWorkflowGraphRun, readWorkflowGraphRun, writeWorkflowGraphRun } from "./graph-run-store";
+
+const state = globalThis as typeof globalThis & { msoGraphInstance?: string; msoGraphPending?: Map<string, Promise<void>> };
+const INSTANCE = state.msoGraphInstance ??= randomUUID();
+const pending = state.msoGraphPending ??= new Map<string, Promise<void>>();
+type Resolver = (name: string) => CapabilityTool | undefined;
+
+function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
+function canonical(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
+ if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => `${JSON.stringify(key)}:${canonical(child)}`).join(",")}}`;
+ return JSON.stringify(value);
+}
+function inputObject(raw: unknown): Record<string, unknown> {
+ if (!graphObject(raw) || Buffer.byteLength(JSON.stringify(raw)) > 64 * 1024) throw new Error("workflow graph input must be an object up to 64 KiB");
+ assertWorkflowMetadataOnly(raw); return structuredClone(raw);
+}
+
+async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<void> {
+ const rows = new Map(run.nodes.map((row) => [row.id, row])), outputs: Record<string, unknown> = {};
+ const edgeState = new Map(graph.edges.map((edge) => [edge.id, "pending" as "pending" | "enabled" | "disabled"]));
+ const incoming = new Map(graph.nodes.map((node) => [node.id, graph.edges.filter((edge) => edge.target === node.id)]));
+ const outgoing = new Map(graph.nodes.map((node) => [node.id, graph.edges.filter((edge) => edge.source === node.id)]));
+ const disableOutgoing = (nodeId: string) => { for (const edge of outgoing.get(nodeId) ?? []) if (edgeState.get(edge.id) === "pending") edgeState.set(edge.id, "disabled"); };
+ const resolveOutgoing = (nodeId: string, branch?: boolean) => {
+ for (const edge of outgoing.get(nodeId) ?? []) {
+ if (branch === undefined || !edge.sourceHandle) edgeState.set(edge.id, "enabled");
+ else edgeState.set(edge.id, edge.sourceHandle === String(branch) ? "enabled" : "disabled");
+ }
+ };
+
+ try {
+ let remaining = new Set(graph.nodes.map((node) => node.id));
+ while (remaining.size) {
+ if (Date.now() - Date.parse(run.startedAt) > 15 * 60_000) throw new Error("workflow graph exceeded 15 minutes; remaining nodes were not started");
+ let progressed = false;
+ for (const node of graph.nodes) {
+ if (!remaining.has(node.id)) continue;
+ const deps = incoming.get(node.id) ?? [];
+ if (deps.some((edge) => edgeState.get(edge.id) === "pending")) continue;
+ const row = rows.get(node.id)!;
+ if (node.disabled || (deps.length > 0 && deps.every((edge) => edgeState.get(edge.id) === "disabled"))) {
+ row.state = "skipped"; row.finishedAt = new Date().toISOString(); row.logs.push(node.disabled ? "Node disabled by workflow definition." : "Skipped because no incoming branch was selected.");
+ disableOutgoing(node.id); remaining.delete(node.id); progressed = true; run.updatedAt = new Date().toISOString(); await writeWorkflowGraphRun(run); continue;
+ }
+ row.state = "running"; row.startedAt = new Date().toISOString(); row.logs.push("Node started."); run.updatedAt = row.startedAt; await writeWorkflowGraphRun(run);
+ const started = Date.now();
+ try {
+ const result = await executeNode(node, run, graph, input, outputs, context, resolve);
+ row.output = compact(result.output); row.state = "completed"; outputs[node.id] = result.output;
+ if (result.log) row.logs.push(result.log); resolveOutgoing(node.id, result.branch);
+ } catch (error) {
+ row.state = "failed"; row.error = redactText(error instanceof Error ? error.message : "node failed", 800); row.logs.push(row.error);
+ run.failedNodeId = node.id; run.failedNodeName = node.name; run.error = row.error; run.state = "failed";
+ for (const pendingId of remaining) {
+ if (pendingId === node.id) continue;
+ const blocked = rows.get(pendingId)!; if (blocked.state === "queued") { blocked.state = "blocked"; blocked.logs.push(`Blocked by failed node ${node.name}.`); }
+ }
+ throw error;
+ } finally {
+ row.durationMs = Date.now() - started; row.finishedAt = new Date().toISOString(); run.updatedAt = row.finishedAt; await writeWorkflowGraphRun(run);
+ }
+ remaining.delete(node.id); progressed = true;
+ }
+ if (!progressed && remaining.size) throw new Error("workflow graph could not make progress; inspect dependencies/branches");
+ }
+ run.state = "completed";
+ } catch (error) {
+ if (run.state !== "failed") { run.state = "failed"; run.error = redactText(error instanceof Error ? error.message : "workflow graph failed", 800); }
+ }
+ run.finishedAt = run.updatedAt = new Date().toISOString(); await writeWorkflowGraphRun(run);
+}
+
+export async function startWorkflowGraph(graph: WorkflowGraph, rawInput: unknown, idempotencyKey: string, context: CapabilityRunContext, resolve: Resolver, storagePrincipal?: string) {
+ if (!(storagePrincipal ?? context.principal) || !context.sessionId) throw new Error("workflow graph requires an authenticated principal/session");
+ if (graph.status === "archived") throw new Error("archived workflow graph cannot run");
+ if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey)) throw new Error("idempotency_key must be 1-128 simple characters");
+ const owner = workflowGraphOwner(storagePrincipal ?? context.principal!), input = inputObject(rawInput), fingerprint = hash(canonical({ graphId: graph.id, revision: graph.revision, input }));
+ const id = hash(`${owner}:${idempotencyKey}`).slice(0, 32);
+ return lockWorkflowGraphRun(owner, id, async () => {
+ const existing = await readWorkflowGraphRun(owner, id);
+ if (existing) { if (existing.fingerprint !== fingerprint) throw new Error("idempotency_key already identifies a different graph/input/revision"); return publicWorkflowGraphRun(existing); }
+ await pruneWorkflowGraphRuns(owner);
+ const run: WorkflowGraphRun = {
+ version: 1, id, owner, sessionId: context.sessionId!, graphId: graph.id, graphRevision: graph.revision, graphName: graph.name,
+ idempotencyKey, fingerprint, state: "running", startedAt: new Date().toISOString(), updatedAt: new Date().toISOString(), pid: process.pid, instance: INSTANCE,
+ nodes: graph.nodes.map((node) => ({ id: node.id, name: node.name, type: node.type, state: "queued", logs: [] })),
+ };
+ await writeWorkflowGraphRun(run);
+ const work = execute(run, graph, input, context, resolve).catch(() => undefined).finally(() => pending.delete(id)); pending.set(id, work);
+ return publicWorkflowGraphRun(run);
+ });
+}
+
+export async function workflowGraphRunStatus(principal: string, id: string, waitMs = 0) {
+ if (!Number.isSafeInteger(waitMs) || waitMs < 0 || waitMs > 25_000) throw new Error("wait_ms must be 0-25000");
+ const owner = workflowGraphOwner(principal); let run = await readWorkflowGraphRun(owner, id);
+ if (!run) throw new Error("workflow graph run not found for this principal");
+ if (run.state === "running" && pending.has(id) && waitMs > 0) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([pending.get(id), new Promise((resolve) => { timer = setTimeout(resolve, waitMs); })]); clearTimeout(timer); run = await readWorkflowGraphRun(owner, id) ?? run;
+ }
+ if (run.state === "running" && run.instance !== INSTANCE) {
+ let gone = false; try { process.kill(run.pid, 0); } catch (error) { gone = (error as NodeJS.ErrnoException).code === "ESRCH"; }
+ if (gone) { run.state = "interrupted"; run.updatedAt = run.finishedAt = new Date().toISOString(); await writeWorkflowGraphRun(run); }
+ }
+ return publicWorkflowGraphRun(run);
+}
diff --git a/lib/workflow/graph-run-store.ts b/lib/workflow/graph-run-store.ts
new file mode 100644
index 00000000..1e2a6673
--- /dev/null
+++ b/lib/workflow/graph-run-store.ts
@@ -0,0 +1,66 @@
+import { randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { agentSessionsDir } from "@/lib/agent/session-paths";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import type { WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+
+const MAX_RUN_BYTES = 1024 * 1024;
+const MAX_RECEIPTS = 1000;
+
+function root(): string { return path.join(agentSessionsDir(), ".workflow-graph-runs"); }
+function file(owner: string, id: string): string {
+ if (!/^[a-f0-9]{64}$/.test(owner) || !/^[a-f0-9]{32}$/.test(id)) throw new Error("invalid workflow graph run identity");
+ return path.join(root(), owner, `${id}.json`);
+}
+async function ensureOwnerDir(owner: string): Promise<void> {
+ const dir = path.dirname(file(owner, "0".repeat(32)));
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ const stat = await fs.lstat(dir);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("unsafe workflow graph run directory");
+ await fs.chmod(dir, 0o700).catch(() => undefined);
+}
+
+export async function readWorkflowGraphRun(owner: string, id: string): Promise<WorkflowGraphRun | null> {
+ try {
+ const target = file(owner, id), stat = await fs.lstat(target);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_RUN_BYTES || (stat.mode & 0o077)) throw new Error("unsafe workflow graph run");
+ const parsed = JSON.parse(await fs.readFile(target, "utf8")) as WorkflowGraphRun;
+ if (parsed.version !== 1 || parsed.owner !== owner || parsed.id !== id || !Array.isArray(parsed.nodes)) throw new Error("invalid workflow graph run");
+ return parsed;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw error;
+ }
+}
+
+export async function writeWorkflowGraphRun(run: WorkflowGraphRun): Promise<void> {
+ await ensureOwnerDir(run.owner);
+ const target = file(run.owner, run.id), temp = `${target}.${randomUUID()}.tmp`, body = JSON.stringify(run);
+ if (Buffer.byteLength(body) > MAX_RUN_BYTES) throw new Error("workflow graph run receipt exceeds 1 MiB");
+ try {
+ await fs.writeFile(temp, body, { flag: "wx", mode: 0o600 });
+ await fs.rename(temp, target);
+ } finally { await fs.unlink(temp).catch(() => undefined); }
+}
+
+export function lockWorkflowGraphRun<T>(owner: string, id: string, fn: () => Promise<T>): Promise<T> {
+ return withSecurityStoreLock(file(owner, id), fn);
+}
+
+export async function pruneWorkflowGraphRuns(owner: string): Promise<void> {
+ await ensureOwnerDir(owner);
+ const dir = path.dirname(file(owner, "0".repeat(32))), entries = await fs.readdir(dir);
+ const receipts: Array<{ name: string; mtime: number }> = [];
+ for (const name of entries) {
+ if (!/^[a-f0-9]{32}\.json$/.test(name)) continue;
+ const stat = await fs.stat(path.join(dir, name)); receipts.push({ name, mtime: stat.mtimeMs });
+ }
+ receipts.sort((a, b) => b.mtime - a.mtime);
+ for (const old of receipts.slice(MAX_RECEIPTS - 1)) await fs.unlink(path.join(dir, old.name)).catch(() => undefined);
+}
+
+export function publicWorkflowGraphRun(run: WorkflowGraphRun) {
+ const { owner: _owner, pid: _pid, instance: _instance, sessionId: _sessionId, fingerprint: _fingerprint, ...safe } = run;
+ return { ...safe, pollAfterMs: run.state === "running" ? 1500 : 0 };
+}
diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.ts
new file mode 100644
index 00000000..ab315b9f
--- /dev/null
+++ b/lib/workflow/graph-runtime.ts
@@ -0,0 +1,138 @@
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { capabilityReportedFailure } from "@/lib/capabilities/result-outcome";
+import { executeCapabilityCall } from "@/lib/capabilities/execute";
+import { isCapabilityDirectResult, type CapabilityRunContext, type CapabilityTool } from "@/lib/capabilities/tool";
+import { boundedResultText } from "@/lib/capabilities/result-budget";
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphRun, WorkflowGraphRunNode } from "@/lib/contracts/workflow-graph";
+import { graphObject } from "./graph-schema";
+
+type Resolver = (name: string) => CapabilityTool | undefined;
+type NodeExecutionResult = { output: unknown; branch?: boolean; log?: string };
+
+const BLOCKED_TOOL_NODES = new Set(["workflow_start", "workflow_finish", "workflow_cancel", "flow_run", "flow_status"]);
+
+function compact(value: unknown): unknown {
+ try {
+ return JSON.parse(boundedResultText(typeof value === "string" ? { text: value } : value, { maxTextBytes: 12 * 1024, overflowHint: "Open the underlying project/tool result for full details." }));
+ } catch { return { text: String(value).slice(0, 12_000) }; }
+}
+
+function resultData(result: unknown): unknown {
+ if (capabilityReportedFailure(result)) throw new Error("downstream tool reported an error");
+ if (!isCapabilityDirectResult(result)) return result;
+ if (result.isError) throw new Error("downstream tool reported an error");
+ if (result.structuredContent) return result.structuredContent;
+ const text = result.content.filter((item) => item.type === "text").map((item) => item.text).join("\n");
+ try { return JSON.parse(text); } catch { return { text }; }
+}
+
+function safePath(root: unknown, ref: string): unknown {
+ const parts = ref.split(".");
+ if (!parts.length || parts.length > 16 || parts.some((part) => !/^[A-Za-z0-9_:-]+$/.test(part) || ["__proto__", "constructor", "prototype"].includes(part))) throw new Error("invalid workflow reference");
+ let value = root;
+ for (const part of parts) {
+ if ((!graphObject(value) && !Array.isArray(value)) || !Object.hasOwn(value, part)) throw new Error(`unresolved workflow reference: ${ref}`);
+ value = (value as Record<string, unknown>)[part];
+ }
+ return structuredClone(value);
+}
+
+function bind(value: unknown, context: unknown, depth = 0): unknown {
+ if (depth > 14) throw new Error("workflow references too deep");
+ if (Array.isArray(value)) return value.map((item) => bind(item, context, depth + 1));
+ if (!graphObject(value)) return value;
+ if (Object.hasOwn(value, "$ref")) {
+ if (Object.keys(value).length !== 1 || typeof value.$ref !== "string") throw new Error("workflow $ref must be the whole value");
+ return safePath(context, value.$ref);
+ }
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, bind(child, context, depth + 1)]));
+}
+
+async function callTool(name: string, args: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<unknown> {
+ const tool = resolve(name);
+ if (!tool) throw new Error(`workflow tool unavailable: ${name}`);
+ const outcome = await executeCapabilityCall({ tool, args, scope: context.scope, actor: context.actor, context });
+ if (outcome.kind !== "success") throw new Error(outcome.message);
+ return resultData(outcome.result);
+}
+
+async function resolvedProject(hint: unknown): Promise<{ id: string; name: string; path: string; matchedBy: string }> {
+ if (typeof hint !== "string" || !hint) throw new Error("project node requires config.project");
+ const project = await resolveProjectHint(hint);
+ if (!project || project.matchedBy === "fuzzy") throw new Error("project node requires an exact resolvable project");
+ return { id: project.id, name: project.name, path: project.path, matchedBy: project.matchedBy };
+}
+
+async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph: WorkflowGraph, graphInput: Record<string, unknown>, outputs: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<NodeExecutionResult> {
+ const runtimeContext = { input: graphInput, nodes: Object.fromEntries(Object.entries(outputs).map(([id, output]) => [id, { output }])), graph: { id: graph.id, name: graph.name, metadata: graph.metadata } };
+ const config = bind(node.config, runtimeContext) as Record<string, unknown>;
+ const project = typeof config.project === "string" ? config.project : graph.metadata.project;
+ if (node.type === "manual") return { output: graphInput, log: "Manual trigger accepted." };
+ if (node.type === "project") return { output: await resolvedProject(config.project ?? project), log: "Canonical project resolved at runtime." };
+ if (node.type === "folder") {
+ const resolved = await resolvedProject(config.project ?? project), relative = typeof config.path === "string" ? config.path : ".";
+ const target = path.resolve(resolved.path, relative), root = resolved.path.endsWith(path.sep) ? resolved.path : resolved.path + path.sep;
+ if (target !== resolved.path && !target.startsWith(root)) throw new Error("folder node path escapes project root");
+ const stat = await fs.stat(target); if (!stat.isDirectory()) throw new Error("folder node target is not a directory");
+ return { output: { project: resolved.id, path: target, relativePath: path.relative(resolved.path, target) || "." }, log: "Folder resolved inside the canonical project root." };
+ }
+ if (node.type === "skill") {
+ const query = typeof config.query === "string" ? config.query : typeof config.key === "string" ? config.key : node.name;
+ return { output: await callTool("skills_search", { query, top_k: Number(config.top_k) || 8, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Skill catalog queried with provenance/trust metadata." };
+ }
+ if (node.type === "knowledge") {
+ if (!project) throw new Error("knowledge node requires project binding");
+ if (typeof config.query === "string" && config.query) return { output: await callTool("project_memory_search", { project, query: config.query, limit: Number(config.limit) || 8, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Project memory queried." };
+ return { output: await callTool("project_knowledge_get", { project, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Project knowledge resolved." };
+ }
+ if (node.type === "condition") {
+ const ref = typeof config.path === "string" ? config.path : "input";
+ const value = safePath(runtimeContext, ref), branch = Object.hasOwn(config, "equals") ? JSON.stringify(value) === JSON.stringify(config.equals) : Boolean(value);
+ return { output: { value, branch }, branch, log: `Condition evaluated to ${branch}.` };
+ }
+ if (node.type === "output") return { output: Object.hasOwn(config, "value") ? config.value : { nodes: outputs }, log: "Workflow output collected." };
+ if (node.type === "tool") {
+ const tool = typeof config.tool === "string" ? config.tool : "";
+ if (!tool || BLOCKED_TOOL_NODES.has(tool)) throw new Error("tool node requires a bounded non-workflow tool");
+ const args = graphObject(config.arguments) ? structuredClone(config.arguments) : {};
+ if (context.workflowId) args.workflow_id = context.workflowId;
+ return { output: await callTool(tool, args, context, resolve), log: `Tool ${tool} completed.` };
+ }
+ if (node.type === "project_function") {
+ if (!project || typeof config.name !== "string") throw new Error("project_function node requires project and name");
+ return { output: await callTool("project_function_call", { project, name: config.name, input: graphObject(config.input) ? config.input : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project function ${config.name} completed.` };
+ }
+ if (node.type === "project_mcp") {
+ if (!project || typeof config.server !== "string" || typeof config.tool !== "string") throw new Error("project_mcp node requires project/server/tool");
+ return { output: await callTool("project_mcp_call", { project, server: config.server, tool: config.tool, arguments: graphObject(config.arguments) ? config.arguments : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project MCP ${config.server}.${config.tool} completed.` };
+ }
+ if (node.type === "script") {
+ if (!project || typeof config.script_id !== "string") throw new Error("script node requires project and script_id");
+ return { output: await callTool("project_script_run", { project, script_id: config.script_id, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Script ${config.script_id} completed.` };
+ }
+ if (node.type === "agent") {
+ if (!project || typeof config.message !== "string") throw new Error("agent node requires project and message");
+ const args: Record<string, unknown> = { project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" };
+ if (context.workflowId) args.workflow_id = context.workflowId;
+ return { output: await callTool("project_agent_run", args, context, resolve), log: "Project agent action completed." };
+ }
+ if (node.type === "subflow") {
+ if (!project || typeof config.flow !== "string") throw new Error("subflow node requires project and flow");
+ const started = await callTool("flow_run", { project, flow: config.flow, input: graphObject(config.input) ? config.input : {}, idempotency_key: `${run.id}:${node.id}`, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve) as Record<string, unknown>;
+ const runId = typeof started.id === "string" ? started.id : typeof started.run_id === "string" ? started.run_id : undefined;
+ if (!runId) return { output: started, log: `Subflow ${config.flow} started.` };
+ let latest: unknown = started;
+ for (let tries = 0; tries < 24; tries += 1) {
+ latest = await callTool("flow_status", { run_id: runId, wait_ms: 25_000 }, context, resolve);
+ if (graphObject(latest) && latest.state !== "running") break;
+ }
+ if (graphObject(latest) && latest.state !== "completed") throw new Error(`subflow ${config.flow} did not complete successfully`);
+ return { output: latest, log: `Subflow ${config.flow} completed.` };
+ }
+ throw new Error(`unsupported workflow node type: ${node.type}`);
+}
+
+export function nodeRuntimeView(row: WorkflowGraphRunNode): WorkflowGraphRunNode { return structuredClone(row); }
+export { executeNode, compact };
diff --git a/lib/workflow/graph-schema.test.ts b/lib/workflow/graph-schema.test.ts
new file mode 100644
index 00000000..b73be783
--- /dev/null
+++ b/lib/workflow/graph-schema.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+import { parseWorkflowGraphDefinition } from "./graph-schema";
+
+const base = () => ({
+ name: "Deploy app", description: "generic", status: "draft", inputs: {}, metadata: {},
+ nodes: [
+ { id: "start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "done", name: "Done", type: "output", position: { x: 200, y: 0 }, config: {} },
+ ], edges: [{ id: "e1", source: "start", target: "done" }],
+});
+
+describe("workflow graph schema", () => {
+ it("accepts a bounded acyclic metadata-only graph", () => expect(parseWorkflowGraphDefinition(base()).nodes).toHaveLength(2));
+ it("rejects cycles", () => expect(() => parseWorkflowGraphDefinition({ ...base(), edges: [{ id: "e1", source: "start", target: "done" }, { id: "e2", source: "done", target: "start" }] })).toThrow("cycle"));
+ it("rejects secret-like config fields recursively", () => expect(() => parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "start", name: "Start", type: "tool", position: { x: 0, y: 0 }, config: { nested: { accessToken: "x" } } }, base().nodes[1]] })).toThrow("secret_input_forbidden"));
+});
diff --git a/lib/workflow/graph-schema.ts b/lib/workflow/graph-schema.ts
new file mode 100644
index 00000000..bb27fa3f
--- /dev/null
+++ b/lib/workflow/graph-schema.ts
@@ -0,0 +1,106 @@
+import { WORKFLOW_GRAPH_NODE_TYPES, type WorkflowGraphEdge, type WorkflowGraphMetadata, type WorkflowGraphNode, type WorkflowGraphStatus } from "@/lib/contracts/workflow-graph";
+
+const ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/;
+const NODE_TYPES = new Set<string>(WORKFLOW_GRAPH_NODE_TYPES);
+const STATUSES = new Set<WorkflowGraphStatus>(["draft", "active", "archived"]);
+const SECRET_KEY = /^(secrets?|secretValue|password|passphrase|token|apiKey|apiToken|accessToken|refreshToken|authorization|headers|cookie|cookies|__proto__|constructor|prototype)$/i;
+
+export type WorkflowGraphDefinition = {
+ id?: string;
+ name: string;
+ description: string;
+ status: WorkflowGraphStatus;
+ inputs: Record<string, unknown>;
+ nodes: WorkflowGraphNode[];
+ edges: WorkflowGraphEdge[];
+ metadata: WorkflowGraphMetadata;
+};
+
+export function graphObject(value: unknown): value is Record<string, unknown> {
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
+}
+
+export function assertWorkflowMetadataOnly(value: unknown, depth = 0): void {
+ if (depth > 14) throw new Error("workflow graph metadata too deep");
+ if (Array.isArray(value)) { value.forEach((item) => assertWorkflowMetadataOnly(item, depth + 1)); return; }
+ if (!graphObject(value)) return;
+ for (const [key, child] of Object.entries(value)) {
+ if (SECRET_KEY.test(key)) throw new Error("secret_input_forbidden");
+ assertWorkflowMetadataOnly(child, depth + 1);
+ }
+}
+
+function text(value: unknown, max: number): value is string {
+ return typeof value === "string" && value.trim().length > 0 && value.length <= max;
+}
+
+function safePosition(value: unknown): { x: number; y: number } {
+ if (!graphObject(value)) throw new Error("node position must be an object");
+ const x = Number(value.x), y = Number(value.y);
+ if (!Number.isFinite(x) || !Number.isFinite(y) || Math.abs(x) > 100_000 || Math.abs(y) > 100_000) throw new Error("node position invalid");
+ return { x, y };
+}
+
+function parseNode(value: unknown): WorkflowGraphNode {
+ if (!graphObject(value)) throw new Error("invalid workflow node");
+ if (!text(value.id, 96) || !ID.test(value.id)) throw new Error("invalid workflow node id");
+ if (!text(value.name, 120)) throw new Error("invalid workflow node name");
+ if (typeof value.type !== "string" || !NODE_TYPES.has(value.type)) throw new Error("invalid workflow node type");
+ if (!graphObject(value.config)) throw new Error("workflow node config must be an object");
+ assertWorkflowMetadataOnly(value.config);
+ if (value.disabled !== undefined && typeof value.disabled !== "boolean") throw new Error("invalid workflow node disabled flag");
+ return { id: value.id, name: value.name, type: value.type as WorkflowGraphNode["type"], position: safePosition(value.position), config: structuredClone(value.config), ...(value.disabled ? { disabled: true } : {}) };
+}
+
+function parseEdge(value: unknown, nodeIds: Set<string>): WorkflowGraphEdge {
+ if (!graphObject(value) || !text(value.id, 96) || !ID.test(value.id) || !text(value.source, 96) || !text(value.target, 96)) throw new Error("invalid workflow edge");
+ if (!nodeIds.has(value.source) || !nodeIds.has(value.target) || value.source === value.target) throw new Error("workflow edge references invalid node");
+ const handle = (key: "sourceHandle" | "targetHandle") => value[key] === undefined ? undefined : (text(value[key], 64) && ID.test(value[key] as string) ? String(value[key]) : (() => { throw new Error("invalid workflow edge handle"); })());
+ return { id: value.id, source: value.source, target: value.target, ...(handle("sourceHandle") ? { sourceHandle: handle("sourceHandle") } : {}), ...(handle("targetHandle") ? { targetHandle: handle("targetHandle") } : {}) };
+}
+
+function assertAcyclic(nodes: WorkflowGraphNode[], edges: WorkflowGraphEdge[]): void {
+ const indegree = new Map(nodes.map((node) => [node.id, 0]));
+ const outgoing = new Map(nodes.map((node) => [node.id, [] as string[]]));
+ for (const edge of edges) { indegree.set(edge.target, (indegree.get(edge.target) ?? 0) + 1); outgoing.get(edge.source)?.push(edge.target); }
+ const queue = [...indegree.entries()].filter(([, count]) => count === 0).map(([id]) => id);
+ let visited = 0;
+ while (queue.length) {
+ const id = queue.shift()!; visited += 1;
+ for (const target of outgoing.get(id) ?? []) { const next = (indegree.get(target) ?? 0) - 1; indegree.set(target, next); if (next === 0) queue.push(target); }
+ }
+ if (visited !== nodes.length) throw new Error("workflow graph contains a cycle; loops are not supported in v2 MVP");
+}
+
+function parseMetadata(value: unknown): WorkflowGraphMetadata {
+ if (value === undefined) return {};
+ if (!graphObject(value)) throw new Error("workflow metadata must be an object");
+ assertWorkflowMetadataOnly(value);
+ const out: WorkflowGraphMetadata = {};
+ for (const key of ["intent", "normalizedIntent", "project", "fingerprint"] as const) if (typeof value[key] === "string" && value[key]) out[key] = String(value[key]).slice(0, 1000);
+ if (["user", "learned-from-session", "clone", "import"].includes(String(value.provenance))) out.provenance = value.provenance as WorkflowGraphMetadata["provenance"];
+ if (Array.isArray(value.sourceDigests)) out.sourceDigests = value.sourceDigests.filter((item): item is string => typeof item === "string").slice(0, 32).map((item) => item.slice(0, 128));
+ if (Array.isArray(value.tags)) out.tags = value.tags.filter((item): item is string => typeof item === "string").slice(0, 32).map((item) => item.slice(0, 64));
+ return out;
+}
+
+export function parseWorkflowGraphDefinition(raw: unknown): WorkflowGraphDefinition {
+ if (!graphObject(raw) || Buffer.byteLength(JSON.stringify(raw)) > 256 * 1024) throw new Error("workflow graph must be an object up to 256 KiB");
+ assertWorkflowMetadataOnly(raw);
+ if (raw.id !== undefined && (!text(raw.id, 96) || !ID.test(raw.id))) throw new Error("invalid workflow graph id");
+ if (!text(raw.name, 160) || typeof raw.description !== "string" || raw.description.length > 2000) throw new Error("workflow graph name/description invalid");
+ if (typeof raw.status !== "string" || !STATUSES.has(raw.status as WorkflowGraphStatus)) throw new Error("workflow graph status invalid");
+ if (!graphObject(raw.inputs) || Object.keys(raw.inputs).length > 64) throw new Error("workflow graph inputs invalid");
+ if (!Array.isArray(raw.nodes) || raw.nodes.length < 1 || raw.nodes.length > 200) throw new Error("workflow graph needs 1-200 nodes");
+ const nodes = raw.nodes.map(parseNode), nodeIds = new Set(nodes.map((node) => node.id));
+ if (nodeIds.size !== nodes.length) throw new Error("duplicate workflow node id");
+ if (!Array.isArray(raw.edges) || raw.edges.length > 400) throw new Error("workflow graph supports up to 400 edges");
+ const edges = raw.edges.map((edge) => parseEdge(edge, nodeIds));
+ if (new Set(edges.map((edge) => edge.id)).size !== edges.length) throw new Error("duplicate workflow edge id");
+ assertAcyclic(nodes, edges);
+ return { ...(typeof raw.id === "string" ? { id: raw.id } : {}), name: raw.name.trim(), description: raw.description, status: raw.status as WorkflowGraphStatus, inputs: structuredClone(raw.inputs), nodes, edges, metadata: parseMetadata(raw.metadata) };
+}
+
+export function normalizeWorkflowIntent(value: string): string {
+ return value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, " ").trim().replace(/\s+/g, " ").slice(0, 1000);
+}
diff --git a/lib/workflow/graph-store.test.ts b/lib/workflow/graph-store.test.ts
new file mode 100644
index 00000000..f0fa9b97
--- /dev/null
+++ b/lib/workflow/graph-store.test.ts
@@ -0,0 +1,33 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { LearnedRecipe } from "./types";
+
+const dir = await mkdtemp(path.join(os.tmpdir(), "mso-graph-store-"));
+process.env.OS_AGENT_SESSIONS_DIR = dir;
+const store = await import("./graph-store");
+
+const graph = { name: "Generic build", description: "test", status: "draft" as const, inputs: {}, metadata: { intent: "build project", normalizedIntent: "build project" }, nodes: [
+ { id: "start", name: "Start", type: "manual" as const, position: { x: 0, y: 0 }, config: {} },
+ { id: "out", name: "Output", type: "output" as const, position: { x: 200, y: 0 }, config: {} },
+], edges: [{ id: "e", source: "start", target: "out" }] };
+
+beforeAll(() => { process.env.OS_WORKFLOW_GRAPH_LEARNING_TEST = "1"; });
+afterAll(async () => { delete process.env.OS_WORKFLOW_GRAPH_LEARNING_TEST; await rm(dir, { recursive: true, force: true }); });
+
+describe("private workflow graph store", () => {
+ it("isolates principals and enforces revisions", async () => {
+ const created = await store.createWorkflowGraph("principal-a", graph);
+ expect((await store.listWorkflowGraphs("principal-a"))).toHaveLength(1);
+ expect((await store.listWorkflowGraphs("principal-b"))).toHaveLength(0);
+ await expect(store.updateWorkflowGraph("principal-a", created.id, "wrong", { ...graph, id: created.id })).rejects.toThrow("revision changed");
+ const updated = await store.updateWorkflowGraph("principal-a", created.id, created.revision, { ...graph, id: created.id, name: "Updated" });
+ expect(updated.name).toBe("Updated");
+ });
+ it("deduplicates learned private drafts by fingerprint", async () => {
+ const recipe: LearnedRecipe = { id: "recipe-private", actor: "principal-learn", scope: "write", intent: "repeat safe route", normalizedIntent: "repeat safe route", project: "project-x", summary: "ok", embeddingVersion: "fixture", embedding: [], bestSteps: [{ id: "s", tool: "sys_stats", state: "completed", ts: new Date().toISOString() }], lastSteps: [], attempts: 1, successes: 1, failures: 0, averageDurationMs: 1, lastDurationMs: 1, averageWallDurationMs: 1, lastWallDurationMs: 1, quality: { stepAttempts: 1, completedSteps: 1, failedSteps: 0, deniedSteps: 0, rateLimitedSteps: 0, invalidArgSteps: 0, retries: 0, rollbackSignals: 0, timedSteps: 0, totalStepDurationMs: 0, averageStepDurationMs: 0 }, lastQuality: { stepAttempts: 1, completedSteps: 1, failedSteps: 0, deniedSteps: 0, rateLimitedSteps: 0, invalidArgSteps: 0, retries: 0, rollbackSignals: 0, timedSteps: 0, totalStepDurationMs: 0, averageStepDurationMs: 0 }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
+ const first = await store.ensureLearnedWorkflowGraph(recipe), second = await store.ensureLearnedWorkflowGraph(recipe);
+ expect(first?.id).toBe(second?.id); expect((await store.listWorkflowGraphs(recipe.actor))).toHaveLength(1);
+ });
+});
diff --git a/lib/workflow/graph-store.ts b/lib/workflow/graph-store.ts
new file mode 100644
index 00000000..8151da81
--- /dev/null
+++ b/lib/workflow/graph-store.ts
@@ -0,0 +1,176 @@
+import { createHash, randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { agentSessionsDir } from "@/lib/agent/session-paths";
+import type { LearnedRecipe } from "./types";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import { normalizeWorkflowIntent, parseWorkflowGraphDefinition, type WorkflowGraphDefinition } from "./graph-schema";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+
+const STORE_VERSION = 1;
+const MAX_STORE_BYTES = 4 * 1024 * 1024;
+const MAX_GRAPHS = 200;
+
+type WorkflowGraphStore = { version: 1; owner: string; graphs: WorkflowGraph[] };
+
+function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
+export function workflowGraphOwner(principal: string): string { return hash(principal); }
+function root(): string { return path.join(agentSessionsDir(), ".workflow-graphs"); }
+function file(owner: string): string {
+ if (!/^[a-f0-9]{64}$/.test(owner)) throw new Error("invalid workflow graph owner");
+ return path.join(root(), owner, "graphs.json");
+}
+function graphRevision(graph: Omit<WorkflowGraph, "revision">): string { return hash(JSON.stringify(graph)); }
+
+async function safeDirectory(owner: string): Promise<string> {
+ const dir = path.dirname(file(owner));
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ const stat = await fs.lstat(dir);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("unsafe workflow graph directory");
+ await fs.chmod(dir, 0o700).catch(() => undefined);
+ return dir;
+}
+
+function parseStoredGraph(raw: unknown): WorkflowGraph {
+ if (!raw || typeof raw !== "object") throw new Error("invalid stored workflow graph");
+ const row = raw as Partial<WorkflowGraph>;
+ const definition = parseWorkflowGraphDefinition(row);
+ if (typeof row.id !== "string" || typeof row.createdAt !== "string" || typeof row.updatedAt !== "string" || typeof row.revision !== "string") throw new Error("invalid stored workflow graph metadata");
+ return { ...definition, version: 2, id: row.id, createdAt: row.createdAt, updatedAt: row.updatedAt, revision: row.revision };
+}
+
+async function readStore(owner: string): Promise<WorkflowGraphStore> {
+ const target = file(owner);
+ try {
+ const stat = await fs.lstat(target);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_STORE_BYTES || (stat.mode & 0o077)) throw new Error("unsafe workflow graph store");
+ const parsed: unknown = JSON.parse(await fs.readFile(target, "utf8"));
+ if (!parsed || typeof parsed !== "object") throw new Error("invalid workflow graph store");
+ const row = parsed as { version?: unknown; owner?: unknown; graphs?: unknown };
+ if (row.version !== STORE_VERSION || row.owner !== owner || !Array.isArray(row.graphs) || row.graphs.length > MAX_GRAPHS) throw new Error("invalid workflow graph store");
+ return { version: 1, owner, graphs: row.graphs.map(parseStoredGraph) };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 1, owner, graphs: [] };
+ throw error;
+ }
+}
+
+async function writeStore(store: WorkflowGraphStore): Promise<void> {
+ await safeDirectory(store.owner);
+ const target = file(store.owner), temp = `${target}.${randomUUID()}.tmp`;
+ const body = JSON.stringify(store, null, 2) + "\n";
+ if (Buffer.byteLength(body) > MAX_STORE_BYTES) throw new Error("workflow graph store exceeds 4 MiB");
+ try {
+ await fs.writeFile(temp, body, { flag: "wx", mode: 0o600 });
+ await fs.rename(temp, target);
+ } finally { await fs.unlink(temp).catch(() => undefined); }
+}
+
+function withGraphLock<T>(owner: string, fn: () => Promise<T>): Promise<T> {
+ return withSecurityStoreLock(file(owner), fn);
+}
+
+function materialize(definition: WorkflowGraphDefinition, previous?: WorkflowGraph): WorkflowGraph {
+ const now = new Date().toISOString(), id = definition.id ?? previous?.id ?? randomUUID();
+ const base = {
+ version: 2 as const, id, name: definition.name, description: definition.description,
+ status: definition.status, inputs: definition.inputs, nodes: definition.nodes, edges: definition.edges,
+ metadata: definition.metadata, createdAt: previous?.createdAt ?? now, updatedAt: now,
+ };
+ return { ...base, revision: graphRevision(base) };
+}
+
+export async function listWorkflowGraphs(principal: string): Promise<WorkflowGraph[]> {
+ const owner = workflowGraphOwner(principal), store = await readStore(owner);
+ return store.graphs.slice().sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
+}
+
+export async function getWorkflowGraph(principal: string, id: string): Promise<WorkflowGraph | null> {
+ return (await listWorkflowGraphs(principal)).find((graph) => graph.id === id) ?? null;
+}
+
+export async function createWorkflowGraph(principal: string, raw: unknown): Promise<WorkflowGraph> {
+ const owner = workflowGraphOwner(principal), definition = parseWorkflowGraphDefinition(raw);
+ return withGraphLock(owner, async () => {
+ const store = await readStore(owner);
+ if (store.graphs.length >= MAX_GRAPHS) throw new Error("private workflow graph limit reached");
+ const graph = materialize({ ...definition, id: definition.id ?? randomUUID() });
+ if (store.graphs.some((row) => row.id === graph.id)) throw new Error("workflow graph id already exists");
+ store.graphs.push(graph); await writeStore(store); return graph;
+ });
+}
+
+export async function updateWorkflowGraph(principal: string, id: string, expectedRevision: string, raw: unknown): Promise<WorkflowGraph> {
+ const owner = workflowGraphOwner(principal), definition = parseWorkflowGraphDefinition(raw);
+ return withGraphLock(owner, async () => {
+ const store = await readStore(owner), index = store.graphs.findIndex((graph) => graph.id === id);
+ if (index < 0) throw new Error("workflow graph not found");
+ const current = store.graphs[index];
+ if (current.revision !== expectedRevision) throw new Error("workflow graph revision changed; refresh before editing");
+ if (definition.id && definition.id !== id) throw new Error("workflow graph id mismatch");
+ const graph = materialize({ ...definition, id }, current); store.graphs[index] = graph; await writeStore(store); return graph;
+ });
+}
+
+export async function deleteWorkflowGraph(principal: string, id: string, expectedRevision: string): Promise<{ id: string; deleted: true }> {
+ const owner = workflowGraphOwner(principal);
+ return withGraphLock(owner, async () => {
+ const store = await readStore(owner), current = store.graphs.find((graph) => graph.id === id);
+ if (!current) throw new Error("workflow graph not found");
+ if (current.revision !== expectedRevision) throw new Error("workflow graph revision changed; refresh before deleting");
+ store.graphs = store.graphs.filter((graph) => graph.id !== id); await writeStore(store); return { id, deleted: true };
+ });
+}
+
+export async function cloneWorkflowGraph(principal: string, id: string): Promise<WorkflowGraph> {
+ const source = await getWorkflowGraph(principal, id);
+ if (!source) throw new Error("workflow graph not found");
+ return createWorkflowGraph(principal, {
+ name: `${source.name} Copy`, description: source.description, status: "draft", inputs: source.inputs,
+ nodes: source.nodes, edges: source.edges, metadata: { ...source.metadata, provenance: "clone", fingerprint: undefined },
+ });
+}
+
+function tokens(value: string): Set<string> { return new Set(normalizeWorkflowIntent(value).split(" ").filter((word) => word.length > 2)); }
+function overlap(a: string, b: string): number {
+ const left = tokens(a), right = tokens(b); if (!left.size || !right.size) return 0;
+ let hit = 0; for (const word of left) if (right.has(word)) hit += 1;
+ return hit / Math.max(left.size, right.size);
+}
+
+export async function findMatchingWorkflowGraph(principal: string, intent: string, projectKeys: string[] = []): Promise<WorkflowGraph | null> {
+ const normalized = normalizeWorkflowIntent(intent), projects = new Set(projectKeys.filter(Boolean));
+ const candidates = (await listWorkflowGraphs(principal)).filter((graph) => graph.status !== "archived");
+ const scored = candidates.map((graph) => {
+ const sameIntent = graph.metadata.normalizedIntent === normalized;
+ const projectScore = !graph.metadata.project || !projects.size ? 0.2 : projects.has(graph.metadata.project) ? 1 : -1;
+ const score = (sameIntent ? 4 : overlap(intent, graph.metadata.intent ?? graph.name) * 2) + projectScore + (graph.status === "active" ? 0.5 : 0);
+ return { graph, score };
+ }).filter((row) => row.score > 0.85).sort((a, b) => b.score - a.score || Date.parse(b.graph.updatedAt) - Date.parse(a.graph.updatedAt));
+ return scored[0]?.graph ?? null;
+}
+
+function learnedFingerprint(recipe: LearnedRecipe): string {
+ return hash(JSON.stringify({ intent: recipe.normalizedIntent, project: recipe.project ?? "", steps: recipe.bestSteps.map((step) => [step.tool, step.target ?? "", step.args ?? {}]) }));
+}
+
+export async function ensureLearnedWorkflowGraph(recipe: LearnedRecipe): Promise<WorkflowGraph | null> {
+ if (!recipe.successes || !recipe.bestSteps.length) return null;
+ const principal = recipe.actor, fingerprint = learnedFingerprint(recipe), owner = workflowGraphOwner(principal);
+ return withGraphLock(owner, async () => {
+ const store = await readStore(owner), existing = store.graphs.find((graph) => graph.metadata.fingerprint === fingerprint);
+ if (existing) return existing;
+ if (store.graphs.length >= MAX_GRAPHS) return null;
+ const nodes = [
+ { id: "manual", name: "Manual Trigger", type: "manual" as const, position: { x: 60, y: 120 }, config: {} },
+ ...recipe.bestSteps.map((step, index) => ({ id: `step-${index + 1}`, name: step.tool, type: "tool" as const, position: { x: 300 + index * 240, y: 120 }, config: { tool: step.tool, arguments: step.args ?? {}, learnedTarget: step.target ?? "" } })),
+ { id: "output", name: "Output", type: "output" as const, position: { x: 300 + recipe.bestSteps.length * 240, y: 120 }, config: {} },
+ ];
+ const edges = nodes.slice(1).map((node, index) => ({ id: `edge-${index + 1}`, source: nodes[index]!.id, target: node.id }));
+ const definition = parseWorkflowGraphDefinition({
+ name: recipe.intent.slice(0, 120), description: `Learned draft from ${recipe.successes} successful session run(s).`, status: "draft",
+ inputs: {}, nodes, edges, metadata: { intent: recipe.intent, normalizedIntent: recipe.normalizedIntent, project: recipe.project, provenance: "learned-from-session", fingerprint, sourceDigests: [hash(recipe.id)] },
+ });
+ const graph = materialize({ ...definition, id: randomUUID() }); store.graphs.push(graph); await writeStore(store); return graph;
+ });
+}
diff --git a/lib/workflow/graph-target.ts b/lib/workflow/graph-target.ts
new file mode 100644
index 00000000..adc3a427
--- /dev/null
+++ b/lib/workflow/graph-target.ts
@@ -0,0 +1,20 @@
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+
+export async function resolveWorkflowGraphNodeTarget(graph: WorkflowGraph, nodeId: string) {
+ const node = graph.nodes.find((item) => item.id === nodeId);
+ if (!node) throw new Error("workflow node not found");
+ if (node.type !== "project" && node.type !== "folder") throw new Error("only project/folder nodes have file targets");
+ const hint = typeof node.config.project === "string" ? node.config.project : graph.metadata.project;
+ if (!hint) throw new Error("project binding is missing");
+ const project = await resolveProjectHint(hint);
+ if (!project || project.matchedBy === "fuzzy") throw new Error("project binding is not exact");
+ if (node.type === "project") return { project: project.id, name: project.name, path: project.path, relativePath: "." };
+ const relative = typeof node.config.path === "string" && node.config.path ? node.config.path : ".";
+ const target = path.resolve(project.path, relative), root = project.path.endsWith(path.sep) ? project.path : project.path + path.sep;
+ if (target !== project.path && !target.startsWith(root)) throw new Error("folder target escapes project root");
+ const stat = await fs.stat(target); if (!stat.isDirectory()) throw new Error("folder target is not a directory");
+ return { project: project.id, name: project.name, path: target, relativePath: path.relative(project.path, target) || "." };
+}
diff --git a/lib/workflow/learning.ts b/lib/workflow/learning.ts
index b445cf8a..5621a4e1 100644
--- a/lib/workflow/learning.ts
+++ b/lib/workflow/learning.ts
@@ -1,4 +1,4 @@
-import { randomUUID } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import { allows } from "@/lib/capabilities/scope";
import { embedSkillText, normalizeSemanticText, SKILL_EMBEDDING_VERSION } from "@/lib/skills/semantic";
import { compactRecipeSteps, elapsedMs, enrichBestSteps, mergeQuality, summarizeWorkflowQuality } from "./quality";
@@ -7,6 +7,8 @@ import { safeMemoryText } from "./sanitize";
import { actorKey, removeActiveWorkflow, workflowFor } from "./state";
import { loadWorkflowStore, persistWorkflowStore } from "./storage";
import type { FinishWorkflowResult, LearnedRecipe, RecipeAccess } from "./types";
+import { ensureLearnedWorkflowGraph } from "./graph-store";
+import { rememberAgentMemory } from "@/lib/agent/memory-store";
export async function finishWorkflow(input: {
actor?: string;
@@ -91,6 +93,18 @@ export async function finishWorkflow(input: {
.forEach((row) => delete store.recipes[row.id]);
}
await persistWorkflowStore(store);
+ // Successful sanitized session routes automatically become private graph drafts.
+ // This is best-effort learning: graph persistence must never turn workflow_finish into a failure.
+ if (input.success && (process.env.NODE_ENV !== "test" || process.env.OS_WORKFLOW_GRAPH_LEARNING_TEST === "1")) await ensureLearnedWorkflowGraph(recipe).catch(() => undefined);
+ if (input.success && process.env.NODE_ENV !== "test") {
+ const memoryKey = `workflow:${createHash("sha256").update(`${recipe.normalizedIntent}|${recipe.project ?? ""}`).digest("hex").slice(0, 20)}`;
+ const route = recipe.bestSteps.map((step) => step.tool).join(" → ").slice(0, 1200);
+ const value = safeMemoryText([`Intent: ${recipe.intent}`, recipe.project ? `Project: ${recipe.project}` : "", `Outcome: ${recipe.summary}`, route ? `Successful route: ${route}` : ""].filter(Boolean).join("\n"), 3000);
+ if (value) await rememberAgentMemory(recipeOwner, "MEMORY.md", memoryKey, value, {
+ kind: "procedural", sensitivity: "private", confidence: Math.min(1, 0.65 + Math.min(recipe.successes, 7) * 0.05),
+ provenance: { authority: "observed", channel: "system" },
+ }).catch(() => undefined);
+ }
const improvedByMs = input.success && previousFastestMs != null && durationMs < previousFastestMs
? previousFastestMs - durationMs : undefined;