From f5aee2a5051765bce7c1748c48d482f8bfdb8abb Mon Sep 17 00:00:00 2001 From: rUv Date: Sun, 4 Jan 2026 20:28:44 +0000 Subject: [PATCH] checkpoint: File edit: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🚀 Generated with [Claude Code](https://claude.com/claude-code) 📊 V3 Development Progress Checkpoint Co-Authored-By: Claude Sonnet 4 --- .../cli/__tests__/mcp-client.test.ts | 482 ++++++++++++++++++ v3/@claude-flow/deployment/README.md | 326 ++++++++++++ .../deployment/src/release-manager.ts | 2 +- 3 files changed, 809 insertions(+), 1 deletion(-) create mode 100644 v3/@claude-flow/cli/__tests__/mcp-client.test.ts create mode 100644 v3/@claude-flow/deployment/README.md diff --git a/v3/@claude-flow/cli/__tests__/mcp-client.test.ts b/v3/@claude-flow/cli/__tests__/mcp-client.test.ts new file mode 100644 index 0000000000..413dbdc5d5 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/mcp-client.test.ts @@ -0,0 +1,482 @@ +/** + * V3 CLI MCP Client Tests + * Tests for MCP tool invocation with proper mocking + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { + callMCPTool, + getToolMetadata, + listMCPTools, + hasTool, + getToolCategories, + validateToolInput, + MCPClientError +} from '../src/mcp-client.js'; + +// Mock MCP tool modules +vi.mock('../../../mcp/tools/agent-tools.js', () => ({ + agentTools: [ + { + name: 'agent/spawn', + description: 'Spawn a new agent', + category: 'agent', + inputSchema: { + type: 'object', + required: ['agentType'], + properties: { + agentType: { type: 'string' }, + id: { type: 'string' }, + config: { type: 'object' } + } + }, + handler: vi.fn(async (input) => ({ + agentId: input.id || 'test-agent', + agentType: input.agentType, + status: 'active', + createdAt: new Date().toISOString() + })) + }, + { + name: 'agent/list', + description: 'List all agents', + category: 'agent', + inputSchema: { + type: 'object', + properties: { + status: { type: 'string' }, + limit: { type: 'number' } + } + }, + handler: vi.fn(async () => ({ + agents: [ + { id: 'agent-1', agentType: 'coder', status: 'active', createdAt: '2024-01-01T00:00:00Z' }, + { id: 'agent-2', agentType: 'tester', status: 'idle', createdAt: '2024-01-01T00:01:00Z' } + ], + total: 2 + })) + }, + { + name: 'agent/terminate', + description: 'Terminate an agent', + category: 'agent', + inputSchema: { + type: 'object', + required: ['agentId'], + properties: { + agentId: { type: 'string' }, + graceful: { type: 'boolean' } + } + }, + handler: vi.fn(async (input) => ({ + agentId: input.agentId, + terminated: true, + terminatedAt: new Date().toISOString() + })) + } + ] +})); + +vi.mock('../../../mcp/tools/swarm-tools.js', () => ({ + swarmTools: [ + { + name: 'swarm/init', + description: 'Initialize a swarm', + category: 'swarm', + inputSchema: { + type: 'object', + required: ['topology'], + properties: { + topology: { type: 'string' }, + maxAgents: { type: 'number' } + } + }, + handler: vi.fn(async (input) => ({ + swarmId: 'swarm-test', + topology: input.topology, + initializedAt: new Date().toISOString(), + config: { + topology: input.topology, + maxAgents: input.maxAgents || 15, + currentAgents: 0 + } + })) + } + ] +})); + +vi.mock('../../../mcp/tools/memory-tools.js', () => ({ + memoryTools: [ + { + name: 'memory/store', + description: 'Store data in memory', + category: 'memory', + inputSchema: { + type: 'object', + required: ['key', 'value'], + properties: { + key: { type: 'string' }, + value: { type: 'string' }, + namespace: { type: 'string' } + } + }, + handler: vi.fn(async (input) => ({ + key: input.key, + stored: true, + timestamp: new Date().toISOString() + })) + } + ] +})); + +vi.mock('../../../mcp/tools/config-tools.js', () => ({ + configTools: [ + { + name: 'config/get', + description: 'Get configuration value', + category: 'config', + inputSchema: { + type: 'object', + properties: { + key: { type: 'string' } + } + }, + handler: vi.fn(async (input) => ({ + key: input.key, + value: 'test-value' + })) + } + ] +})); + +describe('MCP Client', () => { + describe('callMCPTool', () => { + it('should call agent/spawn tool successfully', async () => { + const result = await callMCPTool('agent/spawn', { + agentType: 'coder', + id: 'test-coder-1' + }); + + expect(result).toMatchObject({ + agentId: 'test-coder-1', + agentType: 'coder', + status: 'active' + }); + expect(result.createdAt).toBeDefined(); + }); + + it('should call agent/list tool successfully', async () => { + const result = await callMCPTool<{ agents: unknown[]; total: number }>('agent/list', { + status: 'active', + limit: 10 + }); + + expect(result.agents).toHaveLength(2); + expect(result.total).toBe(2); + expect(result.agents[0]).toHaveProperty('id'); + expect(result.agents[0]).toHaveProperty('agentType'); + }); + + it('should call agent/terminate tool successfully', async () => { + const result = await callMCPTool('agent/terminate', { + agentId: 'agent-1', + graceful: true + }); + + expect(result).toMatchObject({ + agentId: 'agent-1', + terminated: true + }); + expect(result.terminatedAt).toBeDefined(); + }); + + it('should call swarm/init tool successfully', async () => { + const result = await callMCPTool('swarm/init', { + topology: 'hierarchical-mesh', + maxAgents: 15 + }); + + expect(result).toMatchObject({ + swarmId: 'swarm-test', + topology: 'hierarchical-mesh' + }); + expect(result.config).toMatchObject({ + topology: 'hierarchical-mesh', + maxAgents: 15 + }); + }); + + it('should call memory/store tool successfully', async () => { + const result = await callMCPTool('memory/store', { + key: 'test-key', + value: 'test-value', + namespace: 'default' + }); + + expect(result).toMatchObject({ + key: 'test-key', + stored: true + }); + expect(result.timestamp).toBeDefined(); + }); + + it('should call config/get tool successfully', async () => { + const result = await callMCPTool('config/get', { + key: 'swarm.topology' + }); + + expect(result).toMatchObject({ + key: 'swarm.topology', + value: 'test-value' + }); + }); + + it('should throw MCPClientError for non-existent tool', async () => { + await expect( + callMCPTool('nonexistent/tool', {}) + ).rejects.toThrow(MCPClientError); + + await expect( + callMCPTool('nonexistent/tool', {}) + ).rejects.toThrow('MCP tool not found: nonexistent/tool'); + }); + + it('should wrap handler errors in MCPClientError', async () => { + // Create a mock tool that throws an error + const { agentTools } = await import('../../../mcp/tools/agent-tools.js'); + const errorTool = agentTools.find(t => t.name === 'agent/spawn'); + + if (errorTool) { + vi.mocked(errorTool.handler).mockRejectedValueOnce(new Error('Handler error')); + + await expect( + callMCPTool('agent/spawn', { agentType: 'coder' }) + ).rejects.toThrow(MCPClientError); + + await expect( + callMCPTool('agent/spawn', { agentType: 'coder' }) + ).rejects.toThrow("Failed to execute MCP tool 'agent/spawn'"); + } + }); + + it('should pass context to tool handler', async () => { + const context = { userId: 'test-user', sessionId: 'test-session' }; + + const result = await callMCPTool('agent/spawn', { + agentType: 'coder' + }, context); + + expect(result).toBeDefined(); + // Tool should have access to context + }); + + it('should handle empty input object', async () => { + const result = await callMCPTool('agent/list', {}); + + expect(result).toHaveProperty('agents'); + expect(result).toHaveProperty('total'); + }); + }); + + describe('getToolMetadata', () => { + it('should return metadata for existing tool', () => { + const metadata = getToolMetadata('agent/spawn'); + + expect(metadata).toBeDefined(); + expect(metadata?.name).toBe('agent/spawn'); + expect(metadata?.description).toBe('Spawn a new agent'); + expect(metadata?.category).toBe('agent'); + expect(metadata?.inputSchema).toBeDefined(); + expect(metadata).not.toHaveProperty('handler'); + }); + + it('should return undefined for non-existent tool', () => { + const metadata = getToolMetadata('nonexistent/tool'); + + expect(metadata).toBeUndefined(); + }); + + it('should not include handler in metadata', () => { + const metadata = getToolMetadata('agent/spawn'); + + expect(metadata).toBeDefined(); + expect(metadata).not.toHaveProperty('handler'); + }); + + it('should return complete metadata structure', () => { + const metadata = getToolMetadata('swarm/init'); + + expect(metadata).toMatchObject({ + name: 'swarm/init', + description: expect.any(String), + category: 'swarm', + inputSchema: expect.any(Object) + }); + }); + }); + + describe('listMCPTools', () => { + it('should list all available tools', () => { + const tools = listMCPTools(); + + expect(tools.length).toBeGreaterThan(0); + expect(tools.every(t => t.name && t.description)).toBe(true); + }); + + it('should filter tools by category', () => { + const agentTools = listMCPTools('agent'); + + expect(agentTools.length).toBeGreaterThan(0); + expect(agentTools.every(t => t.category === 'agent')).toBe(true); + }); + + it('should return empty array for non-existent category', () => { + const tools = listMCPTools('nonexistent'); + + expect(tools).toEqual([]); + }); + + it('should not include handlers in listed tools', () => { + const tools = listMCPTools(); + + expect(tools.every(t => !('handler' in t))).toBe(true); + }); + + it('should include all metadata fields', () => { + const tools = listMCPTools(); + + tools.forEach(tool => { + expect(tool).toHaveProperty('name'); + expect(tool).toHaveProperty('description'); + expect(tool).toHaveProperty('inputSchema'); + expect(tool).toHaveProperty('category'); + }); + }); + }); + + describe('hasTool', () => { + it('should return true for existing tool', () => { + expect(hasTool('agent/spawn')).toBe(true); + expect(hasTool('agent/list')).toBe(true); + expect(hasTool('swarm/init')).toBe(true); + }); + + it('should return false for non-existent tool', () => { + expect(hasTool('nonexistent/tool')).toBe(false); + expect(hasTool('invalid')).toBe(false); + }); + + it('should be case-sensitive', () => { + expect(hasTool('agent/spawn')).toBe(true); + expect(hasTool('Agent/Spawn')).toBe(false); + }); + }); + + describe('getToolCategories', () => { + it('should return all unique categories', () => { + const categories = getToolCategories(); + + expect(categories).toContain('agent'); + expect(categories).toContain('swarm'); + expect(categories).toContain('memory'); + expect(categories).toContain('config'); + }); + + it('should return sorted categories', () => { + const categories = getToolCategories(); + const sorted = [...categories].sort(); + + expect(categories).toEqual(sorted); + }); + + it('should not contain duplicates', () => { + const categories = getToolCategories(); + const unique = [...new Set(categories)]; + + expect(categories).toEqual(unique); + }); + }); + + describe('validateToolInput', () => { + it('should validate required fields', () => { + const result = validateToolInput('agent/spawn', { + agentType: 'coder', + id: 'test-1' + }); + + expect(result.valid).toBe(true); + expect(result.errors).toBeUndefined(); + }); + + it('should detect missing required fields', () => { + const result = validateToolInput('agent/spawn', { + id: 'test-1' + // Missing required 'agentType' + }); + + expect(result.valid).toBe(false); + expect(result.errors).toBeDefined(); + expect(result.errors).toContain('Missing required field: agentType'); + }); + + it('should return invalid for non-existent tool', () => { + const result = validateToolInput('nonexistent/tool', {}); + + expect(result.valid).toBe(false); + expect(result.errors).toContain("Tool 'nonexistent/tool' not found"); + }); + + it('should validate multiple required fields', () => { + const result = validateToolInput('agent/terminate', { + // Missing required 'agentId' + graceful: true + }); + + expect(result.valid).toBe(false); + expect(result.errors).toContain('Missing required field: agentId'); + }); + + it('should pass with all required fields present', () => { + const result = validateToolInput('agent/terminate', { + agentId: 'agent-1', + graceful: true + }); + + expect(result.valid).toBe(true); + expect(result.errors).toBeUndefined(); + }); + + it('should allow optional fields to be missing', () => { + const result = validateToolInput('swarm/init', { + topology: 'hierarchical' + // maxAgents is optional + }); + + expect(result.valid).toBe(true); + }); + }); + + describe('MCPClientError', () => { + it('should create error with tool name', () => { + const error = new MCPClientError('Test error', 'test/tool'); + + expect(error.message).toBe('Test error'); + expect(error.toolName).toBe('test/tool'); + expect(error.name).toBe('MCPClientError'); + }); + + it('should include cause error', () => { + const cause = new Error('Original error'); + const error = new MCPClientError('Wrapper error', 'test/tool', cause); + + expect(error.cause).toBe(cause); + }); + + it('should be instanceof Error', () => { + const error = new MCPClientError('Test', 'tool'); + + expect(error instanceof Error).toBe(true); + expect(error instanceof MCPClientError).toBe(true); + }); + }); +}); diff --git a/v3/@claude-flow/deployment/README.md b/v3/@claude-flow/deployment/README.md new file mode 100644 index 0000000000..4053c55c69 --- /dev/null +++ b/v3/@claude-flow/deployment/README.md @@ -0,0 +1,326 @@ +# @claude-flow/deployment + +Release management, CI/CD, and versioning module for Claude Flow v3. + +## Features + +- **Version Bumping**: Automatic version management (major, minor, patch, prerelease) +- **Changelog Generation**: Generate changelogs from conventional commits +- **Git Integration**: Automatic tagging and committing +- **NPM Publishing**: Publish packages with tag support (alpha, beta, latest) +- **Pre-Release Validation**: Lint, test, build, and dependency checks +- **Dry Run Mode**: Test releases without making changes + +## Installation + +```bash +npm install @claude-flow/deployment +``` + +## Quick Start + +### Prepare a Release + +```typescript +import { prepareRelease } from '@claude-flow/deployment'; + +// Bump patch version and generate changelog +const result = await prepareRelease({ + bumpType: 'patch', + generateChangelog: true, + createTag: true, + commit: true +}); + +console.log(`Released ${result.newVersion}`); +``` + +### Publish to NPM + +```typescript +import { publishToNpm } from '@claude-flow/deployment'; + +// Publish with 'latest' tag +const result = await publishToNpm({ + tag: 'latest', + access: 'public' +}); + +console.log(`Published ${result.packageName}@${result.version}`); +``` + +### Validate Package + +```typescript +import { validate } from '@claude-flow/deployment'; + +// Run all validation checks +const result = await validate({ + lint: true, + test: true, + build: true, + checkDependencies: true +}); + +if (!result.valid) { + console.error('Validation failed:', result.errors); +} +``` + +## API Reference + +### ReleaseManager + +```typescript +import { ReleaseManager } from '@claude-flow/deployment'; + +const manager = new ReleaseManager(); + +// Prepare release with options +const result = await manager.prepareRelease({ + bumpType: 'minor', // major | minor | patch | prerelease + version: '2.0.0', // Override version + channel: 'beta', // alpha | beta | rc | latest + generateChangelog: true, // Generate CHANGELOG.md + createTag: true, // Create git tag + commit: true, // Commit changes + dryRun: false, // Test without changes + skipValidation: false, // Skip validation checks + tagPrefix: 'v', // Tag prefix (v2.0.0) + changelogPath: 'CHANGELOG.md' // Changelog file path +}); +``` + +#### Version Bumping + +```typescript +// Bump patch: 1.0.0 -> 1.0.1 +await manager.prepareRelease({ bumpType: 'patch' }); + +// Bump minor: 1.0.0 -> 1.1.0 +await manager.prepareRelease({ bumpType: 'minor' }); + +// Bump major: 1.0.0 -> 2.0.0 +await manager.prepareRelease({ bumpType: 'major' }); + +// Bump prerelease: 1.0.0 -> 1.0.0-alpha.1 +await manager.prepareRelease({ bumpType: 'prerelease', channel: 'alpha' }); + +// Increment prerelease: 1.0.0-alpha.1 -> 1.0.0-alpha.2 +await manager.prepareRelease({ bumpType: 'prerelease', channel: 'alpha' }); +``` + +#### Changelog Generation + +Generates changelog from conventional commits: + +```bash +# Commit format: type(scope): message +git commit -m "feat(api): add new endpoint" +git commit -m "fix(auth): resolve login issue" +git commit -m "feat(ui): update design BREAKING CHANGE: new layout" +``` + +Generated changelog: +```markdown +## [2.0.0] - 2026-01-04 + +### BREAKING CHANGES + +- **ui**: update design BREAKING CHANGE: new layout + +### Features + +- **api**: add new endpoint +- **ui**: update design + +### Bug Fixes + +- **auth**: resolve login issue +``` + +### Publisher + +```typescript +import { Publisher } from '@claude-flow/deployment'; + +const publisher = new Publisher(); + +// Publish to npm +const result = await publisher.publishToNpm({ + tag: 'latest', // npm tag (alpha, beta, latest) + access: 'public', // public | restricted + dryRun: false, // Test publish without actual publish + registry: 'https://registry.npmjs.org/', + otp: '123456', // 2FA OTP code + skipBuild: false, // Skip build step + buildCommand: 'npm run build' // Custom build command +}); + +// Check if version exists +const exists = await publisher.checkVersionExists('my-package', '1.0.0'); + +// Get latest version +const latest = await publisher.getLatestVersion('my-package', 'latest'); + +// Verify npm authentication +const authenticated = await publisher.verifyAuth(); + +// Pack to tarball +const tarball = await publisher.pack('./dist'); +``` + +### Validator + +```typescript +import { Validator } from '@claude-flow/deployment'; + +const validator = new Validator(); + +// Validate package +const result = await validator.validate({ + lint: true, // Run linter + test: true, // Run tests + build: true, // Run build + checkDependencies: true, // Check dependencies + checkGitStatus: true, // Check uncommitted changes + lintCommand: 'npm run lint', + testCommand: 'npm test', + buildCommand: 'npm run build' +}); + +console.log('Valid:', result.valid); +console.log('Errors:', result.errors); +console.log('Warnings:', result.warnings); +console.log('Checks:', result.checks); +``` + +## Complete Release Workflow + +```typescript +import { Validator, ReleaseManager, Publisher } from '@claude-flow/deployment'; + +async function release(version: string, tag: string) { + // 1. Validate package + console.log('Validating package...'); + const validator = new Validator(); + const validation = await validator.validate(); + + if (!validation.valid) { + console.error('Validation failed:', validation.errors); + process.exit(1); + } + + // 2. Prepare release + console.log('Preparing release...'); + const manager = new ReleaseManager(); + const release = await manager.prepareRelease({ + version, + generateChangelog: true, + createTag: true, + commit: true + }); + + if (!release.success) { + console.error('Release preparation failed:', release.error); + process.exit(1); + } + + // 3. Publish to npm + console.log('Publishing to npm...'); + const publisher = new Publisher(); + const publish = await publisher.publishToNpm({ + tag, + access: 'public' + }); + + if (!publish.success) { + console.error('Publish failed:', publish.error); + process.exit(1); + } + + console.log(`Successfully released ${publish.packageName}@${publish.version}`); +} + +// Run release +release('2.0.0', 'latest'); +``` + +## CLI Usage + +```bash +# Prepare release +npx @claude-flow/deployment release --version 2.0.0 --changelog --tag + +# Publish to npm +npx @claude-flow/deployment publish --tag latest --access public + +# Validate package +npx @claude-flow/deployment validate +``` + +## Dry Run Mode + +Test releases without making changes: + +```typescript +// Test release preparation +await prepareRelease({ + bumpType: 'minor', + dryRun: true +}); + +// Test npm publish +await publishToNpm({ + tag: 'beta', + dryRun: true +}); +``` + +## Channel/Tag Strategy + +- **`alpha`**: Early development versions (1.0.0-alpha.1) +- **`beta`**: Feature complete, testing (1.0.0-beta.1) +- **`rc`**: Release candidate (1.0.0-rc.1) +- **`latest`**: Stable production release (1.0.0) + +```typescript +// Prerelease workflow +await prepareRelease({ bumpType: 'prerelease', channel: 'alpha' }); // 1.0.0-alpha.1 +await publishToNpm({ tag: 'alpha' }); + +await prepareRelease({ bumpType: 'prerelease', channel: 'beta' }); // 1.0.0-beta.1 +await publishToNpm({ tag: 'beta' }); + +await prepareRelease({ bumpType: 'patch' }); // 1.0.0 +await publishToNpm({ tag: 'latest' }); +``` + +## Environment Variables + +```bash +# NPM authentication +export NPM_TOKEN="your-token" + +# Custom registry +export NPM_CONFIG_REGISTRY="https://registry.npmjs.org/" +``` + +## Error Handling + +```typescript +try { + const result = await prepareRelease({ bumpType: 'minor' }); + + if (!result.success) { + console.error('Release failed:', result.error); + console.warn('Warnings:', result.warnings); + } +} catch (error) { + console.error('Unexpected error:', error); +} +``` + +## License + +MIT diff --git a/v3/@claude-flow/deployment/src/release-manager.ts b/v3/@claude-flow/deployment/src/release-manager.ts index bfafac0e60..3d43519cec 100644 --- a/v3/@claude-flow/deployment/src/release-manager.ts +++ b/v3/@claude-flow/deployment/src/release-manager.ts @@ -131,7 +131,7 @@ export class ReleaseManager { let newMajor = parseInt(major); let newMinor = parseInt(minor); let newPatch = parseInt(patch); - let newPrerelease = prerelease; + let newPrerelease: string | undefined = prerelease; let newPrereleaseNum = prereleaseNum ? parseInt(prereleaseNum) : 0; switch (bumpType) {