# MyAIDev Method - Technical Architecture Guide

**Version**: 0.3.3
**Target Audience**: Developers, System Architects, Contributors
**Last Updated**: 2026-02-10

## 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. [Skill System](#skill-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 skills** for automated workflows
- **Claude Code integration** via skills

### 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
│   └── mcp/                            # MCP server implementations
│       ├── wordpress-server.js         # WordPress MCP server
│       └── mcp-launcher.js             # MCP lifecycle manager
├── skills/                             # Skill definitions
│   ├── content-writer/SKILL.md    # Content writing skill
│   ├── myaidev-architect/SKILL.md        # SPARC architecture skill
│   ├── myaidev-coder/SKILL.md            # SPARC coding skill
│   ├── myaidev-tester/SKILL.md           # SPARC testing skill
│   ├── myaidev-reviewer/SKILL.md         # SPARC review skill
│   ├── myaidev-documenter/SKILL.md       # SPARC documentation skill
│   ├── wordpress-publisher/SKILL.md    # WordPress publishing skill
│   ├── coolify-deployer/SKILL.md       # Coolify deployment skill
│   └── configure/SKILL.md              # Platform configuration skill
├── 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 skills 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. Skill-Script Duality Pattern

**Problem**: Need both interactive AI skills 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 Skill     │
    │  Entry    │ │   Entry        │
    └───────────┘ └────────────────┘
    CLI execution  Claude Code skill
    npm scripts    Skills
    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);

// skills/payloadcms-publish/SKILL.md - AI skill
// Uses PayloadCMSUtils via Claude Code tool invocation
// Provides conversational interface, error guidance, workflow orchestration
```

### 4. Claude Code Integration Pattern

Following Claude Code best practices with skills-based architecture:

#### Lightweight Skills (<3k tokens)
```markdown
<!-- skills/payloadcms-publish/SKILL.md -->
---
name: payloadcms-publish
description: PayloadCMS publishing skill
version: 2.0.0
token_target: 2800
---

# Concise skill 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 Skill
  ├─> Sub-skill 1 (Deploy App A)
  ├─> Sub-skill 2 (Deploy App B)
  └─> Sub-skill 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 skills and 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
   skills/                (skill definitions)
   src/mcp/               (MCP server files)

2. Copy skills from package
   skills/*/SKILL.md → skills/

3. Generate configuration
   CLAUDE.md with available skills
   .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: 'list', listType: 'number', tag: 'ol', children: [...] }
  list (unordered) → { type: 'list', listType: 'bullet', tag: 'ul', children: [...] }
  code → { type: 'code', language: 'lang', children: [...] }
  blockquote → { type: 'quote', children: [...] }
  hr → { type: 'horizontalrule', version: 1 }
  text → { type: 'text', text: '...', format: 0 }
```

**Note**: As of v0.2.19, list nodes use `type: 'list'` (spec-compliant) instead of `type: 'bullet'/'number'`.

**Inline Formatting** (v0.2.19+):
```javascript
Format Codes (bitwise flags):
  0   → Plain text
  1   → Bold (**text**)
  2   → Italic (*text*)
  3   → Bold + Italic (***text***)
  4   → Strikethrough (~~text~~)
  8   → Underline
  16  → Code (`text`)
  32  → Subscript
  64  → Superscript
  128 → Highlight

Examples:
  **bold**              → { type: 'text', text: 'bold', format: 1 }
  *italic*              → { type: 'text', text: 'italic', format: 2 }
  `code`                → { type: 'text', text: 'code', format: 16 }
  [link](url)           → { type: 'link', url: 'url', children: [...] }
```

**Lexical Validation** (v0.2.19+):

The PayloadCMS utils now include comprehensive validation methods:

```javascript
// Validate complete Lexical structure
const validation = utils.validateLexicalStructure(lexicalJSON, {
  strict: false,        // Warn on unknown node types
  strictFormat: false   // Validate format codes
});

// Returns: { valid: boolean, errors: [], warnings: [] }

// Validate individual format codes
const formatInfo = utils.validateFormatCode(3); // Bold + Italic
// Returns: {
//   valid: true,
//   format: 3,
//   flags: ['BOLD', 'ITALIC'],
//   description: 'BOLD + ITALIC'
// }
```

**Validation Rules**:
- Root must have `type: 'root'` and `children` array
- Headings must have `tag: 'h1'` through `'h6'`
- Lists must have `listType: 'bullet'|'number'|'check'` and `tag: 'ul'|'ol'`
- List children must be `listitem` nodes
- Text nodes must have `text` (string) and `format` (number 0-255)
- Links must have `url` (string) and `children` array
- Format codes must be valid bitwise combinations (0-255)

**Testing Coverage** (v0.2.19+):
- 26 comprehensive conversion tests
- 23 validation method tests
- 9 integration tests with real-world examples
- Performance tested with 100+ paragraph documents
- TECHNICAL_ARCHITECTURE.md compliance verified

### 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                                              │
│    /payloadcms-publish "article.md" --status published       │
└───────────────────────┬──────────────────────────────────────┘
                        │
┌───────────────────────▼──────────────────────────────────────┐
│ 2. Skill/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                                              │
│    /docusaurus-publish "guide.md" --type docs                │
└───────────────────────┬──────────────────────────────────────┘
                        │
┌───────────────────────▼──────────────────────────────────────┐
│ 2. Skill/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                                                 │
│ /coolify-deployer --name myapp --repo https://...           │
└───────────────────────┬──────────────────────────────────────┘
                        │
┌───────────────────────▼──────────────────────────────────────┐
│ Skill/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 skill delegation
Main Skill
  ├─> Database Skill: Deploy PostgreSQL
  │   └─> Returns: DATABASE_URL
  │
  ├─> Backend Skill: Deploy API with DATABASE_URL
  │   └─> Returns: API_URL
  │
  └─> Frontend Skill: 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')
  });
}
```

---

## Skill System

### Two-Tier Skill Strategy

MyAIDev Method employs a **two-tier skill architecture** that balances open community innovation with premium cloud-hosted capabilities.

```
┌─────────────────────────────────────────────────────────────────┐
│                    MyAIDev Skill Ecosystem                       │
│                                                                 │
│  ┌───────────────────────────┐  ┌────────────────────────────┐  │
│  │  TIER 1: Open Source      │  │  TIER 2: Premium Cloud     │  │
│  │  Community Marketplace    │  │  MyAIDev Platform API      │  │
│  │                           │  │                            │  │
│  │  • Free to use            │  │  • Auth token required     │  │
│  │  • Community contributed  │  │  • Cloud-hosted execution  │  │
│  │  • PR-based review        │  │  • API-delivered via       │  │
│  │  • Curated & vetted       │  │    dev.myai1.ai            │  │
│  │  • Local execution        │  │  • Advanced capabilities   │  │
│  │  • SKILL.md installed     │  │  • Managed & maintained    │  │
│  │    to .claude/skills/     │  │    by MyAIDev team         │  │
│  └───────────────────────────┘  └────────────────────────────┘  │
│                                                                 │
│  CLI: addon install <name>      CLI: (authenticated API calls)  │
│  Slash: /find-skills            Slash: (auto-provisioned)       │
└─────────────────────────────────────────────────────────────────┘
```

#### Tier 1: Open Source Community Skills

Open source skills are the foundation of the MyAIDev ecosystem. They are contributed by the community, distributed via the [MyAIDev Marketplace](https://github.com/myaione/myaidev-marketplace), and installed locally as `SKILL.md` files.

| Aspect | Detail |
|--------|--------|
| **Distribution** | `myaidev-marketplace` GitHub repository |
| **Cost** | Free |
| **Contribution** | Anyone via PR-based submission (`addon submit`) |
| **Review process** | Automated CI validation + manual review by maintainers |
| **Security vetting** | Scanned for destructive commands, credential access, dynamic code execution, and malware patterns |
| **Quality curation** | Frontmatter validation, content structure checks, documentation requirements |
| **Execution** | Local — runs inside the user's Claude Code session |
| **Installation** | `addon install <name>` copies `SKILL.md` to `.claude/skills/` |
| **Discovery** | `addon list`, `addon search`, `/find-skills` slash command |

**Security & Quality Pipeline**:
```
Contributor submits PR
  → CI validates (frontmatter, structure, size limits)
  → CI security scan (destructive commands, credential paths, eval/exec, curl|sh)
  → CI checks for binary files and disallowed file types
  → Maintainer reviews code quality, usefulness, and safety
  → Merge triggers webhook → skill ingested to marketplace database
  → Users can install verified skills
```

#### Tier 2: Premium Cloud-Hosted Skills

Premium skills are proprietary capabilities provided by the MyAIDev platform. They run server-side via authenticated API calls and offer advanced functionality not available in the open source tier.

| Aspect | Detail |
|--------|--------|
| **Distribution** | API from `dev.myai1.ai` |
| **Cost** | Premium (subscription or usage-based) |
| **Authentication** | Requires auth token from `dev.myai1.ai` (`myaidev-method login`) |
| **Maintenance** | Managed and maintained by the MyAIDev team |
| **Execution** | Cloud-hosted — processing happens server-side |
| **Capabilities** | Advanced AI pipelines, proprietary integrations, managed infrastructure tools |
| **Updates** | Automatic — always the latest version via API |
| **SLA** | Platform uptime and support guarantees |

**Access Flow**:
```
User authenticates (myaidev-method login)
  → Auth token stored locally (~/.myaidev/auth.json)
  → CLI/skill makes authenticated API call to dev.myai1.ai
  → Platform executes premium capability server-side
  → Results returned to user's session
```

#### Tier Comparison

| Feature | Tier 1 (Open Source) | Tier 2 (Premium Cloud) |
|---------|---------------------|----------------------|
| Cost | Free | Subscription |
| Execution | Local | Cloud-hosted |
| Source | Community | MyAIDev team |
| Updates | Manual reinstall | Automatic via API |
| Offline use | Yes | No (requires network) |
| Customizable | Yes (edit SKILL.md) | No (managed service) |
| Review process | PR-based | Internal QA |
| Support | Community | Platform support |

### Skill Architecture

Skills are markdown files (`SKILL.md`) organized in dedicated directories under `skills/`.

**Skill Definition Structure** (applies to Tier 1 open source skills):
```markdown
<!-- skills/skill-name/SKILL.md -->
---
name: skill-name
description: Brief description
version: 2.0.0
capabilities:
  - Capability 1
  - Capability 2
skill_type: publishing|deployment|administration
token_target: 2800  # Lightweight skill target
---

# Skill Name

**Purpose**: Clear statement of skill'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 skill 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 Skills

#### 1. Content Writer Skill
```yaml
File: skills/content-writer/SKILL.md
Purpose: Generate SEO-optimized content
Capabilities:
  - Research topics
  - Structure content
  - Optimize for SEO
  - Generate markdown files
Token Target: <3k
```

#### 2. WordPress Publisher Skill
```yaml
File: skills/wordpress-publisher/SKILL.md
Purpose: WordPress publishing and administration
Capabilities:
  - Health checks
  - Security scanning
  - Performance analysis
  - Comprehensive reporting
Token Target: <3k
```

#### 3. PayloadCMS Publishing Skill
```yaml
File: skills/payloadcms-publish/SKILL.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 Skill
```yaml
File: skills/docusaurus-publish/SKILL.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 Skill
```yaml
File: skills/mintlify-publish/SKILL.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 Skill
```yaml
File: skills/astro-publish/SKILL.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 Deployer Skill
```yaml
File: skills/coolify-deployer/SKILL.md
Purpose: Deploy applications to Coolify
Patterns:
  - Lightweight: Direct script invocation
  - Extended Thinking: Complex deployment decisions
  - Sub-skill Delegation: Multi-app deployments
Token Target: Adaptive (2k-10k based on complexity)
Capabilities:
  - Application deployment
  - Database provisioning
  - Environment management
  - Monitoring and logging
```

#### 8. SPARC Architecture Skills
```yaml
Files:
  - skills/myaidev-architect/SKILL.md   # Architecture design
  - skills/myaidev-coder/SKILL.md       # Code implementation
  - skills/myaidev-tester/SKILL.md      # Test creation
  - skills/myaidev-reviewer/SKILL.md    # Code review
  - skills/myaidev-documenter/SKILL.md  # Documentation
Purpose: Full SPARC development workflow
```

#### 9. Configure Skill
```yaml
File: skills/configure/SKILL.md
Purpose: Platform configuration and setup
```

### Invoking Skills

Skills are invoked directly by name as Claude Code skills.

**Available Skills**:
1. `/content-writer` → Content creation
2. `/wordpress-publisher` → WordPress publishing
3. `/payloadcms-publish` → PayloadCMS publishing
4. `/docusaurus-publish` → Docusaurus publishing
5. `/mintlify-publish` → Mintlify publishing
6. `/astro-publish` → Astro publishing
7. `/coolify-deployer` → Coolify deployment
8. `/myaidev-architect` → Architecture design
9. `/myaidev-coder` → Code implementation
10. `/myaidev-tester` → Test creation
11. `/myaidev-reviewer` → Code review
12. `/myaidev-documenter` → Documentation
13. `/configure` → Platform configuration

---

## Integration Patterns

### Pattern 1: Claude Code → Skill → Script → Utility

```
User: /payloadcms-publish "article.md"
  │
  ▼
Claude Code: Invokes skill
  │
  ▼
Skill: skills/payloadcms-publish/SKILL.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: Skill-to-Skill Delegation

```
Main Skill: Complex Publishing Workflow
  │
  ├─> Content Writer Skill: Generate content
  │   └─> Markdown file created
  │
  ├─> PayloadCMS Skill: Publish to CMS
  │   └─> CMS entry created
  │
  └─> Docusaurus Skill: Publish to docs
      └─> Documentation updated
```

### Pattern 4: MCP Server Integration

```
Claude Code
  │
  ▼
MCP Protocol
  │
  ▼
WordPress MCP Server (src/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 Skill Definition

```markdown
<!-- skills/newplatform-publish/SKILL.md -->
---
name: newplatform-publish
description: Publish content to NewPlatform
version: 2.0.0
capabilities:
  - Authenticate with NewPlatform
  - Convert markdown
  - Publish content
skill_type: publishing
token_target: 2800
---

# NewPlatform Publishing Skill

**Purpose**: Publish markdown content to NewPlatform.

## Workflow

### Step 1: Configuration Validation
1. Check NEWPLATFORM_URL and NEWPLATFORM_API_KEY
2. If missing → prompt `/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"
Skill: Executes workflow → Reports success with URL
```

## Tool Usage Pattern
```
1. Read(markdown_file)
2. authenticateNewPlatform()
3. publishToNewPlatform()
4. Report success
```
```

#### Step 5: Update .env.example

```bash
# .env.example

# NewPlatform Configuration
NEWPLATFORM_URL=https://api.newplatform.com
NEWPLATFORM_API_KEY=your-api-key-here
```

#### Step 6: Update CLI Init

```javascript
// bin/cli.js - setupClaude() function

const claudeMd = `
## Available Skills

### Publishing Platforms
- \`/wordpress-publisher\` - Publish to WordPress
- \`/payloadcms-publish\` - Publish to PayloadCMS
- \`/newplatform-publish\` - Publish to NewPlatform  // ADD THIS
...
`;
```

#### Step 7: Update Documentation

1. Add section to PUBLISHING_GUIDE.md
2. Update README.md features list
3. Add platform-specific guide if needed

#### Step 8: 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 9: 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 Skill

For skills that don't require new platforms (e.g., workflow orchestration, reporting):

1. **Create Skill Definition**: `skills/new-skill/SKILL.md`
2. **Create Script** (if needed): `src/scripts/new-skill.js`
3. **Update CLAUDE.md**: Add to skills list
4. **Update CLI Init**: Include in welcome message
5. **Test**: Verify skill 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 skills directory', async () => {
  const testDir = await createTestProject();
  await runInit(testDir);
  const skillsDir = path.join(testDir, 'skills');
  assert(fs.existsSync(skillsDir));
});
```

### 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)

- **Lightweight Skills**: Keep skills under 3k tokens
- **Lazy Loading**: Load utility libraries only when needed
- **Caching**: Cache authentication tokens, git state
- **Parallel Execution**: Use sub-skill 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 /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
/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

- **Skill**: AI-powered capability defined in a `SKILL.md` file within a dedicated `skills/` directory
- **API-Based Publishing**: Content publishing via HTTP APIs (WordPress, PayloadCMS)
- **CLI**: Command Line Interface
- **Community Skill**: Tier 1 open source skill contributed via the marketplace PR review process
- **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**: Rich text editor format used by PayloadCMS
- **MCP**: Model Context Protocol for AI tool integration
- **MyAIDev Marketplace**: GitHub-hosted repository for curated open source skill distribution
- **Nixpacks**: Automatic build system used by Coolify
- **Premium Skill**: Tier 2 cloud-hosted skill provided via authenticated API calls to dev.myai1.ai
- **Skill Invocation**: Claude Code skill invoked with `/skill-name`
- **Skill Tier**: Classification of skills as open source (Tier 1) or premium cloud-hosted (Tier 2)
- **Static Site Generator**: Tool that generates static HTML from markdown (Docusaurus, Astro)
- **Sub-skill**: Delegated skill for parallel task execution
- **Token**: Authentication credential or AI context unit
- **Utility Class**: Reusable JavaScript class with core platform logic

---

## Contributing

To contribute to MyAIDev Method:

1. **Fork Repository**: https://github.com/myaione/myaidev-method
2. **Create Feature Branch**: `git checkout -b feature/new-platform`
3. **Follow Patterns**: Use existing utilities as templates
4. **Write Tests**: Add tests for new functionality
5. **Update Docs**: Document new features comprehensively
6. **Submit PR**: Provide clear description of changes

---

## License

MIT License - See LICENSE file for details.

---

## Support

- **GitHub Issues**: https://github.com/myaione/myaidev-method/issues
- **NPM Package**: https://www.npmjs.com/package/myaidev-method
- **Documentation**: See USER_GUIDE.md, PUBLISHING_GUIDE.md

---

**Document Version**: 1.0.0
**Package Version**: 0.2.1
**Last Updated**: 2025-10-16
