Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

fix(workflow): reject unsupported steps and invalid condition gates

Rudy Celekli235f2f9449bb
diff --git a/v3/@claude-flow/cli/__tests__/workflow-validation-runtime.test.ts b/v3/@claude-flow/cli/__tests__/workflow-validation-runtime.test.ts
index a5136ffbc0..9bb83ef00e 100644
--- a/v3/@claude-flow/cli/__tests__/workflow-validation-runtime.test.ts
+++ b/v3/@claude-flow/cli/__tests__/workflow-validation-runtime.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const state = vi.hoisted(() => ({ cwd: '', execute: vi.fn() }));
@@ -40,3 +40,45 @@ it('still warns about a task with no available agent and keeps legacy agent decl
expect(await validate({ steps: [{ name: 'missing', type: 'task' }] })).toMatchObject({ valid: false, warnings: [expect.objectContaining({ line: 1 })] });
expect(await validate({ steps: [{ agent: 'legacy' }, { agentType: 'legacy' }, { agent_type: 'other' }] })).toMatchObject({ valid: true, stats: { agents: 2 } });
});
+
+it('rejects a misspelled condition gate before saving or executing the workflow', async () => {
+ const doc = { name: 'gate', steps: [
+ { name: 'work', type: 'task', config: { agentId: 'worker' } },
+ { name: 'approval', type: 'condition', config: { condition: 'approved == true' } },
+ ] };
+ expect(await call('workflow_create', doc)).toMatchObject({ success: false, error: expect.stringContaining('config.when') });
+ expect(await validate(doc)).toMatchObject({ valid: false, errors: [expect.objectContaining({ line: 2 })] });
+ expect(state.execute).not.toHaveBeenCalled();
+});
+
+it.each(['parallel', 'loop'])('rejects an unimplemented %s step instead of recording a successful workflow', async type => {
+ const doc = { name: type, steps: [{ name: 'unsupported', type }] };
+ expect(await call('workflow_create', doc)).toMatchObject({ success: false, error: expect.stringContaining('not implemented') });
+ expect(await validate(doc)).toMatchObject({ valid: false, errors: [expect.objectContaining({ line: 1 })] });
+});
+
+it('fails a previously saved workflow with an unsupported step before dispatching a task', async () => {
+ const created = await call('workflow_create', { name: 'legacy', steps: [
+ { name: 'work', type: 'task', config: { agentId: 'worker' } },
+ { name: 'wait', type: 'wait', config: { ms: 0 } },
+ ] });
+ const storePath = join(state.cwd, '.claude-flow', 'workflows', 'store.json');
+ const store = JSON.parse(readFileSync(storePath, 'utf-8'));
+ store.workflows[created.workflowId].steps[1].type = 'loop';
+ writeFileSync(storePath, JSON.stringify(store));
+
+ expect(await call('workflow_execute', { workflowId: created.workflowId })).toMatchObject({
+ status: 'failed', failedStep: 'step-2', error: expect.stringContaining('not implemented'),
+ });
+ expect(state.execute).not.toHaveBeenCalled();
+});
+
+it('evaluates an explicit boolean condition without treating false as a successful match', async () => {
+ const created = await call('workflow_create', { name: 'approval', variables: { approved: false }, steps: [
+ { name: 'gate', type: 'condition', config: { when: 'approved == true' } },
+ ] });
+ expect(await call('workflow_execute', { workflowId: created.workflowId })).toMatchObject({ status: 'completed' });
+ const storePath = join(state.cwd, '.claude-flow', 'workflows', 'store.json');
+ const store = JSON.parse(readFileSync(storePath, 'utf-8'));
+ expect(store.workflows[created.workflowId].steps[0].result).toMatchObject({ truthy: false });
+});
diff --git a/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts
index 497b1299a2..be7ba21333 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts
@@ -46,6 +46,37 @@ interface WorkflowStore {
version: string;
}
+type Condition = { constant: boolean } | { variable: string; expected: string | number | boolean };
+
+function parseCondition(when: unknown): Condition | Error {
+ if (typeof when !== 'string' || !when.trim()) {
+ return new Error('condition step requires a non-empty config.when');
+ }
+ const expression = when.trim();
+ if (expression === 'true' || expression === 'false') {
+ return { constant: expression === 'true' };
+ }
+ const match = expression.match(/^([a-zA-Z_]\w*)\s*===?\s*(?:'([^']*)'|"([^"]*)"|(-?\d+(?:\.\d+)?)|(true|false))$/);
+ if (!match) {
+ return new Error('condition config.when must compare a variable to a quoted string, number, or boolean using == or ===');
+ }
+ const expected = match[2] ?? match[3] ?? (match[4] !== undefined ? Number(match[4]) : match[5] === 'true');
+ return { variable: match[1], expected };
+}
+
+function validateExecutableStep(step: Pick<WorkflowStep, 'type' | 'config'>): string | undefined {
+ if (step.type === 'parallel' || step.type === 'loop') {
+ return `step type '${step.type}' is not implemented by the workflow runtime`;
+ }
+ if (step.type === 'condition') {
+ const parsed = parseCondition(step.config?.when);
+ if (parsed instanceof Error) return parsed.message;
+ } else if (step.type !== 'task' && step.type !== 'wait') {
+ return `unsupported workflow step type '${step.type}'`;
+ }
+ return undefined;
+}
+
function getWorkflowDir(): string {
return join(getProjectCwd(), STORAGE_DIR, WORKFLOW_DIR);
}
@@ -226,8 +257,8 @@ export const workflowTools: MCPTool[] = [
type: 'object',
properties: {
name: { type: 'string' },
- type: { type: 'string', enum: ['task', 'condition', 'parallel', 'loop', 'wait'] },
- config: { type: 'object' },
+ type: { type: 'string', enum: ['task', 'condition', 'wait'] },
+ config: { type: 'object', description: 'Condition steps require config.when; parallel and loop steps are not yet supported' },
},
},
},
@@ -255,6 +286,11 @@ export const workflowTools: MCPTool[] = [
status: 'pending' as const,
}));
+ for (const step of steps) {
+ const error = validateExecutableStep(step);
+ if (error) return { success: false, error: `${step.stepId} (${step.name}): ${error}` };
+ }
+
const workflow: WorkflowRecord = {
workflowId,
name: input.name as string,
@@ -307,6 +343,21 @@ export const workflowTools: MCPTool[] = [
return { workflowId, error: 'Workflow already running' };
}
+ // Older stored workflows may predate creation-time validation. Reject
+ // unsupported steps before dispatching any task with side effects.
+ for (const step of workflow.steps) {
+ const error = validateExecutableStep(step);
+ if (error) {
+ workflow.status = 'failed';
+ workflow.error = `${step.stepId} (${step.name}): ${error}`;
+ step.status = 'failed';
+ step.result = { error: workflow.error };
+ workflow.completedAt = new Date().toISOString();
+ saveWorkflowStore(store);
+ return { workflowId, status: 'failed', failedStep: step.stepId, error: workflow.error };
+ }
+ }
+
// Indices may name a step or the end boundary (used when resuming
// after the final step). Reject invalid control flow before any writes.
const validIndex = (value: unknown): value is number =>
@@ -434,26 +485,20 @@ export const workflowTools: MCPTool[] = [
step.result = { waitedMs: ms };
stepEntry = { stepId: step.stepId, type: 'wait', status: 'completed', durationMs: ms };
} else if (step.type === 'condition') {
- // Simple condition: config.when is a JS expression evaluated against workflow.variables.
- // For safety, we only support `var === 'value'` or `var === number`.
const cfg = step.config as Record<string, unknown>;
- const expr = String(cfg.when || 'true').trim();
- const m = expr.match(/^([a-zA-Z_][\w]*)\s*===?\s*(['\"])?([^'\"]*)\2?$/);
- let truthy = false;
- if (m) {
- const v = workflow.variables[m[1]];
- const expected = m[2] ? m[3] : Number(m[3]);
- truthy = v === expected;
- } else if (expr === 'true') truthy = true;
+ const parsed = parseCondition(cfg.when);
+ if (parsed instanceof Error) throw parsed;
+ const truthy = 'constant' in parsed
+ ? parsed.constant
+ : workflow.variables[parsed.variable] === parsed.expected;
+ const expr = String(cfg.when).trim();
step.result = { conditionExpr: expr, truthy };
// condition can declare a target step index to jump to via cfg.thenStep / cfg.elseStep
if (typeof cfg.thenStep === 'number' && truthy) i = (cfg.thenStep as number) - 1;
if (typeof cfg.elseStep === 'number' && !truthy) i = (cfg.elseStep as number) - 1;
stepEntry = { stepId: step.stepId, type: 'condition', status: 'completed' };
} else {
- // parallel/loop are deferred — mark skipped honestly rather than mock-completing.
- step.result = { _note: `step type '${step.type}' not yet implemented in runtime` };
- stepEntry = { stepId: step.stepId, type: step.type, status: 'skipped' };
+ throw new Error(`step type '${step.type}' is not implemented by the workflow runtime`);
}
step.status = stepEntry.status === 'skipped' ? 'skipped' : 'completed';
step.completedAt = new Date().toISOString();
@@ -980,6 +1025,13 @@ export const workflowTools: MCPTool[] = [
const agentSet = new Set<string>();
steps.forEach((s, i) => {
const step = (s ?? {}) as Record<string, unknown>;
+ if (typeof step.type === 'string') {
+ const error = validateExecutableStep({
+ type: step.type as WorkflowStep['type'],
+ config: (step.config ?? {}) as Record<string, unknown>,
+ });
+ if (error) errors.push({ line: i + 1, message: `step ${i + 1}: ${error}`, severity: 'error' });
+ }
// Match workflow_execute: control steps do not dispatch agents,
// and task steps use config.agentId or the workflow default.
const config = step.config as Record<string, unknown> | undefined;