/**
* Matrix Pattern Init Command
* Initialize a new matrix pattern system
*/
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Default configuration template
*/
const DEFAULT_CONFIG = {
matrix_pattern: {
version: '1.0.0',
initialized: true,
created: new Date().toISOString(),
id: null, // Will be generated
config: {
max_patterns: 1000,
auto_cleanup: true,
sync: {
horizontal: {
enabled: true,
conflict_resolution: 'merge',
auto_sync: false
},
vertical: {
enabled: true,
conflict_resolution: 'latest',
auto_sync: false
}
},
validation: {
strict_mode: true,
forward_only: true,
allow_overwrites: false
}
},
directories: {
matrix: '.matrix_pattern/matrix',
metadata: '.matrix_pattern/metadata',
horizontals: '.matrix_pattern/metadata/horizontals',
sync_reports: '.matrix_pattern/metadata/sync-reports'
},
horizontals: {
// Default horizontal patterns
api: {
description: 'API layer patterns',
sync_strategy: 'merge',
priority: 1
},
ui: {
description: 'User interface patterns',
sync_strategy: 'replace',
priority: 2
},
data: {
description: 'Data layer patterns',
sync_strategy: 'merge',
priority: 3
}
},
mcp: {
enabled: true,
server_config: {
name: 'matrix-pattern-mcp-server',
version: '1.0.0',
description: 'Advanced pattern management and synchronization server'
}
}
}
};
/**
* Parse horizontal patterns from string
*/
function parseHorizontals(horizontalsString) {
if (!horizontalsString) return DEFAULT_CONFIG.matrix_pattern.horizontals;
const patterns = horizontalsString.split(',').map(p => p.trim());
const horizontals = {};
patterns.forEach((pattern, index) => {
horizontals[pattern] = {
description: `${pattern.charAt(0).toUpperCase() + pattern.slice(1)} layer patterns`,
sync_strategy: 'merge',
priority: index + 1
};
});
return horizontals;
}
/**
* Create directory structure
*/
async function createDirectoryStructure(basePath, config) {
const dirs = Object.values(config.matrix_pattern.directories);
for (const dir of dirs) {
const fullPath = path.join(basePath, dir);
await fs.ensureDir(fullPath);
console.log(`✓ Created directory: ${dir}`);
}
// Create additional metadata directories
await fs.ensureDir(path.join(basePath, '.matrix_pattern/logs'));
await fs.ensureDir(path.join(basePath, '.matrix_pattern/backups'));
console.log('✓ Created additional directories: logs, backups');
}
/**
* Create horizontal metadata files
*/
async function createHorizontalMetadata(basePath, config) {
const horizontalsDir = path.join(basePath, config.matrix_pattern.directories.horizontals);
for (const [name, settings] of Object.entries(config.matrix_pattern.horizontals)) {
const metadataFile = path.join(horizontalsDir, `${name}.json`);
const metadata = {
name,
...settings,
created: new Date().toISOString(),
last_sync: null,
cells_count: 0
};
await fs.writeJson(metadataFile, metadata, { spaces: 2 });
console.log(`✓ Created horizontal metadata: ${name}`);
}
}
/**
* Create CLAUDE_INSTRUCTIONS.md file
*/
async function createClaudeInstructions(basePath, config) {
const templatePath = path.join(__dirname, '..', '..', 'templates', 'CLAUDE_INSTRUCTIONS.md');
let content;
try {
content = await fs.readFile(templatePath, 'utf8');
} catch (error) {
// Use default if template not found
content = getDefaultClaudeInstructions();
}
// Generate horizontal-specific sections
const horizontals = Object.keys(config.matrix_pattern.horizontals);
const horizontalSections = generateClaudeHorizontalSections(horizontals);
// Replace placeholders
content = content
.replace('{{HORIZONTALS_SECTION}}', horizontalSections)
.replace('{{INIT_DATE}}', new Date().toISOString())
.replace('{{SELECTED_HORIZONTALS}}', horizontals.join(', '));
// Write to project root (not .matrix_pattern directory)
await fs.writeFile(path.join(basePath, 'CLAUDE_INSTRUCTIONS.md'), content);
console.log('✓ Created CLAUDE_INSTRUCTIONS.md');
}
function generateClaudeHorizontalSections(horizontals) {
const sections = [];
const horizontalGuides = {
api: `### API Horizontal
- Document ALL endpoint changes (internal and external)
- Include request/response schemas
- Note authentication requirements
- Mark empty only if ZERO API changes`,
schema: `### Schema Horizontal
- Document ALL data structure changes
- Include database migrations
- Note type definitions and validation
- Mark empty only if ZERO data changes`,
tests: `### Tests Horizontal
- List test scenarios (implementation optional)
- Include unit, integration, E2E test plans
- Note coverage requirements
- NEVER mark empty - always describe tests`,
specs: `### Specs Horizontal
- ALWAYS fill first - sets intention
- Include problem statement and solution
- Note acceptance criteria
- NEVER mark empty - core of every vertical`,
frontend: `### Frontend Horizontal
- Document UI component changes
- Include state management updates
- Note user interactions
- Mark empty for backend-only work`,
backend: `### Backend Horizontal
- Document service layer changes
- Include business logic updates
- Note infrastructure changes
- Mark empty for frontend-only work`,
ui: `### UI Horizontal
- Document user interface changes
- Include component structure
- Note styling and themes
- Mark empty for backend-only work`,
data: `### Data Horizontal
- Document data models and storage
- Include database schemas
- Note data flow and transformations
- Mark empty if no data changes`
};
for (const horizontal of horizontals) {
if (horizontalGuides[horizontal]) {
sections.push(horizontalGuides[horizontal]);
}
}
if (sections.length === 0) {
sections.push('### Custom Horizontals\nDocument according to your horizontal instructions.');
}
return sections.join('\n\n');
}
function getDefaultClaudeInstructions() {
return `# Matrix Pattern System - Claude Instructions
## Core Principle: "Every Change Has a Specification"
The Matrix Pattern System ensures all development work is properly specified before implementation.
### Quick Start
1. **Before coding**: Create a vertical with specs
2. **During coding**: Implement freely
3. **After coding**: Update build logs
### Essential Commands
- \`matrix_create_cell --vertical "<name>" --horizontal "<type>" --content "<markdown>"\`
- \`matrix_list_verticals\` - See all work
- \`matrix_sync_vertical --vertical "<name>"\` - Check completeness
### Your Horizontals
{{SELECTED_HORIZONTALS}}
### Remember
- Specify in the matrix, implement in code
- Use matrix for ALL work (features, bugs, refactoring)
- Keep specs minimal but clear
- You have full freedom to implement
*Initialized: {{INIT_DATE}}*
`;
}
/**
* Create README file
*/
async function createReadme(basePath) {
const readmeContent = `# Matrix Pattern System
This directory contains a Matrix Pattern System initialization.
## Structure
- \`.matrix_pattern/matrix/\` - Matrix cell data storage
- \`.matrix_pattern/metadata/\` - System metadata
- \`.matrix_pattern/metadata/horizontals/\` - Horizontal pattern configurations
- \`.matrix_pattern/metadata/sync-reports/\` - Synchronization reports
- \`.matrix_pattern/logs/\` - System logs
- \`.matrix_pattern/backups/\` - System backups
## Usage
The Matrix Pattern System provides tools for managing pattern synchronization across horizontal and vertical dimensions.
### MCP Server
Start the MCP server:
\`\`\`bash
matrix-pattern start
\`\`\`
### Basic Operations
- Create cells: Use the \`matrix_create_cell\` tool
- Read cells: Use the \`matrix_read_cell\` tool
- Sync horizontally: Use the \`matrix_sync_horizontal\` tool
- Sync vertically: Use the \`matrix_sync_vertical\` tool
## Configuration
Configuration is stored in \`.matrix_pattern/config.json\`. Modify this file to adjust system behavior.
For more information, see: https://github.com/matrix-pattern/mcp-server
`;
await fs.writeFile(path.join(basePath, '.matrix_pattern/README.md'), readmeContent);
console.log('✓ Created README.md');
}
/**
* Create .gitignore file
*/
async function createGitignore(basePath) {
const gitignoreContent = `# Matrix Pattern System files
.matrix_pattern/logs/
.matrix_pattern/backups/
.matrix_pattern/temp/
# Keep structure but ignore data
.matrix_pattern/matrix/*
!.matrix_pattern/matrix/.gitkeep
# Keep sync reports
!.matrix_pattern/metadata/sync-reports/
# Development files
*.log
*.tmp
.DS_Store
`;
await fs.writeFile(path.join(basePath, '.matrix_pattern/.gitignore'), gitignoreContent);
// Create .gitkeep file
await fs.writeFile(path.join(basePath, '.matrix_pattern/matrix/.gitkeep'), '');
console.log('✓ Created .gitignore and .gitkeep files');
}
/**
* Execute init command
*/
async function execute({ args, flags, cwd }) {
try {
console.log('🚀 Initializing Matrix Pattern System...\n');
// Check if already initialized
const configPath = path.join(cwd, '.matrix_pattern', 'config.json');
const alreadyExists = await fs.pathExists(configPath);
if (alreadyExists && !flags.force) {
console.error('❌ Matrix Pattern System already initialized in this directory.');
console.error(' Use --force to reinitialize.');
process.exit(1);
}
// Create configuration
const config = { ...DEFAULT_CONFIG };
config.matrix_pattern.id = uuidv4();
// Handle custom horizontals
if (flags.horizontals) {
config.matrix_pattern.horizontals = parseHorizontals(flags.horizontals);
console.log(`✓ Custom horizontals: ${flags.horizontals}`);
}
// Handle no-mcp flag
if (flags['no-mcp']) {
config.matrix_pattern.mcp.enabled = false;
console.log('✓ MCP server integration disabled');
}
// Create directory structure
await createDirectoryStructure(cwd, config);
// Write configuration
await fs.writeJson(configPath, config, { spaces: 2 });
console.log('✓ Created configuration file');
// Create horizontal metadata
await createHorizontalMetadata(cwd, config);
// Create documentation
if (!flags['no-docs']) {
await createReadme(cwd);
await createClaudeInstructions(cwd, config);
await createGitignore(cwd);
}
console.log('\n🎉 Matrix Pattern System initialized successfully!');
console.log('\nNext steps:');
console.log(' 1. Start the MCP server: matrix-pattern start');
console.log(' 2. Create your first cell using the MCP tools');
console.log(' 3. Set up horizontal patterns in .matrix_pattern/metadata/horizontals/');
if (config.matrix_pattern.mcp.enabled) {
console.log('\n📖 MCP Server Configuration:');
console.log(` Name: ${config.matrix_pattern.mcp.server_config.name}`);
console.log(` Version: ${config.matrix_pattern.mcp.server_config.version}`);
}
} catch (error) {
console.error('❌ Initialization failed:', error.message);
if (process.env.NODE_ENV === 'development') {
console.error(error.stack);
}
process.exit(1);
}
}
export default { execute };