π 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
feat: implement non-interactive JSON output for swarm command (fixes #206) (#221)
lanemc0457a1020497
diff --git a/package-lock.json b/package-lock.jsonindex f5fd9b55cf..cd59f0abd3 100644--- a/package-lock.json+++ b/package-lock.json@@ -45,8 +45,8 @@"@types/fs-extra": "^11.0.4","@types/gradient-string": "^1.1.6","@types/inquirer": "^9.0.7",- "@types/jest": "^29.5.8",- "@types/node": "^20.10.5",+ "@types/jest": "^29.5.14",+ "@types/node": "^20.19.7","@types/uuid": "^10.0.0","@types/ws": "^8.5.10","@typescript-eslint/eslint-plugin": "^6.15.0",@@ -3722,9 +3722,9 @@"license": "MIT"},"node_modules/@types/node": {- "version": "20.19.4",- "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.4.tgz",- "integrity": "sha512-OP+We5WV8Xnbuvw0zC2m4qfB/BJvjyCwtNjhHdJxV1639SGSKrLmJkc3fMnp2Qy8nJyHp8RO6umxELN/dS1/EA==",+ "version": "20.19.7",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.7.tgz",+ "integrity": "sha512-1GM9z6BJOv86qkPvzh2i6VW5+VVrXxCLknfmTkWEqz+6DqosiY28XUWCTmBcJ0ACzKqx/iwdIREfo1fwExIlkA==","license": "MIT","dependencies": {"undici-types": "~6.21.0"diff --git a/package.json b/package.jsonindex 8b6442e608..676e91ee98 100644--- a/package.json+++ b/package.json@@ -135,8 +135,8 @@"@types/fs-extra": "^11.0.4","@types/gradient-string": "^1.1.6","@types/inquirer": "^9.0.7",- "@types/jest": "^29.5.8",- "@types/node": "^20.10.5",+ "@types/jest": "^29.5.14",+ "@types/node": "^20.19.7","@types/uuid": "^10.0.0","@types/ws": "^8.5.10","@typescript-eslint/eslint-plugin": "^6.15.0",diff --git a/src/cli/commands/swarm-new.ts b/src/cli/commands/swarm-new.tsindex 33573a4ea1..b4c6a446c6 100644--- a/src/cli/commands/swarm-new.ts+++ b/src/cli/commands/swarm-new.ts@@ -471,6 +471,16 @@ export async function swarmAction(ctx: CommandContext) {const options = parseSwarmOptions(ctx.flags);const swarmId = generateId('swarm');+ // Handle JSON output mode+ const isJsonOutput = options.outputFormat === 'json';+ const isNonInteractive = isJsonOutput || options.noInteractive;++ // For JSON output, force executor mode since Claude Code doesn't return structured JSON+ if (isJsonOutput && !options.executor) {+ options.executor = true;+ options.claude = false;+ }+if (options.dryRun) {showDryRunConfiguration(swarmId, objective, options);return;@@ -488,11 +498,14 @@ export async function swarmAction(ctx: CommandContext) {return;}- success(`π Initializing Advanced Swarm: ${swarmId}`);- console.log(`π Objective: ${objective}`);- console.log(`π― Strategy: ${options.strategy}`);- console.log(`ποΈ Mode: ${options.mode}`);- console.log(`π€ Max Agents: ${options.maxAgents}`);+ // Only show messages if not in JSON output mode+ if (!isJsonOutput) {+ success(`π Initializing Advanced Swarm: ${swarmId}`);+ console.log(`π Objective: ${objective}`);+ console.log(`π― Strategy: ${options.strategy}`);+ console.log(`ποΈ Mode: ${options.mode}`);+ console.log(`π€ Max Agents: ${options.maxAgents}`);+ }try {// Initialize comprehensive swarm system@@ -543,6 +556,11 @@ export async function swarmAction(ctx: CommandContext) {await coordinator.initialize();+ // Enable JSON output collection if requested+ if (isJsonOutput) {+ coordinator.enableJsonOutput(objective);+ }+// Initialize Task Executor with enhanced optionsconst executor = new TaskExecutor({maxConcurrentTasks: 10,@@ -664,7 +682,9 @@ export async function swarmAction(ctx: CommandContext) {await setupIncrementalUpdates(coordinator, swarmDir);// Execute the objective- console.log(`\nπ Swarm execution started...`);+ if (!isJsonOutput) {+ console.log(`\nπ Swarm execution started...`);+ }// Start the objective executionawait coordinator.executeObjective(objectiveId);@@ -684,17 +704,23 @@ export async function swarmAction(ctx: CommandContext) {console.log(`π Results: ${swarmDir}`);// Wait for completion in background with minimal output- console.log(`\nβ³ Processing tasks...`);+ if (!isJsonOutput) {+ console.log(`\nβ³ Processing tasks...`);+ }// Background mode uses simple polling, no detailed progressawait waitForSwarmCompletion(coordinator, objectiveId, options);- // Show final results- await showSwarmResults(coordinator, executor, memory, swarmDir);+ // Show final results or output JSON+ if (isJsonOutput) {+ await outputJsonResults(coordinator, options);+ } else {+ await showSwarmResults(coordinator, executor, memory, swarmDir);+ }} else if (!options.background) {// Wait for completion in foreground with detailed progress- if (!options.verbose) {+ if (!options.verbose && !isJsonOutput) {console.log(`\nβ³ Processing tasks...`);// Track task states for detailed display@@ -742,8 +768,12 @@ export async function swarmAction(ctx: CommandContext) {await waitForSwarmCompletion(coordinator, objectiveId, options);}- // Show final results- await showSwarmResults(coordinator, executor, memory, swarmDir);+ // Show final results or output JSON+ if (isJsonOutput) {+ await outputJsonResults(coordinator, options);+ } else {+ await showSwarmResults(coordinator, executor, memory, swarmDir);+ }} else {// Background mode requested - launch in background@@ -853,7 +883,12 @@ function parseSwarmOptions(flags: any) {// Claude Code optionsclaude: flags.claude || false,- executor: flags.executor || false+ executor: flags.executor || false,++ // JSON output options+ outputFormat: flags.outputFormat || flags['output-format'] || 'text',+ outputFile: flags.outputFile || flags['output-file'],+ noInteractive: flags.noInteractive || flags['no-interactive'] || false};}@@ -1518,4 +1553,68 @@ ADVANCED OPTIONS:For more information, see: https://github.com/ruvnet/claude-flow`);+}++/**+ * Output JSON results for non-interactive mode+ */+async function outputJsonResults(coordinator: SwarmCoordinator, options: any): Promise<void> {+ try {+ // Get the final status from coordinator+ const swarmStatus = coordinator.getSwarmStatus();+ const finalStatus = swarmStatus.status === 'completed' ? 'completed' :+ swarmStatus.status === 'failed' ? 'failed' :+ swarmStatus.status === 'timeout' ? 'timeout' : 'cancelled';++ // Get JSON output from coordinator+ const jsonOutput = coordinator.getJsonOutput(finalStatus);++ if (!jsonOutput) {+ // Fallback: create basic JSON structure if aggregator wasn't enabled+ const basicOutput = {+ swarmId: coordinator.getSwarmId(),+ status: finalStatus,+ timestamp: new Date().toISOString(),+ error: 'JSON output aggregation was not properly enabled'+ };+ const fallbackJson = JSON.stringify(basicOutput, null, 2);++ if (options.outputFile) {+ await fs.writeFile(options.outputFile, fallbackJson);+ } else {+ console.log(fallbackJson);+ }+ return;+ }++ // Output to file or stdout+ if (options.outputFile) {+ await coordinator.saveJsonOutput(options.outputFile, finalStatus);+ } else {+ // Output to stdout for command capture+ console.log(jsonOutput);+ }++ } catch (error) {+ // Even if there's an error, output a JSON structure+ const errorOutput = {+ swarmId: coordinator.getSwarmId(),+ status: 'failed',+ timestamp: new Date().toISOString(),+ error: error instanceof Error ? error.message : String(error),+ details: 'Failed to generate JSON output'+ };++ const errorJson = JSON.stringify(errorOutput, null, 2);++ if (options.outputFile) {+ try {+ await fs.writeFile(options.outputFile, errorJson);+ } catch (writeError) {+ console.error(errorJson);+ }+ } else {+ console.log(errorJson);+ }+ }}\ No newline at end of filediff --git a/src/cli/index.ts b/src/cli/index.tsindex 6d6a813dc0..7ca23fcd69 100644--- a/src/cli/index.ts+++ b/src/cli/index.ts@@ -186,7 +186,7 @@ function setupSignalHandlers(): void {}// Main entry point-if (false // import.meta.main not available) {+if (false) { // import.meta.main not availablelet globalOptions: any = {};try {diff --git a/src/cli/node-repl.ts b/src/cli/node-repl.tsindex 4007635772..34ccd74de5 100644--- a/src/cli/node-repl.ts+++ b/src/cli/node-repl.ts@@ -78,90 +78,6 @@ class CommandHistory {}}-class CommandCompleter {- private commands: Map<string, REPLCommand> = new Map();-- setCommands(commands: REPLCommand[]): void {- this.commands.clear();- for (const cmd of commands) {- this.commands.set(cmd.name, cmd);- if (cmd.aliases) {- for (const alias of cmd.aliases) {- this.commands.set(alias, cmd);- }- }- }- }-- complete(line: string): [string[], string] {- const parts = line.trim().split(/\s+/);-- if (parts.length === 1) {- // Complete command names- const prefix = parts[0];- const completions = Array.from(this.commands.keys())- .filter(name => name.startsWith(prefix))- .sort();- return [completions, prefix];- }-- // Complete subcommands and arguments- const commandName = parts[0];- const command = this.commands.get(commandName);-- if (command) {- const subCompletions = this.completeForCommand(command, parts.slice(1));- return [subCompletions, parts[parts.length - 1]];- }-- return [[], line];- }-- private completeForCommand(command: REPLCommand, args: string[]): string[] {- // Basic completion for known commands- switch (command.name) {- case 'agent':- if (args.length === 1) {- return ['spawn', 'list', 'terminate', 'info'].filter(sub =>- sub.startsWith(args[0])- );- }- if (args[0] === 'spawn' && args.length === 2) {- return ['coordinator', 'researcher', 'implementer', 'analyst', 'custom']- .filter(type => type.startsWith(args[1]));- }- break;-- case 'task':- if (args.length === 1) {- return ['create', 'list', 'status', 'cancel', 'workflow'].filter(sub =>- sub.startsWith(args[0])- );- }- if (args[0] === 'create' && args.length === 2) {- return ['research', 'implementation', 'analysis', 'coordination']- .filter(type => type.startsWith(args[1]));- }- break;-- case 'session':- if (args.length === 1) {- return ['list', 'save', 'restore', 'delete', 'export', 'import']- .filter(sub => sub.startsWith(args[0]));- }- break;-- case 'workflow':- if (args.length === 1) {- return ['run', 'validate', 'list', 'status', 'stop', 'template']- .filter(sub => sub.startsWith(args[0]));- }- break;- }-- return [];- }-}/*** Start the Node.js interactive REPL@@ -172,7 +88,6 @@ export async function startNodeREPL(options: any = {}): Promise<void> {input: process.stdin,output: process.stdout,prompt: '',- completer: undefined, // Will be set later});const context: REPLContext = {@@ -185,7 +100,6 @@ export async function startNodeREPL(options: any = {}): Promise<void> {};const history = new CommandHistory(options.historyFile);- const completer = new CommandCompleter();const commands: REPLCommand[] = [{@@ -382,13 +296,6 @@ export async function startNodeREPL(options: any = {}): Promise<void> {},];- // Set up command completion- completer.setCommands(commands);-- // Set completer function- // rl.completer = (line: string) => {- return completer.complete(line);- };// Show initial statusif (options.banner !== false) {diff --git a/src/cli/simple-commands/swarm.js b/src/cli/simple-commands/swarm.jsindex 392d540302..c27d8011d3 100644--- a/src/cli/simple-commands/swarm.js+++ b/src/cli/simple-commands/swarm.js@@ -23,6 +23,8 @@ EXAMPLES:claude-flow swarm "Develop user registration feature" --mode distributedclaude-flow swarm "Optimize React app performance" --strategy optimizationclaude-flow swarm "Create microservice" --executor # Use built-in executor+ claude-flow swarm "Build API endpoints" --output-format json # Get JSON output+ claude-flow swarm "Research AI trends" --output-format json --output-file results.jsonDEFAULT BEHAVIOR:Swarm now opens Claude Code by default with comprehensive MCP tool instructions@@ -75,6 +77,9 @@ OPTIONS:--verbose Enable detailed logging--dry-run Show configuration without executing--executor Use built-in executor instead of Claude Code+ --output-format <format> Output format: json, text (default: text)+ --output-file <path> Save output to file instead of stdout+ --no-interactive Run in non-interactive mode (auto-enabled with --output-format json)--auto (Deprecated: auto-permissions enabled by default)--no-auto-permissions Disable automatic --dangerously-skip-permissions@@ -99,6 +104,17 @@ export async function swarmCommand(args, flags) {showSwarmHelp();return;}++ // Handle JSON output format+ const outputFormat = flags && flags['output-format'];+ const outputFile = flags && flags['output-file'];+ const isJsonOutput = outputFormat === 'json';+ const isNonInteractive = isJsonOutput || (flags && flags['no-interactive']);++ // For JSON output, we need to ensure executor mode since Claude Code doesn't return structured JSON+ if (isJsonOutput && !(flags && flags.executor)) {+ flags = { ...(flags || {}), executor: true };+ }// Check if we should use the old executor (opt-in with --executor flag)if (flags && flags.executor) {@@ -1064,6 +1080,9 @@ OPTIONS:--verbose Enable detailed logging--dry-run Show configuration without executing--executor Use built-in executor instead of Claude Code+ --output-format <format> Output format: json, text (default: text)+ --output-file <path> Save output to file instead of stdout+ --no-interactive Run in non-interactive mode (auto-enabled with --output-format json)--auto (Deprecated: auto-permissions enabled by default)--no-auto-permissions Disable automatic --dangerously-skip-permissionsdiff --git a/src/swarm/coordinator.ts b/src/swarm/coordinator.tsindex e419121a69..d361569ea7 100644--- a/src/swarm/coordinator.ts+++ b/src/swarm/coordinator.ts@@ -12,6 +12,7 @@ import {} from './types.js';import { AutoStrategy } from './strategies/auto.js';import { getClaudeFlowRoot, getClaudeFlowBin } from '../utils/paths.js';+import { SwarmJsonOutputAggregator } from './json-output-aggregator.js';export class SwarmCoordinator extends EventEmitter implements SwarmEventEmitter {private logger: Logger;@@ -34,6 +35,9 @@ export class SwarmCoordinator extends EventEmitter implements SwarmEventEmitterprivate events: SwarmEvent[] = [];private lastHeartbeat: Date = new Date();+ // JSON output aggregation (optional)+ private jsonOutputAggregator?: SwarmJsonOutputAggregator;+// Background processesprivate heartbeatTimer?: NodeJS.Timeout;private monitoringTimer?: NodeJS.Timeout;@@ -414,6 +418,9 @@ export class SwarmCoordinator extends EventEmitter implements SwarmEventEmitterthis.agents.set(agentId.id, agentState);+ // Track agent in JSON output if enabled+ this.trackAgentInJsonOutput(agentState);+// Initialize agent capabilities based on typeawait this.initializeAgentCapabilities(agentState);@@ -629,6 +636,9 @@ export class SwarmCoordinator extends EventEmitter implements SwarmEventEmitterthis.tasks.set(taskId.id, task);+ // Track task in JSON output if enabled+ this.trackTaskInJsonOutput(task);+this.logger.info('Created task', {taskId: taskId.id,type,@@ -1793,6 +1803,9 @@ Ensure your implementation is complete, well-structured, and follows best practitask.context.targetDir = objectiveTargetDir;}this.tasks.set(task.id.id, task);++ // Track task in JSON output if enabled+ this.trackTaskInJsonOutput(task);}// Find tasks with no dependencies and queue them@@ -3042,6 +3055,98 @@ console.log('Tests completed for: ${task.name}');agent.status = 'error';agent.health = 0;this.logger.error('Agent error', { agentId, error });++ // Track error in JSON output if enabled+ if (this.jsonOutputAggregator) {+ this.jsonOutputAggregator.addAgentError(+ agentId,+ error instanceof Error ? error.message : String(error)+ );+ }+ }+ }++ // ===== JSON OUTPUT METHODS =====++ /**+ * Enable JSON output collection for non-interactive mode+ */+ enableJsonOutput(objective: string): void {+ if (!this.jsonOutputAggregator) {+ this.jsonOutputAggregator = new SwarmJsonOutputAggregator(+ this.swarmId.id,+ objective,+ this.config+ );+ this.logger.info('JSON output aggregation enabled', { swarmId: this.swarmId.id });+ }+ }++ /**+ * Get the final JSON output for the swarm+ */+ getJsonOutput(status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed'): string | null {+ if (!this.jsonOutputAggregator) {+ return null;+ }+ return this.jsonOutputAggregator.getJsonOutput(status);+ }++ /**+ * Save JSON output to file+ */+ async saveJsonOutput(+ filePath: string,+ status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed'+ ): Promise<void> {+ if (!this.jsonOutputAggregator) {+ throw new Error('JSON output aggregation not enabled');+ }+ await this.jsonOutputAggregator.saveToFile(filePath, status);+ }++ /**+ * Track agent activity in JSON output+ */+ private trackAgentInJsonOutput(agent: AgentState): void {+ if (this.jsonOutputAggregator) {+ this.jsonOutputAggregator.addAgent(agent);+ }+ }++ /**+ * Track task activity in JSON output+ */+ private trackTaskInJsonOutput(task: TaskDefinition): void {+ if (this.jsonOutputAggregator) {+ this.jsonOutputAggregator.addTask(task);+ }+ }++ /**+ * Add output to JSON aggregator+ */+ private addOutputToJsonAggregator(agentId: string, output: string): void {+ if (this.jsonOutputAggregator) {+ this.jsonOutputAggregator.addAgentOutput(agentId, output);+ }+ }++ /**+ * Add insight to JSON aggregator+ */+ addInsight(insight: string): void {+ if (this.jsonOutputAggregator) {+ this.jsonOutputAggregator.addInsight(insight);+ }+ }++ /**+ * Add artifact to JSON aggregator+ */+ addArtifact(key: string, artifact: any): void {+ if (this.jsonOutputAggregator) {+ this.jsonOutputAggregator.addArtifact(key, artifact);}}}\ No newline at end of filediff --git a/src/swarm/json-output-aggregator.ts b/src/swarm/json-output-aggregator.tsnew file mode 100644index 0000000000..1dca8eb73f--- /dev/null+++ b/src/swarm/json-output-aggregator.ts@@ -0,0 +1,356 @@+/**+ * JSON Output Aggregator for Non-Interactive Swarm Execution+ * Collects and formats swarm results into a comprehensive JSON structure+ */++import { EventEmitter } from 'events';+import { promises as fs } from 'node:fs';+import { generateId } from '../utils/helpers.js';+import { Logger } from '../core/logger.js';+import type {+ SwarmId, AgentId, TaskId, AgentState, TaskDefinition,+ SwarmResults, SwarmMetrics, TaskResult+} from './types.js';++export interface SwarmOutputAggregate {+ swarmId: string;+ objective: string;+ startTime: string;+ endTime: string;+ duration: number;+ status: 'completed' | 'failed' | 'timeout' | 'cancelled';+ summary: {+ totalAgents: number;+ totalTasks: number;+ completedTasks: number;+ failedTasks: number;+ successRate: number;+ };+ agents: AgentOutputData[];+ tasks: TaskOutputData[];+ results: {+ artifacts: Record<string, any>;+ outputs: string[];+ errors: string[];+ insights: string[];+ };+ metrics: SwarmMetrics;+ metadata: {+ strategy: string;+ mode: string;+ configuration: Record<string, any>;+ version: string;+ };+}++export interface AgentOutputData {+ agentId: string;+ name: string;+ type: string;+ status: string;+ startTime: string;+ endTime?: string;+ duration?: number;+ tasksCompleted: number;+ outputs: string[];+ errors: string[];+ metrics: {+ tokensUsed?: number;+ memoryAccess: number;+ operationsPerformed: number;+ };+}++export interface TaskOutputData {+ taskId: string;+ name: string;+ type: string;+ status: string;+ assignedAgent?: string;+ startTime: string;+ endTime?: string;+ duration?: number;+ priority: string;+ output?: string;+ result?: TaskResult;+ artifacts?: Record<string, any>;+ error?: string;+}++export class SwarmJsonOutputAggregator extends EventEmitter {+ private logger: Logger;+ private swarmId: string;+ private objective: string;+ private startTime: Date;+ private endTime?: Date;+ private configuration: Record<string, any>;++ // Data collection+ private agents: Map<string, AgentOutputData> = new Map();+ private tasks: Map<string, TaskOutputData> = new Map();+ private outputs: string[] = [];+ private errors: string[] = [];+ private insights: string[] = [];+ private artifacts: Record<string, any> = {};+ private metrics: SwarmMetrics = this.initializeMetrics();++ constructor(swarmId: string, objective: string, configuration: Record<string, any> = {}) {+ super();+ this.swarmId = swarmId;+ this.objective = objective;+ this.configuration = configuration;+ this.startTime = new Date();++ this.logger = new Logger(+ { level: 'info', format: 'json', destination: 'console' },+ { component: 'SwarmJsonAggregator' }+ );++ this.logger.info('JSON output aggregator initialized', {+ swarmId,+ objective,+ timestamp: this.startTime.toISOString()+ });+ }++ // Agent tracking methods+ addAgent(agent: AgentState): void {+ // Handle null/undefined agent IDs gracefully+ if (!agent || !agent.id) {+ this.logger.warn('Attempted to add agent with null/undefined ID, skipping');+ return;+ }++ const agentIdStr = typeof agent.id === 'string' ? agent.id : agent.id.id;+ const agentData: AgentOutputData = {+ agentId: agentIdStr,+ name: agent.name || agentIdStr,+ type: agent.type,+ status: agent.status,+ startTime: new Date().toISOString(),+ tasksCompleted: 0,+ outputs: [],+ errors: [],+ metrics: {+ memoryAccess: 0,+ operationsPerformed: 0+ }+ };++ this.agents.set(agentIdStr, agentData);+ this.logger.debug('Agent added to output tracking', { agentId: agentIdStr });+ }++ updateAgent(agentId: string, updates: Partial<AgentOutputData>): void {+ const agent = this.agents.get(agentId);+ if (agent) {+ Object.assign(agent, updates);+ this.logger.debug('Agent updated in output tracking', { agentId, updates });+ }+ }++ addAgentOutput(agentId: string, output: string): void {+ const agent = this.agents.get(agentId);+ if (agent) {+ agent.outputs.push(output);+ agent.metrics.operationsPerformed++;+ }+ this.outputs.push(`[${agentId}] ${output}`);+ }++ addAgentError(agentId: string, error: string): void {+ const agent = this.agents.get(agentId);+ if (agent) {+ agent.errors.push(error);+ }+ this.errors.push(`[${agentId}] ${error}`);+ }++ // Task tracking methods+ addTask(task: TaskDefinition): void {+ // Handle null/undefined task IDs gracefully+ if (!task || !task.id) {+ this.logger.warn('Attempted to add task with null/undefined ID, skipping');+ return;+ }++ const taskIdStr = typeof task.id === 'string' ? task.id : task.id.id;+ const taskData: TaskOutputData = {+ taskId: taskIdStr,+ name: task.name || taskIdStr,+ type: task.type,+ status: task.status,+ assignedAgent: task.assignedAt ? (typeof task.assignedAt === 'string' ? task.assignedAt : task.assignedAt.toString()) : undefined,+ startTime: new Date().toISOString(),+ priority: task.priority || 'normal'+ };++ this.tasks.set(taskIdStr, taskData);+ this.logger.debug('Task added to output tracking', { taskId: taskIdStr });+ }++ updateTask(taskId: string, updates: Partial<TaskOutputData>): void {+ const task = this.tasks.get(taskId);+ if (task) {+ Object.assign(task, updates);+ this.logger.debug('Task updated in output tracking', { taskId, updates });+ }+ }++ completeTask(taskId: string, result: TaskResult): void {+ const task = this.tasks.get(taskId);+ if (task) {+ task.status = 'completed';+ task.endTime = new Date().toISOString();+ task.duration = task.startTime ?+ Date.now() - new Date(task.startTime).getTime() : 0;+ task.result = result;+ task.output = result.output;+ task.artifacts = result.artifacts;++ // Update agent completion count+ if (task.assignedAgent) {+ const agent = this.agents.get(task.assignedAgent);+ if (agent) {+ agent.tasksCompleted++;+ }+ }+ }+ }++ // Global tracking methods+ addInsight(insight: string): void {+ this.insights.push(insight);+ this.logger.debug('Insight added', { insight });+ }++ addArtifact(key: string, artifact: any): void {+ this.artifacts[key] = artifact;+ this.logger.debug('Artifact added', { key });+ }++ updateMetrics(updates: Partial<SwarmMetrics>): void {+ Object.assign(this.metrics, updates);+ }++ // Finalization and output+ finalize(status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed'): SwarmOutputAggregate {+ this.endTime = new Date();+ const duration = this.endTime.getTime() - this.startTime.getTime();++ // Calculate summary statistics+ const totalTasks = this.tasks.size;+ const completedTasks = Array.from(this.tasks.values())+ .filter(task => task.status === 'completed').length;+ const failedTasks = Array.from(this.tasks.values())+ .filter(task => task.status === 'failed').length;+ const successRate = totalTasks > 0 ? completedTasks / totalTasks : 0;++ // Finalize agent data+ this.agents.forEach(agent => {+ if (!agent.endTime) {+ agent.endTime = this.endTime.toISOString();+ agent.duration = Date.now() - new Date(agent.startTime).getTime();+ }+ });++ const aggregate: SwarmOutputAggregate = {+ swarmId: this.swarmId,+ objective: this.objective,+ startTime: this.startTime.toISOString(),+ endTime: this.endTime.toISOString(),+ duration,+ status,+ summary: {+ totalAgents: this.agents.size,+ totalTasks,+ completedTasks,+ failedTasks,+ successRate+ },+ agents: Array.from(this.agents.values()),+ tasks: Array.from(this.tasks.values()),+ results: {+ artifacts: this.artifacts,+ outputs: this.outputs,+ errors: this.errors,+ insights: this.insights+ },+ metrics: this.metrics,+ metadata: {+ strategy: this.configuration.strategy || 'auto',+ mode: this.configuration.mode || 'centralized',+ configuration: this.configuration,+ version: '2.0.0-alpha'+ }+ };++ this.logger.info('Swarm output aggregation finalized', {+ swarmId: this.swarmId,+ status,+ duration,+ summary: aggregate.summary+ });++ return aggregate;+ }++ async saveToFile(filePath: string, status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed'): Promise<void> {+ const aggregate = this.finalize(status);+ const json = JSON.stringify(aggregate, this.circularReplacer(), 2);+ await fs.writeFile(filePath, json, 'utf8');+ this.logger.info('Swarm output saved to file', { filePath, size: json.length });+ }++ getJsonOutput(status: 'completed' | 'failed' | 'timeout' | 'cancelled' = 'completed'): string {+ const aggregate = this.finalize(status);+ return JSON.stringify(aggregate, this.circularReplacer(), 2);+ }++ // Handle circular references in JSON serialization+ private circularReplacer(): (key: string, value: any) => any {+ const seen = new WeakSet();+ return (key: string, value: any) => {+ if (typeof value === 'object' && value !== null) {+ if (seen.has(value)) {+ return '[Circular]';+ }+ seen.add(value);+ }+ return value;+ };+ }++ private initializeMetrics(): SwarmMetrics {+ return {+ // Performance metrics+ throughput: 0,+ latency: 0,+ efficiency: 0,+ reliability: 0,++ // Quality metrics+ averageQuality: 0,+ defectRate: 0,+ reworkRate: 0,++ // Resource metrics+ resourceUtilization: {+ cpu: 0,+ memory: 0,+ disk: 0,+ network: 0+ },+ costEfficiency: 0,++ // Agent metrics+ agentUtilization: 0,+ agentSatisfaction: 0,+ collaborationEffectiveness: 0,++ // Timeline metrics+ scheduleVariance: 0,+ deadlineAdherence: 0+ };+ }+}\ No newline at end of filediff --git a/tests/integration/json-output-edge-cases.test.ts b/tests/integration/json-output-edge-cases.test.tsnew file mode 100644index 0000000000..19415491b7--- /dev/null+++ b/tests/integration/json-output-edge-cases.test.ts@@ -0,0 +1,622 @@+/**+ * JSON Output Edge Cases and Error Handling Tests+ * Testing comprehensive edge cases and error scenarios for the JSON output feature+ */++import { describe, it, expect, beforeEach, afterEach } from '@jest/globals';+import { SwarmJsonOutputAggregator } from '../../src/swarm/json-output-aggregator.js';+import { SwarmCoordinator } from '../../src/swarm/coordinator.js';+import fs from 'fs/promises';+import path from 'path';+import { tmpdir } from 'os';+import type { AgentState, TaskDefinition } from '../../src/swarm/types.js';++describe('JSON Output Edge Cases and Error Handling', () => {+ let testDir: string;+ let aggregator: SwarmJsonOutputAggregator;++ beforeEach(async () => {+ // Create a temporary directory for test files+ testDir = await fs.mkdtemp(path.join(tmpdir(), 'claude-flow-edge-test-'));+ aggregator = new SwarmJsonOutputAggregator('edge-test-swarm', 'Edge case testing');+ });++ afterEach(async () => {+ // Clean up test directory+ try {+ await fs.rm(testDir, { recursive: true, force: true });+ } catch (error) {+ // Ignore cleanup errors+ }+ });++ describe('Large Data Volume Tests', () => {+ it('should handle large numbers of agents (100+)', () => {+ // Create 150 agents+ for (let i = 0; i < 150; i++) {+ const mockAgent: AgentState = {+ id: { id: `agent-${i}`, swarmId: 'edge-test-swarm', type: 'researcher', instance: i },+ name: `Agent ${i}`,+ type: 'researcher',+ status: 'idle',+ capabilities: {+ codeGeneration: false,+ codeReview: false,+ testing: false,+ documentation: true,+ research: true,+ analysis: true,+ webSearch: true,+ apiIntegration: false,+ fileSystem: true,+ terminalAccess: false,+ languages: ['markdown'],+ frameworks: [],+ domains: ['research'],+ tools: ['web-search'],+ maxConcurrentTasks: 3,+ maxMemoryUsage: 512,+ maxExecutionTime: 300,+ reliability: 0.9,+ speed: 0.8,+ quality: 0.85+ },+ metrics: {+ tasksCompleted: 0,+ tasksFailed: 0,+ averageExecutionTime: 0,+ successRate: 0,+ cpuUsage: 0,+ memoryUsage: 0,+ diskUsage: 0,+ networkUsage: 0,+ codeQuality: 0,+ testCoverage: 0,+ bugRate: 0,+ userSatisfaction: 0,+ totalUptime: 0,+ lastActivity: new Date(),+ responseTime: 0+ },+ config: {+ autonomyLevel: 0.5,+ learningEnabled: false,+ adaptationEnabled: false,+ maxTasksPerHour: 10,+ maxConcurrentTasks: 1,+ timeoutThreshold: 60,+ reportingInterval: 30,+ heartbeatInterval: 15,+ permissions: [],+ trustedAgents: [],+ expertise: {},+ preferences: {}+ },+ environment: {+ runtime: 'node',+ version: '20.0.0',+ workingDirectory: '/tmp',+ tempDirectory: '/tmp',+ logDirectory: '/var/log',+ apiEndpoints: {},+ credentials: {},+ availableTools: [],+ toolConfigs: {}+ },+ workload: 0,+ health: 1,+ endpoints: [],+ lastHeartbeat: new Date(),+ taskHistory: [],+ errorHistory: [],+ childAgents: [],+ collaborators: []+ };+ aggregator.addAgent(mockAgent);+ }++ const jsonOutput = aggregator.getJsonOutput('completed');+ const output = JSON.parse(jsonOutput);++ expect(output.summary.totalAgents).toBe(150);+ expect(output.agents).toHaveLength(150);+ expect(jsonOutput.length).toBeGreaterThan(50000); // Should be a large JSON string+ });++ it('should handle large numbers of tasks (500+)', () => {+ // Create 500 tasks+ for (let i = 0; i < 500; i++) {+ const mockTask: TaskDefinition = {+ id: { id: `task-${i}`, swarmId: 'edge-test-swarm', sequence: i, priority: 1 },+ type: 'research',+ name: `Task ${i}`,+ description: `Test task number ${i}`,+ requirements: {+ capabilities: ['research'],+ tools: ['web-search'],+ permissions: ['read']+ },+ constraints: {+ dependencies: [],+ dependents: [],+ conflicts: []+ },+ priority: 'normal',+ input: `test input ${i}`,+ instructions: `instructions for task ${i}`,+ context: {},+ status: i % 3 === 0 ? 'completed' : i % 3 === 1 ? 'failed' : 'running',+ createdAt: new Date(),+ updatedAt: new Date(),+ attempts: [],+ statusHistory: []+ };+ aggregator.addTask(mockTask);+ }++ const jsonOutput = aggregator.getJsonOutput('completed');+ const output = JSON.parse(jsonOutput);++ expect(output.summary.totalTasks).toBe(500);+ expect(output.tasks).toHaveLength(500);++ // Verify statistics are calculated correctly+ // Pattern: i % 3 === 0 ? 'completed' : i % 3 === 1 ? 'failed' : 'running'+ // For 500 tasks (0-499): 167 completed, 167 failed, 166 running+ const completedTasks = Math.ceil(500 / 3); // 167+ const failedTasks = Math.floor(500 / 3) + (500 % 3 >= 2 ? 1 : 0); // 166 + 1 = 167++ expect(output.summary.completedTasks).toBe(completedTasks);+ expect(output.summary.failedTasks).toBe(failedTasks);+ });++ it('should handle extremely large output strings', () => {+ // Add an agent with very large outputs+ const mockAgent: AgentState = {+ id: { id: 'agent-large', swarmId: 'edge-test-swarm', type: 'researcher', instance: 1 },+ name: 'Large Output Agent',+ type: 'researcher',+ status: 'busy',+ capabilities: {+ codeGeneration: false,+ codeReview: false,+ testing: false,+ documentation: true,+ research: true,+ analysis: true,+ webSearch: true,+ apiIntegration: false,+ fileSystem: true,+ terminalAccess: false,+ languages: ['markdown'],+ frameworks: [],+ domains: ['research'],+ tools: ['web-search'],+ maxConcurrentTasks: 3,+ maxMemoryUsage: 512,+ maxExecutionTime: 300,+ reliability: 0.9,+ speed: 0.8,+ quality: 0.85+ },+ metrics: {+ tasksCompleted: 0,+ tasksFailed: 0,+ averageExecutionTime: 0,+ successRate: 0,+ cpuUsage: 0,+ memoryUsage: 0,+ diskUsage: 0,+ networkUsage: 0,+ codeQuality: 0,+ testCoverage: 0,+ bugRate: 0,+ userSatisfaction: 0,+ totalUptime: 0,+ lastActivity: new Date(),+ responseTime: 0+ },+ config: {+ autonomyLevel: 0.5,+ learningEnabled: false,+ adaptationEnabled: false,+ maxTasksPerHour: 10,+ maxConcurrentTasks: 1,+ timeoutThreshold: 60,+ reportingInterval: 30,+ heartbeatInterval: 15,+ permissions: [],+ trustedAgents: [],+ expertise: {},+ preferences: {}+ },+ environment: {+ runtime: 'node',+ version: '20.0.0',+ workingDirectory: '/tmp',+ tempDirectory: '/tmp',+ logDirectory: '/var/log',+ apiEndpoints: {},+ credentials: {},+ availableTools: [],+ toolConfigs: {}+ },+ workload: 0,+ health: 1,+ endpoints: [],+ lastHeartbeat: new Date(),+ taskHistory: [],+ errorHistory: [],+ childAgents: [],+ collaborators: []+ };++ aggregator.addAgent(mockAgent);++ // Add 1000 large outputs+ for (let i = 0; i < 1000; i++) {+ const largeOutput = 'x'.repeat(1000) + ` output ${i} ` + 'y'.repeat(1000);+ aggregator.addAgentOutput('agent-large', largeOutput);+ }++ const jsonOutput = aggregator.getJsonOutput('completed');+ const output = JSON.parse(jsonOutput);++ expect(output.results.outputs).toHaveLength(1000);+ expect(jsonOutput.length).toBeGreaterThan(2000000); // Should be very large+ });+ });++ describe('Invalid Data Handling', () => {+ it('should handle agents with missing or invalid IDs', () => {+ const mockAgent: any = {+ id: null, // Invalid ID+ name: 'Invalid Agent',+ type: 'researcher',+ status: 'idle'+ };++ // Should not throw, but should handle gracefully by skipping the agent+ expect(() => {+ aggregator.addAgent(mockAgent);+ }).not.toThrow();++ // Verify the agent was not added+ const jsonOutput = aggregator.getJsonOutput('completed');+ const output = JSON.parse(jsonOutput);+ expect(output.summary.totalAgents).toBe(0);+ });++ it('should handle tasks with missing required fields', () => {+ const mockTask: any = {+ id: { id: 'task-invalid', swarmId: 'edge-test-swarm', sequence: 1, priority: 1 },+ // Missing required fields like type, name, etc.+ description: 'Invalid task',+ status: 'created'+ };++ expect(() => {+ aggregator.addTask(mockTask);+ }).not.toThrow();+ });++ it('should handle null or undefined inputs gracefully', () => {+ expect(() => {+ aggregator.addAgentOutput('nonexistent-agent', 'some output');+ }).not.toThrow();++ expect(() => {+ aggregator.addAgentError('nonexistent-agent', 'some error');+ }).not.toThrow();++ expect(() => {+ aggregator.updateAgent('nonexistent-agent', { status: 'busy' } as any);+ }).not.toThrow();++ expect(() => {+ aggregator.updateTask('nonexistent-task', { status: 'completed' } as any);+ }).not.toThrow();+ });++ it('should handle circular references in artifacts', () => {+ const circularObj: any = { name: 'test' };+ circularObj.self = circularObj; // Create circular reference++ expect(() => {+ aggregator.addArtifact('circular', circularObj);+ const jsonOutput = aggregator.getJsonOutput('completed');+ const output = JSON.parse(jsonOutput); // This should not fail++ // Verify circular reference was replaced with '[Circular]'+ expect(output.results.artifacts.circular.self).toBe('[Circular]');+ }).not.toThrow();+ });+ });++ describe('File System Edge Cases', () => {+ it('should handle invalid file paths', async () => {+ const invalidPath = '/invalid/path/that/does/not/exist/output.json';++ await expect(+ aggregator.saveToFile(invalidPath, 'completed')+ ).rejects.toThrow();+ });++ it('should handle permission errors', async () => {+ // Try to write to a read-only directory (if possible)+ const readOnlyPath = path.join(testDir, 'readonly');+ await fs.mkdir(readOnlyPath);++ try {+ await fs.chmod(readOnlyPath, 0o444); // Read-only+ const filePath = path.join(readOnlyPath, 'output.json');++ await expect(+ aggregator.saveToFile(filePath, 'completed')+ ).rejects.toThrow();+ } catch (error) {+ // Permission changes might not work on all systems+ console.log('Permission test skipped:', error);+ }+ });++ it('should handle very long file paths', async () => {+ const longName = 'a'.repeat(200); // Very long filename+ const longPath = path.join(testDir, `${longName}.json`);++ try {+ await aggregator.saveToFile(longPath, 'completed');+ const exists = await fs.access(longPath).then(() => true).catch(() => false);+ expect(exists).toBe(true);+ } catch (error) {+ // Some file systems have path length limits+ expect(error).toBeInstanceOf(Error);+ }+ });+ });++ describe('Memory and Performance Edge Cases', () => {+ it('should handle rapid successive operations', () => {+ const start = Date.now();++ // Perform 10000 rapid operations+ for (let i = 0; i < 10000; i++) {+ aggregator.addAgentOutput('agent-1', `Output ${i}`);+ aggregator.addInsight(`Insight ${i}`);+ aggregator.updateMetrics({ throughput: i });+ }++ const end = Date.now();+ const duration = end - start;++ expect(duration).toBeLessThan(5000); // Should complete within 5 seconds++ const jsonOutput = aggregator.getJsonOutput('completed');+ const output = JSON.parse(jsonOutput);++ expect(output.results.outputs).toHaveLength(10000);+ expect(output.results.insights).toHaveLength(10000);+ });++ it('should handle concurrent access simulation', async () => {+ // Simulate concurrent operations+ const promises = [];++ for (let i = 0; i < 100; i++) {+ promises.push(+ new Promise<void>((resolve) => {+ setTimeout(() => {+ aggregator.addAgentOutput(`agent-${i % 10}`, `Concurrent output ${i}`);+ aggregator.addInsight(`Concurrent insight ${i}`);+ resolve();+ }, Math.random() * 10);+ })+ );+ }++ await Promise.all(promises);++ const jsonOutput = aggregator.getJsonOutput('completed');+ const output = JSON.parse(jsonOutput);++ expect(output.results.outputs).toHaveLength(100);+ expect(output.results.insights).toHaveLength(100);+ });+ });++ describe('JSON Structure Validation', () => {+ it('should produce valid JSON under all conditions', () => {+ // Add various types of data that might break JSON+ aggregator.addAgentOutput('agent-1', 'Output with "quotes" and \\backslashes\\');+ aggregator.addAgentError('agent-1', 'Error with special chars: \n\r\t');+ aggregator.addInsight('Insight with unicode: π€π¬π');+ aggregator.addArtifact('special', {+ quotes: '"test"',+ backslashes: '\\path\\to\\file',+ unicode: 'π',+ newlines: 'line1\nline2\rline3\tline4'+ });++ const jsonOutput = aggregator.getJsonOutput('completed');++ expect(() => {+ JSON.parse(jsonOutput);+ }).not.toThrow();+ });++ it('should maintain consistent structure regardless of input', () => {+ const emptyOutput = JSON.parse(aggregator.getJsonOutput('completed'));++ // Add some data+ aggregator.addAgentOutput('agent-1', 'test');+ aggregator.addInsight('test insight');++ const populatedOutput = JSON.parse(aggregator.getJsonOutput('completed'));++ // Structure should remain the same+ expect(Object.keys(emptyOutput).sort()).toEqual(Object.keys(populatedOutput).sort());+ expect(Object.keys(emptyOutput.summary).sort()).toEqual(Object.keys(populatedOutput.summary).sort());+ expect(Object.keys(emptyOutput.results).sort()).toEqual(Object.keys(populatedOutput.results).sort());+ expect(Object.keys(emptyOutput.metadata).sort()).toEqual(Object.keys(populatedOutput.metadata).sort());+ });+ });++ describe('SwarmCoordinator Integration Edge Cases', () => {+ it('should handle JSON output when coordinator has errors', () => {+ const coordinator = new SwarmCoordinator({+ id: 'test-swarm',+ name: 'Test Swarm',+ description: 'Test swarm for edge cases',+ strategy: 'auto',+ mode: 'centralized',+ requirements: {+ minAgents: 1,+ maxAgents: 10,+ agentTypes: ['researcher'],+ estimatedDuration: 300,+ maxDuration: 600,+ qualityThreshold: 0.8,+ reviewCoverage: 0.5,+ testCoverage: 0.5,+ reliabilityTarget: 0.9+ },+ constraints: {+ milestones: [],+ resourceLimits: {},+ minQuality: 0.7,+ requiredApprovals: [],+ allowedFailures: 3,+ recoveryTime: 60+ },+ tasks: [],+ dependencies: [],+ status: 'planning',+ progress: {+ totalTasks: 0,+ completedTasks: 0,+ failedTasks: 0,+ runningTasks: 0,+ estimatedCompletion: new Date(),+ timeRemaining: 0,+ percentComplete: 0,+ averageQuality: 0,+ passedReviews: 0,+ passedTests: 0,+ resourceUtilization: {},+ costSpent: 0,+ activeAgents: 0,+ idleAgents: 0,+ busyAgents: 0+ },+ createdAt: new Date(),+ metrics: {+ throughput: 0,+ latency: 0,+ efficiency: 0,+ reliability: 0,+ averageQuality: 0,+ defectRate: 0,+ reworkRate: 0,+ resourceUtilization: {},+ costEfficiency: 0,+ agentUtilization: 0,+ agentSatisfaction: 0,+ collaborationEffectiveness: 0,+ scheduleVariance: 0,+ deadlineAdherence: 0+ }+ });++ coordinator.enableJsonOutput();++ expect(() => {+ const jsonOutput = coordinator.getJsonOutput();+ JSON.parse(jsonOutput);+ }).not.toThrow();+ });++ it('should handle saving JSON output when no agents or tasks exist', async () => {+ const coordinator = new SwarmCoordinator({+ id: 'empty-swarm',+ name: 'Empty Swarm',+ description: 'Swarm with no agents or tasks',+ strategy: 'auto',+ mode: 'centralized',+ requirements: {+ minAgents: 0,+ maxAgents: 0,+ agentTypes: [],+ estimatedDuration: 0,+ maxDuration: 0,+ qualityThreshold: 0,+ reviewCoverage: 0,+ testCoverage: 0,+ reliabilityTarget: 0+ },+ constraints: {+ milestones: [],+ resourceLimits: {},+ minQuality: 0,+ requiredApprovals: [],+ allowedFailures: 0,+ recoveryTime: 0+ },+ tasks: [],+ dependencies: [],+ status: 'completed',+ progress: {+ totalTasks: 0,+ completedTasks: 0,+ failedTasks: 0,+ runningTasks: 0,+ estimatedCompletion: new Date(),+ timeRemaining: 0,+ percentComplete: 100,+ averageQuality: 0,+ passedReviews: 0,+ passedTests: 0,+ resourceUtilization: {},+ costSpent: 0,+ activeAgents: 0,+ idleAgents: 0,+ busyAgents: 0+ },+ createdAt: new Date(),+ metrics: {+ throughput: 0,+ latency: 0,+ efficiency: 0,+ reliability: 0,+ averageQuality: 0,+ defectRate: 0,+ reworkRate: 0,+ resourceUtilization: {},+ costEfficiency: 0,+ agentUtilization: 0,+ agentSatisfaction: 0,+ collaborationEffectiveness: 0,+ scheduleVariance: 0,+ deadlineAdherence: 0+ }+ });++ coordinator.enableJsonOutput();+ const outputPath = path.join(testDir, 'empty-swarm-output.json');++ await expect(+ coordinator.saveJsonOutput(outputPath)+ ).resolves.not.toThrow();++ const exists = await fs.access(outputPath).then(() => true).catch(() => false);+ expect(exists).toBe(true);++ const fileContent = await fs.readFile(outputPath, 'utf-8');+ const output = JSON.parse(fileContent);++ expect(output.summary.totalAgents).toBe(0);+ expect(output.summary.totalTasks).toBe(0);+ expect(output.agents).toHaveLength(0);+ expect(output.tasks).toHaveLength(0);+ });+ });+});\ No newline at end of filediff --git a/tests/integration/json-output.test.ts b/tests/integration/json-output.test.tsnew file mode 100644index 0000000000..ec0923cdda--- /dev/null+++ b/tests/integration/json-output.test.ts@@ -0,0 +1,252 @@+/**+ * Integration tests for JSON output functionality (Issue #206)+ */++import { describe, it, expect, beforeEach, afterEach } from '@jest/globals';+import { SwarmJsonOutputAggregator } from '../../src/swarm/json-output-aggregator.js';+import { SwarmCoordinator } from '../../src/swarm/coordinator.js';+import { generateId } from '../../src/utils/helpers.js';+import { promises as fs } from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';++describe('JSON Output Functionality', () => {+ let tempDir: string;+ let aggregator: SwarmJsonOutputAggregator;+ let coordinator: SwarmCoordinator;++ beforeEach(async () => {+ // Create temporary directory for test files+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-flow-json-test-'));++ // Initialize aggregator+ aggregator = new SwarmJsonOutputAggregator(+ 'test-swarm-123',+ 'Test objective for JSON output',+ { strategy: 'auto', mode: 'centralized', maxAgents: 3 }+ );++ // Initialize coordinator with JSON output enabled+ coordinator = new SwarmCoordinator({+ name: 'Test Swarm',+ description: 'Test swarm for JSON output',+ mode: 'centralized',+ strategy: 'auto',+ maxAgents: 3+ });++ await coordinator.initialize();+ coordinator.enableJsonOutput('Test objective for JSON output');+ });++ afterEach(async () => {+ // Clean up temporary directory+ await fs.rmdir(tempDir, { recursive: true });+ });++ describe('SwarmJsonOutputAggregator', () => {+ it('should initialize with correct metadata', () => {+ const output = aggregator.getJsonOutput('completed');+ const parsed = JSON.parse(output);++ expect(parsed.swarmId).toBe('test-swarm-123');+ expect(parsed.objective).toBe('Test objective for JSON output');+ expect(parsed.status).toBe('completed');+ expect(parsed.metadata.strategy).toBe('auto');+ expect(parsed.metadata.mode).toBe('centralized');+ expect(parsed.metadata.version).toBe('2.0.0-alpha');+ });++ it('should track agents correctly', () => {+ const agent1 = {+ id: 'agent-1',+ name: 'Test Agent 1',+ type: 'researcher' as any,+ status: 'active' as any+ };++ const agent2 = {+ id: 'agent-2',+ name: 'Test Agent 2',+ type: 'coder' as any,+ status: 'active' as any+ };++ aggregator.addAgent(agent1);+ aggregator.addAgent(agent2);++ const output = aggregator.getJsonOutput('completed');+ const parsed = JSON.parse(output);++ expect(parsed.agents).toHaveLength(2);+ expect(parsed.agents[0].agentId).toBe('agent-1');+ expect(parsed.agents[0].name).toBe('Test Agent 1');+ expect(parsed.agents[0].type).toBe('researcher');+ expect(parsed.agents[1].agentId).toBe('agent-2');+ expect(parsed.summary.totalAgents).toBe(2);+ });++ it('should track tasks correctly', () => {+ const task1 = {+ id: 'task-1',+ name: 'Test Task 1',+ type: 'research' as any,+ status: 'completed' as any,+ priority: 'high'+ };++ const task2 = {+ id: 'task-2',+ name: 'Test Task 2',+ type: 'coding' as any,+ status: 'failed' as any,+ priority: 'medium'+ };++ aggregator.addTask(task1);+ aggregator.addTask(task2);++ const output = aggregator.getJsonOutput('completed');+ const parsed = JSON.parse(output);++ expect(parsed.tasks).toHaveLength(2);+ expect(parsed.tasks[0].taskId).toBe('task-1');+ expect(parsed.tasks[0].status).toBe('completed');+ expect(parsed.tasks[1].taskId).toBe('task-2');+ expect(parsed.tasks[1].status).toBe('failed');+ expect(parsed.summary.totalTasks).toBe(2);+ });++ it('should collect agent outputs and errors', () => {+ const agent = {+ id: 'agent-1',+ name: 'Test Agent',+ type: 'researcher' as any,+ status: 'active' as any+ };++ aggregator.addAgent(agent);+ aggregator.addAgentOutput('agent-1', 'Research completed successfully');+ aggregator.addAgentOutput('agent-1', 'Found 5 relevant papers');+ aggregator.addAgentError('agent-1', 'Network timeout during search');++ const output = aggregator.getJsonOutput('completed');+ const parsed = JSON.parse(output);++ expect(parsed.agents[0].outputs).toHaveLength(2);+ expect(parsed.agents[0].outputs[0]).toBe('Research completed successfully');+ expect(parsed.agents[0].errors).toHaveLength(1);+ expect(parsed.agents[0].errors[0]).toBe('Network timeout during search');+ expect(parsed.results.outputs).toHaveLength(2);+ expect(parsed.results.errors).toHaveLength(1);+ });++ it('should calculate summary statistics correctly', () => {+ // Add agents+ aggregator.addAgent({+ id: 'agent-1', name: 'Agent 1', type: 'researcher' as any, status: 'active' as any+ });+ aggregator.addAgent({+ id: 'agent-2', name: 'Agent 2', type: 'coder' as any, status: 'active' as any+ });++ // Add tasks+ aggregator.addTask({+ id: 'task-1', name: 'Task 1', type: 'research' as any, status: 'completed' as any, priority: 'high'+ });+ aggregator.addTask({+ id: 'task-2', name: 'Task 2', type: 'coding' as any, status: 'completed' as any, priority: 'medium'+ });+ aggregator.addTask({+ id: 'task-3', name: 'Task 3', type: 'testing' as any, status: 'failed' as any, priority: 'low'+ });++ const output = aggregator.getJsonOutput('completed');+ const parsed = JSON.parse(output);++ expect(parsed.summary.totalAgents).toBe(2);+ expect(parsed.summary.totalTasks).toBe(3);+ expect(parsed.summary.completedTasks).toBe(2);+ expect(parsed.summary.failedTasks).toBe(1);+ expect(parsed.summary.successRate).toBeCloseTo(0.667, 2);+ });++ it('should save output to file', async () => {+ const filePath = path.join(tempDir, 'test-output.json');++ aggregator.addInsight('This is a test insight');+ aggregator.addArtifact('test-key', { type: 'test', value: 'test-data' });++ await aggregator.saveToFile(filePath, 'completed');++ const fileContent = await fs.readFile(filePath, 'utf8');+ const parsed = JSON.parse(fileContent);++ expect(parsed.swarmId).toBe('test-swarm-123');+ expect(parsed.results.insights).toContain('This is a test insight');+ expect(parsed.results.artifacts['test-key']).toEqual({ type: 'test', value: 'test-data' });+ });+ });++ describe('SwarmCoordinator JSON Integration', () => {+ it('should enable JSON output correctly', () => {+ const jsonOutput = coordinator.getJsonOutput('completed');+ expect(jsonOutput).not.toBeNull();++ const parsed = JSON.parse(jsonOutput!);+ expect(parsed.objective).toBe('Test objective for JSON output');+ });++ it('should track agents and tasks when JSON output is enabled', async () => {+ // Create an agent through coordinator+ const agentId = await coordinator.registerAgent('test-agent', 'researcher');++ // Create a task through coordinator+ const taskId = await coordinator.createTask('research', 'Test research task');++ const jsonOutput = coordinator.getJsonOutput('completed');+ expect(jsonOutput).not.toBeNull();++ const parsed = JSON.parse(jsonOutput!);+ expect(parsed.agents.length).toBeGreaterThan(0);+ expect(parsed.tasks.length).toBeGreaterThan(0);+ });++ it('should save JSON output to file through coordinator', async () => {+ const filePath = path.join(tempDir, 'coordinator-output.json');++ // Add some test data+ coordinator.addInsight('Coordinator test insight');+ coordinator.addArtifact('coordinator-test', { data: 'test' });++ await coordinator.saveJsonOutput(filePath, 'completed');++ const fileContent = await fs.readFile(filePath, 'utf8');+ const parsed = JSON.parse(fileContent);++ expect(parsed.results.insights).toContain('Coordinator test insight');+ expect(parsed.results.artifacts['coordinator-test']).toEqual({ data: 'test' });+ });+ });++ describe('Command Line Integration', () => {+ it('should parse JSON output flags correctly', () => {+ // This would test the parseSwarmOptions function+ // For now, we'll create a mock test structure+ const flags = {+ 'output-format': 'json',+ 'output-file': 'results.json',+ 'no-interactive': true+ };++ // Mock the parseSwarmOptions function behavior+ const outputFormat = flags['output-format'];+ const outputFile = flags['output-file'];+ const noInteractive = flags['no-interactive'];++ expect(outputFormat).toBe('json');+ expect(outputFile).toBe('results.json');+ expect(noInteractive).toBe(true);+ });+ });+});\ No newline at end of file