UNPKG

myaidev-method

Version:

Comprehensive development framework with SPARC methodology for AI-assisted software development, multi-platform publishing (WordPress, PayloadCMS, Astro, Docusaurus, Mintlify), and Coolify deployment

1,828 lines (1,507 loc) 59.8 kB
# MyAIDev Method - Technical Architecture Guide **Version**: 0.2.1 **Target Audience**: Developers, System Architects, Contributors **Last Updated**: 2025-10-16 ## Table of Contents 1. [System Overview](#system-overview) 2. [Architecture Patterns](#architecture-patterns) 3. [Core Components](#core-components) 4. [Publishing System](#publishing-system) 5. [Deployment System](#deployment-system) 6. [Agent System](#agent-system) 7. [Integration Patterns](#integration-patterns) 8. [Data Flow](#data-flow) 9. [Extension Guide](#extension-guide) 10. [Testing Strategy](#testing-strategy) --- ## System Overview ### Purpose MyAIDev Method is an AI-powered CLI toolkit that provides: - **Multi-platform content publishing** (WordPress, PayloadCMS, Docusaurus, Mintlify, Astro) - **Application deployment** (Coolify) - **AI agents** for automated workflows - **Claude Code 2.0 integration** via slash commands and agents ### Technology Stack ```yaml Runtime: - Node.js: >=18.0.0 - Module System: ES Modules (type: "module") Core Dependencies: - @modelcontextprotocol/sdk: ^1.18.0 # MCP protocol integration - marked: ^11.0.0 # Markdown parsing - gray-matter: ^4.0.3 # Frontmatter parsing - simple-git: ^3.22.0 # Git operations - node-fetch: ^3.3.2 # HTTP requests - chalk: ^5.3.0 # Terminal styling - commander: ^12.0.0 # CLI framework - inquirer: ^9.2.15 # Interactive prompts - ora: ^8.0.1 # Terminal spinners - dotenv: ^16.4.1 # Environment config - fs-extra: ^11.2.0 # File operations - ssh2: ^1.15.0 # SSH integration - zod: ^3.23.8 # Schema validation Development: - Test Framework: Custom node-based test runner - Build System: npm scripts + file copying - Distribution: npm registry ``` ### Project Structure ``` myaidev-method/ ├── bin/ │ └── cli.js # Main CLI entry point ├── src/ │ ├── lib/ # Core utility libraries │ │ ├── payloadcms-utils.js # PayloadCMS API wrapper │ │ ├── static-site-utils.js # Unified static site publishing │ │ ├── coolify-utils.js # Coolify deployment wrapper │ │ ├── wordpress-admin-utils.js # WordPress administration │ │ └── report-synthesizer.js # Report generation │ ├── scripts/ # Executable scripts │ │ ├── payloadcms-publish.js # PayloadCMS CLI │ │ ├── docusaurus-publish.js # Docusaurus CLI │ │ ├── mintlify-publish.js # Mintlify CLI │ │ ├── astro-publish.js # Astro CLI │ │ ├── coolify-deploy-app.js # Coolify deployment CLI │ │ ├── coolify-status.js # Coolify status check │ │ ├── coolify-list-resources.js # Coolify resource listing │ │ └── init-project.js # Project initialization │ ├── templates/ │ │ └── claude/ # Claude Code templates │ │ ├── agents/ # Agent definitions (.md) │ │ └── commands/ # Slash commands (.md) │ └── mcp/ # MCP server implementations │ ├── wordpress-server.js # WordPress MCP server │ └── mcp-launcher.js # MCP lifecycle manager ├── .claude/ # Package Claude Code config │ ├── CLAUDE.md # Configuration metadata │ ├── commands/ # Packaged commands │ ├── agents/ # Packaged agents │ └── mcp/ # MCP server files ├── test/ # Test suite │ ├── run-tests.js # Test orchestrator │ ├── test-gutenberg-converter.js # Gutenberg tests │ └── test-installation.js # Installation tests ├── .env.example # Environment template ├── package.json # Package metadata └── Documentation/ ├── README.md # User-facing readme ├── USER_GUIDE.md # Getting started guide ├── PUBLISHING_GUIDE.md # Multi-platform publishing ├── COOLIFY_DEPLOYMENT.md # Deployment guide ├── WORDPRESS_ADMIN_SCRIPTS.md # WordPress utilities └── TECHNICAL_ARCHITECTURE.md # This document ``` --- ## Architecture Patterns ### 1. Platform Adapter Pattern **Problem**: Need to support multiple publishing platforms with different APIs and workflows. **Solution**: Create platform-specific utility classes with unified interfaces. ```javascript // Unified interface class PublishingAdapter { constructor(config) { } async authenticate() { } async publishContent(file, options) { } async updateContent(id, file, options) { } async healthCheck() { } } // Implementations - PayloadCMSUtils: API-based CMS with Lexical conversion - StaticSiteUtils: Git-based publishing with platform detection - CoolifyUtils: Deployment platform with resource management ``` **Benefits**: - Easy to add new platforms - Consistent error handling - Reusable across agents and scripts ### 2. Two-Tier Publishing Architecture Publishing platforms are divided into two categories: #### API-Based Publishers (WordPress, PayloadCMS) ``` Flow: Markdown → API Transform → HTTP POST → Platform API → Published Content Characteristics: - Real-time publishing - JWT/API key authentication - Rich text format conversion (Gutenberg blocks, Lexical nodes) - Immediate feedback - No git operations required ``` #### Git-Based Publishers (Docusaurus, Mintlify, Astro) ``` Flow: Markdown → Frontmatter Transform → File Write → Git Commit → Git Push → CI/CD → Deployed Site Characteristics: - File system operations - Frontmatter transformation - Platform-specific conventions - Automatic git workflow - Deployment via platform's CI/CD ``` ### 3. Agent-Script Duality Pattern **Problem**: Need both interactive AI agents and standalone CLI scripts. **Solution**: Implement core logic in reusable utility libraries, with two entry points: ``` ┌─────────────────┐ │ Core Utility │ (src/lib/payloadcms-utils.js) │ PayloadCMSUtils│ └────────┬────────┘ │ ├─────────────┐ │ │ ┌────▼──────┐ ┌───▼────────────┐ │ Script │ │ AI Agent │ │ Entry │ │ Entry │ └───────────┘ └────────────────┘ CLI execution Claude Code agent npm scripts Slash commands Direct use Conversational ``` **Example**: ```javascript // src/lib/payloadcms-utils.js - Core implementation export class PayloadCMSUtils { async publishContent(file, collection, options) { } } // src/scripts/payloadcms-publish.js - CLI script import { PayloadCMSUtils } from '../lib/payloadcms-utils.js'; const payload = new PayloadCMSUtils(); await payload.publishContent(options.file, options.collection, options); // src/templates/claude/agents/payloadcms-publish.md - AI agent // Uses PayloadCMSUtils via Claude Code tool invocation // Provides conversational interface, error guidance, workflow orchestration ``` ### 4. Claude Code 2.0 Integration Pattern Following official Claude Code 2.0 best practices: #### Lightweight Agents (<3k tokens) ```markdown --- name: payloadcms-publish description: PayloadCMS publishing agent version: 2.0.0 token_target: 2800 --- # Concise agent definition - Clear responsibilities - Step-by-step workflow - Tool usage examples - Error handling patterns ``` #### Extended Thinking Support ``` Trigger keywords: "think", "think hard", "ultrathink" Behavior: Deep analysis before execution Use cases: Complex decisions, troubleshooting, optimization ``` #### Subagent Delegation ``` Main Agent ├─> Subagent 1 (Deploy App A) ├─> Subagent 2 (Deploy App B) └─> Subagent 3 (Configure DB) Pattern: Parallel execution of independent tasks ``` --- ## Core Components ### 1. CLI System (bin/cli.js) **Purpose**: Initialize project configuration for different AI CLIs. **Architecture**: ```javascript program .command('init') .option('--claude') // Claude Code .option('--gemini') // Gemini CLI .option('--codex') // Codex CLI .action(async (options) => { // 1. Determine CLI type (interactive or flag-based) // 2. Call platform-specific setup function // 3. Copy templates (agents, commands, MCP config) // 4. Copy documentation to project root // 5. Create CLAUDE.md configuration // 6. Copy comprehensive .env.example // 7. Display usage instructions }); ``` **Setup Workflow**: ``` 1. Create directory structure .claude/ ├── commands/ (slash commands) ├── agents/ (AI agent definitions) └── mcp/ (MCP server files) 2. Copy templates from package src/templates/claude/agents/*.md → .claude/agents/ src/templates/claude/commands/*.md → .claude/commands/ .claude/mcp/*.js → .claude/mcp/ 3. Generate configuration CLAUDE.md with available commands and agents .env.example with all platform credentials 4. Copy documentation USER_GUIDE.md PUBLISHING_GUIDE.md COOLIFY_DEPLOYMENT.md WORDPRESS_ADMIN_SCRIPTS.md ``` ### 2. PayloadCMS Utility (src/lib/payloadcms-utils.js) **Purpose**: Complete API wrapper for PayloadCMS headless CMS. **Key Features**: - JWT authentication with token caching - Markdown to Lexical rich text conversion - CRUD operations on collections - Media upload support - Health checking **Architecture**: ```javascript class PayloadCMSUtils { constructor(config = {}) { // Auto-load from .env or accept direct config this.url = config.url || process.env.PAYLOADCMS_URL; this.email = config.email; this.password = config.password; this.apiKey = config.apiKey; this.token = null; // JWT token cached after auth } async authenticate() { // POST /api/users/login // Store JWT token for subsequent requests } async request(endpoint, options) { // Unified request handler // Auto-authenticate if token missing // Add Authorization header // Parse JSON response // Handle errors with context } convertMarkdownToLexical(markdown) { // Parse markdown with marked.lexer() // Transform tokens to Lexical nodes // Return Lexical JSON structure } async publishContent(file, collection, options) { // Read file, parse frontmatter // Convert markdown to Lexical // POST to /api/{collection} (create) // Or PATCH to /api/{collection}/{id} (update) } } ``` **Lexical Conversion**: ```javascript Markdown Token → Lexical Node Mapping: heading → { type: 'heading', tag: 'h1-h6', children: [...] } paragraph → { type: 'paragraph', children: [...] } list (ordered) → { type: 'number', listType: 'number', children: [...] } list (unordered) → { type: 'bullet', listType: 'bullet', children: [...] } code → { type: 'code', language: 'lang', children: [...] } blockquote → { type: 'quote', children: [...] } hr → { type: 'horizontalrule', version: 1 } text → { type: 'text', text: '...', format: 0 } ``` ### 3. Static Site Utility (src/lib/static-site-utils.js) **Purpose**: Unified publishing for git-based static site generators. **Supported Platforms**: - Docusaurus (docs + blog) - Mintlify (API documentation) - Astro (content collections + pages) **Architecture**: ```javascript // Platform configuration object const platformConfigs = { docusaurus: { contentDirs: { docs: 'docs', blog: 'blog', pages: 'src/pages' }, frontmatterFields: ['id', 'title', 'sidebar_label', 'sidebar_position', ...], configFile: 'docusaurus.config.js', sidebarFile: 'sidebars.js', requiresNavUpdate: false }, mintlify: { contentDirs: { default: '.' }, frontmatterFields: ['title', 'description', 'icon', 'iconType'], configFile: 'mint.json', requiresNavUpdate: true, // Update mint.json navigation fileExtensions: ['.mdx'] }, astro: { contentDirs: { content: 'src/content', pages: 'src/pages' }, frontmatterFields: ['title', 'description', 'pubDate', 'author', ...], configFile: 'astro.config.mjs', collectionSchema: true, // Type-safe content collections requiresNavUpdate: false } }; class StaticSiteUtils { constructor({ platform, projectPath, gitUserName, gitUserEmail }) { this.platform = platform; this.platformConfig = platformConfigs[platform]; this.projectPath = projectPath || detectFromEnv(); this.git = simpleGit(this.projectPath); } validateProject() { // Check if config file exists // Verify git repository } transformFrontmatter(frontmatter) { // Platform-specific transformations // Docusaurus: Generate id from title // Astro: date → pubDate (ISO 8601) // Mintlify: Require title field } async publishContent(file, options) { // 1. Validate project structure // 2. Read and parse markdown // 3. Transform frontmatter // 4. Determine target directory // 5. Write file // 6. Update navigation (if required) // 7. Git commit and push } async updateNavigation(filename, frontmatter, options) { // Mintlify only // Read mint.json // Add file to specified navigation section // Write updated mint.json } async gitCommitAndPush(filePath, options) { // Configure git user // Stage file // Commit with message // Push to remote (unless --no-push) } } ``` **Frontmatter Transformations**: ```yaml # Universal → Platform-Specific # Docusaurus title: "Guide" → title: "Guide", id: "guide" sidebar_position: 1 → sidebar_position: 1 # Astro date: "2025-10-16" → pubDate: "2025-10-16T00:00:00Z" status: "published" → draft: false # Mintlify title: "API Reference" → title: "API Reference" # If nav-section specified → Update mint.json navigation ``` ### 4. Coolify Utility (src/lib/coolify-utils.js) **Purpose**: Complete API wrapper for Coolify self-hosted PaaS. **Key Features**: - Server management - Project and application CRUD - Deployment operations - Environment variable management - Database provisioning - Health monitoring **Architecture**: ```javascript class CoolifyUtils { constructor({ url, apiKey }) { this.url = url || process.env.COOLIFY_URL; this.apiKey = apiKey || process.env.COOLIFY_API_KEY; this.headers = { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }; } // Resource Management async listServers() { } async listProjects() { } async listApplications() { } async listDatabases() { } // Application Lifecycle async createApplication(config) { } async deployApplication(uuid, options) { } async restartApplication(uuid) { } async stopApplication(uuid) { } async deleteApplication(uuid) { } // Environment Management async getEnvironmentVariables(uuid) { } async updateEnvironmentVariables(uuid, envVars) { } // Monitoring async getDeploymentLogs(uuid) { } async waitForDeployment(uuid, { maxAttempts, interval }) { } async healthCheck() { } // Helpers buildApplicationConfig(options) { } buildDatabaseConfig(options) { } formatServerList(servers) { } generateDeploymentReport(deployment, application) { } } ``` **Deployment Configuration**: ```javascript { name: "app-name", source: { type: "git", repository: "https://github.com/user/repo", branch: "main" }, build_pack: "nixpacks|dockerfile|static", ports_exposes: "3000", domains: ["app.example.com"], environment_variables: { NODE_ENV: "production" }, settings: { auto_deploy: true, instant_deploy: false } } ``` --- ## Publishing System ### API-Based Publishing Flow ``` ┌──────────────────────────────────────────────────────────────┐ │ 1. User Request │ │ /myai-payloadcms-publish "article.md" --status published │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 2. Agent/Script Entry Point │ │ - Parse command arguments │ │ - Load .env configuration │ │ - Instantiate PayloadCMSUtils │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 3. Authentication │ │ POST /api/users/login │ │ {email, password} → JWT token │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 4. Content Processing │ │ - Read markdown file │ │ - Parse frontmatter (title, description, etc.) │ │ - Parse markdown body with marked.lexer() │ │ - Convert to Lexical JSON format │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 5. API Request │ │ POST /api/{collection} │ │ Authorization: JWT {token} │ │ Body: { │ │ title: "...", │ │ content: { root: { ... } }, // Lexical JSON │ │ status: "published" │ │ } │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 6. Response Handling │ │ - Extract document ID │ │ - Construct admin URL │ │ - Report success to user │ └──────────────────────────────────────────────────────────────┘ ``` ### Git-Based Publishing Flow ``` ┌──────────────────────────────────────────────────────────────┐ │ 1. User Request │ │ /myai-docusaurus-publish "guide.md" --type docs │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 2. Agent/Script Entry Point │ │ - Parse command arguments │ │ - Detect or specify platform (docusaurus, mintlify, astro)│ │ - Instantiate StaticSiteUtils │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 3. Project Validation │ │ - Check for platform config file (docusaurus.config.js) │ │ - Verify git repository │ │ - Confirm project path │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 4. Content Processing │ │ - Read markdown file │ │ - Parse frontmatter │ │ - Transform frontmatter (platform-specific) │ │ - Determine target directory (docs/, blog/, src/content/) │ │ - Generate filename │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 5. File Operations │ │ - Write transformed content to target directory │ │ - Update navigation config (Mintlify only) │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 6. Git Workflow │ │ - git add {file} │ │ - git commit -m "Add/Update {file}" │ │ - git push origin {branch} │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ 7. Platform CI/CD (Automatic) │ │ - Platform detects git push │ │ - Runs build process │ │ - Deploys to hosting │ │ - Content goes live │ └──────────────────────────────────────────────────────────────┘ ``` --- ## Deployment System ### Coolify Deployment Architecture ``` ┌──────────────────────────────────────────────────────────────┐ │ User Request │ │ /myai-coolify-deploy --name myapp --repo https://... │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ Agent/Script: coolify-deploy-app.js │ │ - Parse arguments │ │ - Load Coolify credentials │ │ - Instantiate CoolifyUtils │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ Resource Discovery │ │ - List servers (GET /api/v1/servers) │ │ - Select optimal server (user-specified or auto) │ │ - List projects (GET /api/v1/projects) │ │ - Select/create project │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ Application Configuration │ │ buildApplicationConfig({ │ │ name, repository, branch, buildPack, ports, domains, │ │ serverUuid, projectUuid, envVars, settings │ │ }) │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ Create Application │ │ POST /api/v1/applications/public │ │ Body: applicationConfig │ │ Response: { uuid, ...applicationData } │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ Trigger Deployment │ │ POST /api/v1/deploy?uuid={uuid} │ │ Body: { force: false, instant_deploy: false } │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ Monitor Deployment │ │ waitForDeployment(uuid, { maxAttempts: 60, interval: 5s }) │ │ - Poll GET /api/v1/applications/{uuid} │ │ - Check status: building → running | error | timeout │ └───────────────────────┬──────────────────────────────────────┘ │ ┌───────────────────────▼──────────────────────────────────────┐ │ Report Results │ │ - Success: Application URL, deployment time │ │ - Failure: Error logs, rollback options │ └──────────────────────────────────────────────────────────────┘ ``` ### Deployment Workflow Patterns #### Pattern 1: Single Application Deployment ```bash # Step 1: Verify connectivity node src/scripts/coolify-status.js # Step 2: Deploy node src/scripts/coolify-deploy-app.js \ --name "myapp" \ --repo "https://github.com/user/myapp" \ --branch "main" \ --build-pack "nixpacks" \ --port "3000" # Step 3: Monitor # (Automatic via waitForDeployment) ``` #### Pattern 2: Multi-Component Application (Database + Backend + Frontend) ```javascript // Orchestration via agent delegation Main Agent ├─> Database Agent: Deploy PostgreSQL │ └─> Returns: DATABASE_URL │ ├─> Backend Agent: Deploy API with DATABASE_URL │ └─> Returns: API_URL │ └─> Frontend Agent: Deploy UI with API_URL └─> Returns: APP_URL // Parallel execution where possible (DB creation independent of app builds) ``` #### Pattern 3: Environment-Specific Deployment ```javascript // Staging deployApplication({ name: "myapp-staging", branch: "develop", domains: ["staging.myapp.com"], envVars: loadEnv('.env.staging') }); // Production (with approval gate) if (await confirmProduction()) { deployApplication({ name: "myapp-prod", branch: "main", domains: ["myapp.com", "www.myapp.com"], envVars: loadEnv('.env.production') }); } ``` --- ## Agent System ### Agent Architecture Agents are markdown files with YAML frontmatter following Claude Code 2.0 patterns. **Agent Definition Structure**: ```markdown --- name: agent-name description: Brief description version: 2.0.0 capabilities: - Capability 1 - Capability 2 agent_type: publishing|deployment|administration token_target: 2800 # Lightweight agent target --- # Agent Name **Purpose**: Clear statement of agent's role ## Core Responsibilities 1. Responsibility 1 2. Responsibility 2 ## Workflow ### Step 1: Preparation [Detailed step description] ### Step 2: Execution [Detailed step description] ## Usage Examples ### Example 1: Basic Usage [Example with user request and agent response] ### Example 2: Advanced Usage [Example with complex scenario] ## Tool Usage Pattern [Which tools to use and when] ## Error Handling [Common issues and solutions] ``` ### Available Agents #### 1. Content Writer Agent ```yaml File: .claude/agents/content-writer.md Purpose: Generate SEO-optimized content Capabilities: - Research topics - Structure content - Optimize for SEO - Generate markdown files Token Target: <3k ``` #### 2. WordPress Admin Agent ```yaml File: .claude/agents/wordpress-admin.md Purpose: WordPress administration and security Capabilities: - Health checks - Security scanning - Performance analysis - Comprehensive reporting Token Target: <3k ``` #### 3. PayloadCMS Publishing Agent ```yaml File: .claude/agents/payloadcms-publish.md Purpose: Publish content to PayloadCMS Workflow: 1. Authenticate with JWT 2. Convert markdown to Lexical 3. POST to collections API 4. Verify publication Token Target: 2800 ``` #### 4. Docusaurus Publishing Agent ```yaml File: .claude/agents/docusaurus-publish.md Purpose: Publish to Docusaurus docs/blog Workflow: 1. Validate Docusaurus project 2. Transform frontmatter 3. Write to docs/ or blog/ 4. Git commit and push Token Target: <3k ``` #### 5. Mintlify Publishing Agent ```yaml File: .claude/agents/mintlify-publish.md Purpose: Publish to Mintlify docs Workflow: 1. Validate Mintlify project 2. Transform to MDX 3. Update mint.json navigation 4. Git commit and push Token Target: <3k ``` #### 6. Astro Publishing Agent ```yaml File: .claude/agents/astro-publish.md Purpose: Publish to Astro content collections Workflow: 1. Validate Astro project 2. Transform frontmatter (date → pubDate) 3. Write to src/content/{collection}/ 4. Git commit and push Token Target: <3k ``` #### 7. Coolify Deploy Agent ```yaml File: .claude/agents/coolify-deploy.md Purpose: Deploy applications to Coolify Patterns: - Lightweight: Direct script invocation - Extended Thinking: Complex deployment decisions - Subagent Delegation: Multi-app deployments Token Target: Adaptive (2k-10k based on complexity) Capabilities: - Application deployment - Database provisioning - Environment management - Monitoring and logging ``` ### Slash Commands Commands are lightweight wrappers that invoke agents or scripts. **Command Structure**: ```markdown --- name: myai-command-name description: Brief command description --- Brief explanation of what this command does. Invoke the {agent-name} agent to {action}. ## Usage ```bash /myai-command-name "argument" --option value ``` ## Options - `--option1 <value>` - Description - `--option2` - Boolean flag ## Examples Basic usage: ``` /myai-command-name "example" ``` With options: ``` /myai-command-name "example" --option1 value ``` ``` **Available Commands**: 1. `/myai-content-writer` → Content creation 2. `/myai-wordpress-publish` → WordPress publishing 3. `/myai-wordpress-admin` → WordPress administration 4. `/myai-payloadcms-publish` → PayloadCMS publishing 5. `/myai-docusaurus-publish` → Docusaurus publishing 6. `/myai-mintlify-publish` → Mintlify publishing 7. `/myai-astro-publish` → Astro publishing 8. `/myai-coolify-deploy` → Coolify deployment 9. `/myai-configure` → Platform configuration --- ## Integration Patterns ### Pattern 1: Claude Code → Agent → Script → Utility ``` User: /myai-payloadcms-publish "article.md" │ ▼ Claude Code: Interprets slash command │ ▼ Agent: payloadcms-publish.md │ (Provides context, workflow, error handling) ▼ Script: src/scripts/payloadcms-publish.js │ (CLI argument parsing, execution) ▼ Utility: src/lib/payloadcms-utils.js │ (Core API logic) ▼ PayloadCMS API ``` ### Pattern 2: Direct Script Invocation ``` npm run payloadcms:publish -- --file article.md --status published │ ▼ Script: src/scripts/payloadcms-publish.js │ ▼ Utility: src/lib/payloadcms-utils.js │ ▼ PayloadCMS API ``` ### Pattern 3: Agent-to-Agent Delegation ``` Main Agent: Complex Publishing Workflow │ ├─> Content Writer Agent: Generate content │ └─> Markdown file created │ ├─> PayloadCMS Agent: Publish to CMS │ └─> CMS entry created │ └─> Docusaurus Agent: Publish to docs └─> Documentation updated ``` ### Pattern 4: MCP Server Integration ``` Claude Code │ ▼ MCP Protocol │ ▼ WordPress MCP Server (.claude/mcp/wordpress-server.js) │ (Implements MCP SDK, exposes tools) ▼ WordPress REST API ``` **MCP Tools Exposed**: - `wordpress_publish`: Publish content - `wordpress_health_check`: System health - `wordpress_security_scan`: Security analysis - `wordpress_performance_check`: Performance metrics --- ## Data Flow ### Content Publishing Data Flow ``` ┌─────────────────┐ │ User Input │ (Markdown file, frontmatter, images) │ article.md │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Parse & Load │ (gray-matter: frontmatter + content) │ Read file │ └────────┬────────┘ │ ├─────────────────┬─────────────────┐ │ │ │ ▼ ▼ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ API-Based │ │ Git-Based │ │ Deployment │ │ Transform │ │ Transform │ │ Config │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ ▼ ▼ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ Lexical JSON │ │ Frontmatter │ │ App Config │ │ Gutenberg │ │ Transform │ │ JSON │ │ Blocks │ │ File Write │ │ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ ▼ ▼ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ HTTP POST │ │ Git Commit │ │ API POST │ │ to CMS API │ │ & Push │ │ to Coolify │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ ▼ ▼ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ Published │ │ Platform │ │ Deployed │ │ Content │ │ CI/CD │ │ Application │ │ (Live) │ │ Build/Deploy │ │ (Running) │ └──────────────┘ └──────────────┘ └──────────────┘ ``` ### Configuration Data Flow ``` ┌─────────────────┐ │ .env File │ │ PLATFORM_URL= │ │ PLATFORM_KEY= │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ dotenv.parse() │ (Load and parse environment variables) └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Utility Class │ │ Constructor │ (PayloadCMSUtils, CoolifyUtils, etc.) │ this.url = ... │ │ this.apiKey = ..│ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ API Request │ │ Headers: │ │ Authorization │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Platform API │ │ Authenticated │ │ Response │ └─────────────────┘ ``` --- ## Extension Guide ### Adding a New Publishing Platform Follow this step-by-step guide to add support for a new platform. #### Step 1: Create Utility Class ```javascript // src/lib/newplatform-utils.js export class NewPlatformUtils { constructor(config = {}) { // Load from .env or config this.url = config.url || process.env.NEWPLATFORM_URL; this.apiKey = config.apiKey || process.env.NEWPLATFORM_API_KEY; } loadEnvConfig() { // Parse .env file } async authenticate() { // Handle authentication (JWT, API key, OAuth, etc.) } async request(endpoint, options) { // Unified HTTP request wrapper } async publishContent(file, options) { // Main publishing logic // 1. Read file // 2. Parse frontmatter // 3. Transform content (if needed) // 4. API request // 5. Return result } async healthCheck() { // Verify API connectivity } } export default NewPlatformUtils; ``` #### Step 2: Create CLI Script ```javascript // src/scripts/newplatform-publish.js import { Command } from 'commander'; import chalk from 'chalk'; import ora from 'ora'; import { NewPlatformUtils } from '../lib/newplatform-utils.js'; const program = new Command(); program .requiredOption('--file <path>', 'Markdown file to publish') .option('--status <status>', 'Publication status', 'draft') .option('--dry-run', 'Validate without publishing') .parse(process.argv); const options = program.opts(); async function publishContent() { const spinner = ora('Publishing to NewPlatform...').start(); try { const platform = new NewPlatformUtils(); // Verify connection const healthy = await platform.healthCheck(); if (!healthy) throw new Error('NewPlatform not accessible'); // Publish const result = await platform.publishContent(options.file, { status: options.status, dryRun: options.dryRun }); spinner.succeed(chalk.green('Published successfully!')); console.log(chalk.cyan(`URL: ${result.url}`)); } catch (error) { spinner.fail(chalk.red('Publishing failed')); console.error(error.message); process.exit(1); } } publishContent(); ``` #### Step 3: Add npm Script ```json // package.json { "scripts": { "newplatform:publish": "node src/scripts/newplatform-publish.js" } } ``` #### Step 4: Create Agent Definition ```markdown <!-- src/templates/claude/agents/newplatform-publish.md --> --- name: newplatform-publish description: Publish content to NewPlatform version: 2.0.0 capabilities: - Authenticate with NewPlatform - Convert markdown - Publish content agent_type: publishing token_target: 2800 --- # NewPlatform Publishing Agent **Purpose**: Publish markdown content to NewPlatform. ## Workflow ### Step 1: Configuration Validation 1. Check NEWPLATFORM_URL and NEWPLATFORM_API_KEY 2. If missing → prompt `/myai-configure newplatform` ### Step 2: Authentication 1. Authenticate with API 2. Handle auth errors ### Step 3: Content Processing 1. Read markdown file 2. Parse frontmatter 3. Transform content (if needed) ### Step 4: Publishing 1. POST to NewPlatform API 2. Verify success 3. Return URL ## Usage Examples ### Basic Publishing ``` User: "Publish article.md to NewPlatform" Agent: Executes workflow → Reports success with URL ``` ## Tool Usage Pattern ``` 1. Read(markdown_file) 2. authenticateNewPlatform() 3. publishToNewPlatform() 4. Report success ``` ``` #### Step 5: Create Slash Command ```markdown <!-- src/templates/claude/commands/myai-newplatform-publish.md --> --- name: myai-newplatform-publish description: Publish content to NewPlatform --- Publish markdown content to NewPlatform. Invoke the NewPlatform publishing agent. ## Usage ```bash /myai-newplatform-publish "article.md" /myai-newplatform-publish "article.md" --status published ``` ## Options - `--status <draft|published>` - Publication status - `--dry-run` - Validate without publishing ## Examples Publish as draft: ``` /myai-newplatform-publish "article.md" ``` Publish live: ``` /myai-newplatform-publish "article.md" --status published ``` ``` #### Step 6: Update .env.example ```bash # .env.example # NewPlatform Configuration NEWPLATFORM_URL=https://api.newplatform.com NEWPLATFORM_API_KEY=your-api-key-here ``` #### Step 7: Update CLI Init ```javascript // bin/cli.js - setupClaude() function const claudeMd = ` ## Available Commands ### Publishing Platforms - \`/myai-wordpress-publish\` - Publish to WordPress - \`/myai-payloadcms-publish\` - Publish to PayloadCMS - \`/myai-newplatform-publish\` - Publish to NewPlatform // ADD THIS ... `; ``` #### Step 8: Update Documentation 1. Add section to PUBLISHING_GUIDE.md 2. Update README.md features list 3. Add platform-specific guide if needed #### Step 9: Add Tests ```javascript // test/test-newplatform-publish.js import { NewPlatformUtils } from '../src/lib/newplatform-utils.js'; export async function runNewPlatformTests() { console.log('🧪 Running NewPlatform Publishing Tests...\n'); const tests = [ { name: 'Should authenticate successfully', fn: async () => { const platform = new NewPlatformUtils({ url: 'https://test.newplatform.com', apiKey: 'test-key' }); // Test authentication } }, { name: 'Should publish content', fn: async () => { // Test publishing } } ]; // Run tests... } ``` #### Step 10: Version and Publish ```bash # Update version npm version minor # Run tests npm test # Publish npm publish # Push to git git push --tags ``` ### Adding a New Agent For agents that don't require new platforms (e.g., workflow orchestration, reporting): 1. **Create Agent Definition**: `.claude/agents/new-agent.md` 2. **Create Slash Command**: `.claude/commands/myai-new-agent.md` 3. **Create Script** (if needed): `src/scripts/new-agent.js` 4. **Update CLAUDE.md**: Add to agents list 5. **Update CLI Init**: Include in welcome message 6. **Test**: Verify agent loads and executes correctly --- ## Testing Strategy ### Test Structure ``` test/ ├── run-tests.js # Test orchestrator ├── test-gutenberg-converter.js # Gutenberg block tests ├── test-installation.js # Package installation tests ├── test-payloadcms-publish.js # PayloadCMS tests (future) ├── test-static-site-publish.js # Static site tests (future) └── test-coolify-deploy.js # Coolify tests (future) ``` ### Test Runner (run-tests.js) ```javascript import { runGutenbergTests } from './test-gutenberg-converter.js'; import { runInstallationTests } from './test-installation.js'; async function runAllTests() { console.log('🚀 MyAIDev Method - Test Suite'); console.log('═══════════════════════════════\n'); let allPassed = true; // Run test suites const gutenbergPassed = await runGutenbergTests(); const installationPassed = await runInstallationTests(); allPassed = gutenbergPassed && installationPassed; // Overall results console.log('\n═══════════════════════════════'); console.log('📊 OVERALL TEST RESULTS'); console.log('═══════════════════════════════\n'); if (allPassed) { console.log('🎉 ALL TESTS PASSED! 🎉'); process.exit(0); } else { console.log('❌ SOME TESTS FAILED'); process.exit(1); } } runAllTests(); ``` ### Test Categories #### 1. Unit Tests Test individual functions in isolation. ```javascript // Example: Test markdown to Lexical conversion testCase('Should convert H2 heading to Lexical block', () => { const markdown = '## Test Heading'; const result = convertMarkdownToLexical(markdown); assert(result.root.children[0].type === 'heading'); assert(result.root.children[0].tag === 'h2'); }); ``` #### 2. Integration Tests Test complete workflows. ```javascript // Example: Test PayloadCMS publishing workflow testCase('Should publish markdown to PayloadCMS', async () => { const payload = new PayloadCMSUtils({ ...testConfig }); await payload.authenticate(); const result = await payload.publishContent('test.md', 'posts', { status: 'draft' }); assert(result.doc.id !== null); }); ``` #### 3. Installation Tests Verify package installation creates correct structure. ```javascript testCase('Installation should create .claude directory', async () => { const testDir = await createTestProject(); await runInit(testDir); const claudeDir = path.join(testDir, '.claude'); assert(fs.existsSync(claudeDir)); }); ``` ### Running Tests ```bash # Run all tests npm test # Run specific test suite npm run test:gutenberg npm run test:install # Future test commands npm run test:payloadcms npm run test:static-sites npm run test:coolify ``` ### Test Guidelines 1. **Isolation**: Tests should not depend on external services (use mocks) 2. **Cleanup**: Always clean up test directories and resources 3. **Assertions**: Use clear, descriptive assertions 4. **Error Handling**: Test both success and failure paths 5. **Documentation**: Comment complex test logic --- ## Performance Considerations ### 1. Token Optimization (Claude Code 2.0) - **Lightweight Agents**: Keep agents under 3k tokens - **Lazy Loading**: Load utility libraries only when needed - **Caching**: Cache authentication tokens, git state - **Parallel Execution**: Use subagent delegation for independent tasks ### 2. API Request Optimization ```javascript // Batch requests where possible const [servers, projects, apps] = await Promise.all([ coolify.listServers(), coolify.listProjects(), coolify.listApplications() ]); // Cache authentication tokens if (!this.token) { await this.authenticate(); } // Reuse token for subsequent requests ``` ### 3. File Operations ```javascript // Use streams for large files import { createReadStream, createWriteStream } from 'fs'; // Use fs-extra for recursive operations import fs from 'fs-extra'; await fs.copy(source, destination); ``` ### 4. Git Operations ```javascript // Batch git operations await git.add(file).commit(message).push(); // Use shallow clones when appropriate await git.clone(repo, { depth: 1 }); ``` --- ## Security Best Practices ### 1. Credential Management ```javascript // ✅ GOOD: Load from .env const apiKey = process.env.PLATFORM_API_KEY; // ❌ BAD: Hardcoded credentials const apiKey = 'sk-1234567890abcdef'; // ✅ GOOD: Validate before use if (!apiKey) { throw new Error('API key required. Run /myai-configure'); } ``` ### 2. API Key Redaction ```javascript // Utility function to redact sensitive data in logs function redactApiKey(key) { if (!key || key.length < 8) return '***'; return `${key.slice(0, 4)}...${key.slice(-4)}`; } console.log(`Using API key: ${redactApiKey(apiKey)}`); // Output: Using API key: sk-1...f3d2 ``` ### 3. Input Validation ```javascript // Validate user inputs function validateUrl(url) { try { new URL(url); return true; } catch { throw new Error('Invalid URL format'); } } // Sanitize file paths function sanitizePath(filePath) { // Prevent directory traversal if (filePath.includes('..')) { throw new Error('Invalid file path'); } return path.resolve(filePath); } ``` ### 4. Error Handling ```javascript // Don't expose sensitive info in errors try { await api.request('/sensitive-endpoint'); } catch (error) { // ❌ BAD: Exposes API details throw error; // ✅ GOOD: Generic error message throw new Error('API request failed. Check credentials.'); } ``` --- ## Debugging and Troubleshooting ### Debug Mode ```javascript // Enable debug mode via environment variable if (process.env.DEBUG) { console.log('Debug: Request payload', payload); console.log('Debug: API response', response); } ``` ### Logging Utilities ```javascript import chalk from 'chalk'; function logInfo(message) { console.log(chalk.blue('ℹ'), message); } function logSuccess(message) { console.log(chalk.green('✓'), message); } function logWarning(message) { console.log(chalk.yellow('⚠'), message); } function logError(message) { console.error(chalk.red('✗'), message); } ``` ### Common Issues #### Issue: "Authentication failed" ```bash # Verify credentials cat .env | grep PLATFORM # Test connectivity curl -H "Authorization: Bearer $API_KEY" $PLATFORM_URL/api/health # Re-configure /myai-configure ``` #### Issue: "Git operation failed" ```bash # Check git status cd project-path && git status # Verify remote git remote -v # Configure git user git config user.name "Your Name" git config user.email "your-email@example.com" ``` #### Issue: "Module not found" ```bash # Reinstall dependencies npm install # Clear cache npm cache clean --force rm -rf node_modules npm install ``` --- ## Appendix ### A. Environment Variables Reference ```bash # WordPress (API-based) WORDPRESS_URL=https://your-site.com WORDPRESS_USERNAME=your-username WORDPRESS_APP_PASSWORD=xxxx-xxxx-xxxx-xxxx # PayloadCMS (API-based) PAYLOADCMS_URL=https://cms.your-site.com PAYLOADCMS_EMAIL=your-email@example.com PAYLOADCMS_PASSWORD=your-password PAYLOADCMS_API_KEY=your-api-key # Alternative to email/password # Git Configuration (for static sites) GIT_USER_NAME=Your Name GIT_USER_EMAIL=your-email@example.com GIT_REMOTE_URL=origin # Default # Static Site Project Paths (optional) DOCUSAURUS_PROJECT_PATH=./docs MINTLIFY_PROJECT_PATH=./docs ASTRO_PROJECT_PATH=./blog # Coolify Deployment COOLIFY_URL=https://coolify.your-server.com COOLIFY_API_KEY=your-coolify-api-key # Debug Mode DEBUG=true # Enable verbose logging ``` ### B. API Endpoints Reference #### PayloadCMS API ``` POST /api/users/login # Authenticate GET /api # List collections GET /api/{collection} # Get documents GET /api/{collection}/{id} # Get document by ID POST /api/{collection} # Create document PATCH /api/{collection}/{id} # Update document DELETE /api/{collection}/{id} # Delete document POST /api/media # Upload media ``` #### Coolify API ``` GET /api/v1/servers # List servers GET /api/v1/projects # List projects GET /api/v1/applications # List applications POST /api/v1/applications/public # Create application POST /api/v1/deploy?uuid={uuid} # Deploy application GET /api/v1/applications/{uuid} # Get application POST /api/v1/applications/{uuid}/restart # Restart app POST /api/v1/applications/{uuid}/stop # Stop app GET /api/v1/databases # List databases POST /api/v1/databases # Create database ``` ### C. File Format Specifications #### Frontmatter Schema (Universal) ```yaml --- title: "Article Title" # Required for all platforms description: "Brief description" # SEO description date: "2025-10-16" # Publication date (ISO 8601 for Astro) author: "Author Name" # Content author tags: ["tag1", "tag2"] # Content tags status: "draft|published" # Publication status --- ``` #### Platform-Specific Frontmatter **Docusaurus**: ```yaml --- id: "unique-slug" # Document ID sidebar_position: 1 # Sidebar order sidebar_label: "Label" # Sidebar display name --- ``` **Astro**: ```yaml --- pubDate: "2025-10-16T00:00:00Z" # ISO 8601 format (required) draft: false # Boolean draft status heroImage: "/images/hero.jpg" # Featured image --- ``` **Mintlify**: ```yaml --- icon: "rocket" # Icon name from library iconType: "solid" # Icon style --- ``` ### D. Glossary - **Agent**: AI-powered assistant defined in markdown with YAML frontmatter - **API-Based Publishing**: Content publishing via HTTP APIs (WordPress, PayloadCMS) - **CLI**: Command Line Interface - **Coolify**: Self-hosted Platform-as-a-Service (PaaS) for application deployment - **Frontmatter**: YAML metadata at the top of markdown files - **Git-Based Publishing**: Content publishing via file operations and git workflow - **Gutenberg**: WordPress block editor format - **JWT**: JSON Web Token for authentication - **Lexical**: