🌊 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(storage): preserve unreadable task and agent records
Rudy Celekli38cffa89c692
diff --git a/v3/@claude-flow/cli/__tests__/task-agent-store-preservation.test.ts b/v3/@claude-flow/cli/__tests__/task-agent-store-preservation.test.tsnew file mode 100644index 0000000000..c7812df69b--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/task-agent-store-preservation.test.ts@@ -0,0 +1,31 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { mkdtempSync, mkdirSync, 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}));+vi.mock('../src/mcp-tools/agent-execute-core.js',()=>({executeAgentTask:vi.fn()}));+vi.mock('../src/mcp-tools/swarm-tools.js',()=>({pheromoneAgentEligibility:vi.fn()}));+import {taskTools} from '../src/mcp-tools/task-tools.js';+import {agentTools} from '../src/mcp-tools/agent-tools.js';+const task=(name:string,input:any):Promise<any>=>taskTools.find(t=>t.name===name)!.handler(input) as Promise<any>;+const path=(kind:string)=>join(state.cwd,'.claude-flow',kind,'store.json');+beforeEach(()=>{state.cwd=mkdtempSync(join(tmpdir(),'ruflo-preserve-'));for(const k of ['tasks','agents'])mkdirSync(join(state.cwd,'.claude-flow',k),{recursive:true});});+afterEach(()=>rmSync(state.cwd,{recursive:true,force:true}));+it.each(['{ "preserve":', 'null', '[]', '{"tasks":[],"agents":[]}'])('refuses to replace existing invalid stores: %s',async original=>{+ for(const kind of ['tasks','agents'])writeFileSync(path(kind),original);+ await expect(task('task_create',{type:'test',description:'new'})).rejects.toThrow();+ await expect(agentTools.find(t=>t.name==='agent_pool')!.handler({action:'scale',targetSize:1})).rejects.toThrow();+ for(const kind of ['tasks','agents'])expect(readFileSync(path(kind),'utf8')).toBe(original);+});+it('does not overwrite an unreadable agent store during assignment',async()=>{+ const created=await task('task_create',{type:'test',description:'new'});+ writeFileSync(path('agents'),'{ preserve');+ await expect(task('task_assign',{taskId:created.taskId,agentIds:['worker']})).rejects.toThrow();+ expect(readFileSync(path('agents'),'utf8')).toBe('{ preserve');+ expect((await task('task_status',{taskId:created.taskId})).assignedTo).toEqual([]);+});+it('initializes a genuinely missing store',async()=>{+ expect(await task('task_create',{type:'test',description:'new'})).toHaveProperty('taskId');+ expect(await agentTools.find(t=>t.name==='agent_pool')!.handler({action:'scale',targetSize:1})).toMatchObject({action:'scale'});+});diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.tsindex 63e5538cf1..7bcdab8f88 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts@@ -7,6 +7,7 @@import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';import { join } from 'node:path';+import { readRecordStore } from './record-store.js';import { type MCPTool, getProjectCwd } from './types.js';import { validateIdentifier, validateText, validateAgentSpawn } from './validate-input.js';import { executeAgentTask } from './agent-execute-core.js';@@ -74,16 +75,7 @@ function ensureAgentDir(): void {}function loadAgentStore(): AgentStore {- try {- const path = getAgentPath();- if (existsSync(path)) {- const data = readFileSync(path, 'utf-8');- return JSON.parse(data);- }- } catch {- // Return empty store on error- }- return { agents: {}, version: '3.0.0' };+ return readRecordStore(getAgentPath(), 'agents', () => ({ agents: {}, version: '3.0.0' }));}function saveAgentStore(store: AgentStore): void {diff --git a/v3/@claude-flow/cli/src/mcp-tools/record-store.ts b/v3/@claude-flow/cli/src/mcp-tools/record-store.tsnew file mode 100644index 0000000000..a25c756e35--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/record-store.ts@@ -0,0 +1,19 @@+import { readFileSync } from 'node:fs';++/** Only an absent store is empty. Failed reads must never authorize replacement. */+export function readRecordStore<T>(path: string, collection: string, empty: () => T): T {+ let text: string;+ try {+ text = readFileSync(path, 'utf-8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return empty();+ throw error;+ }+ const store = JSON.parse(text);+ const records = store?.[collection];+ if (!store || typeof store !== 'object' || Array.isArray(store)+ || !records || typeof records !== 'object' || Array.isArray(records)) {+ throw new Error(`Invalid ${collection} store at ${path}; existing data was preserved`);+ }+ return store as T;+}diff --git a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/task-tools.tsindex 37e07c3884..06a73db792 100644--- a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts@@ -6,6 +6,7 @@import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';import { join } from 'node:path';+import { readRecordStore } from './record-store.js';import { type MCPTool, getProjectCwd } from './types.js';import { validateIdentifier, validateText } from './validate-input.js';@@ -50,16 +51,7 @@ function ensureTaskDir(): void {}function loadTaskStore(): TaskStore {- try {- const path = getTaskPath();- if (existsSync(path)) {- const data = readFileSync(path, 'utf-8');- return JSON.parse(data);- }- } catch {- // Return empty store on error- }- return { tasks: {}, version: '3.0.0' };+ return readRecordStore(getTaskPath(), 'tasks', () => ({ tasks: {}, version: '3.0.0' }));}function saveTaskStore(store: TaskStore): void {@@ -422,6 +414,11 @@ export const taskTools: MCPTool[] = [const previouslyAssigned = [...task.assignedTo];+ // Load agent store to sync worker state+ const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json');+ readRecordStore<{ agents: Record<string, Record<string, unknown>> }>(+ agentStorePath, 'agents', () => ({ agents: {} }),+ );if (input.unassign) {// Revert previously assigned agents to idlereleaseAgents(previouslyAssigned, taskId);