# PressZone Monorepo - Development Rules

> **CRITICAL**: Follow these rules to avoid breaking the project.

---

## Project Structure (Monorepo)

**Root:** `wp-content/` - This is the monorepo root containing:

### Theme
- `themes/presszone/` - Main PressZone WordPress theme

### Plugins
- `plugins/comments-press-zone/` - Comments system plugin
- `plugins/forum-press-zone/` - Forum plugin
- `plugins/newsletter-press-zone/` - Newsletter plugin
- `plugins/game-press-zone/` - Gamification plugin
- `plugins/artist-press-zone/` - Artist/music store plugin
- `plugins/mce-press-zone/` - Rich text editor plugin
- `plugins/social-press-zone/` - Social feed plugin
- `plugins/wallet-press-zone/` - Virtual currency plugin
- `plugins/whitelabel-press-zone/` - White-label branding plugin

All paths in this document are relative to `wp-content/`.

---

## Standalone Backend Application

**Location:** `press-zone-backend/`

The Press.Zone Backend is a STANDALONE Node.js application that provides translation API services. It is NOT part of any WordPress plugin.

### Architecture
```
press-zone-backend/
├── api/                    # Node.js + Express API server
├── admin-panel/            # React admin dashboard (planned)
├── backup/                 # Database backup scripts
├── nginx/                  # Nginx reverse proxy configs
├── systemd/                # Systemd service files
└── .claude/                # Backend-specific agents & skills
    ├── agents/
    │   └── backend-app-agent.md
    └── skills/backend/
```

### Deployment

The backend is deployed independently from WordPress:
- **API**: https://api.press.zone
- **Admin Panel**: https://admin.translate.press.zone (planned)
- **Production**: Fully containerized Podman Compose stack (PostgreSQL, Redis, API, Worker in bridge network)
- **Translation Engine**: Google Gemini API (`gemini-3-flash-preview`)

### Plugin Integration

WordPress plugins act as CLIENTS to the backend:
- `translate-press-zone` plugin connects to API via REST
- Authentication via API keys
- Webhook callbacks for async translations
- Credit management handled by backend

### Documentation

See `press-zone-backend/README.md` for:
- Setup instructions
- API documentation
- Deployment guide
- Architecture details

---

## Agent Architecture (Decentralized)

### Hierarchy

```
wp-content/
├── .claude/agents/                    # GLOBAL agents (security, compliance)
│   ├── orchestrator.md                # Main orchestrator
│   ├── gemini-orchestrator.md         # Gemini integration
│   ├── wordpress-plugin-security-audit.md  # Security auditor
│   └── plugin-reviewer.md             # Code review standards
│
├── press-zone-backend/.claude/agents/ # Standalone backend agents
├── themes/presszone/.claude/agents/   # Theme-specific agents
├── plugins/comments-press-zone/.claude/agents/
├── plugins/forum-press-zone/.claude/agents/
├── plugins/newsletter-press-zone/.claude/agents/
├── plugins/game-press-zone/.claude/agents/
├── plugins/artist-press-zone/.claude/agents/
├── plugins/mce-press-zone/.claude/agents/
├── plugins/social-press-zone/.claude/agents/
├── plugins/wallet-press-zone/.claude/agents/
└── plugins/whitelabel-press-zone/.claude/agents/
```

### Global Agents (Root `.claude/agents/`)

These agents apply to ALL projects:

| Agent | Purpose |
|-------|---------|
| `orchestrator.md` | Task analysis, delegation, coordination |
| `gemini-orchestrator.md` | Multi-model orchestration |
| `wordpress-plugin-security-audit.md` | Security vulnerability scanning |
| `plugin-reviewer.md` | WordPress.org compliance review |

### Project-Specific Agents

Each project has its own `.claude/agents/` folder with domain experts:

| Agent | Domain |
|-------|--------|
| `admin-panel-expert.md` | Admin Dashboard: UI, settings, unified menu |
| `frontend-php-expert.md` | PHP: Templates, WordPress integration |
| `frontend-js-expert.md` | Frontend JS: Interactions, DOM, AJAX |
| `styling-expert.md` | Frontend Styling: CSS/SCSS, responsive design |
| `database-expert.md` | Database: Custom tables, schema, migrations |
| `users-permissions-expert.md` | Identity: Roles, capabilities, permissions |
| `moderation-expert.md` | Moderation: Spam filtering, reports |
| `engagement-expert.md` | Social: Reactions, notifications, engagement |

### Agent Resolution

When delegating, agents are resolved in this order:
1. **Project-local first**: Check `{project}/.claude/agents/{agent}.md`
2. **Global fallback**: Check `wp-content/.claude/agents/{agent}.md`

```
# Example: Working on comments-press-zone
# Agent path: plugins/comments-press-zone/.claude/agents/frontend-js-expert.md

# Example: Security audit (global)
# Agent path: .claude/agents/wordpress-plugin-security-audit.md
```

---

## Default Operating Mode: Orchestrator

**When Claude Code opens this folder, operate as the Orchestrator Agent.**

### Project Context & Source of Truth

**MANDATORY:** Before planning any new feature, layout change, or backend extension:
1. Read `PROJECT-SPECIFICATION.md` for architecture overview
2. Read the project's local `CLAUDE.md` (if exists) for project-specific rules
3. Verify existing functionality to avoid duplication

### Core Principle

**Delegate implementation work to domain expert agents. Do NOT write code directly.**

### How to Delegate

**Before delegating, gather context by reading relevant files.** Then show the EXACT prompt:
```
🤖 Delegating to: [agent-name]
📋 Project: [project-name]
📋 Prompt: [full prompt text]
```

**CRITICAL: The prompt you display MUST BE IDENTICAL to the Task tool's `prompt` parameter.**

**Prompt MUST include:**
1. `Follow {project}/.claude/agents/[agent].md` (first line, required)
2. Task title and goal
3. Full context with code snippets (line numbers)
4. Existing patterns to follow
5. Specific files to modify (full absolute paths)
6. Step-by-step requirements
7. Build commands to run
8. Verification criteria

### Automated Orchestration: `/delegate`

When `/delegate` is invoked, follow the automated 5-step workflow:
1. **Plan**: Create `PLAN.md` with subtasks and agent assignments
2. **Script**: Generate executable bash scripts in `bash/`
3. **Execute**: Run non-conflicting tasks in parallel
4. **Oversee**: Monitor logs, fix failures
5. **Summarize**: Final report

### Handle Directly (No Delegation)
- Questions about codebase structure
- Explaining existing code
- Read-only exploration
- User explicitly says "don't delegate"

### Visual Verification Workflow (REQUIRED for CSS/Visual Issues)

**CRITICAL**: When presented with a visual problem (text color, font, CSS, visibility, layout, styling issues - anything visually verifiable), you MUST use the Playwright verification loop workflow:

**Workflow:**
1. **Create Playwright test script** that:
   - Navigates to affected page(s)
   - Checks computed styles (colors, display, opacity, etc.)
   - Takes before/after screenshots
   - Validates specific CSS properties
   - Reports PASS/FAIL with specific values

2. **Run verification BEFORE fixing** to confirm the issue

3. **Apply the fix** to CSS/SCSS files

4. **Build CSS**: Run project's build command

5. **Run verification AGAIN** to confirm fix worked

6. **If tests still fail**:
   - Revert changes: `git checkout -- [modified-files]`
   - Analyze test output
   - Try different approach
   - Repeat until verification passes

7. **Only commit when ALL tests pass**

**Why this works:**
- Eliminates "looks fixed but isn't" false positives
- Catches CSS specificity issues immediately
- Provides concrete proof of fix
- Prevents committing broken CSS

**Use `/verify` command** to run this workflow automatically.

---

## Global WordPress Standards

These rules apply to ALL projects in the monorepo.

### 1. PHP Conventions

#### Namespaces by Project

| Project | Namespace |
|---------|-----------|
| Theme | `PressZone` |
| Comments | `CommentsPressZone` |
| Forum | `ForumPressZone` |
| Newsletter | `NewsletterPressZone` |
| Game | `GamePressZone` |
| Artist | `ArtistPressZone` |
| MCE | `McePressZone` |
| Social | `SocialPressZone` |
| Wallet | `WalletPressZone` |
| Whitelabel | `WhitelabelPressZone` |

#### Required File Header
```php
<?php
declare(strict_types=1);

namespace ProjectNamespace;

if (!defined('ABSPATH')) {
    exit;
}
```

### 2. Security Rules (MANDATORY)

#### Output Escaping (ALWAYS)
```php
esc_html($text)           // HTML content
esc_attr($value)          // HTML attributes
esc_url($url)             // URLs
wp_kses_post($html)       // Post content with allowed HTML
```

#### Input Sanitization (ALWAYS)
```php
sanitize_text_field(wp_unslash($_POST['field']))
sanitize_textarea_field(wp_unslash($_POST['content']))
sanitize_key($key)
absint($id)
```

#### Nonce Verification
```php
// REST API: X-WP-Nonce header (automatic)

// AJAX
check_ajax_referer('project_action', 'nonce');

// Forms
wp_nonce_field('project_action');
wp_verify_nonce($_POST['_wpnonce'], 'project_action');
```

### 3. Translation (i18n)

Each project has its own text domain:

| Project | Text Domain |
|---------|-------------|
| Theme | `presszone` |
| Comments | `comments-press-zone` |
| Forum | `forum-press-zone` |
| Newsletter | `newsletter-press-zone` |
| Game | `game-press-zone` |
| Artist | `artist-press-zone` |
| MCE | `mce-press-zone` |
| Social | `social-press-zone` |
| Wallet | `wallet-press-zone` |
| Whitelabel | `whitelabel-press-zone` |

```php
// CORRECT - use project's text domain
__('Hello', 'forum-press-zone')
esc_html__('Hello', 'comments-press-zone')
```

### 4. CSS Architecture (ABSOLUTE BAN ON INLINE CSS)

> **CRITICAL**: NEVER use inline CSS for ANY reason. No exceptions.

```php
// ❌ FORBIDDEN
wp_add_inline_style('handle', $css);
<style>.my-class { color: red; }</style>
<div style="margin-top: 10px;">

// ✅ CORRECT
// All styles in SCSS/CSS files
// Use CSS variables for dynamic values
// Use data attributes + CSS for conditional styles
```

### 5. Accessibility Requirements

- Keyboard navigation for all interactive elements
- `aria-label` on icon-only buttons
- `aria-expanded` on dropdown triggers
- Focus trapping in modals
- `@media (prefers-reduced-motion)` for animations

### 6. Common Mistakes to Avoid

| Mistake | Fix |
|---------|-----|
| Missing text domain | Use project's text domain |
| Missing output escaping | Use `esc_html()`, `esc_attr()`, etc. |
| Missing input sanitization | Use `sanitize_*()` functions |
| Direct DB queries | Use project's Query class |
| `innerHTML` with user data | Use `textContent` or `DOMParser` |
| `<table>` for layout | Use CSS Grid/Flexbox |
| `wp_is_mobile()` for layout | Use CSS media queries |
| Hardcoded colors | Use CSS variables |
| `outline: none` | Use visible `:focus-visible` outline |

---

## Project-Specific Configuration

Each project may have additional rules in its local `CLAUDE.md`:

- `themes/presszone/CLAUDE.md` - Theme-specific rules
- `plugins/*/CLAUDE.md` - Plugin-specific rules

**Always check the project's local `CLAUDE.md` before working on it.**

---

## multilingual-press-zone — Mandatory Agent & Skill Loading

**When working on `plugins/multilingual-press-zone/`, you MUST:**

1. **Follow the expert agent**: `plugins/multilingual-press-zone/.claude/agents/expert.md`
2. **Load skills on demand** from `plugins/multilingual-press-zone/.claude/skills/`

All coding rules, anti-patterns, and validation checklists are in the skill files. The expert agent documents which skills to load for each task type.

---

## Build Commands by Project

| Project | Command | Notes |
|---------|---------|-------|
| Theme | `npm run build` | From `themes/presszone/` |
| Comments | `npm run build:css` + `cd admin && npm run build` | From plugin root |
| Forum | `npm run build:css` + `cd admin && npm run build` | From plugin root |
| Newsletter | `npm run build` | From `admin/` |
| Game | `npm run build` | From plugin root |
| Artist | `pnpm build` | Monorepo with packages |
| MCE | `npm run build` | From plugin root |
| Social | `npm run build` | From plugin root |
| Wallet | N/A | No build step |
| Whitelabel | N/A | No build step |

---

## Dark Mode Integration

**Rule: Theme's dark mode is the primary controller.**

- Class name: `body.dark-mode` (unified across all projects)
- Storage: `localStorage('presszone-dark-mode')`
- All plugins defer to theme when theme is loaded
- Event: `presszone:dark-change`

```javascript
// Plugins listen for theme's dark mode changes:
document.addEventListener('presszone:dark-change', (e) => {
    // React to dark mode change
});
```

---

## Key Files Reference

| Purpose | Location |
|---------|----------|
| Monorepo rules | `wp-content/CLAUDE.md` (this file) |
| Project specification | `wp-content/PROJECT-SPECIFICATION.md` |
| Global agents | `wp-content/.claude/agents/` |
| Theme agents | `themes/presszone/.claude/agents/` |
| Plugin agents | `plugins/*/.claude/agents/` |

---

## Trunk Policy (ALL projects — automated, not optional)

- **Green means landed.** No agent reports a delivery gate as "green" or a task as "done" until the work is merged to `origin/master`. Gate pass → land → receipt carrying the landed master SHA, in one transaction.
- **Land on master frequently, by default** — keeps everyone's code fresh and avoids conflicts. Never ask the owner to merge; landing is the terminal step of every change.
- **Sanctioned lander only**: `wp-content/.claude/scripts/ship.sh land <branch> <worktree>`. Raw pushes to master are rejected by the harness land guard (pre-push hook) by design.
- **Unfinished work lands behind the single shared flag `ipz_unreleased`** (international-press-zone `includes/Core/FeatureFlags.php`). One flag for all work-in-progress surfaces, features, and endpoints — never a new per-feature flag.

---

## Self-Learning

Run `/learn-from-mistakes` ONLY after tasks where you:
- Found and fixed DRY violations
- Discovered undocumented conventions
- Fixed bugs caused by anti-patterns
- Found reusable components

**Skip for:** Simple feature additions, routine CRUD, config changes.
