Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

fix(wordpress): resolve /sites blueprint collision; backup-before-delete + archive

Juan Deniscf31b2658e5c
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py
index 50011ce2..8c29f8de 100644
--- a/backend/app/api/wordpress.py
+++ b/backend/app/api/wordpress.py
@@ -57,8 +57,30 @@ def get_site(site_id):
@wordpress_bp.route('/sites/<int:site_id>', methods=['DELETE'])
@jwt_required()
def delete_site(site_id):
- """Delete site and all its environments."""
- result = WordPressService.delete_site(site_id)
+ """Delete site and all its environments (takes a final backup by default)."""
+ # Back up before delete unless explicitly opted out via ?create_backup=false
+ create_backup = request.args.get('create_backup', 'true').lower() != 'false'
+ result = WordPressService.delete_site(site_id, create_backup=create_backup)
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@wordpress_bp.route('/sites/<int:site_id>/archive', methods=['POST'])
+@jwt_required()
+def archive_site(site_id):
+ """Archive a site: stop the stack but keep all data. Reversible."""
+ result = WordPressService.archive_site(site_id)
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@wordpress_bp.route('/sites/<int:site_id>/unarchive', methods=['POST'])
+@jwt_required()
+def unarchive_site(site_id):
+ """Restore a previously archived site."""
+ result = WordPressService.unarchive_site(site_id)
if result.get('success'):
return jsonify(result), 200
return jsonify(result), 400
diff --git a/backend/app/api/wordpress_sites.py b/backend/app/api/wordpress_sites.py
index 8bc82bab..c8a3f47e 100644
--- a/backend/app/api/wordpress_sites.py
+++ b/backend/app/api/wordpress_sites.py
@@ -1,11 +1,14 @@
"""
-WordPress Sites API
-
-API endpoints for WordPress site management including:
-- Site listing and creation
-- Environment management (dev/staging)
-- Database operations (snapshots, sync, clone)
-- Git integration
+WordPress Sites API — environment sync, database snapshots, and Git integration.
+
+ROUTING NOTE: the WordPress "hub" surface (list/create/get/delete sites,
+environment CRUD, plugins, themes, core update) is owned by ``wordpress_bp``
+(``app/api/wordpress.py``) — the Docker-stack model the UI actually creates
+against. This blueprint owns ONLY the routes that do not overlap with it:
+environment sync, database snapshots, clone-db, and Git integration. Both
+blueprints mount at ``/api/v1/wordpress``; their route paths are kept disjoint
+so neither shadows the other (a duplicate rule would be silently unreachable
+because Flask resolves the first-registered match).
"""
from flask import Blueprint, request, jsonify
@@ -14,284 +17,18 @@ import json
from app import db
from app.models.application import Application
-from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob
-from app.services.wordpress_service import WordPressService
+from app.models.wordpress_site import WordPressSite, DatabaseSnapshot
from app.services.wordpress_env_service import WordPressEnvService
from app.services.db_sync_service import DatabaseSyncService
from app.services.git_wordpress_service import GitWordPressService
-from app.services.resource_tier_service import ResourceTierService
wordpress_sites_bp = Blueprint('wordpress_sites', __name__)
# =============================================================================
-# Site Management
-# =============================================================================
-
-@wordpress_sites_bp.route('/sites', methods=['GET'])
-@jwt_required()
-def list_sites():
- """List all WordPress sites."""
- user_id = get_jwt_identity()
- include_envs = request.args.get('include_environments', 'false').lower() == 'true'
-
- # Get all WordPress applications for this user
- sites = WordPressSite.query.join(Application).filter(
- Application.user_id == user_id,
- Application.app_type == 'wordpress'
- ).all()
-
- # Separate production and environment sites
- production_sites = [s for s in sites if s.is_production]
-
- return jsonify({
- 'sites': [s.to_dict(include_environments=include_envs) for s in production_sites],
- 'total': len(production_sites)
- })
-
-
-@wordpress_sites_bp.route('/sites', methods=['POST'])
-@jwt_required()
-def create_site():
- """Create a new WordPress site."""
- user_id = get_jwt_identity()
- data = request.get_json()
-
- # Check resource tier - block creation on lite tier servers
- tier_info = ResourceTierService.get_tier_info()
- if not tier_info['features']['wordpress_create']:
- min_req = ResourceTierService.get_minimum_requirements()
- return jsonify({
- 'error': 'Server resources insufficient for WordPress',
- 'reason': 'wordpress_blocked',
- 'specs': tier_info['specs'],
- 'tier': tier_info['tier'],
- 'minimum_requirements': min_req,
- 'message': (
- f"WordPress site creation requires at least {min_req['cpu_cores']} CPU cores "
- f"and {min_req['ram_gb']}GB RAM. Your server has {tier_info['specs']['cpu_cores']} core(s) "
- f"and {tier_info['specs']['ram_gb']}GB RAM. Consider upgrading your server."
- )
- }), 403
-
- # Validate required fields
- required = ['name', 'domain', 'db_name', 'db_user', 'db_password', 'admin_email']
- missing = [f for f in required if not data.get(f)]
- if missing:
- return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400
-
- try:
- # Create Application record
- app = Application(
- name=data['name'],
- app_type='wordpress',
- status='deploying',
- php_version=data.get('php_version', '8.2'),
- port=data.get('port'),
- root_path=data.get('root_path', f"/var/www/{data['name'].lower().replace(' ', '_')}"),
- environment_type='production',
- user_id=user_id
- )
- db.session.add(app)
- db.session.flush()
-
- # Create WordPressSite record
- site = WordPressSite(
- application_id=app.id,
- admin_email=data['admin_email'],
- admin_user=data.get('admin_user', 'admin'),
- db_name=data['db_name'],
- db_user=data['db_user'],
- db_host=data.get('db_host', 'localhost'),
- db_prefix=data.get('db_prefix', 'wp_'),
- is_production=True
- )
- db.session.add(site)
-
- # Install WordPress
- install_result = WordPressService.install_wordpress(
- path=app.root_path,
- config={
- 'site_url': f"https://{data['domain']}",
- 'site_title': data['name'],
- 'admin_user': data.get('admin_user', 'admin'),
- 'admin_password': data.get('admin_password'),
- 'admin_email': data['admin_email'],
- 'db_name': data['db_name'],
- 'db_user': data['db_user'],
- 'db_password': data['db_password'],
- 'db_host': data.get('db_host', 'localhost'),
- 'db_prefix': data.get('db_prefix', 'wp_')
- }
- )
-
- if not install_result['success']:
- db.session.rollback()
- return jsonify({'error': install_result.get('error', 'Installation failed')}), 500
-
- # Get WordPress version
- wp_info = WordPressService.get_wordpress_info(app.root_path)
- if wp_info:
- site.wp_version = wp_info.get('version')
-
- app.status = 'running'
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'site': site.to_dict(),
- 'admin_password': install_result.get('admin_password')
- }), 201
-
- except Exception as e:
- db.session.rollback()
- return jsonify({'error': str(e)}), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>', methods=['GET'])
-@jwt_required()
-def get_site(site_id):
- """Get a WordPress site by ID."""
- user_id = get_jwt_identity()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- include_envs = request.args.get('include_environments', 'true').lower() == 'true'
- include_snaps = request.args.get('include_snapshots', 'false').lower() == 'true'
-
- result = site.to_dict(include_environments=include_envs, include_snapshots=include_snaps)
-
- # Add WordPress info from WP-CLI
- if site.application and site.application.root_path:
- wp_info = WordPressService.get_wordpress_info(site.application.root_path)
- if wp_info:
- result['wp_info'] = wp_info
-
- return jsonify(result)
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>', methods=['DELETE'])
-@jwt_required()
-def delete_site(site_id):
- """Delete a WordPress site."""
- user_id = get_jwt_identity()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- # Check if this is a production site with environments
- if site.is_production and site.environments:
- return jsonify({
- 'error': 'Cannot delete production site with active environments. Delete environments first.'
- }), 400
-
- try:
- # Use environment service to clean up (handles files, database, etc.)
- result = WordPressEnvService.delete_environment(
- site_id,
- delete_files=True,
- delete_database=True
- )
-
- if not result['success']:
- return jsonify(result), 500
-
- return jsonify({'success': True, 'message': 'Site deleted'})
-
- except Exception as e:
- return jsonify({'error': str(e)}), 500
-
-
-# =============================================================================
-# Environment Management
+# Environment Sync
# =============================================================================
-@wordpress_sites_bp.route('/sites/<int:site_id>/environments', methods=['GET'])
-@jwt_required()
-def list_environments(site_id):
- """List all environments for a production site."""
- user_id = get_jwt_identity()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- result = WordPressEnvService.get_environment_status(site_id)
- return jsonify(result)
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/environments', methods=['POST'])
-@jwt_required()
-def create_environment(site_id):
- """Create a new environment (dev/staging) for a production site."""
- user_id = get_jwt_identity()
- data = request.get_json()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site:
- return jsonify({'error': 'Site not found'}), 404
-
- env_type = data.get('type', 'development')
- if env_type not in ['development', 'staging']:
- return jsonify({'error': 'Invalid environment type'}), 400
-
- result = WordPressEnvService.create_environment(
- production_site_id=site_id,
- env_type=env_type,
- config=data,
- user_id=user_id
- )
-
- if result['success']:
- return jsonify(result), 201
- else:
- return jsonify(result), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/environments/<int:env_id>', methods=['DELETE'])
-@jwt_required()
-def delete_environment(site_id, env_id):
- """Delete an environment."""
- user_id = get_jwt_identity()
-
- # Verify ownership
- env_site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == env_id,
- Application.user_id == user_id
- ).first()
-
- if not env_site:
- return jsonify({'error': 'Environment not found'}), 404
-
- if env_site.production_site_id != site_id:
- return jsonify({'error': 'Environment does not belong to this site'}), 400
-
- result = WordPressEnvService.delete_environment(env_id)
- if result['success']:
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
@wordpress_sites_bp.route('/sites/<int:site_id>/sync', methods=['POST'])
@jwt_required()
def sync_environment(site_id):
@@ -670,148 +407,3 @@ def create_dev_from_commit(site_id):
return jsonify(result), 201
else:
return jsonify(result), 500
-
-
-# =============================================================================
-# WordPress Operations (Plugins, Themes, etc.)
-# =============================================================================
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/plugins', methods=['GET'])
-@jwt_required()
-def get_plugins(site_id):
- """Get installed plugins for a site."""
- user_id = get_jwt_identity()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site or not site.application:
- return jsonify({'error': 'Site not found'}), 404
-
- plugins = WordPressService.get_plugins(site.application.root_path)
- return jsonify({'plugins': plugins})
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/plugins', methods=['POST'])
-@jwt_required()
-def install_plugin(site_id):
- """Install a plugin."""
- user_id = get_jwt_identity()
- data = request.get_json()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site or not site.application:
- return jsonify({'error': 'Site not found'}), 404
-
- plugin = data.get('plugin')
- if not plugin:
- return jsonify({'error': 'plugin is required'}), 400
-
- result = WordPressService.install_plugin(
- site.application.root_path,
- plugin,
- activate=data.get('activate', True)
- )
-
- if result['success']:
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/themes', methods=['GET'])
-@jwt_required()
-def get_themes(site_id):
- """Get installed themes for a site."""
- user_id = get_jwt_identity()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site or not site.application:
- return jsonify({'error': 'Site not found'}), 404
-
- themes = WordPressService.get_themes(site.application.root_path)
- return jsonify({'themes': themes})
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/themes', methods=['POST'])
-@jwt_required()
-def install_theme(site_id):
- """Install a theme."""
- user_id = get_jwt_identity()
- data = request.get_json()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site or not site.application:
- return jsonify({'error': 'Site not found'}), 404
-
- theme = data.get('theme')
- if not theme:
- return jsonify({'error': 'theme is required'}), 400
-
- result = WordPressService.install_theme(
- site.application.root_path,
- theme,
- activate=data.get('activate', False)
- )
-
- if result['success']:
- return jsonify(result)
- else:
- return jsonify(result), 500
-
-
-@wordpress_sites_bp.route('/sites/<int:site_id>/update', methods=['POST'])
-@jwt_required()
-def update_wordpress(site_id):
- """Update WordPress core."""
- user_id = get_jwt_identity()
-
- site = WordPressSite.query.join(Application).filter(
- WordPressSite.id == site_id,
- Application.user_id == user_id
- ).first()
-
- if not site or not site.application:
- return jsonify({'error': 'Site not found'}), 404
-
- # Create snapshot before update
- snapshot_result = DatabaseSyncService.create_snapshot(
- db_name=site.db_name,
- name=f"pre_update_{site.wp_version}",
- tag='pre-update',
- host=site.db_host,
- user=site.db_user,
- password=WordPressEnvService._get_db_password(site)
- )
-
- result = WordPressService.update_wordpress(site.application.root_path)
-
- if result['success']:
- # Update version in database
- wp_info = WordPressService.get_wordpress_info(site.application.root_path)
- if wp_info:
- site.wp_version = wp_info.get('version')
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'message': result.get('message'),
- 'new_version': site.wp_version,
- 'backup_snapshot': snapshot_result.get('snapshot', {}).get('file_path') if snapshot_result.get('success') else None
- })
- else:
- return jsonify(result), 500
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index 6aa14bb8..16c7e3b2 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -1029,11 +1029,16 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
return {'success': False, 'error': str(e)}
@classmethod
- def delete_site(cls, site_id: int) -> Dict:
- """Delete a WordPress site and all its environments."""
+ def delete_site(cls, site_id: int, create_backup: bool = True) -> Dict:
+ """Delete a WordPress site and all its environments.
+
+ By default a final files + database backup of the production site is
+ captured to ``BACKUP_DIR`` before anything is torn down, so a deleted
+ site stays restorable. The backup lives outside the site root, so it
+ survives the filesystem teardown. Pass ``create_backup=False`` to skip.
+ """
from app import db
- from app.models import WordPressSite, Application
- from app.services.docker_service import DockerService
+ from app.models import WordPressSite
site = WordPressSite.query.get(site_id)
if not site:
@@ -1042,6 +1047,18 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
if not site.is_production:
return {'success': False, 'error': 'Can only delete production sites from this endpoint. Use delete_environment for non-production.'}
+ # Capture a final backup BEFORE any destructive action, while the
+ # containers are still up (wp db export runs inside the running stack).
+ backup_info = None
+ if create_backup and site.application and site.application.root_path:
+ backup_result = cls.backup_wordpress(site.application.root_path, include_db=True)
+ if backup_result.get('success'):
+ backup_info = {
+ 'backup_name': backup_result.get('backup_name'),
+ 'backup_path': backup_result.get('backup_path'),
+ 'size': backup_result.get('size'),
+ }
+
try:
# Delete all child environments first
environments = WordPressSite.query.filter_by(production_site_id=site.id).all()
@@ -1052,7 +1069,85 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
cls._teardown_wp_site(site)
db.session.commit()
- return {'success': True, 'message': 'Site and all environments deleted'}
+ return {
+ 'success': True,
+ 'message': 'Site and all environments deleted',
+ 'backup': backup_info,
+ }
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def archive_site(cls, site_id: int) -> Dict:
+ """Archive a site: stop its stack but keep all data (volumes + files).
+
+ Unlike delete, archiving is fully reversible via ``unarchive_site`` —
+ the Docker volumes (database) and files are preserved, and a final
+ backup is captured for safety. Applies to the production site and all
+ of its child environments.
+ """
+ from app import db
+ from app.models import WordPressSite
+ from app.services.docker_service import DockerService
+
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ if not site.is_production:
+ return {'success': False, 'error': 'Only production sites can be archived'}
+
+ # Best-effort safety backup (archiving keeps the data either way).
+ backup_info = None
+ if site.application and site.application.root_path:
+ backup_result = cls.backup_wordpress(site.application.root_path, include_db=True)
+ if backup_result.get('success'):
+ backup_info = backup_result.get('backup_name')
+
+ try:
+ targets = [site] + WordPressSite.query.filter_by(production_site_id=site.id).all()
+ for wp in targets:
+ if (wp.application and wp.application.root_path
+ and os.path.exists(wp.application.root_path)):
+ # Keep volumes so the database/files survive.
+ DockerService.compose_down(wp.application.root_path, volumes=False)
+ if wp.application:
+ wp.application.status = 'archived'
+
+ db.session.commit()
+ return {'success': True, 'message': 'Site archived', 'backup': backup_info}
+
+ except Exception as e:
+ db.session.rollback()
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def unarchive_site(cls, site_id: int) -> Dict:
+ """Bring an archived site back online by starting its stack again."""
+ from app import db
+ from app.models import WordPressSite
+ from app.services.docker_service import DockerService
+
+ site = WordPressSite.query.get(site_id)
+ if not site:
+ return {'success': False, 'error': 'Site not found'}
+
+ if not site.is_production:
+ return {'success': False, 'error': 'Only production sites can be unarchived'}
+
+ try:
+ targets = [site] + WordPressSite.query.filter_by(production_site_id=site.id).all()
+ for wp in targets:
+ if (wp.application and wp.application.root_path
+ and os.path.exists(wp.application.root_path)):
+ DockerService.compose_up(wp.application.root_path)
+ if wp.application:
+ wp.application.status = 'running'
+
+ db.session.commit()
+ return {'success': True, 'message': 'Site restored from archive'}
except Exception as e:
db.session.rollback()
@@ -1176,7 +1271,7 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
return {'success': False, 'error': str(e)}
@classmethod
- def _teardown_wp_site(cls, wp_site) -> None:
+ def _teardown_wp_site(cls, wp_site, remove_volumes: bool = True) -> None:
"""Tear down Docker stack and delete records for a WordPressSite."""
from app import db
from app.services.docker_service import DockerService
@@ -1184,7 +1279,7 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
if wp_site.application and wp_site.application.root_path:
root_path = wp_site.application.root_path
if os.path.exists(root_path):
- DockerService.compose_down(root_path, remove_volumes=True)
+ DockerService.compose_down(root_path, volumes=remove_volumes)
shutil.rmtree(root_path, ignore_errors=True)
if wp_site.application:
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
new file mode 100644
index 00000000..8de06597
--- /dev/null
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -0,0 +1,335 @@
+# ServerKit WordPress Roadmap
+
+*Turning ServerKit's WordPress support from "a folder + a database + an nginx config" into a **managed WordPress platform object**.*
+
+---
+
+## The thesis: integration, not absence
+
+ServerKit already owns an unusually deep set of primitives — a multi-server agent, container-to-container DB cloning with serialized-safe `search-replace`, full Let's Encrypt + DNS-01 wildcard SSL, S3/B2/MinIO offsite backups, a workflow engine, RBAC/workspaces, status pages, notifications — **plus** a genuinely WordPress-aware environment pipeline (prod → staging → dev → multidev, locking, pre-op snapshots, promote/sync, basic-auth).
+
+A capability audit of ~144 managed-WordPress features scored them:
+
+| Status | Count | Meaning |
+|---|---|---|
+| ✅ **Have** | 23 | Built end-to-end (service + API + UI) |
+| 🟡 **Partial** | 71 | **Exists but generic, half-wired, or backend-only** |
+| ❌ **Missing** | 50 | Genuinely absent |
+
+**That 71 is the roadmap.** Most primitives terminate at a generic `Application`/domain/db-name target and were never wired to the `WordPressSite` object. SSL never touches a WP site; offsite backups never touch a WP snapshot; routes that already work server-side (`flush-cache`, `search-replace`, `harden`, per-site health, disk usage) have **no frontend button at all**. The fastest path to a managed feel is *wiring*, not building.
+
+---
+
+## How to read this document
+
+- Tasks are **globally numbered (#1 … #35)** so they're individually addressable — e.g. "do #12".
+- Tasks are grouped into **Phases 0 → D**, ordered so cheap, high-trust wiring lands before net-new systems.
+- Each task lists **Today** (what already exists, with `file:line`), **Do** (the concrete change), **Reuse** (existing services to lean on), and **Done when** (acceptance).
+
+**Effort legend** (single-developer estimate; many are parallelizable):
+
+| Tag | Meaning |
+|---|---|
+| **S** | ≤ 2 hours — mostly wiring |
+| **M** | ~ half a day to a day |
+| **L** | 1–3 days |
+| **XL** | multi-day epic; split before starting |
+
+**Status legend:**
+
+| Mark | Meaning |
+|---|---|
+| 🐛 | Active defect / data-loss risk — fix regardless of roadmap |
+| 🟡 | **Almost there** — the backend or model already exists; this is glue |
+| ❌ | Net-new build |
+
+---
+
+## Target: the "WordPress site object"
+
+The north star. A managed site should expose this button row on every site **and every environment**, all backed by tasks below:
+
+`Open Site` · `WP Admin` · `Auto Login` · `Create Backup` · `Restore` · `Create Staging` · `Push to Live` · `Pull from Live` · `Purge Cache` · `Update` · `Security Scan` · `View Logs` · `Open Database` · `Open Files` · `WP-CLI` · `Manage Domains`
+
+And this consolidated health header: **WP version · PHP version · SSL status · backup status · update count · disk usage · cache status · security warnings · uptime %**.
+
+---
+
+## Phase 0 — Foundational fixes (blocker, do first)
+
+These are bugs the rest of the roadmap stands on. **Estimated cluster: half a day.**
+
+### #1 — Collapse the duplicate `/sites` blueprints `[S]` 🐛 — ✅ Done
+- **Today:** Both `wordpress_bp` and `wordpress_sites_bp` register at `/api/v1/wordpress` (`backend/app/__init__.py:122-123`), and **both** define `GET /sites` and `POST /sites` (`api/wordpress.py:20,28` vs `api/wordpress_sites.py:31,53`) — plus collisions on `GET/DELETE /sites/<id>`, environments, plugins, themes, and `update`. Flask keeps the first-registered rule, so the bare Docker-template create wins and the richer hardening/install create is **dead-routed**. Behavior depends on URL-map ordering.
+- **Do:** Pick one create surface. Move the unique routes from one blueprint, delete the duplicate `/sites` GET+POST, and register a single create path.
+- **Reuse:** `WordPressService.create_site`, `wordpress_sites.py` create body.
+- **Done when:** Exactly one rule answers `POST /api/v1/wordpress/sites`; the UI payload matches it.
+- **Landed:** `wordpress_bp` (the canonical Docker-stack model the live UI creates against with `{name, adminEmail}`) keeps the hub/plugins/themes/update routes; the shadowed duplicates were removed from `wordpress_sites_bp`, which now owns only its unique routes (sync, snapshots, clone-db, git). Verified **0 path+method collisions** across the two blueprints. Provably behavior-preserving since `wordpress_bp` already won every collision. *(Follow-up for #2/#15: the resource-tier gate and snapshot-before-update that lived in the removed legacy create/update should be ported onto the canonical path.)*
+
+### #2 — Make every create path harden + install properly `[S]` 🐛
+- **Today:** The UI path (`pages/WordPress.jsx:43-65` → `services/wordpress.js:9`) sends only `{name, adminEmail}` and runs the container-only template path — **no** wp-config hardening, **no** admin user, **no** SSL. The hardening path (`WordPressService.install_wordpress` → `harden_wordpress`, `services/wordpress_service.py:146,497`) is the one that gets shadowed by #1.
+- **Do:** Route the single create through `install_wordpress` + `harden_wordpress` regardless of standalone vs Docker.
+- **Reuse:** `install_wordpress` (`:146`), `harden_wordpress` (`:497`).
+- **Done when:** A freshly created site has an admin user, `DISALLOW_FILE_EDIT`/`FORCE_SSL_ADMIN`, XML-RPC off, and shuffled salts.
+
+### #3 — Report the real site URL `[S]` 🐛
+- **Today:** `_enrich_site_data` (`services/wordpress_service.py:918-932`) sets `site.url` to `http://localhost:<port>`, so "Open Site"/"Open WP Admin" are wrong for any real domain.
+- **Do:** Derive `url` from the site's primary domain (HTTPS when SSL present), falling back to the port only when no domain is attached.
+- **Reuse:** `application.domains` (already in `to_dict`, `models/wordpress_site.py:158`).
+- **Done when:** "Open Site" lands on the live domain.
+
+### #4 — Backup-before-delete + archive state `[M]` 🐛 — ✅ Done
+- **Today:** `delete_site` → `_teardown_wp_site` (`services/wordpress_service.py:1032,1178`) does `compose_down(remove_volumes=True)` + `rmtree` with **no snapshot**. `delete_environment` is the same. Promote/sync already snapshot-first — the pattern exists, it's just not applied to delete.
+- **Do:** Take a final `DatabaseSnapshot` (+ optional file archive) before teardown. Add an `archived` state that stops the stack but retains a restorable backup.
+- **Reuse:** `db_sync_service` snapshot creation; the snapshot-first pattern from `environment_pipeline_service.py`.
+- **Done when:** Deleting a site leaves a restorable snapshot; an archived site can be brought back.
+- **Landed:** `delete_site(create_backup=True)` now runs the Docker-aware `backup_wordpress()` (full files + DB to `BACKUP_DIR`, outside the site root so it survives `rmtree`) before teardown, and returns the backup info. New reversible `archive_site` / `unarchive_site` (`compose_down(volumes=False)` keeps data → `status='archived'`; `unarchive` restarts → `running`). New routes `POST /sites/<id>/archive`, `/unarchive`, and `DELETE /sites/<id>?create_backup=false` opt-out; frontend `archiveSite`/`unarchiveSite`/`deleteSite({createBackup})` added. **Also fixed a latent bug:** `_teardown_wp_site` passed `compose_down(remove_volumes=…)` but the real param is `volumes=` — the old call would have raised `TypeError`, so delete was effectively broken. *(Follow-up: surface Archive/Delete buttons in a site DangerZone — there is currently no site-delete UI in the WP hub.)*
+
+---
+
+## Phase A — Glue the object together (almost-there wins)
+
+Every task here reuses a service that already exists and is verified present. **This is the highest "managed feel" per hour.** Many run in parallel. **Estimated cluster: 1–2 days, parallelizable.**
+
+### #5 — Surface the orphaned WP-CLI actions in the UI `[S]` 🟡
+- **Today:** Routes exist and work — `harden` (`api/wordpress.py:499`), `search-replace` (`:513`, serialized-safe), `flush-cache` (`:550`) — but `services/wordpress.js` has **no** `harden`/`searchReplace`/`flushCache` methods, so there's no button.
+- **Do:** Add the three `ApiService` methods + controls on `WordPressDetail` (a "Purge Cache" button, a guarded search-replace dialog, a "Harden" action).
+- **Reuse:** `WordPressService.harden_wordpress/search_replace/flush_cache` (`:497,609,626`).
+- **Done when:** Purge/search-replace/harden are one click each.
+
+### #6 — One consolidated site-health card `[M]` 🟡
+- **Today:** `EnvironmentHealthService.check_health` / `get_disk_usage` compute container/MySQL/WP/disk status; frontend stubs `getProjectHealth`/`getEnvironmentHealth`/`getEnvironmentDiskUsage` exist; `components/wordpress/DiskUsageBar.jsx` is **imported nowhere**. `WordPressDetail` OverviewTab shows static text and calls none of them.
+- **Do:** Assemble one health header (WP/PHP version, SSL status [from #8], backup status, update count [from #7], disk usage, cache status [from #22/#23], security warnings) and render `DiskUsageBar`.
+- **Reuse:** `EnvironmentHealthService`, the existing frontend stubs, `DiskUsageBar.jsx`.
+- **Done when:** The site overview shows a live health header instead of static fields.
+
+### #7 — Update badges + Update buttons `[M]` 🟡
+- **Today:** `get_wordpress_info` (`services/wordpress_service.py:216`) computes `update_available`/`latest_version`; the plugin/theme list JSON already carries per-item update flags. The OverviewTab/PluginsTab/ThemesTab parse none of it. `update_themes` service method is missing (only `update_plugins`/`update_wordpress` exist).
+- **Do:** Render a core update badge + per-plugin/theme "Update" buttons; add `update_themes`.
+- **Reuse:** `update_wordpress` (`:256`), `update_plugins` (`:312`), `get_plugins`/`get_themes`.
+- **Done when:** Available updates show a count and update in place.
+
+### #8 — Wire SSL to the WordPress site `[M]` 🟡
+- **Today:** `ssl_service.obtain_certificate` / `advanced_ssl_service.issue_wildcard_cert` / `setup_auto_renewal` take arbitrary domains and are **never** called by `create_site`; the per-env nginx template listens on `:80` only. `WordPressSite` has no `ssl_status`. The SSL-health methods in `services/security.js` (`getSSLHealth`, `issueWildcardCert`, expiry alerts) have **zero** `.jsx` consumers.
+- **Do:** Add a per-site "Enable SSL" action + an `ssl_status` field; call `SSLService` on create/domain-attach; use a wildcard cert for `staging.*`/`dev.*`/multidev subdomains; surface cert grade/expiry on the site's domain panel.
+- **Reuse:** `ssl_service`, `advanced_ssl_service`, `security.js`.
+- **Done when:** Creating/attaching a domain provisions TLS and the health card shows SSL status.
+
+### #9 — Stop dropping the sanitization profile `[S]` 🟡
+- **Today:** `PromoteModal`/`SyncModal` send `sanitization_profile_id`; `db_sync_service.apply_sanitization_profile` exists — but `api/environment_pipeline.py` / `EnvironmentPipelineService` never resolve the id; only the boolean `options['sanitize']` is honored. The profile (incl. WooCommerce payment-table stripping) is silently ignored.
+- **Do:** Resolve `SanitizationProfile` by id in `promote_database`/`sync_from_production` and pass it to `_transform_dump`.
+- **Reuse:** `apply_sanitization_profile`, `SanitizationProfile` model.
+- **Done when:** A selected profile demonstrably rewrites/strips data on sync.
+
+### #10 — Close the rollback loop on promotions `[M]` 🟡
+- **Today:** `PromotionJob.pre_promotion_snapshot_id` and status `rolled_back` exist; `db_sync_service.restore_snapshot` exists; pre-promotion snapshots are captured on **every** promote — but **nothing ever calls restore** and `rolled_back` is never set. The safety net is captured and never used.
+- **Do:** Add `POST /promotions/<id>/rollback` that restores the linked snapshot and flips status; optionally auto-trigger on failed promote.
+- **Reuse:** `restore_snapshot`, `PromotionJob`.
+- **Done when:** A bad promote can be undone in one click.
+
+### #11 — Push WP snapshots offsite + enforce retention `[M]` 🟡
+- **Today:** `DatabaseSnapshot`s land only in the local `SNAPSHOT_DIR`. `storage_provider_service.upload_file/upload_directory` (S3/B2/MinIO/Wasabi, SSRF-validated, verify-by-MD5) and `backup_service` retention/scheduling/notifications are fully built but bound to the generic `Application` model. `db_sync_service.cleanup_old_snapshots` exists but **no scheduler calls it** and `expires_at` is never set.
+- **Do:** Hand each completed snapshot to `StorageProviderService`; populate `expires_at`; schedule `cleanup_old_snapshots`.
+- **Reuse:** `storage_provider_service`, `backup_service`, the cron scheduler.
+- **Done when:** Snapshots replicate to configured object storage and age out per policy.
+
+### #12 — Deep-link DB, files, and logs from the site `[S]` 🟡
+- **Today:** `QueryRunner.jsx` + `api/databases.py` and the File Manager + host log viewer exist but are reached only by raw DB-name / manual path; none deep-link to a site's `db_name` / docroot / `debug.log`.
+- **Do:** Add "Open Database", "Open Files", and "View Logs" buttons that pass the site's `db_name`/`root_path`.
+- **Reuse:** `QueryRunner`, File Manager, log viewer.
+- **Done when:** Each button opens the right resource pre-scoped to the site.
+
+### #13 — Make push-to-deploy actually deploy WordPress `[M]` 🟡
+- **Today:** `WordPressSite.auto_deploy`/`git_repo_url`/`git_branch`/`last_deploy_commit` are persisted (`connect_repo`) and returned in status, but `auto_deploy` is **never consumed** — inbound git webhooks only deploy generic `Application`s. `git_wordpress_service.rollback_to_commit` and `deploy_from_commit` exist with no route/UI; WP keeps only a single `last_deploy_commit`.
+- **Do:** Route inbound git webhooks to `GitWordPressService.deploy_from_commit` when `auto_deploy` is set; expose a WP deploy history list + rollback button.
+- **Reuse:** `git_wordpress_service`, the existing webhook receiver, the `GitDeployment` history pattern.
+- **Done when:** A push to the tracked branch deploys theme/plugin/code and history is browsable + reversible.
+
+### #14 — Make the WP REST surface API-key reachable `[S]` 🟡
+- **Today:** The `X-API-Key` middleware authenticates only the RBAC decorators, but **all** of `api/wordpress_sites.py` is bare `@jwt_required()` (24 routes), so programmatic automation can't touch WordPress.
+- **Do:** Switch WP routes to the RBAC decorators that honor `g.api_key_user`.
+- **Reuse:** the existing API-key middleware + RBAC decorators.
+- **Done when:** A scoped `sk_` key can drive WP site operations.
+
+---
+
+## Phase B — Lifecycle + login (the platform-object identity)
+
+These are the features that make a user say "this is a managed platform, not a folder." They sit directly on the primitives glued in Phase A. **Estimated cluster: 3–5 days.**
+
+### #15 — True one-click site lifecycle `[L]` ❌
+- **Today:** Create is incoherent (see #1/#2): UI collects only `{name, adminEmail}`; no SSL/PHP/cache options anywhere in the flow.
+- **Do:** A single `WordPressSiteService.create` that orchestrates existing services in sequence — provision DB + admin (`install_wordpress` + `harden_wordpress`), issue SSL (#8), honor a chosen PHP version (#24), optionally enable cache (#22/#23), then register the `WordPressSite`. Expose domain + PHP version + admin + "enable SSL/cache" in `CreateSiteModal`.
+- **Reuse:** everything from Phase 0 + #8.
+- **Done when:** One wizard produces a hardened, TLS'd, admin-ready site on a real domain.
+
+### #16 — Passwordless WP-admin login (the signature feature) `[M]` ❌
+- **Today:** "Open WP Admin" is a dumb `window.open` to `{site.url}/wp-admin`. Grep confirms **zero** login/magic/token/SSO code in the WP API. `create_user` (`:646`) and `reset_password` (`:666`) exist, so managed-admin provisioning is half-done.
+- **Do (no heavy plugin — WP-CLI bridge):**
+ 1. Mint a one-time URL via `wp package install wp-cli/login-command` then `wp login create <user> --url-only` (or a ~30-line mu-plugin validating an HMAC nonce).
+ 2. Backend route resolves the managed admin tied to the operator's JWT email (create one via `create_user` if absent).
+ 3. Write a `wordpress.admin_login` `AuditLog` entry (the generic `AuditLog` already exists).
+ 4. Resolve a relocated login slug via `wp eval 'echo wp_login_url();'` instead of hardcoding `/wp-admin`.
+ 5. Add `auto_login_enabled` + a per-site permitted-users check.
+- **Reuse:** `wordpress_service.wp_cli` (`:61-143`), `create_user`/`reset_password`, `AuditLog`, panel RBAC.
+- **Done when:** "Auto Login" drops a permitted operator straight into `wp-admin`, logged, with no stored WP password.
+
+### #17 — Existing-site import `[M]` ❌
+- **Today:** No import path exists — only blank create or prod→child-env clone.
+- **Do:** Accept a `wp-content`/full-site zip + `.sql` dump (or an SFTP pull), provision DB + files, run the serialized-safe `search-replace` for the new URL, and register a `WordPressSite`.
+- **Reuse:** `db_sync_service` search-replace/clone, `_copy_wordpress_files`, `install_wordpress`, `ftp_service`.
+- **Done when:** An exported site comes up running on a new domain.
+
+### #18 — Clone-to-new-independent-site with fresh credentials `[M]` 🟡
+- **Today:** `create_environment` (`services/wordpress_env_service.py:97-228`) clones files + DB (table-prefix + search-replace) but always links via `production_site_id` and **inherits** the parent's `admin_user`/`admin_email`/credentials (`:165-171`). No "duplicate as a brand-new top-level site".
+- **Do:** Generalize the clone to produce a standalone site and generate **fresh** admin credentials via `create_user`/`reset_password`.
+- **Reuse:** `create_environment` internals, `db_sync_service`.
+- **Done when:** "Clone" yields an independent site with its own credentials.
+
+### #19 — Multisite detection `[S]` 🟡
+- **Today:** `WordPressSite.multisite` is a decorative boolean (`models/wordpress_site.py:25`), never populated from reality.
+- **Do:** Populate it via `wp core is-multisite` during create/health.
+- **Reuse:** `wp_cli`.
+- **Done when:** The flag reflects the actual install.
+
+### #20 — Site labels / tags (agency organization) `[S]` ❌
+- **Today:** No tags/labels/client/group field on `WordPressSite`; UI renders no chips.
+- **Do:** Add a `tags` (and optional `client`/`group`) field + UI chips + filtering on the sites list.
+- **Reuse:** `WordPressSite.to_dict`, `WordPressSiteCard.jsx`.
+- **Done when:** Sites can be tagged and filtered.
+
+### #21 — Temporary preview URL before DNS is pointed `[M]` ❌
+- **Today:** `EnvironmentDomainService.generate_domain` only emits real subdomains or a `.localhost` fallback; the env nginx template listens on `:80` only. No preview hostname scheme.
+- **Do:** Add a wildcard/preview hostname (e.g. `<site>.preview.<panel-domain>` or a `*.sslip.io`-style scheme) with auto TLS so a site is reachable and verifiable pre-DNS.
+- **Reuse:** `environment_domain_service`, wildcard SSL (#8).
+- **Done when:** Every new site gets a working HTTPS preview link immediately.
+
+---
+
+## Phase C — WordPress-aware performance & observability
+
+The headline value of a managed platform, and the most net-new — but it leans on existing nginx/cache/health/metrics/notification primitives. **Estimated cluster: 4–7 days.**
+
+### #22 — Page cache with WP-aware skip rules `[L]` ❌
+- **Today:** `nginx_advanced_service` can emit `proxy_cache_path`/`proxy_cache`/`proxy_cache_bypass` zones with config-test + diff, but the WP location template (`services/nginx_service.py:215-237`) has **no** cache and the WP UI has no cache controls.
+- **Do:** Add `fastcgi_cache`/`proxy_cache` to the per-site vhost with skip rules (`wp-admin`/`wp-login`/preview, auth/cart/checkout cookies, query strings) + a single-URL purge action wired to the existing `flush-cache` (#5).
+- **Reuse:** `nginx_advanced_service`, `nginx_service` WP template.
+- **Done when:** Anonymous hits are cached; logged-in/cart paths bypass; purge works.
+
+### #23 — Per-site Redis object cache `[L]` ❌
+- **Today:** Only a blind `wp cache flush` with nothing behind it.
+- **Do:** Add a Redis service to the compose stack (or a shared Redis DB index per env); `wp plugin install redis-cache --activate`; write `WP_REDIS_HOST`/`WP_REDIS_DATABASE` into `wp-config`; surface enable/status/flush on the site.
+- **Reuse:** `wp_cli`, `wordpress.yaml` compose template, `flush_cache`.
+- **Done when:** Object cache is enabled and reports a hit ratio.
+
+### #24 — Per-site PHP version & limits panel `[M]` 🟡
+- **Today:** The full PHP-FPM API (`getPHPVersions`/`setDefaultPHPVersion`/`installPHPVersion`/`createPHPPool`/`getPHPPools`/`restartPHPFPM` in `services/system.js`) has **zero** frontend consumers; `php_version` on `Application` is write-once with no update route, and pools are decoupled from the WP model.
+- **Do:** A per-site PHP panel (version + `memory_limit`/upload size/`max_execution_time`/workers) bound to the WP environment + an update-pool/change-version route.
+- **Reuse:** `php_service`, `system.js`.
+- **Done when:** A site's PHP version and limits are editable per environment.
+
+### #25 — Per-site traffic / error / cache analytics `[L]` ❌
+- **Today:** All metrics are host/agent-keyed; API analytics covers only ServerKit's own API. No per-site visits/bandwidth/5xx/404/PHP-fatal.
+- **Do:** An nginx access/error + `wp-content/debug.log` ingest pipeline keyed to each WP vhost → visits, bandwidth, bot %, top URLs, 5xx/404, PHP fatals, slow pages, cache hit ratio.
+- **Reuse:** the existing log-tail / `metrics_history_service` aggregation patterns.
+- **Done when:** The site dashboard shows per-site traffic and error analytics.
+
+### #26 — Per-site uptime + auto-incidents `[M]` 🟡
+- **Today:** Status pages / uptime have no FK to a WP site; components are hand-typed with arbitrary `check_target`; `EnvironmentHealthService` outages don't open incidents.
+- **Do:** Background-schedule `EnvironmentHealthService` checks to accrue per-site uptime %; auto-create a status-page component from a managed site; bridge `health_status` → status component + auto-open incident on outage.
+- **Reuse:** `EnvironmentHealthService`, `status_page_service`, `uptime_service`.
+- **Done when:** A managed site appears on a status page with a real uptime % and auto-incidents.
+
+### #27 — WP-aware alerting `[M]` 🟡
+- **Today:** Multi-channel `notification_service` (email/Slack/Discord/Telegram/webhook) exists; the `WorkflowEventBus` `health_check_failed` hook exists; neither knows about WordPress sites.
+- **Do:** Add WP alert rules (site down / health failed / error spike) routed through `notification_service` via the event bus.
+- **Reuse:** `notification_service`, `WorkflowEventBus`.
+- **Done when:** A site outage or error spike pings the configured channel.
+
+---
+
+## Phase D — Safe updates, security depth, agency scale
+
+Highest-effort, broadest surface — but by now the `WordPressSite` is a first-class object with health, SSL, backups, cache, and an API-key-reachable REST surface, so these bind cleanly. **Estimated cluster: 1–2 weeks, parallelizable.**
+
+### #28 — Plugin/theme/core vulnerability scanning `[L]` ❌
+- **Today:** `get_plugins`/`get_themes` return slug + version; the VulnerabilityTab is OS-only (Lynis). No WP vuln feed.
+- **Do:** Cross-reference slug+version against a public WordPress vulnerability API (e.g. a WPScan/Patchstack-style feed), persist findings per `WordPressSite`, surface in the VulnerabilityTab.
+- **Reuse:** `get_plugins`/`get_themes`, the existing vuln UI shell.
+- **Done when:** Vulnerable plugins/themes are flagged per site with severity.
+
+### #29 — Safe update manager `[L]` 🟡
+- **Today:** Update primitives exist (#7); no history, scheduling, exclusions, staging-first, and pre-update backup is DB-only/core-only.
+- **Do:** Scheduled updates via the cron workflow scheduler + a maintenance-window concept; an exclusion list + update-run records per site; **files + db** pre-update snapshot (not just db); run updates against the staging env via the promote pipeline; auto-rollback on failure using the pre-update snapshot + `restore_snapshot` (#10).
+- **Reuse:** cron scheduler, `db_sync_service` snapshots, promote pipeline, `restore_snapshot`.
+- **Done when:** Updates run on a schedule, staging-first, with backup + auto-rollback and a report.
+
+### #30 — Per-site security depth `[L]` 🟡
+- **Today:** ClamAV + file-integrity scan host paths (`/var/www`, `/home`, `/etc`) and can't reach Docker WP volumes; nothing resolves a site to a scannable docroot; integrity never calls `wp ... verify-checksums`; no `wp-login.php`/`xmlrpc` rate-limit jail.
+- **Do:** Per-site scan-target resolution; file integrity via `wp core/plugin/theme verify-checksums`; a Fail2ban jail/filter (or nginx `limit_req` zone) targeting each site's access log for `wp-login.php`/`xmlrpc.php`; per-site `WP_DEBUG`/`SCRIPT_DEBUG` toggle and WP-Cron list/run/disable.
+- **Reuse:** `security_service` (Fail2ban jails), `wp_cli`, `cron_service`, `nginx_service` WP template.
+- **Done when:** A site can be scanned, checksum-verified, brute-force-protected, and debug-toggled.
+
+### #31 — Selective push UI `[S]` 🟡
+- **Today:** The dump layer already supports table filters / files-only / db-only; `PromoteModal` exposes only coarse code/db/full.
+- **Do:** Expose files-only / db-only / specific-folders / specific-tables selectors in `PromoteModal`.
+- **Reuse:** `db_sync_service` `_transform_dump` filters, `environment_pipeline` promote.
+- **Done when:** A promote can move just selected files/tables.
+
+### #32 — Per-site SFTP `[M]` ❌
+- **Today:** FTP is host-global (`ftp_service`); no per-site SFTP.
+- **Do:** Add SFTP via an sshd `Subsystem`/chroot scoped to the site root, bound to the site object.
+- **Reuse:** `ftp_service` patterns.
+- **Done when:** Each site exposes scoped SFTP credentials.
+
+### #33 — Agency scale (workspaces, RBAC, white-label, reports) `[XL]` 🟡
+- **Today:** No `workspace_id` FK on `Application`/`WordPressSite`/`Server`; permissions are global with no per-site ACL; white-label lives in `localStorage` and never reads `Workspace.logo_url`/`primary_color`.
+- **Do:** Add `workspace_id` FKs + per-site ACL rows + environment-tier RBAC in promote/sync/bulk endpoints; server-side branding scoped to workspace; monthly client reports aggregating uptime/updates/backups/security.
+- **Reuse:** `workspace_service`, `permission_service`, `audit_service`.
+- **Done when:** A site/environment can be scoped to a workspace with per-site roles and branded reports.
+
+### #34 — Horizontal scaling `[XL]` ❌
+- **Today:** `nginx_advanced_service` has load-balancing primitives (round-robin/least-conn/IP-hash) but WP containers are stateful (local uploads, no shared object cache).
+- **Do:** Make WP stateless — shared media (uploads on a shared volume or S3 offload), shared Redis object cache (#23), then nginx `upstream` load balancing across replicas with sticky handling where needed.
+- **Reuse:** `nginx_advanced_service`, #23, `storage_provider_service`.
+- **Done when:** A site can run N replicas behind a balancer with consistent media + cache.
+
+### #35 — WordPress workflow nodes, events & CLI `[L]` 🟡
+- **Today:** The event/webhook + workflow engine can't see a `WordPressSite` — `EVENT_CATALOG` has no WP lifecycle events, WP operations emit nothing, the workflow builder has no WP node types, and there's no `serverkit wp` CLI.
+- **Do:** Emit WP lifecycle events (`backup.completed` / `deploy.failed` / `ssl.renewed` / `update.available`); add WordPress workflow nodes that call existing WP services; add CLI verbs (`serverkit wp backup:create` / `env:clone` / `deploy`) against the now-API-key-reachable routes (#14).
+- **Reuse:** `workflow_engine`, `event_service`, `webhook_service`, the API-key surface.
+- **Done when:** "Every Sunday: snapshot all sites, update staging, notify" can be built as a workflow, and the CLI drives it.
+
+---
+
+## The "almost there" cluster (knock these out first)
+
+These are 🟡 tasks where the backend/model already exists — mostly wiring. Highest payoff, lowest risk, very parallelizable:
+
+> **#3, #5, #6, #7, #9, #10, #11, #12, #13, #14, #19, #24, #26, #27, #31**
+
+Plus the two safety bugs: **#1, #4**.
+
+A focused session could realistically land the Phase 0 bugs (#1–#4) and a chunk of the glue cluster (#5, #9, #10, #12, #14) in a single sitting, since each is an isolated wire-up against a service that already works.
+
+---
+
+## Reference — key WordPress files
+
+| Area | File |
+|---|---|
+| Site object model | `backend/app/models/wordpress_site.py` (`WordPressSite`, `DatabaseSnapshot`, `SyncJob`) |
+| WP-CLI + lifecycle | `backend/app/services/wordpress_service.py` |
+| Environment pipeline | `backend/app/services/environment_pipeline_service.py`, `wordpress_env_service.py` |
+| DB clone / search-replace / sanitize | `backend/app/services/db_sync_service.py` |
+| Env Docker / domains / health | `environment_docker_service.py`, `environment_domain_service.py`, `environment_health_service.py` |
+| WP API routes | `backend/app/api/wordpress.py`, `wordpress_sites.py`, `environment_pipeline.py` |
+| Blueprint registration | `backend/app/__init__.py:118-124` |
+| Frontend hub | `frontend/src/pages/WordPress.jsx`, `WordPressDetail.jsx`, `WordPressProject.jsx`, `WordPressProjects.jsx` |
+| Frontend components | `frontend/src/components/wordpress/` |
+| Frontend API client | `frontend/src/services/wordpress.js`, `services/api/wordpress.js` |
+| Reusable primitives | `ssl_service.py`, `advanced_ssl_service.py`, `storage_provider_service.py`, `backup_service.py`, `nginx_advanced_service.py`, `notification_service.py`, `workflow_engine.py`, `security_service.py` |
+
+---
+
+*Scope: 35 tasks across 5 phases. Phase 0 is a blocker; Phase A is mostly wiring of existing services; Phases B–D are the net-new managed-platform layer. Numbers are stable references — cite them directly (e.g. "do #16").*
diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js
index 884dcf23..fbdfbb8a 100644
--- a/frontend/src/services/wordpress.js
+++ b/frontend/src/services/wordpress.js
@@ -13,8 +13,20 @@ const wordpressApi = {
getSite: (id) => api.request(`${BASE_PATH}/${id}`),
- deleteSite: (id) => api.request(`${BASE_PATH}/${id}`, {
- method: 'DELETE'
+ // Deletes the site and all environments. A final files+DB backup is taken
+ // by default (pass { createBackup: false } to skip).
+ deleteSite: (id, { createBackup = true } = {}) => api.request(
+ `${BASE_PATH}/${id}?create_backup=${createBackup}`,
+ { method: 'DELETE' }
+ ),
+
+ // Stop the stack but keep data + files (reversible via unarchiveSite).
+ archiveSite: (id) => api.request(`${BASE_PATH}/${id}/archive`, {
+ method: 'POST'
+ }),
+
+ unarchiveSite: (id) => api.request(`${BASE_PATH}/${id}/unarchive`, {
+ method: 'POST'
}),
// Environment Management