=== PagePilot AI ===
Contributors: pagepilot
Tags: cache, performance, pagespeed, optimization, ai
Requires at least: 6.0
Tested up to: 7.1
Requires PHP: 7.4
Stable tag: 1.7.1
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Next-level WordPress caching and optimization with an AI autopilot that diagnoses PageSpeed issues and applies fixes safely.

== Description ==

PagePilot AI is a complete caching and performance plugin with a headline differentiator: an **AI autopilot** that closes the loop between measurement and fixes.

**How the autopilot works**

1. **Measure** — Runs Google PageSpeed Insights (mobile + desktop) on your homepage. A free API key raises the quota; the plugin works without one by reusing the last scan.
2. **Diagnose** — A rule engine maps each failing PSI audit (render-blocking resources, unused CSS/JS, unminified files, missing compression, offscreen images, slow TTFB, font-display, and more) to concrete setting changes, each with a confidence score, expected savings in ms/KB read from PSI, and a risk level. Problems no plugin can fix (huge DOM, third-party weight, HTTP/1.1 hosting) are reported honestly as "needs you or your host" — never hidden, never claimed as fixed.
3. **Plan** — Changes are ordered by expected impact × confidence. Aggressive-risk fixes (like delaying JS) only run when you enable aggressive mode.
4. **Apply safely** — One change at a time: settings are snapshotted, the cache is purged, and the homepage is health-checked (HTTP 200, no PHP fatal markers, complete HTML, TTFB within bounds). Anything unhealthy is **automatically reverted**.
5. **Verify** — PSI runs again and the report shows before/after scores plus per-metric deltas (FCP, LCP, TBT, CLS, Speed Index).
6. **Explain (optional)** — With your own OpenAI-compatible API key, an LLM advisor turns the report into plain-English explanations. The loop works fully without any LLM.
7. **Monitor** — A weekly scan watches for regressions (10+ point mobile drop) and emails you a one-click re-tune link. It never changes anything on its own.

You can also apply or revert each suggested fix individually from the dashboard issues table, and every change is logged.

**Caching & optimization modules**

* Page Cache — `advanced-cache.php` drop-in serving static HTML, smart purge rules, cache preloader
* Asset Optimizer — CSS/JS minify & combine, defer/delay JS, async CSS, critical CSS per template, unused-CSS removal, font-display swap
* Image Optimizer — WebP/AVIF conversion, lazy loading, LCP preload, missing dimensions
* Database Cleaner — revisions, transients, spam cleanup, table optimization, scheduled runs
* Bloat Remover — heartbeat control, emoji/oEmbed/dashicons/RSD cleanup
* CDN & Cloudflare — asset URL rewriting, Cloudflare purge API
* Object Cache — Redis / Memcached drop-in installer
* Browser Cache & Compression — far-future headers, GZIP, .htaccess / nginx rules

**Automation**

* REST API under `pagepilot-ai/v1` (PSI scans, autopilot runs, issues, settings, purge)
* WP-CLI: `wp pagepilot psi run`, `wp pagepilot autopilot run`, `wp pagepilot purge`, `wp pagepilot settings get|set`, `wp pagepilot monitor run`

**Privacy**

No telemetry. No usage tracking. API keys are stored locally in your database and never logged.

== External services ==

PagePilot AI works fully offline except for the features below. Each one only runs when you use or enable it.

* **PagePilot license server** (pagepilot.ai, only after you activate a Pro key) — sends the license key and this site's address on activation, deactivation and once a day to verify the license. [Terms](https://pagepilot.ai/terms), [Privacy](https://pagepilot.ai/privacy).
* **Google PageSpeed Insights API** (AI Autopilot, weekly monitor) — sends the public URL of the page being measured, plus your API key if you set one, to measure performance. Runs when you start an autopilot run or scan, and weekly when the regression monitor is on. [Terms](https://developers.google.com/terms), [Privacy](https://policies.google.com/privacy).
* **WordPress.com mShots** (AI Autopilot visual guard, off by default) — sends the public page URL to get a screenshot before and after each change. [Terms](https://wordpress.com/tos/), [Privacy](https://automattic.com/privacy/).
* **OpenAI-compatible LLM endpoint of your choice** (AI explanations, off by default) — sends scores, issue titles and estimated savings (never page content, keys or personal data) to the endpoint you configure, with your API key. The provider's own terms apply (for the default endpoint: [OpenAI Terms](https://openai.com/policies/terms-of-use), [Privacy](https://openai.com/policies/privacy-policy)).
* **Cloudflare API** (CDN module, only with your API token) — purges the Cloudflare cache and manages one edge-cache rule for your zone. [Terms](https://www.cloudflare.com/terms/), [Privacy](https://www.cloudflare.com/privacypolicy/).
* **WordPress.org APIs** (Hardening watchdog / integrity scan) — sends installed plugin and theme slugs and your WordPress version to check for updates, closed plugins and core file checksums. [Privacy](https://wordpress.org/about/privacy/).
* **WPScan API** (Hardening watchdog, only with your API key) — sends installed plugin/theme slugs and versions to look up known vulnerabilities. [Terms](https://wpscan.com/terms/), [Privacy](https://wpscan.com/privacy/).
* **YouTube thumbnails** (Asset Optimizer lazy YouTube embeds, when enabled) — visitors' browsers load the video thumbnail from i.ytimg.com instead of the full player. [Terms](https://www.youtube.com/t/terms), [Privacy](https://policies.google.com/privacy).

The Server Compatibility and health checks request your own site (loopback) only.

== Installation ==

1. Upload the `pagepilot-ai` folder to `/wp-content/plugins/` and activate.
2. Follow the 3-step setup wizard: pick a profile, optionally add a PageSpeed Insights API key, done.
3. Open PagePilot AI → Dashboard and press **Run AI Autopilot**.

Getting a free PageSpeed Insights API key: Google Cloud Console → create a project → enable the PageSpeed Insights API → create an API key (no billing required for the free quota).

== Frequently Asked Questions ==

= What is free and what needs Pro? =
Free: page cache, browser cache, minification, image lazy loading, bloat remover, resource hints, login throttling, security headers and the guided security check. Pro (license key, PagePilot AI → License): the AI autopilot and monitor, object cache, Cloudflare edge caching, database cleaner, Real User Monitoring, advanced asset and image options, the vulnerability watchdog, integrity monitor, 7G firewall, login whitelist, WP-CLI and the REST API. Your Pro settings are kept if a license lapses.

= Does it work without a PageSpeed API key? =
Yes. Keyless PSI requests are heavily throttled, so the autopilot reuses the last stored scan when a fresh one is refused. A free key is recommended.

= Does it work without an LLM key? =
Yes. The rule engine makes every decision; the LLM only writes plain-English explanations.

= Can the autopilot break my site? =
Every change is applied alone, health-checked, and automatically reverted on failure. Aggressive changes are opt-in. The full change log lets you revert anything manually.

= I use LiteSpeed hosting. Do I need the LiteSpeed Cache plugin? =
No — remove it. PagePilot AI handles page caching itself on LiteSpeed servers (LiteSpeed reads .htaccess, so the browser-cache and firewall rules work too). The Server Compatibility module probes whether the server itself is already serving cached pages and automatically defers PagePilot's page cache only while it is, so there is never double caching. If the LiteSpeed Cache plugin is still active you will see a notice asking you to deactivate it.

= How is this different from other cache plugins? =
Instead of a static list of toggles, PagePilot AI measures your real PageSpeed audits, maps each failing audit to the exact setting that fixes it with an expected saving, applies fixes one at a time with rollback, and proves the result with a before/after report.

== Changelog ==

= 1.7.1 =
* License check no longer revokes Pro when a firewall or CDN returns a non-API response (e.g. a 403 challenge page); it is treated as a temporary outage and the 14-day grace period applies.
* Page cache now purges when a post is unpublished, trashed or deleted, when comments are moderated, and when menus, Customizer settings or terms change. WP_CACHE is only set once the advanced-cache drop-in is in place.
* Combined CSS with "remove unused CSS" is now keyed per page output, so one page's trimmed stylesheet is never served to another.
* Database cleanup schedule now registers reliably and follows schedule changes; Pro modules are cleaned up on deactivation even after a license lapses.
* Hardening: configuration backups get unguessable filenames, the unused-CSS cache no longer grows from 404 URLs, the index advisor never replays SLEEP/BENCHMARK-style queries, the LLM endpoint must use HTTPS (loopback excepted), and uninstall removes WP_CACHE reliably.
* RUM beacon: 200 samples/hour per template and 2,000/hour site-wide (atomic with a persistent object cache); field data needs 20+ samples before it influences the autopilot.
* Login lockout honors a new PPAI_TRUSTED_PROXIES wp-config constant (Cloudflare / reverse proxies), so one attacker behind a shared proxy no longer locks everyone out.
* JS defer no longer defers a script that a non-deferred script depends on, or one carrying inline "before" code.
* New notice when another caching/optimization plugin (WP Rocket, W3 Total Cache, WP Super Cache, WP Fastest Cache, Autoptimize, SiteGround Optimizer, Hummingbird, Breeze) is active. PagePilot never deactivates other plugins.
* Redis password is read from PPAI_REDIS_PASSWORD / WP_REDIS_PASSWORD in wp-config.php when defined, instead of being written into the object-cache drop-in.
* Cached pages that contain nonces expire after at most 10 hours; Cloudflare edge rules escape cookie names and paths; RUM and slow-query cleanups delete in batches; network activation sets up every site on multisite (and new sites later).
* Delay JS no longer breaks block themes: ES modules (WordPress script modules / Interactivity API) are never delayed, inline "after" scripts now run after their delayed parent instead of before it, and the RUM collector is never delayed.
* Uninstall also removes wp-content/cache when nothing else uses it.
* Fixed a "translation loaded too early" notice on WordPress 6.7+ when WP-CLI is used.
* The built-in security self-audit (wp pagepilot security) no longer flags the Redis drop-in's Lua script call as PHP eval.
* Admin: module tabs show which modules are on, clearer enabled/disabled state, no duplicated help text, a calmer dashboard before the first scan, and the privacy summary is collapsible.

= 1.7.0 =
* LiteSpeed server-cache compatibility (new Server Compatibility module): on LiteSpeed hosts PagePilot now detects whether the server itself is already serving cached pages and only defers its own page cache when it actually is. The ground truth is a loopback probe — up to two plain front-end GETs to the home page looking for an `x-litespeed-cache: hit` response header (no cache-busting args or no-cache headers, which LiteSpeed would honor by bypassing its cache). A failed probe (timeout, WP_Error, non-200) reports "unknown" and never triggers a false deferral. When server caching is active, PagePilot removes its advanced-cache drop-in, purges its page-cache files, and stands down the buffer-capture hooks so there is exactly one page cache; when the server cache goes away it reinstalls the drop-in and resumes automatically. Developers can override with the `ppai_force_page_cache` filter. Also detects the LiteSpeed Cache WordPress plugin (constant, class, or active-plugins check) and shows a persistent admin notice asking you to deactivate it — PagePilot never deactivates other plugins itself. The Server Compatibility tab shows server software, plugin status, probe result with timestamp, and a re-run button; everything is audit-logged.
* On LiteSpeed servers without the LiteSpeed Cache plugin, PagePilot runs at full power — no changes needed. The .htaccess-based features (browser cache rules, 7G/8G firewall) already worked on LiteSpeed since it reads .htaccess.

= 1.6.0 =
* Vulnerability watchdog, part 5 — keyed CVE feed (bring your own key): the watchdog can now also check installed plugins, themes, and WordPress core against the WPScan API for published vulnerabilities. You add your own API token (free tier: 25 lookups per day); the feed stays off until a provider and key are configured. A per-scan cap of 20 lookups with in-scan memoization keeps a single pass inside the free quota, and API results are never cached persistently (WPScan's terms forbid caching vulnerability data). Findings gain a "Known vulnerability (keyed CVE feed)" flag with severity, fixed-in version, and CVE references. The tools UI shows feed status plus "Test connection" and key-removal buttons — the stored key is never rendered back into the admin, and provider/key changes are written to the audit log without the key value. Also on CLI: `wp pagepilot hardening cve-feed test`.

= 1.5.1 =
* Critical fix — object-cache drop-ins (Redis and Memcached) were missing `wp_cache_init()`, so enabling the Object Cache module white-screened the site: every request and every wp-cli call fatal'd with "Cannot redeclare wp_cache_add()" because core loaded its default cache API on top of the drop-in. Both templates now define the no-op `wp_cache_init()` that tells core an external cache is in use. Found by the staging end-to-end test before any user was affected.
* Fix — `wp pagepilot hardening security-check fix` was registered as a subcommand of a leaf command, which WP-CLI forbids; any wp-cli invocation with the plugin active fatal'd. `security-check` is now a single leaf command with an internal router (`wp pagepilot hardening security-check [fix <fix-id>]`).

= 1.5.0 =
* Security Check release, part 1 — guided security check (Hardening module): six checks in priority order — file permissions (wp-config.php 600/640, dirs 755, files 644), the "admin" username, the wp_ table prefix (check-only, too risky to automate), default/empty auth salts, WP_DEBUG display left on, and PHP < 8.1. Each failing check that is safe to fix gets a one-click "Fix" button in the tools UI (admin rename via an inline form; salt rotation behind a "logs everyone out" confirm), plus a status-line summary, REST (`hardening/security-check`, `hardening/security-check/fix`) and CLI (`wp pagepilot hardening security-check [fix <id>]`). Every fix is written to the audit log.
* Security Check release, part 2 — opt-in 7G/8G firewall: the public Perishable Press 7G/8G rules (SQLi, XSS, traversal, scanner probes) as a marker-guarded .htaccess block converged on settings save (never per-request), with a ready-to-copy nginx snippet in the tools UI, REST, and CLI (`wp pagepilot hardening firewall-7g <status|on|off|nginx>`). Default off — the rules can false-positive on filter words in article slugs.
* Security Check release, part 3 — AI crawler blocking: one toggle appends Disallow rules for ~35 AI training bots (GPTBot, ClaudeBot, PerplexityBot, Bytespider, CCBot, Google-Extended, anthropic-ai, cohere-ai and more) to robots.txt. Polite request, not enforcement.
* Security Check release, part 4 — login IP whitelist: one IP or IPv4 CIDR per line; whitelisted IPs bypass the login throttle so you can never lock yourself out. Invalid lines are dropped on save.
* Security Check release, part 5 — login hardening extras: generic "Invalid username or password." login errors (stops username harvesting); application-password brute force now counted toward the throttle (REST Basic-auth previously bypassed it — verified gap, now closed); password-reset requests throttled to 5/hour per IP and per username; readme.html denied at the server level; uploads directory listing disabled (Options -Indexes); optional DISABLE_WP_CRON with server-cron guidance; the watchdog now flags inactive plugins/themes with a "delete recommended" nudge.
* AssetOptimizer: static files served through the plugin now send Last-Modified + ETag, answer 304 Not Modified without reading the file, stream large files in chunks instead of loading them into memory, and only serve gzip when the client actually accepts it.
* Every security toggle change (7G firewall, AI crawlers, readme block, uploads noindex, wp-cron, login errors, reset throttling, whitelist) is written to the audit log as a `security_setting` entry — values only, never raw IPs.

= 1.4.0 =
* Safety wave, part 1 — vulnerability watchdog (Hardening module): weekly cron scan of installed plugins and themes flags updates available but not applied, plugins closed on wordpress.org, and abandoned items (no update in 2+ years), all via the keyless wp.org API. Findings table in the tools UI with per-row "Enable auto-updates" (enforced through the auto_update_plugin/theme filters), status-line summary, REST and CLI (`wp pagepilot hardening watchdog scan|list`). Scan completions are written to the audit log.
* Safety wave, part 2 — core integrity monitor (Hardening module): weekly cron plus manual "Run check" compares md5 hashes of wp-admin and wp-includes against the wordpress.org checksums API (wp-content never touched), with a 20s time budget and clean resume-on-next-cron for large installs. Modified/missing files surface in the tools UI and status line, with REST and CLI (`wp pagepilot hardening integrity scan`). Results are written to the audit log.
* Safety wave, part 3 — safe mode panic button: new `ppai_safe_mode` flag short-circuits ALL module hook registration (and the autopilot/monitor/preload cron handlers) while admin, REST, and CLI keep booting. Toggle from the dashboard (nonce-protected), a persistent admin notice with one-click turn-off, CLI `wp pagepilot safe-mode on|off|status`, and a REST endpoint. Every toggle writes to the audit log.
* Safety wave, part 4 — audit log: new `PagePilotAI\Audit_Log` (option-backed ring buffer, 200 entries, newest-first; scalar-only details, IP hashes never raw IPs). Records login blocks/unblocks (with actor), scan completions, and safe-mode toggles.
* Fix: module CLI commands now register as `wp pagepilot <module> <name>` (previously every command in a module collided on `wp pagepilot <module>` and multi-word names like `watchdog scan` never resolved).

= 1.3.1 =
* Hardening: the server-level XML-RPC `.htaccess` rule now converges on settings save (via the settings-save hook) instead of once per request — normal page loads never read `.htaccess`.

= 1.3.0 =
* New Hardening module ("safety system"): login throttling (10 failures/15 min per IP → 1 h block, always expiring, never permanent — with unblock via REST/CLI and a blocked-attempts counter proving it works); XML-RPC control (off / pingbacks-off / on, plus optional marker-guarded Apache .htaccess block and a ready-to-copy nginx snippet so xmlrpc.php never boots PHP); security headers (nosniff, SAMEORIGIN, Referrer-Policy, minimal Permissions-Policy — HSTS as a separate, warned opt-in); disable file editing in wp-admin; hide the WP version (generator tag + asset query strings); block logged-out user enumeration (?author=N and REST /users). Blocking bots is performance: every rejected bot request saves a full WordPress boot.
* Database module: new autoload cleaner — `get_autoload_offenders()` lists the heaviest autoloaded options, one-click "Don't autoload" per row (nonce + confirm gated) with a 14-name hard denylist that can never be touched, and an "Autoloaded options: ~NNN KB" status line. The opt-in auto-cleanup also deletes orphaned postmeta/termmeta/commentmeta rows in small batches.

= 1.2.0 =
* Cloudflare full-page edge caching: new `cf_edge_cache` + `cf_edge_ttl` settings — caches full HTML at Cloudflare's edge (APO-style) via the Cache Rules API, with a cookie-bypass expression for logged-in users and WooCommerce carts, automatic zone detection (REST + CLI `detect-zone`), idempotent apply/remove on module enable/disable, and an "Edge cache" status line.
* Asset optimizer bundle: lazy-render offscreen elements via content-visibility (conservative selector list, filterable, never header/nav/hero); local YouTube facade (maxresdefault thumbnail with hqdefault fallback, click-to-play, zero external JS/cloud); delay-JS modes (interaction / requestIdleCallback idle / timeout) plus auto-tune — bisects the delayed script list (max 3 rounds) to find the script breaking the visual guard and auto-excludes it.
* Media Library "PPAI" column: per-image optimization status ("WebP −68%") — bytes saved are now stored in `_ppai_webp_stats` / `_ppai_single_stats`; cheap, no extra queries per row.
* RUM "Web Vitals" dashboard: p75 LCP/INP/CLS summary with page-URL + template filters and a recent-measurements table, surfacing the data already collected for the autopilot.

= 1.1.4 =
* Single-file mode: replaced originals are now moved to an `uploads/ppai-originals-backup/` folder (web access blocked) instead of deleted, and the pre-replacement metadata is recorded — so conversion is fully reversible. New "Back up originals" setting (default on), new `restore` WP-CLI command (`--id=` or `--all`) and REST `restore` endpoint, "Originals in backup" dashboard status line.

= 1.1.3 =
* New: Image Optimizer "Single-file mode" — each upload is replaced with ONE resized + compressed WebP (longest side capped at a configurable max dimension, default 1920 px) and WordPress stops generating thumbnails entirely. Reclaims the disk space eaten by the 8–10 thumbnails per upload. Bulk conversion applies it to the existing library and reports bytes reclaimed. Safety rules: the original is never deleted unless the WebP was written and verified; animated GIFs are never touched; if the WebP would be larger than an unresized original, the original is kept.
* Autopilot: PageSpeed's "properly size images" audit now suggests single-file mode (standard risk).

= 1.1.2 =
* Fix: the autopilot now auto-enables a module when it applies a fix to it. Previously a step could be stored (e.g. speculation rules) while its module stayed disabled, so the change silently never took effect.
* Fix: WP-CLI registration fatal (`pagepilot` command could not have subcommands) — subcommands now registered explicitly.

= 1.1.1 =
* AI explanations: new "Muse (via local relay)" provider — the plugin submits report findings to a local file-queue relay service (no API key needed by the site owner) and polls every 15 s from wp-admin until the agent answers; OpenAI-compatible provider kept as fallback. Relay URL is loopback-only enforced (SSRF hardening), relay token stored as a password field. "Explain with Muse" button on the Autopilot history page with honest wait-time messaging.
* New `Verifier::patch()` updates stored reports in place (no more duplicate history entries when explanations arrive).

= 1.1.0 =
* Visual regression guard: every autopilot change is now screenshot-verified (mShots) with GD pixel-diff and automatic revert past a configurable threshold.
* New Real User Monitoring module: privacy-first field-data collection (LCP/INP/CLS, sampled, DNT-respecting, no cookies/PII), p75 aggregation per template, field-vs-lab dashboard table; the autopilot suppresses low-confidence churn when real users are happy.
* Per-template autopilot: PageSpeed measured and fixes planned separately for up to 5 URLs (default: home + latest post + latest page); per-URL verification and delta reports; single-URL mode unchanged.
* Database: slow-query logger (fingerprinting, sampled) + EXPLAIN-based AI index recommender (additive indexes only, utf8mb4 prefix math, large-table confirm gate, apply-with-rollback) and MyISAM → InnoDB conversion detection with one-click apply (backup required, one-way). All surfaced on the dashboard with explicit confirm buttons — never auto-applied.
* REST: module routes now honour a route-level `permission_callback` (public RUM beacon endpoint stays rate-limited and strictly validated).

= 1.0.0 =
* Initial release: 8 optimization modules, AI autopilot loop (measure → diagnose → plan → apply → verify → monitor), optional LLM advisor, REST API, WP-CLI, setup wizard.
