=== WPStack TOP Load Monitor ===
Contributors: wpstackonline
Tags: performance, query monitor, debugging, profiler, slow queries, ai
Requires at least: 5.8
Tested up to: 6.6
Requires PHP: 7.4
Stable tag: 1.1.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Developer-grade performance monitor with real-time snapshots, slow query detection, AI-powered insights, anomaly alerts, and an optional AI chat assistant.

== Description ==

WPStack TOP is a developer-grade performance monitor for WordPress. It records request snapshots to a custom database table, evaluates threshold-based alerts, and surfaces live metrics in an admin dashboard, timeline view, slow-query log, history browser, alerts panel, and AI-powered insights.

No external dependencies. No Composer. No build step. Drop in, activate, and go.

= Core Monitoring =

* **Shutdown Snapshots** — Captures CPU-like load, memory delta, query count, slow queries, duplicate queries, request context, and PHP errors at request shutdown with configurable sampling.
* **Custom DB Table** — Stores snapshots in a dedicated table via `dbDelta`; activation is idempotent.
* **Query Interception** — Hooks into WordPress `log_query` filter to capture raw SQL, execution time, and caller stack for slow queries.
* **PHP Error Capture** — Collects runtime notices, warnings, and fatals into the snapshot payload via `set_error_handler` and shutdown callback.

= Live Visibility =

* **Admin Bar Live Indicator** — Polls from an in-memory ring buffer (no DB hit); pill shows load, queries, and memory with gradient state colors.
* **Admin Dashboard** — Real-time metric cards, Chart.js timeline, recent requests feed, alerts panel, slow-queries panel, errors panel, process breakdown panel, and Smart Insights panel.
* **Snapshot Detail Page** — Dedicated admin page rendering full payload with AI summary, timeline waterfall, query breakdown, error stream, and process breakdown.

= AI-Powered Insights (v1.1.0) =

Four AI features run entirely in PHP — no external API needed:

* **Smart Anomaly Alerts** — Builds a rolling baseline from the last 200 snapshots and flags metrics 3+ standard deviations above baseline using z-score analysis. Adapts over time via exponential moving average.
* **N+1 Query Auto-Detection** — Detects duplicate query patterns fired 5+ times from the same caller. Generates table-specific fix recommendations for postmeta, options, terms, users, and posts tables.
* **Plugin Bloat Attribution** — Weighted scoring model (`hook_ms + slow_query_ms × 2 + duplicates × 10`) ranks plugins by performance cost with load percentage and actionable recommendations.
* **Natural-Language Summary** — Rules engine generates plain-English explanations of each snapshot with health classification (good, warning, critical).

= Optional LLM Enhancement =

When you configure a free API key from NVIDIA or OpenRouter, two additional features unlock:

* **Enhanced AI Summary** — Snapshots get a richer, LLM-generated analysis alongside the PHP-native summary with deeper root-cause insights and specific optimization suggestions.
* **AI Chat Assistant** — A floating chat widget on the dashboard where admins can ask questions like "Why is /checkout slow?" or "Which plugin is heaviest?" and get contextual answers based on live performance data.

Both providers use OpenAI-compatible API format:

* **NVIDIA** — [build.nvidia.com](https://build.nvidia.com) (free, default model: `meta/llama-3.1-8b-instruct`)
* **OpenRouter** — [openrouter.ai](https://openrouter.ai) (free tier, default model: `meta-llama/llama-3.1-8b-instruct:free`)

No external calls are made unless you explicitly configure a provider. All PHP-native insights work without any API key.

= Alerting & Analysis =

* **Threshold-Based Alerts** — Configurable thresholds for load, slow query time, query count, duplicate queries, memory, and runtime.
* **Alert Deduplication** — 5-minute cooldown per alert type to prevent spam.
* **Windowed Stats** — 1-minute, 5-minute, and 15-minute buckets with count, average, peak, and p95 aggregates.
* **Slow Query Log** — Identifies queries exceeding threshold with SQL text, execution time, caller function, and caller file.

= Robustness =

* **In-memory Ring Buffer** — Bounded at 32 entries for admin bar polling; zero database queries on the live path.
* **Settings Cache + Transient Fallback** — Settings read from memory; falls back to a 5-minute transient on cache miss.
* **Idempotent Activation** — Re-activation skips migration when tables already exist.
* **Chart.js Local Fallback** — If CDN fails, a local copy is loaded automatically.
* **Security Hardened** — All REST routes and AJAX endpoints require `manage_options` capability and nonce verification.
* **i18n Ready** — All user-facing strings wrapped in translation functions with text domain `wpstack-top`.

= Developer Experience =

* **Modular Architecture** — Separate classes for Monitor, Store, Alerts, Timeline, Insights, LLM, and Admin UI under `src/` with constructor dependency injection.
* **Settings API** — Persistent settings writable via WP admin form or REST API.
* **Integration Test Harness** — 70+ assertion checks covering class instantiation, REST routes, authorization, settings CRUD, rendering, idempotency, ring buffer, nonces, and SRI.
* **REST API** — Full REST API under `wpstack-top/v1` for dashboard data, snapshots, timeline, insights, chat, and settings.

== Frequently Asked Questions ==

= Does WPStack TOP slow down my site? =

The plugin is designed for low overhead. Sampling is configurable (you can capture only a fraction of requests), hook trace depth is adjustable, admin bar uses an in-memory ring buffer, and snapshot flushing is batched.

= Can I use it on a production site? =

Yes. All endpoints require admin capability and nonce verification, settings are sanitized, no external calls are made unless you explicitly configure an AI provider, and sampling can be reduced to minimize overhead.

= What data is sent to the AI provider? =

Only performance metrics: load times, query counts, memory usage, URLs, plugin names, SQL patterns, and alert messages. No passwords, user data, or API keys are included in the AI context.

= Can I disable the AI features? =

Yes. Leave the AI Provider setting as "Disabled" and no external calls will be made. All PHP-native insights (anomaly detection, N+1 detection, plugin scoring, summary) still work without any AI provider.

= How long are snapshots stored? =

By default, 14 days. You can change this in Settings (1-365 days). Old snapshots are automatically purged.

= Is it compatible with WooCommerce? =

Yes. WPStack TOP works with WooCommerce and can attribute query costs to WooCommerce plugins specifically. N+1 detection includes WooCommerce-specific recommendations.

= Does it work with caching plugins? =

Yes. The plugin monitors at the PHP level, so it captures performance regardless of caching layers. Cache operations are also tracked as a monitoring module.

== Screenshots ==

1. **Live Dashboard** — Metric cards, performance chart, recent requests feed, alerts panel, and Smart Insights panel.
2. **Snapshot Detail — AI Summary** — Health badge, plain-English summary, N+1 query patterns, and plugin cost attribution.
3. **Smart Insights Panel** — N+1 query auto-detection with severity badges and plugin cost attribution bars.
4. **AI Chat Assistant** — Floating chat widget where admins ask questions about site performance and get AI-powered answers.
5. **Settings Page** — Performance thresholds, tracking modules, alert configuration, and AI assistant settings.
6. **Admin Bar Indicator** — Live performance pill on the frontend showing load time, query count, and memory usage.
7. **Timeline Waterfall** — Visual timeline of hook executions, plugin loads, and event timing within a request.
8. **Slow Queries Panel** — SQL text, execution time, caller function, and caller file for queries exceeding threshold.
9. **AI Provider Settings** — NVIDIA and OpenRouter configuration with provider dropdown, API key, and model override.
10. **Plugin Cost Attribution** — Weighted scoring bars showing each plugin's performance cost percentage.

== Changelog ==

= 1.1.0 =

* **AI-Powered Insights**: Smart anomaly alerts using z-score statistics against a rolling baseline (last 200 snapshots). Adapts over time via exponential moving average.
* **N+1 Query Auto-Detection**: Detects duplicate query patterns fired 5+ times from the same caller. Generates table-specific fix recommendations for postmeta, options, terms, users, and posts tables.
* **Plugin Bloat Attribution**: Weighted scoring model (`hook_ms + slow_query_ms × 2 + duplicates × 10`) ranks plugins by performance cost with load percentage and recommendations.
* **Natural-Language Summary**: Rules engine generates plain-English explanations of each snapshot with health classification (good, warning, critical).
* **LLM Integration**: Optional AI chat assistant and enhanced summaries via NVIDIA build.nvidia.com or OpenRouter (free tiers). Both use OpenAI-compatible API format.
* **Smart Insights Panel**: Dashboard panel showing N+1 patterns and plugin cost bars with live data from the REST API.
* **AI Summary on Snapshots**: Snapshot detail page now shows health badge, plain-English summary, N+1 patterns, and plugin attribution.
* **AI Chat Widget**: Floating chat widget on dashboard for asking questions about performance data in natural language.
* **AI Assistant Settings**: Provider selection (Disabled / NVIDIA / OpenRouter), API key, and optional model override in Settings.
* **New REST Endpoints**: `GET /insights`, `GET /insights/{request_id}`, `POST /chat`.
* **Performance**: SQL aggregates for stats, request_id column for snapshot lookup, ring buffer for admin bar, hook trace depth setting, throttled expiration.
* **Code Quality**: Inline JS extracted to separate files, i18n wrappers for all UI strings, explicit REST nonce verification, Chart.js local fallback, alert deduplication with 5-minute cooldown.
* **Integration Tests**: 70+ assertions covering all classes, routes, auth, settings, rendering, and new AI features.
* **Documentation**: Comprehensive user guide (GUIDE.md), 10 screenshots from live test site, screenshot capture guidelines.

= 1.0.0 =

* Initial release with dashboard, timeline, slow queries, history, alerts, and settings.
* Admin bar live indicator with state coloring (green, yellow, red).
* REST API endpoints under `wpstack-top/v1`.
* AJAX fallback for environments without REST.
* Custom database table for snapshot storage via `dbDelta`.
* Query interception via `log_query` filter with caller stack capture.
* PHP error capture via `set_error_handler` and shutdown callback.
* Chart.js 4.4.0 loaded via jsdelivr CDN with SRI hash and local fallback.
* Configurable sampling rate, retention, and tracking modules.
* Threshold-based alerts with email notification support.
* Windowed stats: 1m / 5m / 15m buckets with count / avg / peak / p95.
* In-memory ring buffer (bounded at 32) for admin bar polling.
* Settings cache with transient fallback.

== Upgrade Notice ==

= 1.1.0 =

Major update: AI-powered insights (anomaly detection, N+1 query detection, plugin bloat scoring, natural-language summaries) plus optional LLM integration with NVIDIA and OpenRouter free tiers for enhanced AI summaries and a chat assistant. All AI features are opt-in — no external calls unless you configure a provider.

== License ==

WPStack TOP Load Monitor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
