import { test, describe, beforeEach, afterEach } from 'node:test';
import { strict as assert } from 'node:assert';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
// Simple MatrixFileSystem implementation for testing
class MatrixFileSystem {
constructor(basePath = process.cwd()) {
this.basePath = basePath;
this.matrixRoot = path.join(basePath, '.matrix_pattern');
this.matrixDir = path.join(this.matrixRoot, 'matrix');
this.metadataDir = path.join(this.matrixRoot, 'metadata');
this.horizontalsDir = path.join(this.metadataDir, 'horizontals');
this.syncReportsDir = path.join(this.metadataDir, 'sync-reports');
this.verticalsFile = path.join(this.metadataDir, 'verticals.json');
}
async initialize() {
try {
await fs.mkdir(this.matrixRoot, { recursive: true });
await fs.mkdir(this.matrixDir, { recursive: true });
await fs.mkdir(this.metadataDir, { recursive: true });
await fs.mkdir(this.horizontalsDir, { recursive: true });
await fs.mkdir(this.syncReportsDir, { recursive: true });
try {
await fs.access(this.verticalsFile);
} catch (error) {
if (error.code === 'ENOENT') {
await fs.writeFile(this.verticalsFile, JSON.stringify([], null, 2));
}
}
} catch (error) {
throw new Error(`Failed to initialize matrix structure: ${error.message}`);
}
}
async createCell(vertical, horizontal, content) {
if (await this.cellExists(vertical, horizontal)) {
throw new Error(`Cell ${vertical}:${horizontal} already exists. Matrix Pattern System enforces forward-only constraint.`);
}
const verticalDir = path.join(this.matrixDir, vertical);
const cellFile = path.join(verticalDir, `${horizontal}.md`);
try {
await fs.mkdir(verticalDir, { recursive: true });
await fs.writeFile(cellFile, content, 'utf8');
await this.registerVertical(vertical);
} catch (error) {
throw new Error(`Failed to create cell [${vertical}, ${horizontal}]: ${error.message}`);
}
}
async createEmptyCell(vertical, horizontal, reason = '') {
const verticalDir = path.join(this.matrixDir, vertical);
const emptyFile = path.join(verticalDir, `${horizontal}.empty`);
try {
await fs.mkdir(verticalDir, { recursive: true });
await fs.writeFile(emptyFile, reason, 'utf8');
await this.registerVertical(vertical);
} catch (error) {
throw new Error(`Failed to create empty cell [${vertical}, ${horizontal}]: ${error.message}`);
}
}
async readCell(vertical, horizontal) {
const verticalDir = path.join(this.matrixDir, vertical);
const cellFile = path.join(verticalDir, `${horizontal}.md`);
const emptyFile = path.join(verticalDir, `${horizontal}.empty`);
try {
try {
const content = await fs.readFile(cellFile, 'utf8');
return { content, isEmpty: false, reason: null };
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
try {
const reason = await fs.readFile(emptyFile, 'utf8');
return { content: null, isEmpty: true, reason };
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
return { content: null, isEmpty: false, reason: null };
} catch (error) {
throw new Error(`Failed to read cell [${vertical}, ${horizontal}]: ${error.message}`);
}
}
async cellExists(vertical, horizontal) {
const verticalDir = path.join(this.matrixDir, vertical);
const cellFile = path.join(verticalDir, `${horizontal}.md`);
const emptyFile = path.join(verticalDir, `${horizontal}.empty`);
try {
await fs.access(cellFile);
return true;
} catch (error) {
if (error.code !== 'ENOENT') {
throw new Error(`Failed to check cell existence: ${error.message}`);
}
}
try {
await fs.access(emptyFile);
return true;
} catch (error) {
if (error.code !== 'ENOENT') {
throw new Error(`Failed to check empty cell existence: ${error.message}`);
}
}
return false;
}
async listVerticals() {
try {
const content = await fs.readFile(this.verticalsFile, 'utf8');
return JSON.parse(content);
} catch (error) {
if (error.code === 'ENOENT') return [];
throw new Error(`Failed to read verticals list: ${error.message}`);
}
}
async listHorizontals() {
try {
const verticals = await this.listVerticals();
const horizontalsSet = new Set();
for (const vertical of verticals) {
const verticalDir = path.join(this.matrixDir, vertical);
try {
const files = await fs.readdir(verticalDir);
for (const file of files) {
if (file.endsWith('.md')) {
horizontalsSet.add(file.slice(0, -3));
} else if (file.endsWith('.empty')) {
horizontalsSet.add(file.slice(0, -6));
}
}
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
}
return Array.from(horizontalsSet).sort();
} catch (error) {
throw new Error(`Failed to list horizontals: ${error.message}`);
}
}
async registerVertical(vertical) {
try {
let verticals = [];
// Try to read existing verticals, create empty array if file doesn't exist or empty
try {
const content = await fs.readFile(this.verticalsFile, 'utf8');
const trimmedContent = content.trim();
if (trimmedContent) {
try {
verticals = JSON.parse(trimmedContent);
if (!Array.isArray(verticals)) {
verticals = [];
}
} catch (parseError) {
// Invalid JSON, start with empty array
verticals = [];
}
}
} catch (error) {
if (error.code === 'ENOENT') {
// File doesn't exist, start with empty array
verticals = [];
} else {
throw error;
}
}
if (!verticals.includes(vertical)) {
verticals.push(vertical);
verticals.sort();
await fs.writeFile(this.verticalsFile, JSON.stringify(verticals, null, 2));
}
} catch (error) {
throw new Error(`Failed to register vertical '${vertical}': ${error.message}`);
}
}
async getMatrixStats() {
try {
const verticals = await this.listVerticals();
const horizontals = await this.listHorizontals();
let totalCells = 0;
let filledCells = 0;
let emptyCells = 0;
for (const vertical of verticals) {
for (const horizontal of horizontals) {
if (await this.cellExists(vertical, horizontal)) {
totalCells++;
const cellData = await this.readCell(vertical, horizontal);
if (cellData.isEmpty) {
emptyCells++;
} else {
filledCells++;
}
}
}
}
return {
totalVerticals: verticals.length,
totalHorizontals: horizontals.length,
totalPossibleCells: verticals.length * horizontals.length,
totalExistingCells: totalCells,
filledCells,
emptyCells,
completionRate: verticals.length * horizontals.length > 0 ?
(totalCells / (verticals.length * horizontals.length) * 100).toFixed(2) + '%' : '0%'
};
} catch (error) {
throw new Error(`Failed to get matrix statistics: ${error.message}`);
}
}
}
// Simple SyncEngine implementation for testing
class SyncEngine {
constructor(matrixFileSystem) {
this.mfs = matrixFileSystem;
this.syncReportsDir = 'sync-reports';
this.horizontalReportsDir = path.join(this.syncReportsDir, 'horizontal');
this.verticalReportsDir = path.join(this.syncReportsDir, 'vertical');
}
async initialize() {
await fs.mkdir(this.horizontalReportsDir, { recursive: true });
await fs.mkdir(this.verticalReportsDir, { recursive: true });
}
async syncHorizontal(horizontal) {
await this.initialize();
const verticals = await this.mfs.listVerticals();
const report = {
horizontal,
timestamp: new Date().toISOString(),
summary: {
totalVerticals: verticals.length,
implementedVerticals: 0,
emptyVerticals: 0,
missingVerticals: 0
},
evolutionPattern: [],
verticalDetails: [],
consolidatedState: null
};
for (const vertical of verticals) {
const cellExists = await this.mfs.cellExists(vertical, horizontal);
let cellData = null;
let status = 'missing';
let content = '';
let preview = '';
if (cellExists) {
cellData = await this.mfs.readCell(vertical, horizontal);
content = cellData.content || '';
if (content.trim().length === 0 || cellData.isEmpty) {
status = 'empty';
report.summary.emptyVerticals++;
} else {
status = 'implemented';
report.summary.implementedVerticals++;
preview = content.substring(0, 200);
if (content.length > 200) preview += '...';
}
} else {
report.summary.missingVerticals++;
}
const verticalDetail = {
vertical,
status,
exists: cellExists,
contentLength: content.length,
preview,
lastModified: cellData?.metadata?.lastModified || null,
evolution: this.analyzeEvolution(content, vertical)
};
report.verticalDetails.push(verticalDetail);
}
report.evolutionPattern = this.generateEvolutionPattern(report.verticalDetails);
report.consolidatedState = this.extractConsolidatedState(report.verticalDetails);
const reportContent = this.generateHorizontalReportMarkdown(report);
const reportPath = path.join(this.horizontalReportsDir, `${horizontal}-sync.md`);
await fs.writeFile(reportPath, reportContent, 'utf8');
return {
success: true,
report,
reportPath,
summary: `Generated horizontal sync report for '${horizontal}' - ${report.summary.implementedVerticals} implemented, ${report.summary.emptyVerticals} empty, ${report.summary.missingVerticals} missing`
};
}
async syncVertical(vertical) {
await this.initialize();
const horizontals = await this.mfs.listHorizontals();
const report = {
vertical,
timestamp: new Date().toISOString(),
summary: {
totalHorizontals: horizontals.length,
implementedHorizontals: 0,
emptyHorizontals: 0,
missingHorizontals: 0,
completenessPercentage: 0
},
horizontalDetails: [],
completenessAssessment: null
};
for (const horizontal of horizontals) {
const cellExists = await this.mfs.cellExists(vertical, horizontal);
let cellData = null;
let status = 'missing';
let statusIcon = '❌';
let content = '';
let preview = '';
if (cellExists) {
cellData = await this.mfs.readCell(vertical, horizontal);
content = cellData.content || '';
if (content.trim().length === 0 || cellData.isEmpty) {
status = 'empty';
statusIcon = '⬜';
report.summary.emptyHorizontals++;
} else {
status = 'implemented';
statusIcon = '✅';
report.summary.implementedHorizontals++;
preview = content.substring(0, 200);
if (content.length > 200) preview += '...';
}
} else {
report.summary.missingHorizontals++;
}
const horizontalDetail = {
horizontal,
status,
statusIcon,
exists: cellExists,
contentLength: content.length,
preview,
lastModified: cellData?.metadata?.lastModified || null,
implementation: this.analyzeImplementation(content, horizontal)
};
report.horizontalDetails.push(horizontalDetail);
}
report.summary.completenessPercentage = Math.round(
(report.summary.implementedHorizontals / report.summary.totalHorizontals) * 100
);
report.completenessAssessment = this.generateCompletenessAssessment(report);
const reportContent = this.generateVerticalReportMarkdown(report);
const reportPath = path.join(this.verticalReportsDir, `${vertical}-sync.md`);
await fs.writeFile(reportPath, reportContent, 'utf8');
return {
success: true,
report,
reportPath,
summary: `Generated vertical sync report for '${vertical}' - ${report.summary.completenessPercentage}% complete (${report.summary.implementedHorizontals}/${report.summary.totalHorizontals} implemented)`
};
}
analyzeEvolution(content, vertical) {
if (!content || content.trim().length === 0) {
return { stage: 'none', complexity: 0, patterns: [] };
}
const patterns = [];
let complexity = 0;
if (content.includes('class ') || content.includes('function ')) {
patterns.push('code-implementation');
complexity += 3;
}
if (content.includes('TODO') || content.includes('FIXME')) {
patterns.push('work-in-progress');
complexity += 1;
}
if (content.split('\n').length > 50) {
patterns.push('detailed-implementation');
complexity += 2;
}
if (content.includes('test') || content.includes('spec')) {
patterns.push('testing');
complexity += 2;
}
let stage = 'basic';
if (complexity >= 6) stage = 'advanced';
else if (complexity >= 3) stage = 'intermediate';
return { stage, complexity, patterns };
}
generateEvolutionPattern(verticalDetails) {
const patterns = [];
const stages = verticalDetails.map(v => v.evolution?.stage || 'none');
const stageOrder = ['none', 'basic', 'intermediate', 'advanced'];
let progression = 'scattered';
const implementedStages = stages.filter(s => s !== 'none');
if (implementedStages.length > 0) {
const avgStageIndex = implementedStages.reduce((acc, stage) =>
acc + stageOrder.indexOf(stage), 0) / implementedStages.length;
if (avgStageIndex >= 2.5) progression = 'mature';
else if (avgStageIndex >= 1.5) progression = 'developing';
else progression = 'emerging';
}
patterns.push({
type: 'progression',
value: progression,
description: `Overall evolution stage: ${progression}`
});
const allPatterns = verticalDetails
.flatMap(v => v.evolution?.patterns || [])
.reduce((acc, pattern) => {
acc[pattern] = (acc[pattern] || 0) + 1;
return acc;
}, {});
Object.entries(allPatterns).forEach(([pattern, count]) => {
if (count > 1) {
patterns.push({
type: 'common-pattern',
value: pattern,
count,
description: `${pattern} appears in ${count} verticals`
});
}
});
return patterns;
}
extractConsolidatedState(verticalDetails) {
const implemented = verticalDetails.filter(v => v.status === 'implemented');
if (implemented.length === 0) {
return {
source: null,
content: null,
stage: 'none',
summary: 'No implementations found'
};
}
const mostAdvanced = implemented.reduce((best, current) => {
const currentComplexity = current.evolution?.complexity || 0;
const bestComplexity = best.evolution?.complexity || 0;
return currentComplexity > bestComplexity ? current : best;
});
return {
source: mostAdvanced.vertical,
content: mostAdvanced.preview,
stage: mostAdvanced.evolution?.stage || 'basic',
summary: `Most advanced implementation from ${mostAdvanced.vertical} vertical`
};
}
analyzeImplementation(content, horizontal) {
if (!content || content.trim().length === 0) {
return { quality: 0, completeness: 0, indicators: [] };
}
const indicators = [];
let quality = 0;
if (content.includes('/**') || content.includes('//')) {
indicators.push('documented');
quality += 20;
}
if (content.includes('test') || content.includes('spec')) {
indicators.push('tested');
quality += 25;
}
if (content.includes('class ') || content.includes('module.exports')) {
indicators.push('structured');
quality += 20;
}
if (content.includes('async') || content.includes('Promise')) {
indicators.push('async-ready');
quality += 15;
}
if (!content.includes('TODO') && !content.includes('FIXME')) {
indicators.push('production-ready');
quality += 20;
}
const lines = content.split('\n').filter(line => line.trim().length > 0);
const completeness = Math.min(100, (lines.length / 10) * 100);
return {
quality: Math.min(100, quality),
completeness: Math.min(100, completeness),
indicators
};
}
generateCompletenessAssessment(report) {
const { summary } = report;
let assessment = 'incomplete';
let recommendations = [];
if (summary.completenessPercentage >= 90) {
assessment = 'excellent';
recommendations.push('Consider code review and optimization');
} else if (summary.completenessPercentage >= 75) {
assessment = 'good';
recommendations.push('Focus on completing remaining implementations');
} else if (summary.completenessPercentage >= 50) {
assessment = 'moderate';
recommendations.push('Prioritize high-impact horizontals');
} else if (summary.completenessPercentage >= 25) {
assessment = 'poor';
recommendations.push('Systematic implementation approach needed');
} else {
assessment = 'critical';
recommendations.push('Immediate attention required');
}
return {
level: assessment,
percentage: summary.completenessPercentage,
recommendations
};
}
generateHorizontalReportMarkdown(report) {
const { horizontal, timestamp, summary, evolutionPattern, verticalDetails, consolidatedState } = report;
let markdown = `# Horizontal Sync Report: ${horizontal}
*Generated on: ${new Date(timestamp).toLocaleString()}*
## 📊 Summary
- **Total Verticals**: ${summary.totalVerticals}
- **Implemented**: ${summary.implementedVerticals} (${Math.round((summary.implementedVerticals/summary.totalVerticals)*100)}%)
- **Empty**: ${summary.emptyVerticals} (${Math.round((summary.emptyVerticals/summary.totalVerticals)*100)}%)
- **Missing**: ${summary.missingVerticals} (${Math.round((summary.missingVerticals/summary.totalVerticals)*100)}%)
## 🔄 Evolution Pattern Analysis
`;
evolutionPattern.forEach(pattern => {
markdown += `- **${pattern.type}**: ${pattern.description}\n`;
});
markdown += `
## 📋 Vertical Implementation Details
| Vertical | Status | Content Length | Evolution Stage | Last Modified |
|----------|--------|----------------|-----------------|---------------|
`;
verticalDetails.forEach(detail => {
const statusIcon = detail.status === 'implemented' ? '✅' :
detail.status === 'empty' ? '⬜' : '❌';
const stage = detail.evolution?.stage || 'none';
const modified = detail.lastModified ?
new Date(detail.lastModified).toLocaleDateString() : 'N/A';
markdown += `| ${detail.vertical} | ${statusIcon} ${detail.status} | ${detail.contentLength} chars | ${stage} | ${modified} |\n`;
});
if (consolidatedState && consolidatedState.content) {
markdown += `
## 🎯 Consolidated State
**Source**: ${consolidatedState.source}
**Stage**: ${consolidatedState.stage}
**Summary**: ${consolidatedState.summary}
`;
}
return markdown;
}
generateVerticalReportMarkdown(report) {
const { vertical, timestamp, summary, horizontalDetails, completenessAssessment } = report;
let markdown = `# Vertical Sync Report: ${vertical}
*Generated on: ${new Date(timestamp).toLocaleString()}*
## 📊 Summary
- **Total Horizontals**: ${summary.totalHorizontals}
- **Implemented**: ${summary.implementedHorizontals} ✅
- **Empty**: ${summary.emptyHorizontals} ⬜
- **Missing**: ${summary.missingHorizontals} ❌
- **Completeness**: ${summary.completenessPercentage}%
## 🎯 Completeness Assessment
**Level**: ${completenessAssessment.level.toUpperCase()}
### Recommendations:
`;
completenessAssessment.recommendations.forEach(rec => {
markdown += `- ${rec}\n`;
});
markdown += `
## 📋 Implementation Status
| Horizontal | Status | Content Length | Implementation Quality | Last Modified |
|------------|--------|----------------|------------------------|---------------|
`;
horizontalDetails.forEach(detail => {
const quality = detail.implementation?.quality || 0;
const qualityText = quality >= 80 ? 'High' : quality >= 60 ? 'Medium' : quality >= 40 ? 'Low' : 'Poor';
const modified = detail.lastModified ?
new Date(detail.lastModified).toLocaleDateString() : 'N/A';
markdown += `| ${detail.horizontal} | ${detail.statusIcon} ${detail.status} | ${detail.contentLength} chars | ${qualityText} (${quality}%) | ${modified} |\n`;
});
return markdown;
}
}
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
describe('Matrix Pattern System Integration Tests', () => {
let testDir;
let matrixFs;
let syncEngine;
let originalCwd;
beforeEach(async () => {
// Create temporary test directory
testDir = path.join(__dirname, '../../test-temp', uuidv4());
await fs.ensureDir(testDir);
// Save original working directory and change to test directory
originalCwd = process.cwd();
process.chdir(testDir);
// Initialize matrix file system and sync engine
matrixFs = new MatrixFileSystem(testDir);
await matrixFs.initialize();
syncEngine = new SyncEngine(matrixFs);
await syncEngine.initialize();
});
afterEach(async () => {
// Restore original working directory
process.chdir(originalCwd);
// Clean up test directory
try {
await fs.remove(testDir);
} catch (error) {
// Ignore cleanup errors
}
});
describe('End-to-End Workflow Tests', () => {
test('should complete full matrix creation and sync workflow', async () => {
// Setup test data
const verticals = ['authentication', 'database', 'api'];
const horizontals = ['specification', 'implementation', 'testing'];
// Phase 1: Create initial matrix structure
for (const vertical of verticals) {
for (const horizontal of horizontals) {
const content = `# ${horizontal.toUpperCase()} for ${vertical}\n\nContent for ${vertical}:${horizontal}`;
await matrixFs.createCell(vertical, horizontal, content);
}
}
// Verify matrix structure
const stats = await matrixFs.getMatrixStats();
assert.strictEqual(stats.totalVerticals, verticals.length, 'Should create all verticals');
assert.strictEqual(stats.totalHorizontals, horizontals.length, 'Should create all horizontals');
assert.strictEqual(stats.totalExistingCells, verticals.length * horizontals.length, 'Should create all cells');
assert.strictEqual(stats.filledCells, verticals.length * horizontals.length, 'All cells should be filled');
assert.strictEqual(stats.emptyCells, 0, 'No cells should be empty');
// Phase 2: Test horizontal sync reporting
for (const horizontal of horizontals) {
const syncResult = await syncEngine.syncHorizontal(horizontal);
assert.ok(syncResult.success, `Horizontal sync for ${horizontal} should succeed`);
assert.ok(syncResult.report, `Should generate report for ${horizontal}`);
assert.strictEqual(syncResult.report.summary.implementedVerticals, verticals.length, `All verticals should be implemented for ${horizontal}`);
// Verify report file creation
const reportExists = await fs.pathExists(syncResult.reportPath);
assert.ok(reportExists, `Report file should be created for ${horizontal}`);
}
// Phase 3: Test vertical sync reporting
for (const vertical of verticals) {
const syncResult = await syncEngine.syncVertical(vertical);
assert.ok(syncResult.success, `Vertical sync for ${vertical} should succeed`);
assert.ok(syncResult.report, `Should generate report for ${vertical}`);
assert.strictEqual(syncResult.report.summary.implementedHorizontals, horizontals.length, `All horizontals should be implemented for ${vertical}`);
assert.strictEqual(syncResult.report.summary.completenessPercentage, 100, `${vertical} should be 100% complete`);
// Verify report file creation
const reportExists = await fs.pathExists(syncResult.reportPath);
assert.ok(reportExists, `Report file should be created for ${vertical}`);
}
});
test('should handle mixed implementation states correctly', async () => {
const verticals = ['frontend', 'backend', 'mobile'];
const horizontals = ['design', 'development', 'deployment'];
// Create partial implementation
await matrixFs.createCell(verticals[0], horizontals[0], '# Frontend Design\nCompleted design mockups');
await matrixFs.createCell(verticals[0], horizontals[1], '# Frontend Development\nReact components implemented');
await matrixFs.createEmptyCell(verticals[0], horizontals[2], 'Deployment pending');
await matrixFs.createCell(verticals[1], horizontals[0], '# Backend Design\nAPI specification complete');
await matrixFs.createEmptyCell(verticals[1], horizontals[1], 'Development in progress');
await matrixFs.createEmptyCell(verticals[1], horizontals[2], 'Deployment pending');
// Leave mobile vertical completely empty
// Test horizontal sync for design (partially implemented)
const designSync = await syncEngine.syncHorizontal(horizontals[0]);
assert.ok(designSync.success, 'Design sync should succeed');
assert.strictEqual(designSync.report.summary.implementedVerticals, 2, 'Design should have 2 implementations');
assert.strictEqual(designSync.report.summary.missingVerticals, 1, 'Design should have 1 missing');
// Test vertical sync for frontend (partially complete)
const frontendSync = await syncEngine.syncVertical(verticals[0]);
assert.ok(frontendSync.success, 'Frontend sync should succeed');
assert.strictEqual(frontendSync.report.summary.implementedHorizontals, 2, 'Frontend should have 2 implementations');
assert.strictEqual(frontendSync.report.summary.emptyHorizontals, 1, 'Frontend should have 1 empty');
assert.ok(frontendSync.report.summary.completenessPercentage > 50, 'Frontend should be more than 50% complete');
// Test vertical sync for mobile (completely empty)
const mobileSync = await syncEngine.syncVertical(verticals[2]);
assert.ok(mobileSync.success, 'Mobile sync should succeed');
assert.strictEqual(mobileSync.report.summary.implementedHorizontals, 0, 'Mobile should have no implementations');
assert.strictEqual(mobileSync.report.summary.missingHorizontals, horizontals.length, 'Mobile should have all missing');
assert.strictEqual(mobileSync.report.summary.completenessPercentage, 0, 'Mobile should be 0% complete');
});
test('should generate accurate evolution patterns', async () => {
const vertical = 'user-management';
const horizontals = ['basic', 'intermediate', 'advanced'];
// Create cells with different complexity levels
await matrixFs.createCell(vertical, horizontals[0], 'Simple user registration');
await matrixFs.createCell(vertical, horizontals[1], `
# User Management - Intermediate
class UserService {
async createUser(userData) {
// Implementation with validation
return user;
}
}
TODO: Add email verification
`.trim());
await matrixFs.createCell(vertical, horizontals[2], `
# User Management - Advanced
/**
* Advanced user management system with full authentication
*/
class UserService {
constructor(database, emailService) {
this.db = database;
this.emailService = emailService;
}
async createUser(userData) {
// Complex implementation with async operations
const user = await this.db.users.create(userData);
await this.emailService.sendVerification(user.email);
return user;
}
async authenticate(credentials) {
// Authentication logic
}
}
// Comprehensive test suite
describe('UserService', () => {
test('should create user with verification', async () => {
// Test implementation
});
});
`.trim());
// Generate horizontal sync report
const syncResult = await syncEngine.syncHorizontal('advanced');
assert.ok(syncResult.success, 'Advanced sync should succeed');
const report = syncResult.report;
assert.ok(report.evolutionPattern, 'Should generate evolution pattern');
assert.ok(report.evolutionPattern.length > 0, 'Evolution pattern should have entries');
const progressionPattern = report.evolutionPattern.find(p => p.type === 'progression');
assert.ok(progressionPattern, 'Should identify progression pattern');
// Verify consolidated state extraction
assert.ok(report.consolidatedState, 'Should extract consolidated state');
assert.strictEqual(report.consolidatedState.source, vertical, 'Should identify correct source');
assert.ok(report.consolidatedState.content, 'Should extract content');
});
});
describe('Multiple Cell Creation and Sync', () => {
test('should handle bulk cell creation and cross-referencing', async () => {
const projectVerticals = ['web-app', 'mobile-app', 'api-service', 'database'];
const phaseHorizontals = ['planning', 'design', 'implementation', 'testing', 'deployment'];
// Simulate project development across multiple phases
const cellContents = {
planning: {
'web-app': 'React-based web application with responsive design',
'mobile-app': 'React Native app for iOS and Android',
'api-service': 'Node.js REST API with authentication',
'database': 'PostgreSQL with optimized schemas'
},
design: {
'web-app': 'UI mockups and component architecture',
'mobile-app': 'Mobile-first design patterns',
'api-service': 'API endpoint specifications and data models',
'database': 'Entity-relationship diagrams and indexing strategy'
},
implementation: {
'web-app': '# Web App Implementation\nclass App extends Component { ... }',
'mobile-app': '# Mobile App Implementation\nconst App = () => { ... }',
'api-service': '# API Service Implementation\nconst express = require("express");',
'database': '# Database Schema\nCREATE TABLE users (...);'
}
};
// Create cells in bulk
const creationPromises = [];
for (const [horizontal, verticalContents] of Object.entries(cellContents)) {
for (const [vertical, content] of Object.entries(verticalContents)) {
creationPromises.push(matrixFs.createCell(vertical, horizontal, content));
}
}
// Add some empty cells for incomplete phases
creationPromises.push(
matrixFs.createEmptyCell('web-app', 'testing', 'Testing framework setup pending'),
matrixFs.createEmptyCell('mobile-app', 'testing', 'Test cases not written yet'),
matrixFs.createEmptyCell('web-app', 'deployment', 'CI/CD pipeline configuration needed'),
matrixFs.createEmptyCell('mobile-app', 'deployment', 'App store submission pending')
);
await Promise.all(creationPromises);
// Verify bulk creation
const stats = await matrixFs.getMatrixStats();
assert.ok(stats.totalExistingCells >= 14, 'Should create multiple cells');
assert.ok(stats.filledCells >= 10, 'Should have multiple filled cells');
assert.ok(stats.emptyCells >= 4, 'Should have some empty cells');
// Test cross-vertical analysis for implementation phase
const implementationSync = await syncEngine.syncHorizontal('implementation');
assert.ok(implementationSync.success, 'Implementation sync should succeed');
const report = implementationSync.report;
assert.strictEqual(report.summary.implementedVerticals, 4, 'All verticals should have implementation');
assert.ok(report.evolutionPattern.length > 0, 'Should identify evolution patterns');
// Find code implementation pattern
const codePattern = report.evolutionPattern.find(p =>
p.type === 'common-pattern' && p.value === 'code-implementation'
);
assert.ok(codePattern, 'Should identify code implementation pattern');
assert.ok(codePattern.count >= 3, 'Code pattern should appear in multiple verticals');
});
test('should maintain consistency during concurrent sync operations', async () => {
const verticals = ['service1', 'service2', 'service3'];
const horizontals = ['config', 'logic', 'tests'];
// Create test matrix
for (const vertical of verticals) {
for (const horizontal of horizontals) {
const content = `# ${vertical} ${horizontal}\nImplementation content`;
await matrixFs.createCell(vertical, horizontal, content);
}
}
// Run concurrent sync operations
const horizontalSyncPromises = horizontals.map(h => syncEngine.syncHorizontal(h));
const verticalSyncPromises = verticals.map(v => syncEngine.syncVertical(v));
const [horizontalResults, verticalResults] = await Promise.all([
Promise.all(horizontalSyncPromises),
Promise.all(verticalSyncPromises)
]);
// Verify all sync operations succeeded
horizontalResults.forEach((result, index) => {
assert.ok(result.success, `Horizontal sync for ${horizontals[index]} should succeed`);
assert.ok(result.report, `Should generate horizontal report for ${horizontals[index]}`);
});
verticalResults.forEach((result, index) => {
assert.ok(result.success, `Vertical sync for ${verticals[index]} should succeed`);
assert.ok(result.report, `Should generate vertical report for ${verticals[index]}`);
});
// Verify report file consistency
const reportDirs = [
path.join(testDir, 'sync-reports/horizontal'),
path.join(testDir, 'sync-reports/vertical')
];
for (const reportDir of reportDirs) {
const exists = await fs.pathExists(reportDir);
if (exists) {
const files = await fs.readdir(reportDir);
files.forEach(file => {
assert.ok(file.endsWith('.md'), `Report file ${file} should be markdown`);
});
}
}
});
});
describe('Report Generation Verification', () => {
test('should generate comprehensive horizontal reports', async () => {
const vertical = 'report-test';
const horizontals = ['phase1', 'phase2'];
await matrixFs.createCell(vertical, horizontals[0], '# Phase 1\nBasic implementation');
await matrixFs.createCell(vertical, horizontals[1], `
# Phase 2
class AdvancedFeature {
constructor() {
this.initialized = true;
}
async process() {
// Complex async operation
return result;
}
}
// Test coverage
describe('AdvancedFeature', () => {
test('processes correctly', () => {
// Test implementation
});
});
`.trim());
const syncResult = await syncEngine.syncHorizontal(horizontals[1]);
assert.ok(syncResult.success, 'Sync should succeed');
// Verify report structure
const report = syncResult.report;
assert.ok(report.horizontal, 'Report should have horizontal identifier');
assert.ok(report.timestamp, 'Report should have timestamp');
assert.ok(report.summary, 'Report should have summary');
assert.ok(report.verticalDetails, 'Report should have vertical details');
assert.ok(report.evolutionPattern, 'Report should have evolution pattern');
assert.ok(report.consolidatedState, 'Report should have consolidated state');
// Verify evolution analysis
const verticalDetail = report.verticalDetails.find(v => v.vertical === vertical);
assert.ok(verticalDetail, 'Should include vertical detail');
assert.ok(verticalDetail.evolution, 'Should analyze evolution');
assert.ok(verticalDetail.evolution.patterns.includes('code-implementation'), 'Should detect code patterns');
assert.ok(verticalDetail.evolution.patterns.includes('testing'), 'Should detect testing patterns');
// Verify report file content
const reportContent = await fs.readFile(syncResult.reportPath, 'utf8');
assert.ok(reportContent.includes('# Horizontal Sync Report'), 'Report should have proper header');
assert.ok(reportContent.includes('## 📊 Summary'), 'Report should have summary section');
assert.ok(reportContent.includes('## 🔄 Evolution Pattern Analysis'), 'Report should have evolution section');
assert.ok(reportContent.includes('## 📋 Vertical Implementation Details'), 'Report should have details table');
});
test('should generate comprehensive vertical reports', async () => {
const vertical = 'comprehensive-vertical';
const horizontals = ['basic', 'advanced', 'expert'];
await matrixFs.createCell(vertical, horizontals[0], 'Simple implementation');
await matrixFs.createCell(vertical, horizontals[1], `
/**
* Advanced implementation with documentation
*/
async function advancedFunction() {
// Complex logic with async operations
return await processData();
}
`.trim());
await matrixFs.createEmptyCell(vertical, horizontals[2], 'Not yet implemented');
const syncResult = await syncEngine.syncVertical(vertical);
assert.ok(syncResult.success, 'Vertical sync should succeed');
const report = syncResult.report;
assert.ok(report.vertical, 'Report should have vertical identifier');
assert.ok(report.completenessAssessment, 'Report should have completeness assessment');
// Verify completeness calculation
const expectedPercentage = Math.round((2 / 3) * 100); // 2 out of 3 implemented
assert.strictEqual(report.summary.completenessPercentage, expectedPercentage, 'Should calculate correct completion percentage');
// Verify assessment
assert.ok(['moderate', 'good'].includes(report.completenessAssessment.level), 'Should assess completion level appropriately');
assert.ok(report.completenessAssessment.recommendations.length > 0, 'Should provide recommendations');
// Verify horizontal details
const implementedDetails = report.horizontalDetails.filter(h => h.status === 'implemented');
const emptyDetails = report.horizontalDetails.filter(h => h.status === 'empty');
assert.strictEqual(implementedDetails.length, 2, 'Should identify implemented horizontals');
assert.strictEqual(emptyDetails.length, 1, 'Should identify empty horizontals');
// Verify implementation analysis
const advancedDetail = report.horizontalDetails.find(h => h.horizontal === horizontals[1]);
assert.ok(advancedDetail.implementation, 'Should analyze implementation');
assert.ok(advancedDetail.implementation.quality > 0, 'Should calculate quality score');
assert.ok(advancedDetail.implementation.indicators.includes('documented'), 'Should detect documentation');
assert.ok(advancedDetail.implementation.indicators.includes('async-ready'), 'Should detect async patterns');
// Verify report file content
const reportContent = await fs.readFile(syncResult.reportPath, 'utf8');
assert.ok(reportContent.includes('# Vertical Sync Report'), 'Report should have proper header');
assert.ok(reportContent.includes('## 🎯 Completeness Assessment'), 'Report should have assessment section');
assert.ok(reportContent.includes('## 📋 Implementation Status'), 'Report should have status table');
assert.ok(reportContent.includes('**Quality**'), 'Report should include quality indicators');
});
});
describe('Error Handling Scenarios', () => {
test('should handle sync operations on empty matrix', async () => {
// Attempt sync operations on empty matrix
const horizontalResult = await syncEngine.syncHorizontal('nonexistent-horizontal');
const verticalResult = await syncEngine.syncVertical('nonexistent-vertical');
assert.ok(horizontalResult.success, 'Horizontal sync should succeed even with no data');
assert.strictEqual(horizontalResult.report.summary.implementedVerticals, 0, 'Should report zero implementations');
assert.ok(verticalResult.success, 'Vertical sync should succeed even with no data');
assert.strictEqual(verticalResult.report.summary.implementedHorizontals, 0, 'Should report zero implementations');
});
test('should handle corrupted cell files gracefully', async () => {
const vertical = 'corruption-test';
const horizontal = 'test-cell';
// Create a normal cell first
await matrixFs.createCell(vertical, horizontal, 'Normal content');
// Manually corrupt the cell file
const cellPath = path.join(testDir, '.matrix_pattern/matrix', vertical, `${horizontal}.md`);
await fs.writeFile(cellPath, '\x00\x01\x02Invalid binary content\x03\x04', 'binary');
// Sync operations should handle corruption gracefully
const result = await syncEngine.syncHorizontal(horizontal);
assert.ok(result.success, 'Sync should succeed despite corruption');
// The corrupted cell should be handled appropriately
const verticalDetail = result.report.verticalDetails.find(v => v.vertical === vertical);
assert.ok(verticalDetail, 'Should include corrupted vertical in report');
});
test('should handle file system permission errors', async () => {
// This test is platform-dependent and may not work in all environments
// It's included for completeness but may need to be skipped on some systems
const vertical = 'permission-test';
const horizontal = 'test-cell';
try {
await matrixFs.createCell(vertical, horizontal, 'Test content');
// Try to make directory read-only (may not work on all systems)
const verticalDir = path.join(testDir, '.matrix_pattern/matrix', vertical);
try {
await fs.chmod(verticalDir, 0o444); // Read-only
} catch (chmodError) {
// Skip this test if chmod fails (common in some environments)
return;
}
// Sync should handle permission errors gracefully
const result = await syncEngine.syncHorizontal(horizontal);
assert.ok(result.success, 'Should handle permission errors gracefully');
// Restore permissions for cleanup
await fs.chmod(verticalDir, 0o755);
} catch (error) {
// Skip test if file system operations fail
return;
}
});
test('should validate input parameters', async () => {
// Test with invalid parameters
try {
await syncEngine.syncHorizontal('');
assert.fail('Should reject empty horizontal name');
} catch (error) {
assert.ok(error.message, 'Should provide error message for empty horizontal');
}
try {
await syncEngine.syncVertical('');
assert.fail('Should reject empty vertical name');
} catch (error) {
assert.ok(error.message, 'Should provide error message for empty vertical');
}
// Test with null/undefined parameters
try {
await syncEngine.syncHorizontal(null);
assert.fail('Should reject null horizontal');
} catch (error) {
assert.ok(error.message, 'Should handle null parameters');
}
});
});
describe('Directory Structure Validation', () => {
test('should maintain proper directory structure after operations', async () => {
const verticals = ['struct-test-1', 'struct-test-2'];
const horizontals = ['phase-a', 'phase-b'];
// Create cells and perform sync operations
for (const vertical of verticals) {
for (const horizontal of horizontals) {
await matrixFs.createCell(vertical, horizontal, `Content for ${vertical}:${horizontal}`);
}
}
// Perform sync operations
await Promise.all([
...horizontals.map(h => syncEngine.syncHorizontal(h)),
...verticals.map(v => syncEngine.syncVertical(v))
]);
// Verify directory structure integrity
const expectedPaths = [
'.matrix_pattern',
'.matrix_pattern/matrix',
'.matrix_pattern/metadata',
'.matrix_pattern/metadata/verticals.json',
'sync-reports',
'sync-reports/horizontal',
'sync-reports/vertical'
];
for (const expectedPath of expectedPaths) {
const fullPath = path.join(testDir, expectedPath);
const exists = await fs.pathExists(fullPath);
assert.ok(exists, `Path ${expectedPath} should exist`);
}
// Verify vertical directories exist
for (const vertical of verticals) {
const verticalPath = path.join(testDir, '.matrix_pattern/matrix', vertical);
const exists = await fs.pathExists(verticalPath);
assert.ok(exists, `Vertical directory ${vertical} should exist`);
const stat = await fs.stat(verticalPath);
assert.ok(stat.isDirectory(), `${vertical} should be a directory`);
}
// Verify cell files exist
for (const vertical of verticals) {
for (const horizontal of horizontals) {
const cellPath = path.join(testDir, '.matrix_pattern/matrix', vertical, `${horizontal}.md`);
const exists = await fs.pathExists(cellPath);
assert.ok(exists, `Cell file ${vertical}:${horizontal} should exist`);
}
}
});
test('should create report directories automatically', async () => {
// Remove report directories if they exist
const horizontalReportDir = path.join(testDir, 'sync-reports/horizontal');
const verticalReportDir = path.join(testDir, 'sync-reports/vertical');
await fs.remove(horizontalReportDir);
await fs.remove(verticalReportDir);
// Perform sync operation which should recreate directories
await matrixFs.createCell('auto-test', 'test-horizontal', 'Test content');
const result = await syncEngine.syncHorizontal('test-horizontal');
assert.ok(result.success, 'Sync should succeed');
// Verify directories were recreated
const horizontalExists = await fs.pathExists(horizontalReportDir);
assert.ok(horizontalExists, 'Horizontal report directory should be created automatically');
});
});
});