🌊 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(cli): render analyze diff from the analyze_diff result shape (#4101)
Muhammad Zubairf7d885a58037
diff --git a/v3/@claude-flow/cli/__tests__/analyze-diff-render-4101.test.ts b/v3/@claude-flow/cli/__tests__/analyze-diff-render-4101.test.tsnew file mode 100644index 0000000000..cc10ec92ba--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/analyze-diff-render-4101.test.ts@@ -0,0 +1,90 @@+vi.mock('../src/mcp-client.js', () => ({ callMCPTool: vi.fn(), MCPClientError: class extends Error {} }));+import { afterEach, describe, expect, it, vi } from 'vitest';+import { output } from '../src/output.js';+import { callMCPTool } from '../src/mcp-client.js';+import { analyzeCommand } from '../src/commands/analyze.js';+import {+ assessFileRisk,+ assessOverallRisk,+ classifyDiff,+ suggestReviewers,+ type DiffFile,+} from '../src/ruvector/diff-classifier.js';++// Build the fixture with the classifier the analyze_diff MCP tool uses, so the+// test breaks if the renderer and the tool drift apart again.+function analyzeDiffResult(files: DiffFile[]) {+ const fileRisks = files.map(assessFileRisk);+ return {+ ref: 'HEAD~1',+ timestamp: Date.now(),+ files,+ risk: assessOverallRisk(files, fileRisks),+ classification: classifyDiff(files),+ fileRisks,+ recommendedReviewers: suggestReviewers(files, fileRisks),+ summary: `${files.length} files changed`,+ };+}++const files: DiffFile[] = [+ { path: 'src/auth/session.ts', status: 'modified', additions: 350, deletions: 20, hunks: 6, binary: false },+ { path: 'docs/notes.md', status: 'added', additions: 4, deletions: 0, hunks: 1, binary: false },+];++async function runDiff(flags: Record<string, unknown>) {+ const lines: string[] = [];+ vi.spyOn(output, 'writeln').mockImplementation((line = '') => { lines.push(String(line)); });+ const diff = analyzeCommand.subcommands!.find((c) => c.name === 'diff')!;+ const result = await diff.action!({ args: ['HEAD~1'], flags: { _: [], ...flags }, cwd: process.cwd(), interactive: false });+ return { result, printed: lines.join('\n') };+}++afterEach(() => vi.restoreAllMocks());++describe('analyze diff renders the analyze_diff result shape', () => {+ it('prints counts, risk breakdown and high-risk files without throwing', async () => {+ const fixture = analyzeDiffResult(files);+ vi.mocked(callMCPTool).mockResolvedValue(fixture);+ const { result, printed } = await runDiff({ risk: true });++ expect(result.success).toBe(true);+ expect(printed).toMatch(/Files Changed\s*\|\s*2\b/);+ expect(printed).toMatch(/Total Lines Changed\s*\|\s*374\b/);+ const highRisk = fixture.fileRisks.filter((r) => r.risk === 'high' || r.risk === 'critical');+ expect(highRisk.length).toBeGreaterThan(0);+ expect(printed).toContain('High Risk Files');+ expect(printed).toContain('src/auth/session.ts');+ expect(printed).not.toContain('undefined');+ });++ it('shows the classifier category in the summary and classification table', async () => {+ const fixture = analyzeDiffResult(files);+ vi.mocked(callMCPTool).mockResolvedValue(fixture);+ const { result, printed } = await runDiff({});++ expect(result.success).toBe(true);+ expect(printed).toContain(`Type: ${fixture.classification.primary}`);+ expect(printed).not.toContain('Type: undefined');+ });++ it('names the file in the verbose file-level table', async () => {+ vi.mocked(callMCPTool).mockResolvedValue(analyzeDiffResult(files));+ const { result, printed } = await runDiff({ verbose: true });++ expect(result.success).toBe(true);+ expect(printed).toContain('File-Level Analysis');+ expect(printed).toContain('docs/notes.md');+ });++ it('reports a tool error instead of rendering an empty analysis', async () => {+ vi.mocked(callMCPTool).mockResolvedValue({ error: true, message: 'bad ref', ref: 'nope' });+ const errors: string[] = [];+ vi.spyOn(output, 'printError').mockImplementation((message: string) => { errors.push(message); });+ const diff = analyzeCommand.subcommands!.find((c) => c.name === 'diff')!;+ const result = await diff.action!({ args: ['nope'], flags: { _: [] }, cwd: process.cwd(), interactive: false });++ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(errors.join('\n')).toContain('bad ref');+ });+});diff --git a/v3/@claude-flow/cli/src/commands/analyze.ts b/v3/@claude-flow/cli/src/commands/analyze.tsindex d79f1d133c..017cc6b912 100644--- a/v3/@claude-flow/cli/src/commands/analyze.ts+++ b/v3/@claude-flow/cli/src/commands/analyze.ts@@ -17,6 +17,7 @@import type { Command, CommandContext, CommandResult } from '../types.js';import { output } from '../output.js';import { callMCPTool, MCPClientError } from '../mcp-client.js';+import type { DiffClassification, DiffFile, FileRisk, OverallRisk } from '../ruvector/diff-classifier.js';import * as path from 'path';import * as fs from 'fs/promises';import { writeFile } from 'fs/promises';@@ -103,48 +104,32 @@ const diffCommand: Command = {try {// Call MCP tool for diff analysis+ // Shape returned by the analyze_diff MCP tool (ruvector/diff-classifier.ts).+ // Typed from the classifier itself so the renderer cannot drift from it again.const result = await callMCPTool<{- ref: string;- timestamp: string;- files: Array<{- path: string;- status: string;- additions: number;- deletions: number;- binary: boolean;- }>;- risk: {- overall: string;- score: number;- breakdown: {- fileCount: number;- totalChanges: number;- highRiskFiles: string[];- securityConcerns: string[];- breakingChanges: string[];- testCoverage: string;- };- };- classification: {- category: string;- subcategory?: string;- confidence: number;- reasoning: string;- };- fileRisks: Array<{- path: string;- risk: string;- score: number;- reasons: string[];- }>;- recommendedReviewers: string[];- summary: string;+ ref?: string;+ timestamp?: number;+ files?: DiffFile[];+ risk?: OverallRisk;+ classification?: DiffClassification;+ fileRisks?: FileRisk[];+ recommendedReviewers?: string[];+ summary?: string;+ error?: boolean;+ message?: string;}>('analyze_diff', {ref,- includeFileRisks: verbose,+ // Always request file risks: the handler computes them anyway, and the+ // high-risk file list below is derived from them.+ includeFileRisks: true,includeReviewers: showReviewers || showAll,});+ if (result.error) {+ output.printError(`Diff analysis failed: ${result.message ?? 'unknown error'}`);+ return { success: false, exitCode: 1 };+ }+// JSON outputif (formatType === 'json') {output.printJson(result);@@ -155,15 +140,20 @@ const diffCommand: Command = {// Summary boxconst files = result.files || [];- const risk = result.risk || { overall: 'unknown', score: 0, breakdown: { fileCount: 0, totalChanges: 0, highRiskFiles: [], securityConcerns: [], breakingChanges: [], testCoverage: 'unknown' } };- const classification = result.classification || { category: 'unknown', confidence: 0, reasoning: '' };+ const fileRisks = result.fileRisks || [];+ const risk = result.risk || { overall: 'low', score: 0, breakdown: { low: 0, medium: 0, high: 0, critical: 0 } };+ const classification = result.classification;+ const category = classification?.primary ?? 'unknown';+ const secondary = classification?.secondary?.length ? classification.secondary.join(', ') : '';+ const totalChanges = files.reduce((sum, f) => sum + f.additions + f.deletions, 0);+ const highRiskFiles = fileRisks.filter((r) => r.risk === 'high' || r.risk === 'critical').map((r) => r.file);output.printBox([`Ref: ${result.ref || 'HEAD'}`,`Files: ${files.length}`,`Risk: ${getRiskDisplay(risk.overall)} (${risk.score}/100)`,- `Type: ${classification.category}${classification.subcategory ? ` (${classification.subcategory})` : ''}`,+ `Type: ${category}${secondary ? ` (${secondary})` : ''}`,``,result.summary || 'No summary available',].join('\n'),@@ -179,36 +169,30 @@ const diffCommand: Command = {output.printTable({columns: [{ key: 'metric', header: 'Metric', width: 25 },- { key: 'value', header: 'Value', width: 30 },+ { key: 'value', header: 'Value', width: 42 },],data: [{ metric: 'Overall Risk', value: getRiskDisplay(risk.overall) },{ metric: 'Risk Score', value: `${risk.score}/100` },- { metric: 'Files Changed', value: risk.breakdown.fileCount },- { metric: 'Total Lines Changed', value: risk.breakdown.totalChanges },- { metric: 'Test Coverage', value: risk.breakdown.testCoverage },+ { metric: 'Files Changed', value: files.length },+ { metric: 'Total Lines Changed', value: totalChanges },+ { metric: 'Files by Risk', value: `low ${risk.breakdown.low} / medium ${risk.breakdown.medium} / high ${risk.breakdown.high} / critical ${risk.breakdown.critical}` },],});- // Security concerns- if (risk.breakdown.securityConcerns.length > 0) {- output.writeln();- output.writeln(output.bold(output.warning('Security Concerns')));- output.printList(risk.breakdown.securityConcerns.map(c => output.warning(c)));- }-- // Breaking changes- if (risk.breakdown.breakingChanges.length > 0) {+ // Risk factors reported by the classifier+ const riskFactors = classification?.riskFactors ?? [];+ if (riskFactors.length > 0) {output.writeln();- output.writeln(output.bold(output.error('Potential Breaking Changes')));- output.printList(risk.breakdown.breakingChanges.map(c => output.error(c)));+ output.writeln(output.bold(output.warning('Risk Factors')));+ output.printList(riskFactors.map(c => output.warning(c)));}// High risk files- if (risk.breakdown.highRiskFiles.length > 0) {+ if (highRiskFiles.length > 0) {output.writeln();output.writeln(output.bold('High Risk Files'));- output.printList(risk.breakdown.highRiskFiles.map(f => output.warning(f)));+ output.printList(highRiskFiles.map(f => output.warning(f)));}}@@ -224,14 +208,17 @@ const diffCommand: Command = {{ key: 'value', header: 'Value', width: 40 },],data: [- { field: 'Category', value: classification.category },- { field: 'Subcategory', value: classification.subcategory || '-' },- { field: 'Confidence', value: `${(classification.confidence * 100).toFixed(0)}%` },+ { field: 'Category', value: category },+ { field: 'Secondary', value: secondary || '-' },+ { field: 'Confidence', value: `${((classification?.confidence ?? 0) * 100).toFixed(0)}%` },+ { field: 'Impact', value: classification?.impactLevel ?? '-' },],});- output.writeln();- output.writeln(output.dim(`Reasoning: ${classification.reasoning}`));+ if (classification?.testingStrategy?.length) {+ output.writeln();+ output.writeln(output.dim(`Testing strategy: ${classification.testingStrategy.join(', ')}`));+ }}// Reviewers@@ -249,14 +236,14 @@ const diffCommand: Command = {}// Verbose file-level details- if (verbose && result.fileRisks) {+ if (verbose && fileRisks.length > 0) {output.writeln();output.writeln(output.bold('File-Level Analysis'));output.writeln(output.dim('-'.repeat(50)));output.printTable({columns: [- { key: 'path', header: 'File', width: 40 },+ { key: 'file', header: 'File', width: 40 },{ key: 'risk', header: 'Risk', width: 12, format: (v) => getRiskDisplay(String(v)) },{ key: 'score', header: 'Score', width: 8, align: 'right' },{ key: 'reasons', header: 'Reasons', width: 30, format: (v) => {@@ -264,7 +251,7 @@ const diffCommand: Command = {return reasons.slice(0, 2).join('; ');}},],- data: result.fileRisks,+ data: fileRisks.map((r) => ({ ...r })),});}@@ -281,7 +268,7 @@ const diffCommand: Command = {{ key: 'additions', header: '+', width: 8, align: 'right', format: (v) => output.success(`+${v}`) },{ key: 'deletions', header: '-', width: 8, align: 'right', format: (v) => output.error(`-${v}`) },],- data: files.slice(0, 20),+ data: files.slice(0, 20).map((f) => ({ ...f })),});if (files.length > 20) {