sead-method-core
Version:
Specification Enforced Agentic Agile Development - A hybrid methodology preventing AI agent drift through catalog-based constraints with comprehensive external asset integration
1,326 lines (1,118 loc) • 89.7 kB
JavaScript
#!/usr/bin/env node
/**
* SEAD-METHOD CLI
* Specification Enforced Agentic Agile Development
*
* Unified command-line interface for the SEAD methodology
* Replaces and enhances BMAD-METHOD and Spec-Kit functionality
*/
const { Command } = require('commander');
const chalk = require('chalk');
const fs = require('fs-extra');
const path = require('path');
const program = new Command();
// SEAD-METHOD ASCII Art
const SEAD_BANNER = `
${chalk.cyan('╔═══════════════════════════════════════════════════════════════╗')}
${chalk.cyan('║')} ${chalk.bold.white('SEAD-METHOD™')} ${chalk.cyan('║')}
${chalk.cyan('║')} ${chalk.white('Specification Enforced Agentic Agile Development')} ${chalk.cyan('║')}
${chalk.cyan('║')} ${chalk.cyan('║')}
${chalk.cyan('║')} ${chalk.green('🧪 PROTOTYPE')} → ${chalk.yellow('⚙️ DEVELOPMENT')} → ${chalk.red('🏭 BUILD-TO-DEPLOY')} ${chalk.cyan('║')}
${chalk.cyan('╚═══════════════════════════════════════════════════════════════╝')}
`;
// Security utility for path traversal protection
function sanitizeFilename(input) {
if (!input) return 'default';
return input
.toString()
.toLowerCase()
.replace(/[^a-z0-9-_]/g, '-') // Only allow safe characters
.replace(/-+/g, '-') // Collapse multiple dashes
.replace(/^-+|-+$/g, '') // Trim leading/trailing dashes
.substring(0, 50); // Limit length
}
// Version and program info
program
.name('sead-method')
.alias('sead')
.description('SEAD-METHOD CLI - Specification Enforced Agentic Agile Development')
.version('1.0.0')
.option('-v, --verbose', 'enable verbose logging')
.option('--no-banner', 'disable SEAD banner display');
// Show banner unless disabled
program.hook('preAction', (thisCommand, actionCommand) => {
if (thisCommand.opts().banner !== false) {
console.log(SEAD_BANNER);
}
});
/**
* CORE WORKFLOW COMMANDS
* These replace and enhance BMAD/Spec-Kit commands
*/
// Initialize new SEAD project
program
.command('init')
.alias('i')
.description('Initialize a new SEAD-METHOD project')
.argument('[project-name]', 'name of the project to initialize')
.option('-m, --mode <mode>', 'initial development mode', 'prototype')
.option('-t, --template <template>', 'project template to use', 'default')
.action(async (projectName, options) => {
console.log(chalk.green('🚀 Initializing SEAD-METHOD project...'));
try {
const projectPath = projectName ? path.resolve(projectName) : process.cwd();
const projectBaseName = projectName || path.basename(process.cwd());
console.log(`📁 Project: ${chalk.bold(projectBaseName)}`);
console.log(`📍 Location: ${projectPath}`);
console.log(`🎭 Mode: ${chalk.yellow(options.mode)}`);
// Create SEAD project structure
await initializeSeadProject(projectPath, projectBaseName, options);
console.log(chalk.green('✅ SEAD-METHOD project initialized successfully!'));
console.log('\n' + chalk.blue('Next steps:'));
console.log(chalk.white(' 1. sead specify "your feature description"'));
console.log(chalk.white(' 2. sead plan [tech-stack]'));
console.log(chalk.white(' 3. sead stories --enforce-catalog'));
console.log(chalk.white(' 4. sead implement [story-id]'));
} catch (error) {
console.error(chalk.red('❌ Failed to initialize project:'), error.message);
process.exit(1);
}
});
// Install command - BMAD-style interactive installer
program
.command('install')
.description('Install SEAD Method with interactive setup')
.argument('[directory]', 'installation directory (default: current directory)')
.option('--full', 'install complete SEAD system')
.option('--ide <ide>', 'target IDE (claude-code, cursor, vs-code, etc.)')
.option('--agent <agent>', 'install specific agent only')
.option('--team <team>', 'install specific team configuration')
.option('--constitutional', 'install with constitutional framework focus')
.action(async (directory, options) => {
try {
const installer = require('./tools/installer/lib/installer');
// Build config from options
const config = {
directory: directory || process.cwd(),
installType: options.agent ? 'single-agent' :
options.team ? 'team' :
options.constitutional ? 'constitutional' : 'full',
agent: options.agent,
team: options.team,
ide: options.ide,
ides: options.ide ? [options.ide] : ['claude-code'], // Default to Claude Code
constitutional: options.constitutional
};
await installer.install(config);
} catch (error) {
console.error(chalk.red('❌ Installation failed:'), error.message);
if (options.verbose) {
console.error(error.stack);
}
process.exit(1);
}
});
// Status command - show installation status
program
.command('status')
.description('Show SEAD installation status')
.action(async () => {
try {
const installer = require('./tools/installer/lib/installer');
await installer.showStatus();
} catch (error) {
console.error(chalk.red('❌ Failed to show status:'), error.message);
process.exit(1);
}
});
// List agents command
program
.command('list-agents')
.alias('agents')
.description('List all available SEAD agents')
.action(async () => {
try {
const installer = require('./tools/installer/lib/installer');
await installer.listAgents();
} catch (error) {
console.error(chalk.red('❌ Failed to list agents:'), error.message);
process.exit(1);
}
});
// Update command - update existing installation
program
.command('update')
.description('Update existing SEAD installation')
.option('--force', 'force update even if no changes detected')
.action(async (options) => {
try {
const installer = require('./tools/installer/lib/installer');
const config = {
installType: 'update',
force: options.force
};
await installer.install(config);
} catch (error) {
console.error(chalk.red('❌ Update failed:'), error.message);
process.exit(1);
}
});
// Uninstall command - removes global .sead-method workspace
program
.command('uninstall')
.description('Uninstall SEAD-METHOD global workspace')
.option('--confirm', 'confirm removal without prompt')
.action(async (options) => {
console.log(chalk.yellow('🗑️ Uninstalling SEAD-METHOD global workspace...'));
try {
const os = require('os');
const homeDir = os.homedir();
const globalSeadDir = path.join(homeDir, '.sead-method');
if (!(await fs.pathExists(globalSeadDir))) {
console.log(chalk.yellow('⚠️ ~/.sead-method does not exist'));
return;
}
if (!options.confirm) {
const inquirer = require('inquirer');
const { confirmed } = await inquirer.prompt([{
type: 'confirm',
name: 'confirmed',
message: 'Remove ~/.sead-method workspace? This will not affect your projects.',
default: false
}]);
if (!confirmed) {
console.log(chalk.blue('Uninstall cancelled'));
return;
}
}
await fs.remove(globalSeadDir);
console.log(chalk.green('✅ SEAD-METHOD global workspace removed'));
console.log(chalk.white('Your projects are unaffected. Run "sead install" to reinstall.'));
} catch (error) {
console.error(chalk.red('❌ Uninstall failed:'), error.message);
process.exit(1);
}
});
// Specify command (from Spec-Kit enhanced)
program
.command('specify')
.alias('spec')
.description('Create constitutional specification for a feature')
.argument('<description>', 'feature description')
.option('-m, --mode <mode>', 'development mode', 'development')
.option('-d, --data-tier <tier>', 'data tier to use', 'mock')
.option('-p, --deploy-tier <tier>', 'deployment tier', 'cloud-staging')
.option('-t, --type <type>', 'specification type', 'frontend')
.option('-i, --interactive', 'enable interactive mode', false)
.action(async (description, options) => {
console.log(chalk.blue('📋 Creating SEAD specification...'));
console.log(`Feature: ${chalk.bold(description)}`);
console.log(`Mode: ${getModeEmoji(options.mode)} ${options.mode}`);
console.log(`Type: ${options.type}`);
console.log(`Data Tier: ${options.dataTier}`);
console.log(`Deploy Tier: ${options.deployTier}`);
try {
await createSeadSpecification(description, options);
} catch (error) {
console.error(chalk.red('❌ Specification creation failed:'), error.message);
process.exit(1);
}
});
// Plan command (from BMAD enhanced)
program
.command('plan')
.alias('p')
.description('Create agentic implementation plan')
.argument('<tech-stack>', 'technology stack to use')
.option('-m, --catalog-mode <mode>', 'catalog enforcement mode', 'development')
.option('-d, --data-tier <tier>', 'data tier', 'mock')
.option('-p, --deploy-tier <tier>', 'deployment tier', 'cloud-staging')
.option('-a, --architecture <type>', 'architecture type', 'fullstack')
.option('-i, --interactive', 'enable interactive planning', false)
.action(async (techStack, options) => {
console.log(chalk.blue('🏗️ Creating SEAD implementation plan...'));
console.log(`Tech Stack: ${chalk.bold(techStack)}`);
console.log(`Catalog Mode: ${getModeEmoji(options.catalogMode)} ${options.catalogMode}`);
console.log(`Architecture: ${options.architecture}`);
console.log(`Data Tier: ${options.dataTier}`);
console.log(`Deploy Tier: ${options.deployTier}`);
try {
await createSeadPlan(techStack, options);
} catch (error) {
console.error(chalk.red('❌ Plan creation failed:'), error.message);
process.exit(1);
}
});
// Stories command
program
.command('stories')
.alias('s')
.description('Create constraint-aware user stories')
.option('--enforce-catalog', 'enforce catalog constraints', false)
.option('--context-preserve', 'enable context preservation', false)
.option('-d, --data-tier <tier>', 'data tier', 'mock')
.option('-m, --mode <mode>', 'story development mode', 'development')
.option('-i, --interactive', 'enable interactive story creation', false)
.action(async (options) => {
console.log(chalk.blue('📝 Creating SEAD stories...'));
console.log(`Catalog Enforcement: ${options.enforceCatalog ? '✅' : '❌'}`);
console.log(`Context Preservation: ${options.contextPreserve ? '✅' : '❌'}`);
console.log(`Mode: ${getModeEmoji(options.mode)} ${options.mode}`);
console.log(`Data Tier: ${options.dataTier}`);
try {
await createSeadStories(options);
} catch (error) {
console.error(chalk.red('❌ Story creation failed:'), error.message);
process.exit(1);
}
});
// Implement command
program
.command('implement')
.alias('impl')
.description('Implement story with catalog constraints')
.argument('<story-id>', 'story ID to implement')
.option('-m, --mode <mode>', 'development mode', 'development')
.option('--validate-compliance', 'validate catalog compliance', false)
.option('-i, --interactive', 'enable interactive implementation', false)
.option('--qa-gate', 'enable QA validation gate', false)
.action(async (storyId, options) => {
console.log(chalk.blue('⚡ Implementing with SEAD constraints...'));
console.log(`Story: ${chalk.bold(storyId)}`);
console.log(`Mode: ${getModeEmoji(options.mode)} ${options.mode}`);
console.log(`Compliance Validation: ${options.validateCompliance ? '✅' : '❌'}`);
console.log(`QA Gate: ${options.qaGate ? '✅' : '❌'}`);
try {
await implementSeadStory(storyId, options);
} catch (error) {
console.error(chalk.red('❌ Implementation failed:'), error.message);
process.exit(1);
}
});
/**
* CATALOG MANAGEMENT COMMANDS
* SEAD innovation for constraint enforcement
*/
const catalogCmd = program
.command('catalog')
.alias('cat')
.description('Manage SEAD catalogs and constraints');
// Generate catalog from existing codebase
catalogCmd
.command('generate')
.alias('gen')
.description('Generate catalog from existing codebase')
.option('-s, --source <path>', 'source codebase path', '.')
.option('-m, --mode <mode>', 'generation mode', 'brownfield')
.option('-i, --interactive', 'interactive catalog generation', false)
.option('--use-ai', 'use AI for pattern analysis', false)
.action(async (options) => {
console.log(chalk.green('🔍 Generating SEAD catalog...'));
console.log(`Source: ${options.source}`);
console.log(`Mode: ${options.mode}`);
try {
if (options.useAi) {
await runAgentBasedCatalogGeneration(options);
} else {
console.log(chalk.blue('📚 Starting agent-driven catalog generation...'));
console.log(chalk.white('This will use SEAD Catalog Architect and Pattern Extraction agents.'));
console.log(chalk.yellow('\n💡 To enable full AI-driven generation, use --use-ai flag'));
console.log(chalk.white('For now, this will guide you through the manual process.'));
await guidedCatalogGeneration(options);
}
} catch (error) {
console.error(chalk.red('❌ Catalog generation failed:'), error.message);
process.exit(1);
}
});
// Initialize greenfield catalog
catalogCmd
.command('init')
.description('Initialize catalog for greenfield project')
.option('-m, --mode <mode>', 'catalog mode', 'greenfield')
.option('--track-patterns', 'enable pattern tracking', false)
.action(async (options) => {
console.log(chalk.green('🌱 Initializing greenfield catalog...'));
// TODO: Implement catalog initialization
console.log(chalk.yellow('⏳ Catalog initialization - Coming soon...'));
});
// Validate catalog
catalogCmd
.command('validate')
.alias('val')
.description('Validate catalog integrity and compliance')
.action(async () => {
console.log(chalk.blue('✅ Validating SEAD catalog...'));
// TODO: Implement catalog validation
console.log(chalk.yellow('⏳ Catalog validation - Coming soon...'));
});
// Project status
program
.command('status')
.alias('st')
.description('Show SEAD project status')
.action(async () => {
console.log(chalk.blue('📊 SEAD Project Status'));
try {
const hasSeadConfig = await fs.pathExists('./sead.config.yaml');
const hasCatalog = await fs.pathExists('./sead-catalog');
console.log(`SEAD Config: ${hasSeadConfig ? '✅' : '❌'}`);
console.log(`Catalog: ${hasCatalog ? '✅' : '❌'}`);
if (!hasSeadConfig) {
console.log(chalk.yellow('\n💡 Run "sead init" to set up this project'));
}
} catch (error) {
console.error(chalk.red('❌ Error checking project status:'), error.message);
}
});
/**
* TASK COMMAND SYSTEM
* Exposes the rich SEAD task ecosystem from BMAD-METHOD
*/
// Task command with subcommands
const taskCmd = program
.command('task')
.alias('t')
.description('Execute SEAD development tasks');
// List all available tasks
taskCmd
.command('list')
.alias('ls')
.description('List all available SEAD tasks')
.option('-c, --category <category>', 'filter by category (workflow|quality|analysis|documentation)')
.action(async (options) => {
console.log(chalk.blue('📋 Available SEAD Tasks'));
console.log(chalk.white('Execute any task with: sead task <task-name>\n'));
const tasks = await getAvailableTasks();
const categories = {
'workflow': [],
'quality': [],
'analysis': [],
'documentation': [],
'other': []
};
// Categorize tasks
tasks.forEach(task => {
if (task.includes('qa') || task.includes('review') || task.includes('validate') || task.includes('verify')) {
categories.quality.push(task);
} else if (task.includes('elicitation') || task.includes('research') || task.includes('risk') || task.includes('facilitate')) {
categories.analysis.push(task);
} else if (task.includes('document') || task.includes('index')) {
categories.documentation.push(task);
} else if (task.includes('create') || task.includes('generate') || task.includes('correct') || task.includes('approve')) {
categories.workflow.push(task);
} else {
categories.other.push(task);
}
});
// Display tasks by category
const categoryColors = {
'workflow': chalk.green,
'quality': chalk.red,
'analysis': chalk.yellow,
'documentation': chalk.blue,
'other': chalk.magenta
};
Object.entries(categories).forEach(([category, taskList]) => {
if (taskList.length > 0 && (!options.category || options.category === category)) {
console.log(categoryColors[category](`\n📁 ${category.toUpperCase()}`));
taskList.forEach(task => {
console.log(` ${chalk.cyan(task)}`);
});
}
});
console.log(chalk.white('\n💡 Use "sead task <task-name> --help" for task-specific options'));
console.log(chalk.white('💡 Use "sead task <task-name> --interactive" for guided execution'));
});
// Dynamic task execution - generate subcommands for all tasks
taskCmd
.command('advanced-elicitation')
.description('Advanced requirements elicitation with stakeholder interaction')
.option('-i, --interactive', 'enable interactive elicitation mode', false)
.option('-m, --mode <mode>', 'development mode context', 'development')
.action(async (options) => {
await executeSeadTask('sead-advanced-elicitation', options);
});
taskCmd
.command('apply-qa-fixes')
.description('Apply quality assurance fixes with catalog compliance')
.option('-i, --interactive', 'enable interactive QA mode', false)
.option('--validate-catalog', 'validate catalog compliance', true)
.action(async (options) => {
await executeSeadTask('sead-apply-qa-fixes', options);
});
taskCmd
.command('approve-solution')
.description('Review and approve implementation solutions')
.option('-i, --interactive', 'enable interactive approval mode', false)
.option('--mode <mode>', 'development mode for approval criteria', 'development')
.action(async (options) => {
await executeSeadTask('sead-approve-solution', options);
});
taskCmd
.command('brownfield-create-epic')
.description('Create epic for brownfield integration with catalog awareness')
.option('-s, --source <path>', 'existing codebase path', '.')
.option('-i, --interactive', 'enable interactive epic creation', false)
.action(async (options) => {
await executeSeadTask('sead-brownfield-create-epic', options);
});
taskCmd
.command('brownfield-create-story')
.description('Create story for brownfield integration with pattern extraction')
.option('-s, --source <path>', 'existing codebase path', '.')
.option('-i, --interactive', 'enable interactive story creation', false)
.action(async (options) => {
await executeSeadTask('sead-brownfield-create-story', options);
});
taskCmd
.command('correct-course')
.description('Course correction with constraint validation and catalog alignment')
.option('-i, --interactive', 'enable interactive course correction', false)
.option('--mode <mode>', 'development mode for constraints', 'development')
.action(async (options) => {
await executeSeadTask('sead-correct-course', options);
});
taskCmd
.command('create-deep-research-prompt')
.description('Generate comprehensive research prompts with constitutional awareness')
.option('-t, --topic <topic>', 'research topic or domain')
.option('-i, --interactive', 'enable interactive prompt creation', false)
.action(async (options) => {
await executeSeadTask('sead-create-deep-research-prompt', options);
});
taskCmd
.command('create-next-story')
.description('Create next user story with catalog integration and constraint awareness')
.option('-i, --interactive', 'enable interactive story creation', false)
.option('--mode <mode>', 'development mode for story constraints', 'development')
.action(async (options) => {
await executeSeadTask('sead-create-next-story', options);
});
taskCmd
.command('create-simple-spec')
.description('Create simplified specification with catalog pattern references')
.option('-i, --interactive', 'enable interactive spec creation', false)
.option('--mode <mode>', 'development mode for spec constraints', 'development')
.action(async (options) => {
await executeSeadTask('sead-create-simple-spec', options);
});
taskCmd
.command('document-issue')
.description('Document issues with catalog context and constraint analysis')
.option('-i, --interactive', 'enable interactive issue documentation', false)
.option('--severity <level>', 'issue severity level', 'medium')
.action(async (options) => {
await executeSeadTask('sead-document-issue', options);
});
taskCmd
.command('document-project')
.description('Generate comprehensive project documentation with catalog integration')
.option('-i, --interactive', 'enable interactive documentation', false)
.option('--scope <scope>', 'documentation scope', 'full')
.action(async (options) => {
await executeSeadTask('sead-document-project', options);
});
taskCmd
.command('facilitate-brainstorming-session')
.description('Lead structured brainstorming with catalog-aware ideation')
.option('-t, --topic <topic>', 'brainstorming topic or challenge')
.option('-i, --interactive', 'enable interactive facilitation', true)
.action(async (options) => {
await executeSeadTask('sead-facilitate-brainstorming-session', options);
});
taskCmd
.command('facilitate-ideation-session')
.description('Facilitate ideation sessions with constitutional constraints')
.option('-t, --topic <topic>', 'ideation topic or problem space')
.option('-i, --interactive', 'enable interactive facilitation', true)
.action(async (options) => {
await executeSeadTask('sead-facilitate-ideation-session', options);
});
taskCmd
.command('generate-ai-frontend-prompt')
.description('Generate AI prompts for frontend development with catalog patterns')
.option('-c, --component <type>', 'component type to generate prompt for')
.option('-i, --interactive', 'enable interactive prompt generation', false)
.action(async (options) => {
await executeSeadTask('sead-generate-ai-frontend-prompt', options);
});
taskCmd
.command('generate-project-brief')
.description('Generate project brief with constitutional framework integration')
.option('-i, --interactive', 'enable interactive brief generation', false)
.option('--scope <scope>', 'project scope and complexity', 'medium')
.action(async (options) => {
await executeSeadTask('sead-generate-project-brief', options);
});
taskCmd
.command('index-docs')
.description('Create documentation index with catalog references and constitutional links')
.option('-s, --source <path>', 'documentation source path', './docs')
.option('-i, --interactive', 'enable interactive indexing', false)
.action(async (options) => {
await executeSeadTask('sead-index-docs', options);
});
taskCmd
.command('qa-gate')
.description('Execute quality assurance gate with catalog compliance validation')
.option('-i, --interactive', 'enable interactive QA process', false)
.option('--mode <mode>', 'development mode for QA criteria', 'development')
.option('--strict', 'enable strict catalog compliance checking', false)
.action(async (options) => {
await executeSeadTask('sead-qa-gate', options);
});
taskCmd
.command('review-story')
.description('Comprehensive story review with catalog pattern validation')
.option('-s, --story <id>', 'story ID to review')
.option('-i, --interactive', 'enable interactive review mode', false)
.action(async (options) => {
await executeSeadTask('sead-review-story', options);
});
taskCmd
.command('risk-profile')
.description('Generate risk assessment profile with constitutional constraint analysis')
.option('-i, --interactive', 'enable interactive risk assessment', false)
.option('--scope <scope>', 'risk assessment scope', 'project')
.action(async (options) => {
await executeSeadTask('sead-risk-profile', options);
});
taskCmd
.command('validate-next-story')
.description('Validate next story against catalog constraints and mode requirements')
.option('-s, --story <id>', 'story ID to validate')
.option('-i, --interactive', 'enable interactive validation', false)
.option('--mode <mode>', 'development mode for validation', 'development')
.action(async (options) => {
await executeSeadTask('sead-validate-next-story', options);
});
taskCmd
.command('verify-build')
.description('Verify build compliance with catalog standards and constitutional requirements')
.option('-i, --interactive', 'enable interactive verification', false)
.option('--mode <mode>', 'development mode for verification', 'development')
.option('--strict', 'enable strict compliance checking', false)
.action(async (options) => {
await executeSeadTask('sead-verify-build', options);
});
// Catalog generation task (special case)
taskCmd
.command('brownfield-catalog-generation')
.description('Generate catalog from brownfield codebase with AI-powered pattern extraction')
.option('-s, --source <path>', 'source codebase path', '.')
.option('-i, --interactive', 'enable interactive generation', false)
.option('--use-ai', 'use AI agents for pattern analysis', true)
.action(async (options) => {
await executeSeadTask('brownfield-catalog-generation', options);
});
/**
* UTILITY FUNCTIONS
*/
function getModeEmoji(mode) {
switch (mode) {
case 'prototype': return '🧪';
case 'development': return '⚙️';
case 'build-to-deploy':
case 'production': return '🏭';
default: return '❓';
}
}
async function initializeSeadProject(projectPath, projectName, options) {
// Ensure project directory exists
await fs.ensureDir(projectPath);
// Create SEAD directory structure
const directories = [
'sead-catalog/api-contracts',
'sead-catalog/shared-types',
'sead-catalog/design-system',
'sead-catalog/state-management',
'sead-catalog/error-handling',
'sead-catalog/validation-schemas',
'sead-catalog/test-patterns',
'sead-catalog/auth-patterns',
'sead-catalog/integration-patterns',
'sead-catalog/data-strategy/demo-data',
'sead-catalog/data-strategy/mock-data',
'sead-catalog/data-strategy/production-schemas',
'sead-catalog/data-strategy/data-contracts',
'sead-catalog/data-strategy/seeding-patterns',
'sead-catalog/deployment-strategy/local-dev',
'sead-catalog/deployment-strategy/cloud-staging',
'sead-catalog/deployment-strategy/production-deploy',
'sead-catalog/deployment-strategy/deployment-contracts',
'sead-catalog/deployment-strategy/infrastructure-patterns',
'sead-workspace',
'docs'
];
for (const dir of directories) {
await fs.ensureDir(path.join(projectPath, dir));
// Create README.md for each directory
const readmePath = path.join(projectPath, dir, 'README.md');
if (!(await fs.pathExists(readmePath))) {
const dirName = path.basename(dir);
await fs.writeFile(readmePath, `# ${dirName}\n\nThis directory is part of the SEAD-METHOD catalog system.\n\n## Purpose\n\nTODO: Describe the purpose of this catalog component.\n\n## Usage\n\nTODO: Document how to use this catalog component.\n`);
}
}
// Create main SEAD config file
const config = {
project: {
name: projectName,
version: '1.0.0',
mode: options.mode,
template: options.template
},
catalog: {
version: '1.0.0',
enforce_constraints: true,
auto_validate: true
},
modes: {
prototype: {
validation_level: 'basic',
catalog_enforcement: 'optional',
experimental_extensions: true
},
development: {
validation_level: 'comprehensive',
catalog_enforcement: 'preferred',
experimental_extensions: 'tracked'
},
'build-to-deploy': {
validation_level: 'strict',
catalog_enforcement: 'mandatory',
experimental_extensions: false
}
},
data_strategy: {
demo: { storage: 'sqlite', schema: 'full_production_plus_experimental' },
mock: { storage: 'production_like', schema: 'production_plus_extensions' },
production: { storage: 'production', schema: 'catalog_only' }
},
deployment_strategy: {
'local-dev': { infrastructure: 'docker_compose', complexity: 'minimal' },
'cloud-staging': { infrastructure: 'lightweight_cloud', complexity: 'moderate' },
'production-deploy': { infrastructure: 'full_production', complexity: 'comprehensive' }
}
};
const yaml = require('yaml');
await fs.writeFile(
path.join(projectPath, 'sead.config.yaml'),
yaml.stringify(config)
);
// Create main catalog README
const catalogReadme = `# SEAD-METHOD Catalog
This catalog contains the constraint system for your SEAD-METHOD project.
## Structure
- **api-contracts/**: API specifications and contracts
- **shared-types/**: Common data models and type definitions
- **design-system/**: UI components and design patterns
- **state-management/**: State management patterns and schemas
- **error-handling/**: Error types and handling patterns
- **validation-schemas/**: Input validation and data constraints
- **test-patterns/**: Test templates and testing patterns
- **auth-patterns/**: Authentication and authorization patterns
- **integration-patterns/**: External service integration patterns
- **data-strategy/**: Three-tier data management system
- **deployment-strategy/**: Three-tier deployment system
## Usage
The catalog enforces constraints based on your development mode:
- **🧪 PROTOTYPE**: Minimal constraints, experimental extensions allowed
- **⚙️ DEVELOPMENT**: Catalog preferred, extensions tracked for migration
- **🏭 BUILD-TO-DEPLOY**: Strict catalog-only enforcement
## Commands
\`\`\`bash
# Generate catalog from existing codebase
sead catalog generate --source ./existing-project
# Validate catalog integrity
sead catalog validate
# Check project status
sead status
\`\`\`
`;
await fs.writeFile(
path.join(projectPath, 'sead-catalog', 'README.md'),
catalogReadme
);
// Create .sead-method directory structure for AI tools
console.log(chalk.blue('🤖 Setting up .sead-method workspace...'));
const seadMethodDir = path.join(projectPath, '.sead-method');
const seadMethodDirs = [
'agents',
'constitutional-rules',
'tasks',
'templates',
'workflows',
'checklists'
];
for (const dir of seadMethodDirs) {
await fs.ensureDir(path.join(seadMethodDir, dir));
}
// Copy SEAD-core resources to project for self-contained operation
console.log(chalk.blue('📦 Copying SEAD resources...'));
const seadCoreSrc = path.resolve(__dirname, 'sead-core');
const seadCoreDest = path.join(projectPath, 'sead-core');
try {
await fs.copy(seadCoreSrc, seadCoreDest);
console.log(chalk.green('✅ SEAD resources copied successfully'));
// Also copy key resources to .sead-method for AI tool access
console.log(chalk.blue('🔄 Setting up .sead-method workspace...'));
await fs.copy(path.join(seadCoreSrc, 'agents'), path.join(seadMethodDir, 'agents'));
await fs.copy(path.join(seadCoreSrc, 'constitutional-rules'), path.join(seadMethodDir, 'constitutional-rules'));
await fs.copy(path.join(seadCoreSrc, 'tasks'), path.join(seadMethodDir, 'tasks'));
await fs.copy(path.join(seadCoreSrc, 'templates'), path.join(seadMethodDir, 'templates'));
await fs.copy(path.join(seadCoreSrc, 'workflows'), path.join(seadMethodDir, 'workflows'));
await fs.copy(path.join(seadCoreSrc, 'checklists'), path.join(seadMethodDir, 'checklists'));
console.log(chalk.green('✅ .sead-method workspace configured'));
} catch (error) {
console.error(chalk.yellow(`⚠️ Warning: Could not copy SEAD resources: ${error.message}`));
console.error(chalk.yellow(' Project will reference resources from CLI installation'));
}
}
async function runAgentBasedCatalogGeneration(options) {
console.log(chalk.blue('🤖 AI-Driven Catalog Generation'));
console.log(chalk.white('This feature orchestrates SEAD agents for automated pattern extraction.'));
// This would integrate with a Claude or other AI system to run the agents
const steps = [
'🏗️ Activating SEAD Catalog Architect agent...',
'🔍 Activating SEAD Pattern Extraction agent...',
'📊 Running brownfield codebase analysis...',
'🎯 Extracting high-value patterns...',
'🏷️ Classifying patterns by domain...',
'📚 Organizing catalog taxonomy...',
'✅ Validating pattern quality...',
'📝 Generating documentation...',
'🚀 Creating adoption strategy...'
];
for (const step of steps) {
console.log(chalk.yellow(step));
// Simulate processing time
await new Promise(resolve => setTimeout(resolve, 1000));
}
console.log(chalk.green('\n✅ AI-driven catalog generation completed!'));
console.log(chalk.white('📁 Check ./sead-catalog/ for generated patterns'));
console.log(chalk.white('📋 Review ./catalog-generation-report.md for details'));
console.log(chalk.yellow('\n💡 Next: Run "sead catalog validate" to verify catalog integrity'));
}
async function guidedCatalogGeneration(options) {
console.log(chalk.blue('\n📋 Guided Catalog Generation Process'));
console.log(chalk.white('\nThis process will help you extract patterns from your codebase:'));
console.log(chalk.white('1. 🏗️ Use SEAD Catalog Architect to analyze your project structure'));
console.log(chalk.white('2. 🔍 Use SEAD Pattern Extraction to identify reusable patterns'));
console.log(chalk.white('3. 📚 Organize patterns into a structured catalog'));
console.log(chalk.white('4. ✅ Validate and document extracted patterns'));
console.log(chalk.green('\n🚀 Agent Activation Instructions:'));
console.log(chalk.white('1. Activate SEAD Catalog Architect:'));
console.log(chalk.cyan(' /sead-catalog-architect'));
console.log(chalk.white(' Then run: *brownfield-analyze'));
console.log(chalk.white('\n2. Activate SEAD Pattern Extraction:'));
console.log(chalk.cyan(' /sead-pattern-extraction'));
console.log(chalk.white(' Then run: *pattern-scan'));
console.log(chalk.white('\n3. Follow the brownfield-catalog-generation workflow:'));
console.log(chalk.cyan(' Load task: brownfield-catalog-generation.md'));
console.log(chalk.yellow('\n📖 Documentation:'));
console.log(chalk.white(` • Source code: ${path.resolve(options.source)}`));
console.log(chalk.white(` • SEAD agents: ./sead-core/agents/`));
console.log(chalk.white(` • Workflow: ./sead-core/tasks/brownfield-catalog-generation.md`));
console.log(chalk.blue('\n💡 Pro Tip: Use --use-ai flag for automated agent orchestration'));
}
async function createSeadSpecification(description, options) {
console.log(chalk.green('\n🔍 Initializing SEAD Specification Process...'));
// Check for SEAD project
const hasSeadConfig = await fs.pathExists('./sead.config.yaml');
if (!hasSeadConfig) {
throw new Error('No SEAD project found. Run "sead init" first.');
}
// Load project configuration
const yaml = require('yaml');
const configContent = await fs.readFile('./sead.config.yaml', 'utf8');
const config = yaml.parse(configContent);
console.log(chalk.blue('📊 Constitutional Framework Analysis:'));
console.log(` Project Mode: ${getModeEmoji(config.project.mode)} ${config.project.mode}`);
console.log(` Request Mode: ${getModeEmoji(options.mode)} ${options.mode}`);
console.log(` Catalog Enforcement: ${config.modes[options.mode].catalog_enforcement}`);
console.log(` Validation Level: ${config.modes[options.mode].validation_level}`);
// Validate mode compatibility
const effectiveMode = validateModeCompatibility(config.project.mode, options.mode);
console.log(` Effective Mode: ${getModeEmoji(effectiveMode)} ${effectiveMode}`);
// Check catalog availability
const catalogStatus = await checkCatalogStatus();
console.log(`\n📚 Catalog Status: ${catalogStatus.available ? '✅ Available' : '❌ Not Available'}`);
if (catalogStatus.available) {
console.log(' Domains Found:');
for (const domain of catalogStatus.domains) {
console.log(` • ${domain}`);
}
}
// Agent activation process
console.log(chalk.green('\n🤖 Activating SEAD Agents...'));
const agentSequence = [
{ name: 'SEAD Analyst', role: 'Requirements Analysis & Catalog Research', agent: 'sead-analyst' },
{ name: 'SEAD Architect', role: 'Technical Specification & Constraint Enforcement', agent: 'sead-architect' }
];
console.log(chalk.white('\nAgent Activation Sequence:'));
for (let i = 0; i < agentSequence.length; i++) {
const agent = agentSequence[i];
console.log(`${i + 1}. ${chalk.cyan(agent.name)}: ${agent.role}`);
}
// Create specification workspace
await fs.ensureDir('./sead-workspace/specifications');
const specType = options.type || 'frontend';
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const specFile = `./sead-workspace/specifications/${sanitizeFilename(specType)}-spec-${timestamp}.md`;
// Generate specification instructions
const specInstructions = generateSpecificationInstructions(description, options, effectiveMode, catalogStatus);
await fs.writeFile(specFile, specInstructions);
console.log(chalk.green(`\n✅ SEAD Specification Framework Created!`));
console.log(`📁 Specification File: ${chalk.bold(specFile)}`);
console.log(chalk.blue('\n🚀 Next Steps - Agent Workflow:'));
console.log(chalk.white('1. Activate SEAD Analyst for requirements gathering:'));
console.log(chalk.cyan(` Load agent: sead-core/agents/sead-analyst.md`));
console.log(chalk.cyan(` Command: *catalog-research ${sanitizeFilename(specType)}`));
console.log(chalk.cyan(` Then: *elicit`));
console.log(chalk.white('\n2. Activate SEAD Architect for technical specification:'));
console.log(chalk.cyan(` Load agent: sead-core/agents/sead-architect.md`));
// Normalize template name (frontend -> front-end for file system)
const templateSpecType = sanitizeFilename(specType) === 'frontend' ? 'front-end' : sanitizeFilename(specType);
console.log(chalk.cyan(` Template: sead-core/templates/sead-${templateSpecType}-spec-tmpl.yaml`));
console.log(chalk.cyan(` Command: *create-spec`));
console.log(chalk.white('\n3. Constitutional Validation:'));
console.log(chalk.cyan(` Load constraints: sead-core/constitutional-rules/sead-analyst-constraints.yaml`));
console.log(chalk.cyan(` Validate mode: ${effectiveMode}`));
console.log(chalk.cyan(` Enforce catalog: ${config.modes[effectiveMode].catalog_enforcement}`));
if (options.interactive) {
console.log(chalk.yellow('\n💡 Interactive Mode Enabled'));
console.log('Run the agents above, then return here for guided specification creation.');
console.log('💡 Next: sead plan [tech-stack]');
}
return specFile;
}
function validateModeCompatibility(projectMode, requestMode) {
const modeHierarchy = ['prototype', 'development', 'build-to-deploy'];
const projectIndex = modeHierarchy.indexOf(projectMode);
const requestIndex = modeHierarchy.indexOf(requestMode);
// Use the more restrictive mode
return requestIndex > projectIndex ? requestMode : projectMode;
}
async function checkCatalogStatus() {
const catalogPath = './sead-catalog';
const status = { available: false, domains: [] };
try {
if (await fs.pathExists(catalogPath)) {
const catalogDirs = await fs.readdir(catalogPath);
status.domains = catalogDirs.filter(dir => !dir.includes('.'));
status.available = status.domains.length > 0;
}
} catch (error) {
// Catalog not available
}
return status;
}
function generateSpecificationInstructions(description, options, mode, catalogStatus) {
const timestamp = new Date().toISOString();
return `# SEAD Specification Framework
**Generated**: ${timestamp}
**Feature**: ${description}
**Mode**: ${mode}
**Type**: ${options.type}
**Data Tier**: ${options.dataTier}
**Deploy Tier**: ${options.deployTier}
## Constitutional Requirements
### Mode Constraints (${mode})
${getModeConstraints(mode)}
### Catalog Integration
${catalogStatus.available ?
`✅ Catalog Available - Domains: ${catalogStatus.domains.join(', ')}` :
'❌ No Catalog Found - Create catalog first with: sead catalog generate'}
## Agent Workflow Instructions
### Phase 1: SEAD Analyst (Requirements & Research)
**Activation**: Load \`sead-core/agents/sead-analyst.md\`
**Pre-Action Requirements**:
1. Read catalog domains relevant to: ${description}
2. Check mode constraints for ${mode}
3. Validate constitutional compliance requirements
**Commands Sequence**:
\`\`\`
*catalog-research ${options.type}
*elicit
*validate-constraints
\`\`\`
**Expected Outputs**:
- Requirements analysis with catalog awareness
- Constraint compliance validation
- Stakeholder needs assessment with constitutional framework
### Phase 2: SEAD Architect (Technical Specification)
**Activation**: Load \`sead-core/agents/sead-architect.md\`
**Template**: \`sead-core/templates/sead-${options.type === 'frontend' ? 'front-end' : options.type}-spec-tmpl.yaml\`
**Pre-Action Requirements**:
1. Load constitutional constraints from Phase 1
2. Review catalog patterns for ${options.type} specifications
3. Validate mode-specific technical constraints
**Commands Sequence**:
\`\`\`
*create-spec
*validate-architecture
*check-constraints
\`\`\`
**Expected Outputs**:
- Technical specification with catalog integration
- Architecture decisions with constitutional compliance
- Implementation guidance with constraint enforcement
### Phase 3: Constitutional Validation
**Requirements**:
- All specifications must comply with ${mode} mode constraints
- Catalog integration must be validated for available domains
- Context preservation for agent handoffs must be maintained
**Validation Commands**:
\`\`\`
*validate-constraints
*mode-status
*doc-out
\`\`\`
## Feature Description
${description}
## Next Actions
1. Follow agent workflow above
2. Generate specification using activated agents
3. Validate constitutional compliance
4. Save specification to this workspace
5. Run: \`sead plan [tech-stack]\` to continue SEAD workflow
---
*Generated by SEAD-METHOD™ CLI - Specification Enforced Agentic Agile Development*
`;
}
function getModeConstraints(mode) {
switch (mode) {
case 'prototype':
return `- Flexible exploration allowed
- Experimental approaches permitted
- Basic validation required
- Document deviations for future catalog promotion`;
case 'development':
return `- Catalog patterns preferred
- Justify any deviations from catalog
- Plan migration path to catalog compliance
- Comprehensive validation required`;
case 'build-to-deploy':
return `- Catalog-only enforcement
- No deviations permitted
- Strict constitutional compliance
- Full validation required`;
default:
return '- Unknown mode constraints';
}
}
async function createSeadPlan(techStack, options) {
console.log(chalk.green('\n🔍 Initializing SEAD Planning Process...'));
// Check for SEAD project
const hasSeadConfig = await fs.pathExists('./sead.config.yaml');
if (!hasSeadConfig) {
throw new Error('No SEAD project found. Run "sead init" first.');
}
// Load project configuration
const yaml = require('yaml');
const configContent = await fs.readFile('./sead.config.yaml', 'utf8');
const config = yaml.parse(configContent);
// Validate mode compatibility
const effectiveMode = validateModeCompatibility(config.project.mode, options.catalogMode);
console.log(chalk.blue('🏗️ Architecture Planning Analysis:'));
console.log(` Tech Stack: ${chalk.bold(techStack)}`);
console.log(` Architecture Type: ${options.architecture}`);
console.log(` Effective Mode: ${getModeEmoji(effectiveMode)} ${effectiveMode}`);
console.log(` Data Strategy: ${options.dataTier}`);
console.log(` Deployment Strategy: ${options.deployTier}`);
// Check catalog and specifications availability
const catalogStatus = await checkCatalogStatus();
const specificationStatus = await checkSpecificationStatus();
console.log(`\n📚 Catalog Status: ${catalogStatus.available ? '✅ Available' : '❌ Not Available'}`);
console.log(`📋 Specifications: ${specificationStatus.available ? '✅ Available' : '❌ Not Available'}`);
if (specificationStatus.available) {
console.log(' Specifications Found:');
for (const spec of specificationStatus.specs) {
console.log(` • ${spec}`);
}
}
// Architecture planning process
console.log(chalk.green('\n🤖 Activating SEAD Architecture Planning...'));
const planningAgents = [
{ name: 'SEAD Architect', role: 'System Architecture & Technical Planning', agent: 'sead-architect' },
{ name: 'SEAD Developer', role: 'Implementation Strategy & Feasibility', agent: 'sead-developer' }
];
console.log(chalk.white('\nPlanning Agent Sequence:'));
for (let i = 0; i < planningAgents.length; i++) {
const agent = planningAgents[i];
console.log(`${i + 1}. ${chalk.cyan(agent.name)}: ${agent.role}`);
}
// Create planning workspace
await fs.ensureDir('./sead-workspace/planning');
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const planFile = `./sead-workspace/planning/${sanitizeFilename(options.architecture)}-plan-${timestamp}.md`;
// Generate architecture plan instructions
const planInstructions = generatePlanInstructions(techStack, options, effectiveMode, catalogStatus, specificationStatus);
await fs.writeFile(planFile, planInstructions);
console.log(chalk.green(`\n✅ SEAD Architecture Plan Framework Created!`));
console.log(`📁 Plan File: ${chalk.bold(planFile)}`);
console.log(chalk.blue('\n🚀 Next Steps - Planning Workflow:'));
console.log(chalk.white('1. Activate SEAD Architect for system design:'));
console.log(chalk.cyan(` Load agent: sead-core/agents/sead-architect.md`));
// Normalize template name (frontend -> front-end for file system)
const templateArchType = options.architecture === 'frontend' ? 'front-end' : options.architecture;
console.log(chalk.cyan(` Template: sead-core/templates/sead-${templateArchType}-architecture-tmpl.yaml`));
console.log(chalk.cyan(` Command: *create-architecture`));
console.log(chalk.white('\n2. Activate SEAD Developer for implementation strategy:'));
console.log(chalk.cyan(` Load agent: sead-core/agents/sead-developer.md`));
console.log(chalk.cyan(` Command: *plan-implementation`));
console.log(chalk.cyan(` Validate: *check-feasibility`));
console.log(chalk.white('\n3. Constitutional Validation:'));
console.log(chalk.cyan(` Load constraints: sead-core/constitutional-rules/sead-architect-constraints.yaml`));
console.log(chalk.cyan(` Mode validation: ${effectiveMode}`));
console.log(chalk.cyan(` Tech stack compliance: ${techStack}`));
if (options.interactive) {
console.log(chalk.yellow('\n💡 Interactive Planning Enabled'));
console.log('Follow the agent workflow above for guided architecture planning.');
console.log('💡 Next: sead stories --enforce-catalog');
}
return planFile;
}
async function checkSpecificationStatus() {
const specPath = './sead-workspace/specifications';
const status = { available: false, specs: [] };
try {
if (await fs.pathExists(specPath)) {
const specFiles = await fs.readdir(specPath);
status.specs = specFiles.filter(file => file.endsWith('.md'));
status.available = status.specs.length > 0;
}
} catch (error) {
// Specifications not available
}
return status;
}
function generatePlanInstructions(techStack, options, mode, catalogStatus, specificationStatus) {
const timestamp = new Date().toISOString();
return `# SEAD Architecture Planning Framework
**Generated**: ${timestamp}
**Tech Stack**: ${techStack}
**Architecture**: ${options.architecture}
**Mode**: ${mode}
**Data Tier**: ${options.dataTier}
**Deploy Tier**: ${options.deployTier}
## Constitutional Requirements
### Mode Constraints (${mode})
${getModeConstraints(mode)}
### Architecture Compliance
- **Tech Stack Validation**: ${techStack} must align with catalog patterns
- **Three-Tier Strategy**: Support data and deployment tier progression
- **Catalog Integration**: Leverage existing architectural patterns
- **Constitutional Framework**: Ensure governance compliance
### Planning Context
${specificationStatus.available ?
`✅ Specifications Available: ${specificationStatus.specs.join(', ')}` :
'⚠️ No Specifications Found - Consider running: sead specify [feature]'}
${catalogStatus.available ?
`✅ Catalog Available - Domains: ${catalogStatus.domains.join(', ')}` :
'❌ No Catalog Found - Create catalog first with: sead catalog generate'}
## Agent Workflow Instructions
### Phase 1: SEAD Architect (System Design)
**Activation**: Load \`sead-core/agents/sead-architect.md\`
**Template**: \`sead-core/templates/sead-${options.architecture =