=== Agent IA WooCommerce | Aria · Rank Press ===
Contributors: rankpress
Tags: woocommerce, subscriptions, dunning, payment recovery, stripe, churn, mrr, ai agent
Requires at least: 5.7
Tested up to: 6.8
Requires PHP: 7.4
Stable tag: 2.1.13
License: GPLv2 or later

A Super AI Agent for WooCommerce covering 6 business roles: refunds, product creation, marketing campaigns, business analytics, strategic recommendations and subscription recovery.

== Description ==

**Stop losing 15-30% of your MRR to failed renewals.**

Aria is a Super AI Agent for WooCommerce that handles 6 business roles from one chat: customer service (refunds, emails, address fixes), product creation (text + AI images), marketing campaigns (coupons, segments), business analytics, strategic recommendations, and 24/7 recovery of failed subscription renewals (WooCommerce Subscriptions) — **without sending a single email to your customers**.

Unlike dunning tools that bombard your customers with "your card failed" emails (and remind them they pay you), Aria works invisibly in the background. Your customers never know there was an issue.

= 5 Recovery Vectors (parallel) =

1. **Silent Retry** — On-hold subs with failed renewal orders → retry via saved payment token
2. **Orphan Renewal** — Subs where the scheduled payment action crashed silently (Kinsta-style bugs, Action Scheduler failures)
3. **Manual→Auto Switch** — Manual-renewal subs that have a valid saved token → flip to auto-renewal
4. **Missing Renewals** — Subs with empty or past next_payment dates and no completed renewal since → force trigger
5. **Decline-Code Router** — Stops wasted retries on hard declines (expired_card, lost_card), reroutes insufficient_funds to next payday, handles 3DS gracefully

= Why "Silent" matters =

Industry data shows every dunning email triggers churn ideation : the customer sees "your card failed" and starts wondering if they still need the service. By recovering invisibly, you avoid that moment entirely. Customer sees their normal debit, business continues as usual.

= Safety mechanisms (all 5 modules share) =

* **Cross-modules lock 1h** — No sub can be touched twice within an hour, preventing double-charges between modules
* **Idempotence guard 24h** — If a renewal order < 24h exists, skip (anti double-charge with native WCS retry framework)
* **"Ever-paid" filter** — Refuses to charge subs whose first payment never succeeded (anti-surprise on dormant new signups)
* **Silent mode global** — `pre_wp_mail` filter blocks all customer emails during mission runs
* **Decline-code awareness** — Marks hard-decline subs to skip useless retries (saves Stripe's 8-attempt cap)

= The Mission Console =

Press one button. Watch Aria :

1. Scan all active subscriptions
2. Identify recovery candidates by vector
3. Route candidates by decline code
4. Attempt silent recoveries with built-in protections
5. Validate results
6. Deliver a Mission Report : cash recovered, subs rescued, MRR uplift, avg confidence

Every action is logged with a confidence score (in v1 these are deterministic heuristics; in v2 they'll be powered by real LLM analysis).

= What v2 will add (roadmap) =

* LLM-powered diagnosis of unknown Action Scheduler errors (Aria reads the logs and explains)
* ML-based retry timing per customer (training on your own recovery data)
* Anomaly detection : "Aria noticed 4× more on-hold subs this week than baseline"
* "Ask Aria" chatbox for open-ended questions about your subscription health

= Made by =

[Rank Press](https://rankpress.com) — makers of the AI Super Agent plugin for WordPress SEO + Content. Recovery Agent is part of our AI Agent family.

== Installation ==

1. Upload the plugin folder to `/wp-content/plugins/`
2. Activate through the 'Plugins' menu
3. Go to **Agent IA** in the WordPress sidebar
4. Hit "Start first scan (read-only)" to see what Aria would do
5. When ready, click "Run mission now" for a real recovery
6. (Optional) Configure mission parameters at **Agent IA → Mission Parameters**

The plugin auto-schedules a daily mission at 03:00 (configurable).

== Frequently Asked Questions ==

= Does this send emails to my customers ? =

**No, never.** That's the entire point. Aria works silently. The plugin actively blocks customer emails during missions via the `pre_wp_mail` filter.

= Will it double-charge my customers ? =

**No.** Three independent safeguards prevent this :
1. Cross-modules lock (1h) — once Aria touches a sub, no module can touch it again for 1h
2. Idempotence guard (24h) — if a renewal order < 24h exists, the sub is skipped
3. WooCommerce's native retry framework — Aria waits for it to finish before stepping in (default 8 days)

= What if Aria fails to recover a sub ? =

Logged with full context. Aria won't infinite-loop on a hard decline — once a sub is flagged "expired_card" or "lost_card", further silent retries are skipped until you (or your customer) update the payment method.

= Does it require WooCommerce Subscriptions ? =

Yes. WooCommerce Subscriptions is required for full functionality. WooCommerce alone is required as the bare minimum.

= Is it compatible with Stripe ? =

Yes, primary tested with Stripe. Other gateways supporting WooCommerce Subscriptions auto-renewal will also work (Mollie, Bancontact via Stripe, SEPA mandates, etc.).

= Where can I see what Aria did ? =

The dashboard shows :
* **Last 30 days** stats (cash, subs rescued, MRR, avg confidence)
* **All-time** stats
* **Live activity feed** — every action with timestamp, module, result, confidence
* **Mission history** — clickable for full details per mission

== Changelog ==

= 1.0.6 =
* **100 % français** — interface entièrement traduite, jargon technique remplacé par des termes clairs ("dry-run" → "aperçu sans toucher", "live mode" → "mode prélèvement réel", "subs rescued" → "abonnements sauvés", etc.).
* **PIVOT SÉCURITÉ** — la clé Anthropic n'est plus stockée côté client. Toutes les requêtes IA transitent par un proxy hébergé sur app.rankpress.com. Avant, un grep du wp_options dans une fuite SQL exposait la clé centrale ; maintenant impossible.
* **Auto-enrollment silencieux** — à la 1ère visite admin, le plugin génère un secret local 256-bit et s'enroll automatiquement auprès du serveur (avec challenge HMAC pour vérifier le contrôle du domaine). L'utilisateur n'a RIEN à configurer.
* **Signature HMAC sur chaque requête** — timestamp + nonce + body + secret_local. Une license_key volée est inutilisable sans le secret local (qui n'a jamais quitté le site).
* **Nouveau menu "Demander à Aria"** — chat live avec l'IA. Posez vos questions en langage naturel ("Pourquoi le renouvellement #1234 n'est pas passé ?", "Combien d'abonnements actifs j'ai ?"). L'IA consulte vos données via 7 tools strictement en LECTURE SEULE.
* **Côté serveur (rankpress-server)** — nouveau module `agent-ia-recovery` strictement isolé du SEO. Menu admin séparé, tables dédiées (`wp_rpa_server_keys`, `wp_rpa_server_calls`), endpoints distincts, zéro modification de code SEO.

= 1.0.5 =
* Safety: Every install now ships in **safe mode** — `live_mode_unlocked = 0`. Until the user explicitly unlocks live mode after reviewing at least one dry-run, every mission (manual or auto-cron) is silently forced into `dry_run`. This is the single biggest protection against accidental charges by users who install the plugin without reading anything.
* Safety: Hard monetary caps — per-charge (default 500 €) and per-mission cumulative (default 5000 €). Modules skip + log any subscription whose total exceeds the per-charge cap, and the entire mission stops when the cumulative total hits the per-mission cap. Configurable in Settings → Safety caps.
* Safety: Order notes — every successful recovery now writes a private order note to the WooCommerce order ("Recovered silently by Aria — mission #X, module: …, confidence: N%, amount: …"). Permanent audit trail visible in the WooCommerce admin, separate from the rpa_activities table.
* Safety: `manual_to_auto` module is now OFF by default and carries a visible warning in Settings ("Sensitive: customers may have explicitly chosen manual renewal for legitimate reasons — bank transfer, check, etc. — only enable if you understand the consent implications"). This is the only module that could alter a customer's billing choice without notification.
* Feature: Optional AI layer powered by Claude Haiku 4.5 (Anthropic).
  - Auto-detects `RPA_CLAUDE_API_KEY` or `RANKPRESS_CLAUDE_API_KEY` constants in `wp-config.php`. Read-only access — never modifies anything in the Rankpress SEO plugin's config.
  - Diagnoses unknown Stripe decline codes via LLM (cached 30 days per code). Returns a category + action that route through the same safe meta flags as hardcoded codes — the LLM never charges anything directly.
  - Generates a short narrative recap displayed at the top of each Mission Report ("AI" tag on the header). Falls back to the deterministic message if disabled or API unavailable.
  - Toggle in Settings, only shown when an API key is detected. Off by default even when the key is configured.
* Database: New column `ai_narrative TEXT` on `rpa_missions`, populated post-mission by `RPA_LLM_Client::generate_mission_narrative()`.
* UI: Live-mode safety banner on the dashboard with "Unlock live mode" CTA (appears after the first dry-run completes). Toast confirmation on unlock. AI status badge (on / not configured) on the dashboard. Sensitive-module warning card in Settings.
* New REST endpoint: `POST /rpa/v1/unlock-live` (admin only, requires at least one completed dry-run).
* Strict isolation: zero touch to `rankpress-server` and `rankpress-client` (SEO plugin) — all options, hooks, tables prefixed `rpa_*` / `wp_rpa_*`; the only crossover is reading the immutable `RANKPRESS_CLAUDE_API_KEY` constant.

= 1.0.4 =
* UX: New zero-friction dashboard — hero shows the 30-day cash recovered as a big number, plus a projected yearly value. The agent status now reads as "On duty / On a mission / Paused" instead of generic "Active".
* UX: Activity feed and mission history get proper empty states ("No activity yet — your first mission will appear here") instead of an empty list.
* UX: Onboarding is now a single-card, single-button experience. The first scan still runs in read-only mode.
* UX: Toast notifications confirm mission outcomes ("Aria rescued 3 subscriptions, 47.50 € recovered").
* UX: Settings page simplified — 3 essentials (Status / Agent name / Cadence) up front, everything else (aggressiveness, modules, manual cron override) hidden in an "Advanced (power users only)" accordion.
* Feature: Anti-concurrence — a global `rpa_mission_running` lock prevents two missions from running simultaneously (double-click, cron + manual, browser retry). The API returns HTTP 409 and the UI polls for the lock to release.
* Feature: New `/rpa/v1/status` endpoint to let the UI know when a mission is running without re-triggering one.
* Fix: `method_exists()` was used on the global function `wc_get_order_notes`, which always returned false (the fallback decline-code parser never ran on older Stripe setups). Now uses `function_exists()`.
* Fix: Orphan Renewal module checked `function_exists('wcs_get_subscriptions')` (plural) but used `wcs_get_subscription()` (singular) — the check was effectively useless.
* Fix: `get_option( 'rpa_settings' )['…']` could emit a PHP warning if the option wasn't created yet (fresh install before activation hook). Normalized everywhere.
* Fix: Pacing's `apply_cron_schedule()` now respects `auto_mission_enabled`. Previously, after each mission it could re-create the cron even if the user had paused the agent.
* Fix: SQL `LIMIT 200` was hardcoded in Orphan / Missing / Manual→Auto scans, capping large stores at 200 candidates per run even with batch=1000. Now dynamic (× 3 margin on max_per_run, capped at 5000).
* Reliability: Missions now run with `set_time_limit(900)` + `ignore_user_abort(true)` to survive long scans on large stores.
* Housekeeping: `uninstall.php` added — full cleanup (tables, options, cron events, all `rpa_*` transients, decline-code subscription meta) when the user deletes the plugin from WordPress admin.
* i18n: All user-facing UI strings now go through `__()` / `_e()` (text domain: `rankpress-agent-ia`).

= 1.0.3 =
* Feature: Auto-Pacing — Aria now decides the optimal batch size + cron frequency automatically based on the number of eligible subscriptions detected. 5 paces (Standard / Elevated / Accelerated / High throughput / Rescue mode) adapt in real time as the queue grows or shrinks.
* UX: Header now displays Aria's current pace mode with color-coded badge and dynamic tagline ("Your queue is healthy", "Heavy load - running hourly to catch up", etc.)
* UX: Settings page simplified — the technical batch/freq radios are hidden behind a "Manual override (for power users only)" accordion. Default users see one toggle: "Auto-pace by Aria (recommended)".
* Activity feed now logs pace changes ("Aria switched to Accelerated mode") for full transparency.
* Cron auto-reschedules after each mission based on remaining queue size.

= 1.0.2 =
* Feature: Batch size now configurable (50 / 200 / 500 / 1000 subs per module per run). Supports large stores with thousands of stuck subscriptions.
* Feature: Cron frequency now configurable (Daily 03:00 / Twice daily / Hourly). For high-volume stores and post-incident catch-up.
* Helper: `RPA_Database::get_max_per_run()` reads the setting (clamped 1-1000) — used by all 5 modules.
* Helper: `rpa_reschedule_auto_mission()` (re)schedules the cron according to current settings, called on activation + after settings save.

= 1.0.1 =
* Fix: auto-mission toggle now correctly read from nested rpa_settings (the cron was running even when disabled)
* Fix: Silent Mode email blocking IDs hardcoded (the regex-based generation produced double-underscore IDs that didn't match WCS filters → emails could leak)
* Fix: Silent Retry now respects meta flags set by Decline-Code Router (`_rpa_skip_silent_retry`, `_rpa_needs_3ds`, `_rpa_next_retry_at`) → hard declines stop wasting Stripe attempt slots, payday reroutes are honored
* Fix: Missing Renewals activities now logged under the correct module name (before: all attributed to Orphan Renewal, making Missing Renewals stats always 0)
* UX: Stats cards now refresh in-place after a mission (no page reload needed)
* UX: Mission history rows are clickable to reopen a past mission report
* UX: Onboarding dismisses after the dry-run (before: required a real mission)
* UX: Success notice on settings save

= 1.0.0 =
* Initial release
* 5 recovery modules (Silent Retry, Orphan Renewal, Manual→Auto, Missing Renewals, Decline-Code Router)
* Mission Console with animated agent UX
* Mission Report with confidence scores
* Live Activity Feed
* Mission Parameters (aggressiveness, modules, schedule)
* Daily auto-mission at 03:00
* Onboarding dry-run

== Screenshots ==

1. The Mission Console — one button, multi-vector silent recovery
2. Animated mission flow — Aria scans, analyzes, routes, recovers, reports
3. Mission Report with confidence scores and detailed breakdown
4. Live Activity Feed showing every action in real time
5. Mission Parameters — configure aggressiveness, modules, schedule
