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(task,console): task_update accepts only the five statuses; a task stored as "complete" is never shown pending or re-dispatched

Dragan Spiridonovbc1421677731
diff --git a/plugins/ruflo-console/hooks/data/automate.ts b/plugins/ruflo-console/hooks/data/automate.ts
index 8735e31b0c..958f413f1e 100644
--- a/plugins/ruflo-console/hooks/data/automate.ts
+++ b/plugins/ruflo-console/hooks/data/automate.ts
@@ -262,10 +262,30 @@ export function sparkline(values: readonly number[]): string {
return finite.map(value => BARS[hi === lo ? 3 : Math.round(((value - lo) / (hi - lo)) * (BARS.length - 1))]).join('')
}
-/** A task's lane on the kanban: what ruflo's task tools write (pending, in_progress, completed, failed, cancelled). */
+/**
+ * A stored task status as one of ruflo's five, reading the spellings older CLIs stored as written ("complete", "done",
+ * "canceled", "running"); anything else is returned trimmed and lower-cased, so callers that compare against the five
+ * treat it as not finished. Every reader that decides on status goes through this (kanban, mission scheduling, cancel).
+ */
+export function taskStatusOf(status: string | undefined): string {
+ const key = (status ?? '').trim().toLowerCase()
+
+ if (key === 'complete' || key === 'done') return 'completed'
+ if (key === 'canceled') return 'cancelled'
+ if (key === 'running' || key === 'in-progress' || key === 'inprogress') return 'in_progress'
+
+ return key
+}
+
+/**
+ * A task's lane on the kanban: what ruflo's task tools write (pending, in_progress, completed, failed, cancelled), plus the
+ * spellings older CLIs stored as written (task_update took any string): "complete" sat in PENDING and inflated its count.
+ */
export function laneOf(status: string): 'pending' | 'running' | 'done' {
- if (/^(in_progress|running|assigned|active|busy)$/.test(status)) return 'running'
- if (/^(completed|done|failed|cancelled|canceled|error)$/.test(status)) return 'done'
+ const key = status.trim().toLowerCase()
+
+ if (/^(in_progress|in-progress|inprogress|running|assigned|active|busy)$/.test(key)) return 'running'
+ if (/^(completed|complete|done|failed|cancelled|canceled|error)$/.test(key)) return 'done'
return 'pending'
}
diff --git a/plugins/ruflo-console/hooks/data/wf-guide.ts b/plugins/ruflo-console/hooks/data/wf-guide.ts
index 6434106313..2dead8062b 100644
--- a/plugins/ruflo-console/hooks/data/wf-guide.ts
+++ b/plugins/ruflo-console/hooks/data/wf-guide.ts
@@ -17,6 +17,7 @@ import { cleanText } from './wf-clean'
import { membersOf } from './hive'
import type { AgentRecord, ClaimRecord, HiveAgentRecord, HiveInfo, SwarmInfo, TaskRecord } from './parse'
import { idOf, plain } from './parse'
+import { taskStatusOf } from './automate'
import type { WfAgent, WfRun } from './workflows'
export type NestKind = 'swarm' | 'hive' | 'queen' | 'worker' | 'claim' | 'task' | 'note'
@@ -24,7 +25,8 @@ export type NestRow = { depth: number; kind: NestKind; label: string; detail: st
const MAX_ROWS = 60
const isOpenClaim = (claim: ClaimRecord): boolean => !/released|completed|cancel/i.test(claim.status)
-const isOpenTask = (task: TaskRecord): boolean => !/completed|failed|cancelled/i.test(task.status)
+// Finished by its canonical status ("complete", "done", "canceled" from older CLIs included) or by the words the regex always matched.
+const isOpenTask = (task: TaskRecord): boolean => !(['completed', 'failed', 'cancelled'].includes(taskStatusOf(task.status)) || /completed|failed|cancelled/i.test(task.status))
/** swarm > hive (queen) > worker > claim > task, each level only from what the stores say; a missing level is a note, never invented. */
export function nestingOf(input: { swarm: SwarmInfo | null; hive: HiveInfo | null; agents: readonly AgentRecord[]; hiveAgents: readonly HiveAgentRecord[]; claims: readonly ClaimRecord[]; tasks: readonly TaskRecord[] }): NestRow[] {
diff --git a/plugins/ruflo-console/hooks/data/wf-links.ts b/plugins/ruflo-console/hooks/data/wf-links.ts
index 3be17bc930..53c54b6d25 100644
--- a/plugins/ruflo-console/hooks/data/wf-links.ts
+++ b/plugins/ruflo-console/hooks/data/wf-links.ts
@@ -10,6 +10,7 @@
import type { MissionRecord } from '../mission-types'
import type { Mission } from './missions'
import { plain, type TaskRecord } from './parse'
+import { taskStatusOf } from './automate'
import type { WfRun } from './workflows'
/** A mission task as either source names it: the console's ledger, or the ADR-406 observation. */
@@ -83,7 +84,7 @@ export function refsOf(ledger: Iterable<MissionRecord>, observed: readonly Missi
}
const tagOf = (task: TaskRecord, prefix: 'mission' | 'task'): string | undefined => task.tags?.find(tag => tag.startsWith(`${prefix}:`))?.slice(prefix.length + 1)
-const isOpen = (status: string | undefined): boolean => status !== 'completed' && status !== 'failed' && status !== 'cancelled'
+const isOpen = (status: string | undefined): boolean => !['completed', 'failed', 'cancelled'].includes(taskStatusOf(status))
/** Builds the index over every agent of `runs` (the ruflo swarm folded in as a run, as the page holds it). */
export function linkAgents(refs: readonly MissionTaskRef[], runs: readonly WfRun[], tasks: readonly TaskRecord[]): LinkIndex {
diff --git a/plugins/ruflo-console/hooks/mission-control.ts b/plugins/ruflo-console/hooks/mission-control.ts
index 4d3daefa8e..132b91d12d 100644
--- a/plugins/ruflo-console/hooks/mission-control.ts
+++ b/plugins/ruflo-console/hooks/mission-control.ts
@@ -12,6 +12,7 @@ import { PHASE_NAME, plan as planOf, stageOf, type Plan, type Profile, profileOf
import { capGate, capOf, refreshCost } from './mission-guard'
import type { Host } from './host'
import { plain, type TaskRecord } from './data/parse'
+import { taskStatusOf } from './data/automate'
import { keepText } from './field-keep'
import { checkLimit, keepLines, LONG_TEXT_MAX, withBreaks } from './full-text'
import { isAvailable, MISSION_SKILLS, slashOf, GOALS_PLUGIN } from './mission-skills'
@@ -75,7 +76,8 @@ export function derive(mission: MissionRecord, tasks: readonly TaskRecord[]): Ma
const out = new Map<string, Derived>()
for (const task of mission.tasks) {
- const status = rufloTaskOf(tasks, task)?.status
+ // Read through taskStatusOf: a task stored as "complete" by an older CLI is done, never handed to Claude again.
+ const status = taskStatusOf(rufloTaskOf(tasks, task)?.status)
const done = (id: string) => out.get(id) === 'done'
out.set(task.id, status === 'completed' ? 'done' : status === 'failed' ? 'failed' : status === 'cancelled' ? 'cancelled' : status === 'in_progress' || status === 'running' ? 'running' : task.dependsOn.every(done) ? 'ready' : 'waiting')
diff --git a/plugins/ruflo-console/hooks/mission-specs.ts b/plugins/ruflo-console/hooks/mission-specs.ts
index f241473072..62ea13a1f4 100644
--- a/plugins/ruflo-console/hooks/mission-specs.ts
+++ b/plugins/ruflo-console/hooks/mission-specs.ts
@@ -1,6 +1,7 @@
/** The confirm-gated writes of Mission Control: create the mission and its tasks, hand a task to Claude, cancel. */
import type { ActionSpec } from './actions'
import { plain, type TaskRecord } from './data/parse'
+import { taskStatusOf } from './data/automate'
import { stageOf, toMissionPlan, type Profile } from './goap'
import { checkLimit, MISSION_OBJECTIVE_MAX } from './full-text'
import type { Host } from './host'
@@ -239,7 +240,7 @@ export function setPaused(state: State, host: Host, paused: boolean): void {
/** Cancel: cancel every task not done in the ruflo task store, then ask the mission record to cancel (allowed only from some states). */
export function cancelSpec(state: State, host: Host, mission: MissionRecord, tasks: readonly TaskRecord[]): ActionSpec {
- const open = mission.tasks.filter(task => task.rufloTaskId !== undefined && !['completed', 'cancelled'].includes(rufloTaskOf(tasks, task)?.status ?? ''))
+ const open = mission.tasks.filter(task => task.rufloTaskId !== undefined && !['completed', 'cancelled'].includes(taskStatusOf(rufloTaskOf(tasks, task)?.status)))
return {
label: `cancel mission ${mission.id} (${open.length} open tasks)`,
diff --git a/plugins/ruflo-console/tests/automate.spec.ts b/plugins/ruflo-console/tests/automate.spec.ts
index aa3d74821a..3a3e248545 100644
--- a/plugins/ruflo-console/tests/automate.spec.ts
+++ b/plugins/ruflo-console/tests/automate.spec.ts
@@ -68,6 +68,11 @@ describe('the catalog', () => {
expect(taskVerbs('completed')).toEqual([])
expect(['pending', 'in_progress', 'completed', 'cancelled', 'weird'].map(laneOf)).toEqual(['pending', 'running', 'done', 'done', 'pending'])
})
+
+ it('a task an older CLI stored as "complete" is done, not pending, and offers no assign or cancel', () => {
+ expect(['complete', 'Completed ', 'in-progress', 'canceled'].map(laneOf)).toEqual(['done', 'done', 'running', 'done'])
+ expect(taskVerbs('complete')).toEqual([])
+ })
})
describe('typed values', () => {
diff --git a/plugins/ruflo-console/tests/mission-control.spec.ts b/plugins/ruflo-console/tests/mission-control.spec.ts
index 3323b15114..36eb02e873 100644
--- a/plugins/ruflo-console/tests/mission-control.spec.ts
+++ b/plugins/ruflo-console/tests/mission-control.spec.ts
@@ -83,6 +83,15 @@ describe('mission control: status comes from the ruflo task store', () => {
expect(progressOf(mission, tasks)).toEqual({ done: 1, total: 3 })
})
+ it('never hands a task an older CLI stored as "complete" to Claude again', () => {
+ const mission = missionOf()
+
+ expect(derive(mission, [task('r1', 'complete', [])]).get('t1')).toBe('done')
+ expect(nextTask(mission, [task('r1', 'complete', [])])?.id).toBe('t2')
+ expect(derive(mission, [task('r1', ' Done ', [])]).get('t1')).toBe('done')
+ expect(derive(mission, [task('r1', 'canceled', [])]).get('t1')).toBe('cancelled')
+ })
+
it('hands out the first ready task, none while one is running or failed, none while paused or cancelled', () => {
const mission = missionOf()
diff --git a/v3/@claude-flow/cli/__tests__/task-update-status-enum.test.ts b/v3/@claude-flow/cli/__tests__/task-update-status-enum.test.ts
new file mode 100644
index 0000000000..89e512e5da
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/task-update-status-enum.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+const state = vi.hoisted(() => ({ cwd: '' }));
+vi.mock('../src/mcp-tools/types.js', () => ({ getProjectCwd: () => state.cwd }));
+import { statusOf, taskTools } from '../src/mcp-tools/task-tools.js';
+const call = (name: string, input: any): Promise<any> => taskTools.find(t => t.name === name)!.handler(input) as Promise<any>;
+const stored = (id: string) => JSON.parse(readFileSync(join(state.cwd, '.claude-flow/tasks/store.json'), 'utf8')).tasks[id];
+beforeEach(() => { state.cwd = mkdtempSync(join(tmpdir(), 'ruflo-task-status-')); });
+afterEach(() => rmSync(state.cwd, { recursive: true, force: true }));
+
+it('stores a known alias as its canonical status', async () => {
+ const { taskId } = await call('task_create', { type: 'test', description: 'task' });
+ const result = await call('task_update', { taskId, status: 'complete' });
+ expect(result.success).toBe(true);
+ expect(stored(taskId).status).toBe('completed');
+});
+
+it('refuses a status that is none of the five and leaves the task unchanged', async () => {
+ const { taskId } = await call('task_create', { type: 'test', description: 'task' });
+ const result = await call('task_update', { taskId, status: 'finished-ish', progress: 50 });
+ expect(result).toMatchObject({ success: false });
+ expect(result.error).toContain('pending, in_progress, completed, failed, cancelled');
+ expect(stored(taskId)).toMatchObject({ status: 'pending', progress: 0 });
+});
+
+it('accepts the canonical statuses in any case and rejects prototype keys', () => {
+ expect(['pending', 'IN_PROGRESS', ' failed ', 'running', 'canceled'].map(statusOf)).toEqual(['pending', 'in_progress', 'failed', 'in_progress', 'cancelled']);
+ expect(['constructor', '__proto__', 'toString', 42, null].map(statusOf)).toEqual([null, null, null, null, null]);
+});
+
+it('keeps aliases reachable on every transport: no schema enum for the registry to reject first', () => {
+ const schema = taskTools.find(t => t.name === 'task_update')!.inputSchema as any;
+ expect(schema.properties.status.enum).toBeUndefined();
+ expect(schema.properties.status.description).toContain('pending, in_progress, completed, failed or cancelled');
+});
+
+it('refuses an empty status instead of treating it as absent', async () => {
+ const { taskId } = await call('task_create', { type: 'test', description: 'task' });
+ expect(await call('task_update', { taskId, status: '' })).toMatchObject({ success: false });
+});
+
+it('completing through task_update finishes the task like task_complete: progress, time, worker freed and counted once', async () => {
+ mkdirSync(join(state.cwd, '.claude-flow/agents'), { recursive: true });
+ writeFileSync(join(state.cwd, '.claude-flow/agents/store.json'), JSON.stringify({ agents: { worker: { agentId: 'worker', status: 'idle', currentTask: null, taskCount: 0 } }, version: '3.0.0' }));
+ const { taskId } = await call('task_create', { type: 'test', description: 'task' });
+ await call('task_assign', { taskId, agentIds: ['worker'] });
+ await call('task_update', { taskId, status: 'complete' });
+ await call('task_update', { taskId, status: 'completed' });
+ expect(stored(taskId)).toMatchObject({ status: 'completed', progress: 100 });
+ expect(stored(taskId).completedAt).toEqual(expect.any(String));
+ const worker = JSON.parse(readFileSync(join(state.cwd, '.claude-flow/agents/store.json'), 'utf8')).agents.worker;
+ expect(worker).toMatchObject({ status: 'idle', currentTask: null, taskCount: 1 });
+});
+
+it('complete -> pending -> complete without reassignment counts the worker once', async () => {
+ mkdirSync(join(state.cwd, '.claude-flow/agents'), { recursive: true });
+ writeFileSync(join(state.cwd, '.claude-flow/agents/store.json'), JSON.stringify({ agents: { worker: { agentId: 'worker', status: 'idle', currentTask: null, taskCount: 0 } }, version: '3.0.0' }));
+ const { taskId } = await call('task_create', { type: 'test', description: 'task' });
+ await call('task_assign', { taskId, agentIds: ['worker'] });
+ await call('task_update', { taskId, status: 'completed' });
+ await call('task_update', { taskId, status: 'pending' });
+ await call('task_update', { taskId, status: 'completed', progress: 40 });
+ const worker = JSON.parse(readFileSync(join(state.cwd, '.claude-flow/agents/store.json'), 'utf8')).agents.worker;
+ expect(worker.taskCount).toBe(1);
+ expect(stored(taskId).progress).toBe(100);
+});
diff --git a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts
index 06a73db792..937e7454f5 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts
@@ -15,12 +15,29 @@ const STORAGE_DIR = '.claude-flow';
const TASK_DIR = 'tasks';
const TASK_FILE = 'store.json';
+export const TASK_STATUSES = ['pending', 'in_progress', 'completed', 'failed', 'cancelled'] as const;
+type TaskStatus = (typeof TASK_STATUSES)[number];
+
+// Spellings agents write for the same five states (seen in the wild: "complete").
+const STATUS_ALIASES: Readonly<Record<string, TaskStatus>> = {
+ complete: 'completed', done: 'completed', canceled: 'cancelled',
+ running: 'in_progress', 'in-progress': 'in_progress', inprogress: 'in_progress',
+};
+
+/** The canonical status for a written one (trimmed, any case, known aliases), or null when it is none of the five. */
+export function statusOf(value: unknown): TaskStatus | null {
+ if (typeof value !== 'string') return null;
+ const key = value.trim().toLowerCase();
+ if ((TASK_STATUSES as readonly string[]).includes(key)) return key as TaskStatus;
+ return Object.hasOwn(STATUS_ALIASES, key) ? STATUS_ALIASES[key] : null;
+}
+
interface TaskRecord {
taskId: string;
type: string;
description: string;
priority: 'low' | 'normal' | 'high' | 'critical';
- status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'cancelled';
+ status: TaskStatus;
progress: number;
assignedTo: string[];
tags: string[];
@@ -329,7 +346,9 @@ export const taskTools: MCPTool[] = [
type: 'object',
properties: {
taskId: { type: 'string', description: 'Task ID' },
- status: { type: 'string', description: 'New status' },
+ // No schema enum: the HTTP/WebSocket registry validates enums before the handler, which would refuse the aliases there
+ // while stdio accepted them. The handler is the one place that normalises and refuses, for every transport.
+ status: { type: 'string', description: 'New status: pending, in_progress, completed, failed or cancelled' },
progress: { type: 'number', description: 'Progress percentage (0-100)' },
assignTo: { type: 'array', items: { type: 'string' }, description: 'Agent IDs to assign' },
result: { type: 'object', description: 'Result data (e.g. the failure of a failed task)' },
@@ -340,28 +359,53 @@ export const taskTools: MCPTool[] = [
// Validate user-provided input (#1425)
const vId = validateIdentifier(input.taskId, 'taskId');
if (!vId.valid) return { success: false, error: vId.error };
+ // A status outside the five is stored as written otherwise, and every reader that buckets
+ // by status (task_list filters, the console kanban) then miscounts it: "complete" read as pending.
+ const status = input.status === undefined ? undefined : statusOf(input.status);
+ if (status === null) {
+ return { success: false, error: `status must be one of ${TASK_STATUSES.join(', ')}` };
+ }
const store = loadTaskStore();
const taskId = input.taskId as string;
const task = store.tasks[taskId];
if (task) {
- if (input.status) {
- const newStatus = input.status as TaskRecord['status'];
+ // Worker effects run AFTER the task store is saved, as task_complete does: a failed save must not leave
+ // workers freed and counted against a task that still reads unfinished.
+ let afterSave: (() => void) | undefined;
+ if (status !== undefined) {
+ const newStatus = status;
+ const wasCompleted = task.status === 'completed';
task.status = newStatus;
if (newStatus === 'in_progress' && !task.startedAt) {
task.startedAt = new Date().toISOString();
}
- // A failed task frees its workers, as task_complete and task_cancel do;
- // otherwise a worker whose run failed stays `busy` forever.
- if (newStatus === 'failed') {
+ // A finished task frees its workers, as task_complete and task_cancel do; otherwise a worker
+ // whose task was finished through task_update stays `busy` forever, and a later task_complete
+ // returns early because the status already reads completed.
+ if (newStatus === 'failed' || newStatus === 'cancelled') {
+ task.completedAt = new Date().toISOString();
+ afterSave = () => releaseAgents(task.assignedTo, taskId);
+ }
+ if (newStatus === 'completed' && !wasCompleted) {
task.completedAt = new Date().toISOString();
- releaseAgents(task.assignedTo, taskId);
+ // Credited only to a worker still holding this task, so complete -> pending -> complete
+ // (no reassignment in between) never counts the same work twice.
+ afterSave = () => updateAgents(task.assignedTo, (agent) => {
+ if (agent.currentTask === taskId) {
+ agent.status = 'idle';
+ agent.currentTask = null;
+ agent.taskCount = ((agent.taskCount as number) || 0) + 1;
+ }
+ });
}
}
if (typeof input.progress === 'number') {
task.progress = Math.min(100, Math.max(0, input.progress as number));
}
+ // Completing is 100% whatever progress the same call carried.
+ if (task.status === 'completed') task.progress = 100;
if (input.assignTo) {
task.assignedTo = input.assignTo as string[];
}
@@ -369,6 +413,7 @@ export const taskTools: MCPTool[] = [
task.result = input.result as Record<string, unknown>;
}
saveTaskStore(store);
+ afterSave?.();
return {
success: true,