🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(workflow): list, status, stop and run read the shape and errors the workflow tools return
Rudy Celekli28a9fefaa3d4
diff --git a/v3/@claude-flow/cli/__tests__/workflow-cli-tool-shape.test.ts b/v3/@claude-flow/cli/__tests__/workflow-cli-tool-shape.test.tsnew file mode 100644index 0000000000..87c4309e9e--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/workflow-cli-tool-shape.test.ts@@ -0,0 +1,102 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++// Drive the `workflow` CLI subcommands against the real workflow MCP tools so a+// drift between what the tool returns and what the command reads shows up here.+const state = vi.hoisted(() => ({ cwd: '', tools: [] as any[], success: vi.fn(), error: vi.fn(), table: vi.fn(), info: vi.fn() }));+vi.mock('../src/mcp-tools/types.js', () => ({ getProjectCwd: () => state.cwd }));+vi.mock('../src/mcp-client.js', () => ({+ MCPClientError: class extends Error {},+ callMCPTool: (name: string, input: object) => state.tools.find(t => t.name === name).handler(input),+}));+vi.mock('../src/output.js', () => ({+ output: new Proxy({}, {+ get: (_t, prop) =>+ prop === 'printSuccess' ? state.success+ : prop === 'printError' ? state.error+ : prop === 'printTable' ? state.table+ : prop === 'printInfo' ? state.info+ : prop === 'createSpinner' ? () => ({ start() {}, succeed() {}, fail() {}, stop() {} })+ : (value: unknown) => value,+ }),+}));+import { workflowTools } from '../src/mcp-tools/workflow-tools.js';+import { workflowCommand } from '../src/commands/workflow.js';++state.tools = workflowTools;+const tool = (name: string, input: object) => workflowTools.find(t => t.name === name)!.handler(input) as Promise<any>;+const sub = (name: string) => workflowCommand.subcommands!.find(c => c.name === name)!;+const run = (name: string, args: string[] = [], flags: Record<string, unknown> = {}) =>+ sub(name).action!({ args, flags, interactive: false } as any);+const start = async () => (await tool('workflow_run', { template: 'bugfix', task: 'fix it' })).workflowId as string;++beforeEach(() => {+ state.cwd = mkdtempSync(join(tmpdir(), 'ruflo-workflow-cli-'));+ for (const m of [state.success, state.error, state.table, state.info]) m.mockReset();+});+afterEach(() => rmSync(state.cwd, { recursive: true, force: true }));++describe('workflow run', () => {+ it('reports a rejected template as an error instead of crashing on the missing summary', async () => {+ const result = await run('run', [], { template: 'bad template!' });+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(state.error).not.toHaveBeenCalledWith(expect.stringContaining('TypeError'));+ });+});++describe('workflow list', () => {+ it('lists existing workflows when no status filter is given', async () => {+ const workflowId = await start();+ const result = await run('list');+ expect(result).toMatchObject({ success: true });+ expect(state.info).not.toHaveBeenCalledWith('No workflows found');+ const rows = state.table.mock.calls[0][0].data;+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ id: workflowId, status: 'running' });+ });+});++describe('workflow status', () => {+ it('shows a stored workflow instead of crashing on a missing metrics block', async () => {+ const workflowId = await start();+ const result = await run('status', [workflowId]);+ expect(result).toMatchObject({ success: true });+ expect(state.error).not.toHaveBeenCalled();+ });++ it('reports a missing workflow as an error', async () => {+ const result = await run('status', ['workflow-nope']);+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(state.error).toHaveBeenCalledWith(expect.stringContaining('Workflow not found'));+ expect(state.error).not.toHaveBeenCalledWith(expect.stringContaining('TypeError'));+ });+});++describe('workflow stop', () => {+ it('stops a running workflow', async () => {+ const workflowId = await start();+ const result = await run('stop', [workflowId], { force: true });+ expect(result).toMatchObject({ success: true });+ expect(state.success).toHaveBeenCalledWith(`Workflow ${workflowId} stopped`);+ expect((await tool('workflow_status', { workflowId })).status).toBe('failed');+ });++ it('does not claim a missing workflow was stopped', async () => {+ const result = await run('stop', ['workflow-nope'], { force: true });+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(state.success).not.toHaveBeenCalled();+ expect(state.error).toHaveBeenCalledWith(expect.stringContaining('Workflow not found'));+ });++ it('does not claim an already finished workflow was stopped', async () => {+ const workflowId = await start();+ await run('stop', [workflowId], { force: true });+ state.success.mockReset();+ const result = await run('stop', [workflowId], { force: true });+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(state.success).not.toHaveBeenCalled();+ expect(state.error).toHaveBeenCalledWith(expect.stringContaining('already finished'));+ });+});diff --git a/v3/@claude-flow/cli/src/commands/workflow.ts b/v3/@claude-flow/cli/src/commands/workflow.tsindex 4770aad20e..60d272fd03 100644--- a/v3/@claude-flow/cli/src/commands/workflow.ts+++ b/v3/@claude-flow/cli/src/commands/workflow.ts@@ -138,6 +138,13 @@ const runCommand: Command = {},});+ const runError = toolError(result);+ if (runError || !result.metrics) {+ spinner.fail('Workflow failed');+ output.printError(`Workflow error: ${runError ?? 'workflow_run returned no workflow summary'}`);+ return { success: false, exitCode: 1 };+ }+if (dryRun) {spinner.succeed('Workflow validated successfully');} else {@@ -327,19 +334,26 @@ const listCommand: Command = {try {const result = await callMCPTool<{workflows: Array<{- id: string;- template: string;+ workflowId: string;+ name: string;status: string;- startedAt: string;+ stepCount: number;+ createdAt: string;completedAt?: string;- progress: number;}>;total: number;+ error?: string;}>('workflow_list', {status: status || 'all',limit,});+ const listError = toolError(result);+ if (listError || !Array.isArray(result.workflows)) {+ output.printError(`Failed to list workflows: ${listError ?? 'workflow_list returned no workflows'}`);+ return { success: false, exitCode: 1 };+ }+if (ctx.flags.format === 'json') {output.printJson(result);return { success: true, data: result };@@ -356,13 +370,19 @@ const listCommand: Command = {output.printTable({columns: [- { key: 'id', header: 'ID', width: 15 },- { key: 'template', header: 'Template', width: 15 },+ { key: 'id', header: 'ID', width: 30 },+ { key: 'name', header: 'Name', width: 24 },{ key: 'status', header: 'Status', width: 12, format: formatStageStatus },- { key: 'progress', header: 'Progress', width: 10, align: 'right', format: (v) => `${v}%` },- { key: 'startedAt', header: 'Started', width: 20, format: (v) => new Date(String(v)).toLocaleString() }+ { key: 'steps', header: 'Steps', width: 6, align: 'right' },+ { key: 'createdAt', header: 'Created', width: 20, format: (v) => new Date(String(v)).toLocaleString() }],- data: result.workflows+ data: result.workflows.map(w => ({+ id: w.workflowId,+ name: w.name,+ status: w.status,+ steps: w.stepCount,+ createdAt: w.createdAt,+ }))});output.writeln();@@ -403,55 +423,58 @@ const statusCommand: Command = {try {const result = await callMCPTool<{- id: string;- template: string;+ workflowId: string;+ name: string;status: string;progress: number;- stages: Array<{- name: string;- status: string;- startedAt?: string;- completedAt?: string;- agents: string[];- output?: string;- }>;- metrics: {- duration: number;- tokensUsed: number;- agentsSpawned: number;- };+ currentStep: number;+ totalSteps: number;+ completedSteps: number;+ startedAt?: string;+ completedAt?: string;+ steps?: Array<{ stepId: string; name: string; type: string; status: string }>;+ error?: string;}>('workflow_status', {workflowId,+ verbose: true,});+ const statusError = toolError(result);+ if (statusError) {+ output.printError(`Failed to get status: ${statusError}`);+ return { success: false, exitCode: 1 };+ }+if (ctx.flags.format === 'json') {output.printJson(result);return { success: true, data: result };}+ const started = result.startedAt ? Date.parse(result.startedAt) : NaN;+ const ended = result.completedAt ? Date.parse(result.completedAt) : Date.now();+output.writeln();output.printBox([- `ID: ${result.id}`,- `Template: ${result.template}`,+ `ID: ${result.workflowId}`,+ `Name: ${result.name}`,`Status: ${formatStageStatus(result.status)}`,- `Progress: ${result.progress}%`,- `Duration: ${(result.metrics.duration / 1000).toFixed(1)}s`,- `Tokens: ${result.metrics.tokensUsed.toLocaleString()}`,- `Agents: ${result.metrics.agentsSpawned}`+ `Progress: ${Math.round(result.progress)}% (${result.completedSteps}/${result.totalSteps} steps)`,+ ...(Number.isNaN(started) ? [] : [`Duration: ${((ended - started) / 1000).toFixed(1)}s`]),+ ...(result.error ? [`Error: ${result.error}`] : []),].join('\n'),'Workflow Status');output.writeln();- output.writeln(output.bold('Stage Progress'));+ output.writeln(output.bold('Step Progress'));output.printTable({columns: [- { key: 'name', header: 'Stage', width: 20 },+ { key: 'name', header: 'Step', width: 24 },+ { key: 'type', header: 'Type', width: 10 },{ key: 'status', header: 'Status', width: 12, format: formatStageStatus },- { key: 'agents', header: 'Agents', width: 25, format: (v) => Array.isArray(v) ? v.length.toString() : '0' }],- data: result.stages+ data: result.steps ?? []});return { success: true, data: result };@@ -505,11 +528,18 @@ const stopCommand: Command = {workflowId: string;stopped: boolean;stoppedAt: string;+ error?: string;}>('workflow_stop', {workflowId,graceful: !force,});+ const stopError = toolError(result);+ if (stopError || result.stopped !== true) {+ output.printError(`Failed to stop workflow: ${stopError ?? 'the workflow was not stopped'}`);+ return { success: false, exitCode: 1 };+ }+output.printSuccess(`Workflow ${workflowId} stopped`);return { success: true, data: result };@@ -678,6 +708,17 @@ export const workflowCommand: Command = {};// Helper functions+/**+ * The workflow MCP tools report failure as `{ error }` (or `{ success: false, error }`)+ * instead of throwing, so a command that reads the result without checking it prints+ * a false success or crashes on a field the error result does not have.+ */+function toolError(result: unknown): string | undefined {+ const r = result as { error?: unknown } | undefined | null;+ if (!r) return 'the workflow tool returned no result';+ return typeof r.error === 'string' && r.error.length > 0 ? r.error : undefined;+}+function formatStageStatus(status: unknown): string {const statusStr = String(status);switch (statusStr) {diff --git a/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.tsindex be7ba21333..6a425d0982 100644--- a/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts@@ -635,7 +635,8 @@ export const workflowTools: MCPTool[] = [let workflows = Object.values(store.workflows);// Apply filters- if (input.status) {+ // 'all' is the CLI's explicit "no filter" value (`workflow list` sends it by default).+ if (input.status && input.status !== 'all') {workflows = workflows.filter(w => w.status === input.status);}