# WordPress Admin Scripts

Reusable Node.js utilities for WordPress administration tasks with predictable JSON output for agent processing.

## Overview

The MyAIDev Method package includes scriptable WordPress admin utilities that can be:
- Run directly via `npm run` commands
- Called via `npx myaidev-method` commands
- Used by the `wordpress-admin` skill for automated analysis
- Integrated into CI/CD pipelines for monitoring

## Installation

```bash
npm install myaidev-method
# or
npx myaidev-method@latest init --claude
```

## Configuration

All scripts use WordPress REST API credentials from `.env`:

```bash
WORDPRESS_URL=https://your-site.com
WORDPRESS_USERNAME=admin_username
WORDPRESS_APP_PASSWORD=xxxx xxxx xxxx xxxx
```

Create WordPress Application Password:
1. Go to WordPress Admin → Users → Your Profile
2. Scroll to "Application Passwords"
3. Enter name (e.g., "MyAIDev Scripts") and click "Add New"
4. Copy the generated password to `.env`

## Available Scripts

### 1. Health Check

Comprehensive WordPress site health assessment.

**Usage:**
```bash
# Via npm
npm run wordpress:health-check

# Via npx
npx myaidev-method wordpress:health-check

# With options
npm run wordpress:health-check -- --format text --output health-report.txt
npx myaidev-method wordpress:health-check -- --verbose
```

**Options:**
- `--format <type>` - Output format: `json` (default) or `text`
- `--output <file>` / `-o <file>` - Write output to file
- `--verbose` / `-v` - Show detailed progress
- `--help` / `-h` - Show help

**Checks performed:**
- WordPress version status
- Plugin health and updates
- Content health (posts, media, cleanup needs)
- User security audit
- Performance metrics

**Output Structure (JSON):**
```json
{
  "success": true,
  "timestamp": "2025-10-01T12:00:00.000Z",
  "site": { "name": "...", "url": "..." },
  "overall_health": {
    "score": 85,
    "grade": "B",
    "status": "healthy"
  },
  "checks": [...],
  "summary": {
    "total_checks": 5,
    "passed": 4,
    "warnings": 1,
    "critical": 0
  },
  "recommendations": [...]
}
```

**Exit Codes:**
- `0` - No critical issues
- `1` - Scan error
- `2` - Critical issues found

---

### 2. Security Scan

Security vulnerability detection and user audit.

**Usage:**
```bash
# Via npm
npm run wordpress:security-scan

# Via npx
npx myaidev-method wordpress:security-scan

# With options
npm run wordpress:security-scan -- --detailed --output security-report.json
```

**Options:**
- `--format <type>` - Output format: `json` (default) or `text`
- `--output <file>` / `-o <file>` - Write output to file
- `--verbose` / `-v` - Show detailed progress
- `--detailed` / `-d` - Include detailed vulnerability info
- `--help` / `-h` - Show help

**Security checks:**
- User account security audit
- Plugin vulnerability detection
- Outdated software detection
- Common security misconfigurations
- Weak password patterns

**Output Structure (JSON):**
```json
{
  "success": true,
  "timestamp": "2025-10-01T12:00:00.000Z",
  "site": { "name": "...", "url": "..." },
  "security_score": 85,
  "vulnerabilities": [],
  "warnings": [...],
  "summary": {
    "critical_issues": 0,
    "warnings": 2,
    "status": "warning"
  },
  "recommendations": [...]
}
```

**Exit Codes:**
- `0` - No security issues
- `1` - Scan error
- `2` - Warnings found
- `3` - Critical vulnerabilities found

---

### 3. Performance Check

Performance analysis with timing measurements.

**Usage:**
```bash
# Via npm
npm run wordpress:performance-check

# Via npx
npx myaidev-method wordpress:performance-check

# With options
npm run wordpress:performance-check -- --iterations 5 --output perf-report.json
```

**Options:**
- `--format <type>` - Output format: `json` (default) or `text`
- `--output <file>` / `-o <file>` - Write output to file
- `--verbose` / `-v` - Show detailed progress
- `--iterations <n>` / `-i <n>` - Number of timing iterations (default: 3)
- `--help` / `-h` - Show help

**Performance checks:**
- API response time measurement (avg, median, min, max)
- Database content analysis
- Media file optimization opportunities
- Plugin performance impact
- Resource usage patterns

**Output Structure (JSON):**
```json
{
  "success": true,
  "timestamp": "2025-10-01T12:00:00.000Z",
  "site": { "name": "...", "url": "..." },
  "performance_score": 85,
  "timing": {
    "average": 250,
    "median": 245,
    "min": 230,
    "max": 280
  },
  "metrics": {
    "post_count": 150,
    "media_count": 400,
    "plugin_count": 15,
    "active_plugins": 12
  },
  "analysis": {...},
  "recommendations": [...]
}
```

**Exit Codes:**
- `0` - No performance issues
- `1` - Check error
- `2` - Performance warnings

---

### 4. Comprehensive Report

Runs all checks and synthesizes into comprehensive report.

**Usage:**
```bash
# Via npm
npm run wordpress:comprehensive-report

# Via npx
npx myaidev-method wordpress:comprehensive-report

# With options
npm run wordpress:comprehensive-report -- --format markdown --output wp-report.md
npm run wordpress:comprehensive-report -- --save-individual --verbose
```

**Options:**
- `--format <type>` - Output format: `markdown` (default) or `json`
- `--output <file>` / `-o <file>` - Write output to file
- `--verbose` / `-v` - Show detailed progress
- `--save-individual` - Save individual report files as well
- `--health-only` - Only run health check
- `--security-only` - Only run security scan
- `--performance-only` - Only run performance check
- `--help` / `-h` - Show help

**Report includes:**
- Executive summary with all scores
- Critical issues requiring immediate attention
- Warnings and recommendations
- Prioritized action items
- Key metrics and statistics
- Individual check results

**Exit Codes:**
- `0` - No critical issues
- `1` - Error occurred
- `2` - Warnings found
- `3` - Critical issues found

---

## Agent Integration

These scripts are designed to work with the `wordpress-admin` skill:

### Example: WordPress Admin Skill Workflow

```bash
# Agent calls comprehensive report
npx myaidev-method wordpress:comprehensive-report --format json --output /tmp/wp-report.json

# Agent reads and processes JSON output
# Agent generates natural language analysis
# Agent provides actionable recommendations
```

### Skill Usage Pattern

1. **Script Execution**: Skill runs script to get structured data
2. **Data Processing**: Skill parses JSON output
3. **Analysis**: Skill synthesizes findings with context
4. **Recommendations**: Skill provides prioritized actions

### Calling from Skill

In `.claude/skills/wordpress-admin.md`:

```markdown
## Running Health Check

Use the Bash tool to execute the health check script:

```bash
npm run wordpress:health-check -- --format json --output /tmp/health.json
```

Then read the JSON output:

```bash
# Read the report
cat /tmp/health.json
```

Process the structured data and provide comprehensive analysis.
```

---

## Library Usage

You can also use the utilities programmatically:

```javascript
import { WordPressAdminUtils } from 'myaidev-method/src/lib/wordpress-admin-utils.js';
import { ReportSynthesizer } from 'myaidev-method/src/lib/report-synthesizer.js';

// Initialize
const wpUtils = new WordPressAdminUtils({
  url: 'https://your-site.com',
  username: 'admin',
  appPassword: 'xxxx xxxx xxxx xxxx'
});

// Run health check
const healthData = await wpUtils.runHealthCheck();
console.log(healthData);

// Run security scan
const securityData = await wpUtils.runSecurityScan();
console.log(securityData);

// Synthesize multiple reports
const synthesizer = new ReportSynthesizer();
synthesizer.addReport(healthData, 'health');
synthesizer.addReport(securityData, 'security');

const comprehensive = synthesizer.synthesize();
console.log(comprehensive);

// Generate markdown report
const markdown = synthesizer.generateMarkdownReport();
console.log(markdown);
```

---

## CI/CD Integration

### Example: GitHub Actions

```yaml
name: WordPress Health Check

on:
  schedule:
    - cron: '0 0 * * *'  # Daily at midnight

jobs:
  health-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'

      - name: Install dependencies
        run: npm install myaidev-method

      - name: Run health check
        env:
          WORDPRESS_URL: ${{ secrets.WORDPRESS_URL }}
          WORDPRESS_USERNAME: ${{ secrets.WORDPRESS_USERNAME }}
          WORDPRESS_APP_PASSWORD: ${{ secrets.WORDPRESS_APP_PASSWORD }}
        run: |
          npx myaidev-method wordpress:comprehensive-report \
            --format json \
            --output health-report.json

      - name: Upload report
        uses: actions/upload-artifact@v3
        with:
          name: wordpress-health-report
          path: health-report.json

      - name: Check for critical issues
        run: |
          # Exit code 3 = critical issues
          if [ $? -eq 3 ]; then
            echo "::error::Critical WordPress issues found"
            exit 1
          fi
```

---

## Monitoring & Automation

### Scheduled Health Checks

```bash
# Add to crontab for daily checks
0 0 * * * cd /path/to/project && npm run wordpress:comprehensive-report -- --output /var/log/wp-health-$(date +\%Y\%m\%d).json
```

### Alert on Critical Issues

```bash
#!/bin/bash
# health-check-alert.sh

npm run wordpress:health-check -- --format json --output /tmp/health.json
EXIT_CODE=$?

if [ $EXIT_CODE -eq 2 ]; then
  # Send alert (email, Slack, etc.)
  echo "Critical WordPress issues detected!"
  cat /tmp/health.json | mail -s "WordPress Critical Alert" admin@example.com
fi
```

---

## Troubleshooting

### Authentication Errors

```bash
# Test connection
npx myaidev-method wordpress:health-check --verbose

# Common issues:
# - Incorrect application password (no spaces in .env)
# - Wrong username
# - REST API disabled
# - Firewall blocking requests
```

### Permission Errors

Some operations require administrator privileges:
- Plugin management
- User audits
- Theme information

Ensure the WordPress user has admin role.

### Script Not Found

```bash
# Ensure package is installed
npm list myaidev-method

# Reinstall if needed
npm install myaidev-method

# Run from project root
npm run wordpress:health-check
```

---

## Contributing

To add new WordPress admin utilities:

1. Add functions to `src/lib/wordpress-admin-utils.js`
2. Create script in `src/scripts/wordpress-*.js`
3. Add npm script to `package.json`
4. Update this documentation

---

## License

MIT - See LICENSE file for details
