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): maximize script and search automation

Rahman765e72ef1cdc
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
index ad8c7ea0..fdd6f7d2 100644
--- a/app/api/v1/workflows/route.ts
+++ b/app/api/v1/workflows/route.ts
@@ -16,12 +16,16 @@ import { deleteWorkflowVariable, listWorkflowVariables, setWorkflowVariable } fr
import { workflowNodeCatalog } from "@/lib/workflow/node-catalog";
import { workflowTemplate, workflowTemplates } from "@/lib/workflow/templates";
import { suggestWorkflowGraph } from "@/lib/workflow/ai-assist";
+import { workflowMatchesQuery } from "@/lib/workflow/search";
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import { listAutomationScripts } from "@/lib/orchestration/repo-memory-artifacts";
export const runtime="nodejs";export const dynamic="force-dynamic";const headers={"Cache-Control":"no-store, private"};
const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceof Error?error.message.slice(0,500):String(error).slice(0,500)||"workflow request failed"},{status,headers});
async function auth(minimum:"viewer"|"operator"|"owner"="viewer"){const context=await getSessionContext();if(!context?.session.device_id||!roleAtLeast(context.role,minimum))return null;return{context,principal:`web:${context.session.device_id}`};}
function definition(graph:NonNullable<Awaited<ReturnType<typeof getWorkflowGraph>>>){const{revision:_r,createdAt:_c,updatedAt:_u,version:_v,...rest}=graph;return rest;}
export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,minimum=q.has("variables")?"operator":"viewer",session=await auth(minimum);if(!session)return fail("unauthorized",401);try{
if(q.get("directory")==="1"){const query=(q.get("q")??"").toLowerCase().trim(),tools=msoCapabilityRuntime.list(maxScope()).filter((tool)=>!query||`${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query)).slice(0,150),graphs=await listWorkflowGraphs(session.principal),sessions=await listAgentSessions(session.principal,50);return NextResponse.json({tools,workflows:graphs.filter((graph)=>!query||`${graph.name} ${graph.description} ${(graph.metadata.tags??[]).join(" ")}`.toLowerCase().includes(query)).map((graph)=>({id:graph.id,name:graph.name,status:graph.status,nodeCount:graph.nodes.length,updatedAt:graph.updatedAt})),sessions:sessions.filter((row)=>!query||`${row.title} ${row.name} ${row.cwd??""}`.toLowerCase().includes(query))},{headers});}
+ if(q.get("scripts")==="1"){const hint=q.get("project")?.trim();if(!hint)throw new Error("project is required");const project=await resolveProjectHint(hint);if(!project||project.matchedBy==="fuzzy")throw new Error("exact project not found");const query=(q.get("q")??"").toLowerCase().trim(),scripts=(await listAutomationScripts(project.path)).filter((script)=>!query||`${script.id} ${script.intent} ${script.status} ${script.steps.map((step)=>step.tool).join(" ")}`.toLowerCase().includes(query)).map((script)=>({id:script.id,intent:script.intent,status:script.status,stepCount:script.steps.length,updatedAt:script.updatedAt,project:script.project,tools:script.steps.map((step)=>step.tool)}));return NextResponse.json({project:project.id,scripts},{headers});}
if(q.get("catalog")==="1")return NextResponse.json({nodes:workflowNodeCatalog(q.get("q")??"")},{headers});
if(q.get("templates")==="1")return NextResponse.json({templates:workflowTemplates()},{headers});
if(q.get("variables")==="1")return NextResponse.json({variables:await listWorkflowVariables(session.principal)},{headers});
@@ -30,7 +34,7 @@ export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,mini
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});
+ const graphs=await listWorkflowGraphs(session.principal),query=q.get("q")??"",filters={tag:q.get("tag")||undefined,status:q.get("status")||undefined,project:q.get("project")||undefined,folder:q.get("folder")||undefined,node:q.get("node")||undefined}; return NextResponse.json({graphs:graphs.filter((graph)=>workflowMatchesQuery(graph,query,filters))},{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(rateLimited(`workflow:${action}:${session.context.session.device_id}`,action==="run"?60:30,60_000))return fail("rate_limited",429);
if(action==="create")return NextResponse.json({graph:await createWorkflowGraph(session.principal,body.graph)},{headers});
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 6872a449..d0c92cc5 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -4,6 +4,12 @@
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-16
+
+**Added**
+
+- `workflows` maximize script and search automation
+
## 2026-09-15
**Added**
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index f9e45c77..42433ca4 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -51,7 +51,7 @@ Graph edges stay acyclic. Repetition is represented by the bounded `loop` node o
- `project_function`
- `project_mcp`
- `integration`
-- `script`
+- `script` — execute a saved, validated repo-local RASMIC automation manifest by `project + script_id`; the graph stores only the reference, while runtime re-validates the manifest before replay
- `agent`
- `project`
- `folder`
@@ -60,6 +60,8 @@ Graph edges stay acyclic. Repetition is represented by the bounded `loop` node o
Project/folder nodes resolve the live canonical server path when the graph runs and can open that real directory in MSO Files/Finder.
+Script nodes intentionally do **not** execute arbitrary shell or browser-supplied JavaScript. The Inspector can search the selected project's `.agent/scripts` catalog, shows candidate/tested state and step count, and persists the chosen `script_id` in the graph. Execution delegates to `project_script_run`, which re-reads the manifest and refuses steps outside the bounded replay-safe RASMIC policy. A successful candidate replay is promoted to tested by the existing script runner.
+
## Data binding
Node config supports safe declarative bindings:
@@ -122,7 +124,7 @@ AI assistance has an isolated workflow-design system prompt, receives no implici
`/workflows` provides:
-- private searchable workflow library with folder/tag metadata
+- private searchable workflow library with description/project/folder/tag metadata, clickable tag chips, and shared query syntax (`tag:`, `status:`, `project:`, `folder:`, `node:` plus free-text AND terms)
- draft / active / archived lifecycle
- searchable node palette
- draggable canvas
@@ -165,7 +167,7 @@ MSO deliberately keeps this capability behind one compact MCP tool to preserve t
Actions:
-`list`, `get`, `create`, `update`, `delete`, `clone`, `run`, `status`, `runs`, `versions`, `restore`, `catalog`, `templates`, `create_from_template`, `variables`, `variable_set`, `variable_delete`.
+`list`, `search`, `get`, `create`, `update`, `delete`, `clone`, `run`, `status`, `runs`, `versions`, `restore`, `catalog`, `scripts`, `templates`, `create_from_template`, `variables`, `variable_set`, `variable_delete`. `list` and `search` accept the same workflow query/filter semantics used by the UI; `scripts` returns safe RASMIC manifest summaries for an exact project without exposing raw script files or credentials.
The linear `flow_catalog`, `flow_manage`, `flow_run` and `flow_status` tools remain compatible for small deterministic project-owned sequences.
diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsx
index 8376d852..1d6f46eb 100644
--- a/frontend/slices/workflows/components/workflow-inspector.tsx
+++ b/frontend/slices/workflows/components/workflow-inspector.tsx
@@ -11,6 +11,7 @@ import { openWindow } from "@/features/appshell";
import { resolveNode } from "../lib/api";
import { WorkflowAgentSeatField } from "./workflow-agent-seat-field";
import { WorkflowToolDirectoryField } from "./workflow-tool-directory-field";
+import { WorkflowScriptField } from "./workflow-script-field";
const selectClass="h-9 w-full rounded-md border bg-background px-2";
function Field({label,children}:{label:string;children:React.ReactNode}){return <label className="block space-y-1"><span className="text-muted-foreground">{label}</span>{children}</label>;}
function number(value:unknown,fallback:number){const n=Number(value);return Number.isFinite(n)?n:fallback;}
@@ -21,6 +22,7 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph
const[advancedError,setAdvancedError]=useState("");
const outgoing=useMemo(()=>node?graph.edges.filter((edge)=>edge.source===node.id):[],[graph.edges,node]);
if(!node){const tags=graph.metadata.tags?.join(", ")??"";return <div className="space-y-4 p-3 text-xs"><div className="font-semibold">Workflow settings</div><Field label="Description"><Textarea value={graph.description} onChange={(e)=>onGraph({...graph,description:e.target.value})}/></Field><Field label="Folder"><Input value={graph.metadata.folder??""} placeholder="Automation / Operations" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,folder:e.target.value||undefined}})}/></Field><Field label="Tags"><Input value={tags} placeholder="deploy, qa, daily" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,tags:e.target.value.split(",").map((v)=>v.trim()).filter(Boolean).slice(0,32)}})}/></Field><Field label="Timezone"><Input value={graph.metadata.timezone??"UTC"} placeholder="UTC" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,timezone:e.target.value||undefined}})}/></Field><Field label="Error workflow"><select className={selectClass} value={graph.metadata.errorWorkflowId??""} onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,errorWorkflowId:e.target.value||undefined}})}><option value="">None</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field><p className="text-[10px] text-muted-foreground">Active schedule/webhook triggers execute server-side. Workflow data, versions, runs and variables stay private to the authenticated principal.</p></div>;}
+ const projectValue=String(node.config.project??graph.metadata.project??"");
const patch=(next:Partial<WorkflowGraphNode>)=>onNode({...node,...next}),setConfig=(key:string,value:unknown)=>patch({config:{...node.config,[key]:value}}),removeConfig=(key:string)=>{const next={...node.config};delete next[key];patch({config:next});};
const applyAdvanced=(text:string)=>{try{const value=JSON.parse(text);if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Config must be an object");patch({config:value as Record<string,unknown>});setAdvancedError("");}catch(e){setAdvancedError(e instanceof Error?e.message:"Invalid JSON");}};
const openTarget=async()=>{const resolved=await resolveNode(graph.id,node.id);openWindow("files-manager",resolved.name,undefined,{path:resolved.path},{multi:true});};
@@ -34,6 +36,7 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph
{node.type==="agent"&&<WorkflowAgentSeatField value={String(node.config.orgSeatId??"")} onChange={(value)=>value?setConfig("orgSeatId",value):removeConfig("orgSeatId")}/>}
{(node.type==="project"||node.type==="folder"||node.type==="knowledge"||(node.type==="agent"&&!node.config.orgSeatId)||node.type==="script"||node.type==="project_function"||node.type==="project_mcp"||node.type==="subflow"||(node.type==="memory"&&node.config.scope==="project"))&&<Field label="Project"><Input value={String(node.config.project??graph.metadata.project??"")} placeholder="Canonical project id/name" onChange={(e)=>setConfig("project",e.target.value)}/></Field>}
{node.type==="folder"&&<Field label="Relative path"><Input value={String(node.config.path??".")} onChange={(e)=>setConfig("path",e.target.value)}/></Field>}
+ {node.type==="script"&&<WorkflowScriptField project={projectValue} value={String(node.config.script_id??"")} onChange={(value)=>value?setConfig("script_id",value):removeConfig("script_id")}/>}
{node.type==="tool"&&<><WorkflowToolDirectoryField value={String(node.config.tool??"")} onChange={(value)=>setConfig("tool",value)}/><JsonField label="Arguments JSON" value={node.config.arguments??{}} onChange={(value)=>setConfig("arguments",value)}/></>}
{node.type==="integration"&&<>{["user","provider","connection","operation"].map((key)=><Field key={key} label={key[0]!.toUpperCase()+key.slice(1)}><Input value={String(node.config[key]??"")} onChange={(e)=>setConfig(key,e.target.value)}/></Field>)}</>}
{node.type==="agent"&&<Field label="Agent objective"><Textarea value={String(node.config.message??"")} onChange={(e)=>setConfig("message",e.target.value)}/></Field>}
diff --git a/frontend/slices/workflows/components/workflow-library.tsx b/frontend/slices/workflows/components/workflow-library.tsx
index d9fcaa92..2ede94b3 100644
--- a/frontend/slices/workflows/components/workflow-library.tsx
+++ b/frontend/slices/workflows/components/workflow-library.tsx
@@ -2,7 +2,9 @@
import { FolderOpen } from "lucide-react";
import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import { workflowMatchesQuery, workflowTagQuery } from "@/lib/workflow/search";
import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { WorkflowCreateDialog } from "./workflow-create-dialog";
@@ -18,10 +20,19 @@ export function WorkflowLibrary({ graphs, activeId, search, onSearch, onSelect,
onTemplate: (id: string) => Promise<void>;
onAI: (definition: Definition) => Promise<void>;
}) {
- const query = search.toLowerCase().trim();
- const filtered = graphs.filter((graph) => !query || `${graph.name} ${graph.metadata.folder ?? ""} ${(graph.metadata.tags ?? []).join(" ")}`.toLowerCase().includes(query));
+ const filtered = graphs.filter((graph) => workflowMatchesQuery(graph, search));
return <div className="flex h-full min-h-0 flex-col bg-card/20">
- <div className="space-y-2 border-b p-2"><Input className="h-8" placeholder="Search workflows…" value={search} onChange={(event) => onSearch(event.target.value)}/><WorkflowCreateDialog onBlank={onBlank} onTemplate={onTemplate} onAI={onAI}/></div>
- <ScrollArea className="min-h-0 flex-1"><div className="space-y-1 p-2">{filtered.length === 0 ? <div className="p-3 text-xs text-muted-foreground">No matching private workflows.</div> : null}{filtered.map((graph) => <button key={graph.id} type="button" onClick={() => onSelect(graph.id)} className={`w-full rounded-lg border p-2 text-left text-xs transition-colors ${activeId === graph.id ? "bg-accent" : "bg-card hover:bg-accent/60"}`}><div className="flex items-center gap-2"><FolderOpen className="size-3.5 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1 truncate font-medium">{graph.name}</div></div><div className="mt-1 flex flex-wrap gap-1 pl-5 text-[10px] text-muted-foreground"><span>{graph.status} · {graph.nodes.length} nodes</span>{graph.metadata.folder ? <span>· {graph.metadata.folder}</span> : null}</div></button>)}</div></ScrollArea>
+ <div className="space-y-2 border-b p-2"><Input className="h-8" aria-label="Search workflows" placeholder="deploy tag:qa status:active" value={search} onChange={(event) => onSearch(event.target.value)}/><WorkflowCreateDialog onBlank={onBlank} onTemplate={onTemplate} onAI={onAI}/></div>
+ <ScrollArea className="min-h-0 flex-1"><div className="space-y-1 p-2">
+ {filtered.length === 0 ? <div className="p-3 text-xs text-muted-foreground">No matching private workflows.</div> : null}
+ {filtered.map((graph) => <div key={graph.id} className={`rounded-lg border text-xs ${activeId === graph.id ? "bg-accent" : "bg-card"}`}>
+ <button type="button" onClick={() => onSelect(graph.id)} className="w-full rounded-lg p-2 text-left transition-colors hover:bg-accent/60" aria-pressed={activeId === graph.id}>
+ <div className="flex items-center gap-2"><FolderOpen className="size-3.5 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1 truncate font-medium">{graph.name}</div></div>
+ {graph.description ? <p className="mt-1 line-clamp-2 break-words text-muted-foreground">{graph.description}</p> : null}
+ <div className="mt-1 flex flex-wrap gap-1 break-all text-[10px] text-muted-foreground"><span>{graph.status} · {graph.nodes.length} nodes</span>{graph.metadata.folder ? <span>· {graph.metadata.folder}</span> : null}{graph.metadata.project ? <span>· {graph.metadata.project}</span> : null}</div>
+ </button>
+ {graph.metadata.tags?.length ? <div className="flex flex-wrap gap-1 px-2 pb-2">{graph.metadata.tags.map((tag, index) => <Button key={`${tag}-${index}`} type="button" variant="secondary" size="sm" className="h-auto max-w-full whitespace-normal break-all px-2 py-1 text-[10px]" aria-label={`Filter workflows by tag ${tag}`} onClick={() => onSearch(workflowTagQuery(tag))}>{tag}</Button>)}</div> : null}
+ </div>)}
+ </div></ScrollArea>
</div>;
}
diff --git a/frontend/slices/workflows/components/workflow-script-field.tsx b/frontend/slices/workflows/components/workflow-script-field.tsx
new file mode 100644
index 00000000..0d4e559e
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-script-field.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { FileCode2, Search } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { listWorkflowScripts, type WorkflowScriptSummary } from "../lib/api";
+
+export function WorkflowScriptField({ project, value, onChange }: { project: string; value: string; onChange: (value: string) => void }) {
+ const [open, setOpen] = useState(false), [query, setQuery] = useState(""), [scripts, setScripts] = useState<WorkflowScriptSummary[]>([]), [loadedProject, setLoadedProject] = useState(""), [error, setError] = useState("");
+ useEffect(() => {
+ let cancelled = false;
+ if (!project.trim()) return;
+ const requestedProject = project.trim();
+ void listWorkflowScripts(requestedProject).then((rows) => { if (!cancelled) { setScripts(rows); setLoadedProject(requestedProject); setError(""); } }).catch((reason: unknown) => { if (!cancelled) { setScripts([]); setLoadedProject(requestedProject); setError(reason instanceof Error ? reason.message : "Could not load scripts"); } });
+ return () => { cancelled = true; };
+ }, [project]);
+ const projectReady = Boolean(project.trim()) && loadedProject === project.trim();
+ const filtered = useMemo(() => { if (!projectReady) return []; const q = query.toLowerCase().trim(); return scripts.filter((script) => !q || `${script.id} ${script.intent} ${script.status} ${script.tools.join(" ")}`.toLowerCase().includes(q)); }, [projectReady, query, scripts]);
+ const selected = projectReady ? scripts.find((script) => script.id === value) : undefined;
+ return <div className="space-y-2">
+ <div className="space-y-1"><span className="text-muted-foreground">Script ID</span><Input value={value} placeholder="script_<recipe-id>" onChange={(event) => onChange(event.target.value)}/></div>
+ <Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><Button type="button" variant="outline" className="w-full justify-start" disabled={!project.trim()}><FileCode2 className="mr-2 size-3.5"/>{selected ? selected.intent : project.trim() ? "Choose saved RASMIC script" : "Set project first"}</Button></PopoverTrigger><PopoverContent align="start" className="w-96 max-w-[calc(100vw-2rem)] p-2"><div className="relative mb-2"><Search className="absolute left-2 top-2.5 size-3 text-muted-foreground"/><Input className="pl-7" placeholder="Search script id, intent, tool…" value={query} onChange={(event) => setQuery(event.target.value)}/></div><ScrollArea className="h-72"><div className="space-y-1">{filtered.map((script) => <button key={script.id} type="button" className="w-full rounded-md border p-2 text-left hover:bg-accent" onClick={() => { onChange(script.id); setOpen(false); setQuery(""); }}><div className="flex items-center justify-between gap-2"><span className="truncate font-mono text-[11px] font-semibold">{script.id}</span><Badge variant="outline" className="shrink-0 text-[9px]">{script.status}</Badge></div><p className="mt-1 line-clamp-2 text-[11px]">{script.intent}</p><p className="mt-1 text-[10px] text-muted-foreground">{script.stepCount} steps{script.tools.length ? ` · ${script.tools.join(" · ")}` : ""}</p></button>)}{projectReady && !filtered.length && !error ? <p className="p-3 text-xs text-muted-foreground">No saved scripts match this project/query.</p> : null}{projectReady && error ? <p className="p-3 text-xs text-destructive">{error}</p> : null}{project.trim() && !projectReady ? <p className="p-3 text-xs text-muted-foreground">Loading scripts…</p> : null}</div></ScrollArea></PopoverContent></Popover>
+ {selected ? <div className="rounded-md border p-2 text-[10px] text-muted-foreground"><div className="flex items-center gap-2"><Badge variant="outline">{selected.status}</Badge><span>{selected.stepCount} validated steps</span></div><p className="mt-1">{selected.intent}</p></div> : null}
+ <p className="text-[10px] text-muted-foreground">Saved with the workflow as a script reference. Execution uses MSO&apos;s validated RASMIC runner; arbitrary browser shell/JS is not executed.</p>
+ </div>;
+}
diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.ts
index 7fda5115..55fa9b7d 100644
--- a/frontend/slices/workflows/lib/api.ts
+++ b/frontend/slices/workflows/lib/api.ts
@@ -25,3 +25,6 @@ export async function resolveNode(graphId:string,nodeId:string){return json<{pro
export type WorkflowDirectory = {tools:Array<{name:string;description:string;scope:string;inputSchema:Record<string,unknown>}>;workflows:Array<{id:string;name:string;status:string;nodeCount:number;updatedAt:string}>;sessions:Array<{id:string;title:string;name:string;updatedAt:string;cwd?:string;source:string}>};
export async function listWorkflowDirectory(query=""){return cachedWorkflowResource(`directory:${query}`,15000,()=>json<WorkflowDirectory>(`/api/v1/workflows?directory=1&q=${encodeURIComponent(query)}`));}
+
+export type WorkflowScriptSummary = { id:string; intent:string; status:"candidate"|"tested"; stepCount:number; updatedAt:string; project?:string; tools:string[] };
+export async function listWorkflowScripts(project:string,query=""){const q=new URLSearchParams({scripts:"1",project});if(query.trim())q.set("q",query.trim());return cachedWorkflowResource(`scripts:${project}:${query}`,15000,async()=> (await json<{project:string;scripts:WorkflowScriptSummary[]}>(`/api/v1/workflows?${q}`)).scripts);}
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
index 31458bb4..d6ec88e9 100644
--- a/lib/mcp/tools-flows.ts
+++ b/lib/mcp/tools-flows.ts
@@ -10,6 +10,9 @@ import { listWorkflowGraphVersions, readWorkflowGraphVersion } from "@/lib/workf
import { workflowNodeCatalog } from "@/lib/workflow/node-catalog";
import { workflowTemplate, workflowTemplates } from "@/lib/workflow/templates";
import { deleteWorkflowVariable, listWorkflowVariables, setWorkflowVariable } from "@/lib/workflow/variables";
+import { workflowMatchesQuery } from "@/lib/workflow/search";
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import { listAutomationScripts } from "@/lib/orchestration/repo-memory-artifacts";
const project = { type: "string", maxLength: 4096 };
const flow = { type: "string", maxLength: 64 };
@@ -62,9 +65,10 @@ export const FLOW_TOOLS: McpTool[] = [
run: async (a, context) => {
const principal = privateGraphPrincipal(context), action = str(a, "action");
const data = a.data && typeof a.data === "object" && !Array.isArray(a.data) ? a.data as Record<string, unknown> : {};
- if (action === "list") { const graphs = await listWorkflowGraphs(principal); return { graphs: graphs.map(graph => ({ id: graph.id, name: graph.name, status: graph.status, revision: graph.revision, nodeCount: graph.nodes.length, updatedAt: graph.updatedAt, provenance: graph.metadata.provenance, project: graph.metadata.project })) }; }
+ if (action === "list" || action === "search") { const graphs = await listWorkflowGraphs(principal), query = typeof data.query === "string" ? data.query : "", filters = { tag: typeof data.tag === "string" ? data.tag : undefined, status: typeof data.status === "string" ? data.status : undefined, project: typeof data.project === "string" ? data.project : undefined, folder: typeof data.folder === "string" ? data.folder : undefined, node: typeof data.node === "string" ? data.node : undefined }; return { graphs: graphs.filter((graph) => workflowMatchesQuery(graph, query, filters)).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, folder: graph.metadata.folder, tags: graph.metadata.tags ?? [] })) }; }
if (action === "status") return workflowGraphRunStatus(principal, str(a, "id"), Number(a.wait_ms) || 0);
if (action === "runs") return listWorkflowGraphRuns(workflowGraphOwner(principal), { graphId: typeof data.graph_id === "string" ? data.graph_id : undefined, limit: Number(data.limit) || 30, offset: Number(data.offset) || 0 });
+ if (action === "scripts") { const hint = typeof data.project === "string" ? data.project : ""; if (!hint) throw new Error("project is required"); const project = await resolveProjectHint(hint); if (!project || project.matchedBy === "fuzzy") throw new Error("exact project not found"); const query = typeof data.query === "string" ? data.query.toLowerCase().trim() : ""; const scripts = (await listAutomationScripts(project.path)).filter((script) => !query || `${script.id} ${script.intent} ${script.status} ${script.steps.map((step) => step.tool).join(" ")}`.toLowerCase().includes(query)).map((script) => ({ id: script.id, intent: script.intent, status: script.status, stepCount: script.steps.length, updatedAt: script.updatedAt, project: script.project, tools: script.steps.map((step) => step.tool) })); return { project: project.id, scripts }; }
if (action === "catalog") return { nodes: workflowNodeCatalog(typeof data.query === "string" ? data.query : "") };
if (action === "templates") return { templates: workflowTemplates() };
if (action === "variables") return { variables: await listWorkflowVariables(principal) };
diff --git a/lib/mcp/tools-learning-evidence.test.ts b/lib/mcp/tools-learning-evidence.test.ts
index aad8ce16..d8a3635e 100644
--- a/lib/mcp/tools-learning-evidence.test.ts
+++ b/lib/mcp/tools-learning-evidence.test.ts
@@ -107,7 +107,7 @@ describe("workflow_start bootstrap", () => {
it("replays a bounded read-only candidate script and promotes it to tested", async () => {
const runner = LEARNING_TOOLS.find((tool) => tool.name === "project_script_run")!;
- const { writeAutomationScript, readAutomationScript } = await import("@/lib/orchestration/repo-memory-artifacts");
+ const { writeAutomationScript, readAutomationScript, listAutomationScripts } = await import("@/lib/orchestration/repo-memory-artifacts");
const now = new Date().toISOString();
const script = {
schemaVersion: 1 as const, id: "script-test-health", recipeId: "recipe-test-health",
@@ -120,6 +120,7 @@ describe("workflow_start bootstrap", () => {
createdAt: now, updatedAt: now,
};
await writeAutomationScript(project, script, script.id, true);
+ await expect(listAutomationScripts(project)).resolves.toEqual(expect.arrayContaining([expect.objectContaining({ id: script.id, status: "candidate", intent: "verify system health" })]));
const result = await runner.run({ project, script_id: script.id }, { actor: "mcp:script", scope: "write" }) as {
status: string; success: boolean; stepsExecuted: number; outputs: Array<{ tool: string; state: string }>; manifestPath?: string;
};
diff --git a/lib/orchestration/repo-memory-artifacts.ts b/lib/orchestration/repo-memory-artifacts.ts
index 732f0c49..c688d858 100644
--- a/lib/orchestration/repo-memory-artifacts.ts
+++ b/lib/orchestration/repo-memory-artifacts.ts
@@ -54,3 +54,18 @@ export async function readAutomationScript(projectPath: string, id: string): Pro
}
return null;
}
+
+export async function listAutomationScripts(projectPath: string, limit = 200): Promise<AutomationScriptManifest[]> {
+ const agent = await existingRepoMemoryLayout(projectPath);
+ if (!agent) return [];
+ const dir = path.join(agent, "scripts");
+ const names = await fs.readdir(dir).catch(() => [] as string[]);
+ const ids = new Set<string>();
+ for (const name of names.slice(0, Math.max(1, Math.min(500, limit * 3)))) {
+ const id = name.endsWith(".candidate.json") ? name.slice(0, -".candidate.json".length) : name.endsWith(".json") ? name.slice(0, -".json".length) : "";
+ if (id) ids.add(id);
+ if (ids.size >= limit) break;
+ }
+ const rows = (await Promise.all([...ids].map((id) => readAutomationScript(projectPath, id)))).filter((row): row is AutomationScriptManifest => Boolean(row));
+ return rows.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
+}
diff --git a/lib/workflow/graph-engine.test.ts b/lib/workflow/graph-engine.test.ts
index cd565cb3..3f7ab530 100644
--- a/lib/workflow/graph-engine.test.ts
+++ b/lib/workflow/graph-engine.test.ts
@@ -103,6 +103,21 @@ describe("workflow graph engine", () => {
const recursive = await startWorkflowGraph(parent, {}, "subflow-recursive", context, () => undefined), recursiveDone = await workflowGraphRunStatus("graph-owner", recursive.id, 5000);
expect(recursiveDone.state).toBe("failed"); expect(recursiveDone.nodes.find((node) => node.id === "child")?.error).toContain("recursive");
});
+ it("executes a saved RASMIC script node through project_script_run", async () => {
+ let received: Record<string, unknown> | undefined;
+ const graph = await createWorkflowGraph("graph-owner", { name: "Script run", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "script-start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "script-node", name: "Saved script", type: "script", position: { x: 100, y: 0 }, config: { project: "mso", script_id: "script-health" } },
+ { id: "script-out", name: "Out", type: "output", position: { x: 200, y: 0 }, config: {} },
+ ], edges: [{ id: "script-e1", source: "script-start", target: "script-node" }, { id: "script-e2", source: "script-node", target: "script-out" }] });
+ const tool: CapabilityTool = { name: "project_script_run", description: "fixture", scope: "write", inputSchema: { type: "object", properties: {} }, run: async (args) => { received = args; return { success: true, status: "tested" }; } };
+ const started = await startWorkflowGraph(graph, {}, "script-run-once", context, (name) => name === tool.name ? tool : undefined);
+ const done = await workflowGraphRunStatus("graph-owner", started.id, 5000);
+ expect(done.state).toBe("completed");
+ expect(received).toMatchObject({ project: "mso", script_id: "script-health" });
+ expect(done.nodes.find((node) => node.id === "script-node")?.logs.join(" ")).toContain("script-health");
+ });
+
it("accepts secret-shaped runtime input but redacts it from persisted trigger receipts", async () => {
const graph = await createWorkflowGraph("graph-owner", { name: "Runtime input", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
{ id: "start-runtime", name: "Webhook", type: "webhook", position: { x: 0, y: 0 }, config: {} },
diff --git a/lib/workflow/node-catalog.ts b/lib/workflow/node-catalog.ts
index d6cd94bd..62fb62c5 100644
--- a/lib/workflow/node-catalog.ts
+++ b/lib/workflow/node-catalog.ts
@@ -18,7 +18,7 @@ export const WORKFLOW_NODE_CATALOG:WorkflowNodeCatalogItem[]=[
{type:"project_function",title:"Project Function",category:"Actions",description:"Call a project-owned function.",defaults:{}},
{type:"project_mcp",title:"Project MCP",category:"Actions",description:"Call a project-owned MCP tool.",defaults:{}},
{type:"integration",title:"Integration",category:"Actions",description:"Execute through an existing MSO integration connection; credentials stay outside the graph.",defaults:{}},
- {type:"script",title:"Script",category:"Actions",description:"Run a learned RASMIC script.",defaults:{}},
+ {type:"script",title:"Script",category:"Actions",description:"Run a saved validated RASMIC script by project and script id.",defaults:{}},
{type:"agent",title:"Agent",category:"AI",description:"Run an organization seat or focused project agent action.",defaults:{wait:true,max_scope:"write"}},
{type:"subflow",title:"Subflow",category:"Flow",description:"Run an existing project flow.",defaults:{}},
{type:"project",title:"Project",category:"Context",description:"Resolve canonical project identity/path at runtime.",defaults:{}},
diff --git a/lib/workflow/search.test.ts b/lib/workflow/search.test.ts
new file mode 100644
index 00000000..507adcc2
--- /dev/null
+++ b/lib/workflow/search.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import { workflowMatchesQuery, workflowTagQuery } from "./search";
+
+const graph: WorkflowGraph = {
+ version: 2,
+ id: "graph-1",
+ name: "Deploy QA Daily",
+ description: "Build and deploy the storefront after validation.",
+ status: "active",
+ inputs: {},
+ metadata: { folder: "Automation / Release", project: "mso", tags: ["qa", "daily deploy"] },
+ nodes: [
+ { id: "manual", name: "Manual Trigger", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "script", name: "Health Script", type: "script", position: { x: 100, y: 0 }, config: { script_id: "script-health", token: "must-not-index" } },
+ { id: "tool", name: "Run System Stats", type: "tool", position: { x: 200, y: 0 }, config: { tool: "sys_stats" } },
+ ],
+ edges: [],
+ createdAt: "2026-09-16T00:00:00.000Z",
+ updatedAt: "2026-09-16T00:00:00.000Z",
+ revision: "r1",
+};
+
+describe("workflow search", () => {
+ it("matches case-insensitive free text across workflow and node metadata", () => {
+ expect(workflowMatchesQuery(graph, "storefront health")).toBe(true);
+ expect(workflowMatchesQuery(graph, "SYS_STATS")).toBe(true);
+ expect(workflowMatchesQuery(graph, "missing")).toBe(false);
+ });
+
+ it("supports structured operators with AND semantics", () => {
+ expect(workflowMatchesQuery(graph, "deploy tag:qa status:active project:mso folder:release node:script")).toBe(true);
+ expect(workflowMatchesQuery(graph, "deploy tag:qa status:draft")).toBe(false);
+ expect(workflowMatchesQuery(graph, "tag:ops")).toBe(false);
+ });
+
+ it("supports quoted tag values", () => {
+ const query = workflowTagQuery("daily deploy");
+ expect(query).toBe('tag:"daily deploy"');
+ expect(workflowMatchesQuery(graph, query)).toBe(true);
+ });
+
+ it("applies explicit filters", () => {
+ expect(workflowMatchesQuery(graph, "", { tag: "qa", status: "active", project: "ms", folder: "automation", node: "system stats" })).toBe(true);
+ expect(workflowMatchesQuery(graph, "", { status: "archived" })).toBe(false);
+ });
+
+ it("does not index secret-like node config keys", () => {
+ expect(workflowMatchesQuery(graph, "must-not-index")).toBe(false);
+ });
+});
diff --git a/lib/workflow/search.ts b/lib/workflow/search.ts
new file mode 100644
index 00000000..897de9ad
--- /dev/null
+++ b/lib/workflow/search.ts
@@ -0,0 +1,86 @@
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+
+export type WorkflowSearchFilters = {
+ tag?: string;
+ status?: string;
+ project?: string;
+ folder?: string;
+ node?: string;
+};
+
+type SearchToken = { operator?: keyof WorkflowSearchFilters; value: string };
+const OPERATORS = new Set<keyof WorkflowSearchFilters>(["tag", "status", "project", "folder", "node"]);
+const SAFE_CONFIG_KEYS = new Set(["tool", "name", "server", "flow", "workflowId", "script_id", "query", "source", "message"]);
+const SECRETISH = /(secret|token|password|credential|authorization|cookie|api[_-]?key)/i;
+
+function norm(value: unknown): string {
+ return String(value ?? "").toLowerCase().trim();
+}
+
+function parseQuery(query: string): SearchToken[] {
+ const tokens: SearchToken[] = [];
+ const pattern = /(?:^|\s)(?:(tag|status|project|folder|node):(?:"([^"]*)"|'([^']*)'|(\S+))|"([^"]*)"|'([^']*)'|(\S+))/gi;
+ let match: RegExpExecArray | null;
+ while ((match = pattern.exec(query)) !== null) {
+ const operator = match[1]?.toLowerCase() as keyof WorkflowSearchFilters | undefined;
+ const value = match[2] ?? match[3] ?? match[4] ?? match[5] ?? match[6] ?? match[7] ?? "";
+ if (!value.trim()) continue;
+ tokens.push(operator && OPERATORS.has(operator) ? { operator, value } : { value });
+ }
+ return tokens;
+}
+
+function safeNodeConfigText(graph: WorkflowGraph): string {
+ const values: string[] = [];
+ for (const node of graph.nodes) {
+ for (const [key, value] of Object.entries(node.config ?? {})) {
+ if (!SAFE_CONFIG_KEYS.has(key) || SECRETISH.test(key)) continue;
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") values.push(String(value).slice(0, 500));
+ }
+ }
+ return values.join(" ").toLowerCase();
+}
+
+function freeText(graph: WorkflowGraph): string {
+ return [
+ graph.name,
+ graph.description,
+ graph.status,
+ graph.metadata.folder,
+ graph.metadata.project,
+ ...(graph.metadata.tags ?? []),
+ ...graph.nodes.flatMap((node) => [node.name, node.type]),
+ safeNodeConfigText(graph),
+ ].filter(Boolean).join(" ").toLowerCase();
+}
+
+function matchesOperator(graph: WorkflowGraph, operator: keyof WorkflowSearchFilters, rawValue: string): boolean {
+ const value = norm(rawValue);
+ if (!value) return true;
+ if (operator === "tag") return (graph.metadata.tags ?? []).some((tag) => norm(tag) === value);
+ if (operator === "status") return norm(graph.status) === value;
+ if (operator === "project") return norm(graph.metadata.project).includes(value);
+ if (operator === "folder") return norm(graph.metadata.folder).includes(value);
+ if (operator === "node") return graph.nodes.some((node) => `${node.type} ${node.name}`.toLowerCase().includes(value));
+ return false;
+}
+
+export function workflowMatchesQuery(graph: WorkflowGraph, query = "", filters: WorkflowSearchFilters = {}): boolean {
+ for (const [operator, raw] of Object.entries(filters) as Array<[keyof WorkflowSearchFilters, string | undefined]>) {
+ if (raw && !matchesOperator(graph, operator, raw)) return false;
+ }
+ const haystack = freeText(graph);
+ for (const token of parseQuery(query)) {
+ if (token.operator) {
+ if (!matchesOperator(graph, token.operator, token.value)) return false;
+ continue;
+ }
+ if (!haystack.includes(norm(token.value))) return false;
+ }
+ return true;
+}
+
+export function workflowTagQuery(tag: string): string {
+ const safe = tag.replace(/["\r\n]/g, " ").trim();
+ return /\s/.test(safe) ? `tag:"${safe}"` : `tag:${safe}`;
+}