# AuctionForge Changelog

All notable changes to the AuctionForge plugin are documented in this file.

---

## [3.7.0.7] — 2026-05-02

### Identity stitch on bidder login — keyword interest tallying now actually fires

#### Why
The keyword extractor was filling `wp_af_stats_lot_keywords` correctly (197 lots, 734 distinct keywords on Clumber), but `wp_af_user_interests` and `wp_af_user_recent_activity` were both empty — zero rows of any dimension. Same on every site running the new sync streams.

Root cause: identity stitching (visitor_hash → email) only fired in the tracker AJAX when `is_user_logged_in()` returned true. On these auction sites the actual bidders authenticate via BidSpirit, never as `wp_users` — so the WP login check was always false, the stitch table stayed empty, and `maybe_record_lot_view($url, $email, …)` got called with an empty email and bailed out before tallying. Lot views by real bidders never landed in the user-side interest profile.

#### What changed (no auth-path intervention)
The fix piggybacks on the *existing* fire-and-forget tracking AJAX that already runs after a successful BidSpirit login (`afLogIP("login", bidspiritUser)`). It does not touch the BidSpirit auth path itself.

- **`inc/ip-logger.php` `auctionforge_ajax_log_ip()`** — after the existing `auctionforge_user_tracking` insert, if the request carries a `visitor_hash` and the email is valid, calls `AF_Stats_Visitor_Email_Map::record($vh, $email, $ip)`. Wrapped in try/catch so any failure here can never break the existing tracking response.
- **`assets/js/app.js` + `src/js/app.js` `afLogIP()`** — reads `localStorage['af_vid']` (defensively, ITP/private-mode safe) and includes it as `visitor_hash` in the POST body.
- **`inc/stats/class-stats-init.php` `maybe_record_lot_view()`** — when `$email` is empty (the common case for BidSpirit-only bidders) but a `visitor_hash` is present, falls back to `AF_Stats_Visitor_Email_Map::lookup($visitor_hash)`. If a stitch exists, the view tallies; if not, it stays anonymous.

Net effect: a bidder logs in (BidSpirit), the post-login tracker AJAX fires as it always has, and now also writes one extra row into `af_stats_visitor_emails`. From that point onward, every page they view on the same browser/device tallies into `af_user_interests` keyed on their email. The BidSpirit transaction itself is untouched.

---

## [3.7.0.6] — 2026-05-02

### Critical fix — `X-API-Key` header collision with sibling SmoothByte plugins

#### What was wrong
On any site running both AuctionForge and another SmoothByte-stack plugin that also points its updater at `wpdeploy.smoothbyteit.dev` (e.g. `seo-aeo-optimizer`), the second plugin's `http_request_args` filter overwrote AuctionForge's `X-API-Key` header on every outbound API call. Wpdeploy then 401'd because the key it received belonged to a different plugin instance — usually a `seo_aeo_update_api_key` that wpdeploy had no record of.

The symptom was a quiet, total auth failure: `report-health`, `check-updates`, every `sync-*` route, all 401. The watchdog flagged streams as "gone" and updates stopped flowing. Affected sites: any install where the AuctionForge key and the sibling plugin's key happen to differ. Sites where both plugins shared a key were silently safe (the overwrite was a no-op).

#### Fix
`AuctionForge_Auto_Updater::add_download_auth()` now refuses to clobber an existing `X-API-Key` and, for download URLs, only stamps when the URL slug matches our own. That keeps targeted calls from `api_request()` intact regardless of filter ordering, and prevents either plugin from writing its key onto the other's download URL.

The same fix has been applied to `seo-aeo-optimizer` so both ends of the collision are defensive.

---

## [3.7.0.5] — 2026-05-02

### Sync Status admin panel — diagnostic + manual triggers in wp-admin

#### Why
Diagnosing sync issues used to require shell access on the site or piecing together state from wpdeploy's app.log. This release surfaces the same diagnostics inside wp-admin so a site admin (or anyone with `manage_options`) can see exactly what's happening and trigger fixes in one click.

Lives **inside the existing Sync Status menu** (`Lots → Sync Status`) — appended below the existing content as a "Sync Diagnostics & Manual Controls" section, no duplicate menu entry.

#### What's on the panel

**Connection summary** — plugin version, `af_stats_db_version`, wpdeploy server URL, last 8 chars of API key, keepalive install state + auto-reactivation count.

**Sync streams table** — for each of the 10 cron hooks (user-tracking, user-profile, user-interests, user-activity, lots, bids+wins, vulnerabilities, report-health, check-updates, fraud-enforcement):
- Configured schedule
- Last fired timestamp + status colour-coded (green=success, blue=idle/empty, red=error)
- Record count from last run
- Next scheduled run
- Current watermark (where applicable)
- "Fire now" button — clears doing_cron, calls `do_action($hook)` synchronously, shows the result

**One-shot utilities**
- `Test wpdeploy connection` — calls `/api.php/info` with the site's API key
- `Clear stuck cron lock` — deletes the `doing_cron` transient (the classic fix when scheduled events stop firing)
- `Reinstall keepalive` — overwrites `mu-plugins/auctionforge-keepalive.php` from the bundled template
- `Backfill bids from legacy tracking` — replays `last_event_type='bid'` rows from `wp_auctionforge_user_tracking` into `wp_af_bid_events` so the bids-wins stream picks them up. Useful for sites that have years of bid history in the legacy table but nothing in the new queue
- `Run all due events now` — clears doing_cron and fires every `auctionforge_*` cron event whose timestamp is past due, in one go

Live response output panel shows the JSON returned from each action so you can see what just happened without leaving the page.

#### Files Changed
- **Created:** `inc/admin/class-sync-status-page.php`
- **Modified:** `inc/stats/class-stats-init.php` (load + init the panel)
- **Modified:** `admin/view/sync-status.php` (append `AF_Sync_Status_Page::render_panel()` call at the bottom)
- **Modified:** `auctionforge.php` (Version 3.7.0.4 → 3.7.0.5)

#### Verification
Navigate to **Lots → Sync Status** in wp-admin on any 3.7.0.5 site. Scroll past the existing content to the new "Sync Diagnostics & Manual Controls" section. Click "Test wpdeploy connection" — you should see `{"success": true, "auth_type": "site"}`. Click "Fire now" on any stream — the row's last-fired timestamp should refresh after 1–2 seconds.

---

## [3.7.0.4] — 2026-05-02

### Self-healing: failed plugin updates can no longer take a site offline

#### Why
WordPress's plugin updater isn't transactional — when an update fails partway (corrupt unzip, fatal during the new version's `plugins_loaded`, disk pressure, theme conflict, etc.) WP often deactivates the plugin and leaves the site without it. Once AuctionForge is dropped from `active_plugins`, no AF code runs again — including its sync handlers — until someone notices and reactivates manually. On the AuctionForge site fleet, this had quietly happened to ~5 sites we found; almost certainly more on production sites we don't have filesystem access to.

This release ships an autonomous watchdog that lives outside the AuctionForge plugin entirely so it survives even when AF gets knocked out.

#### What changed

**1. Self-installing keepalive (mu-plugin)**
- `inc/keepalive/auctionforge-keepalive.template.php` — a 50-line WordPress must-use plugin. Lives in `wp-content/mu-plugins/`, which WordPress can't deactivate. On every `plugins_loaded` (priority 1, before any regular plugin), it checks: is `auctionforge/auctionforge.php` on disk but missing from `active_plugins`? If yes AND the file has a valid `Plugin Name:` header (smoke check — don't reactivate a corrupt zip), it re-adds AF and `include`s the file in the same request.
- `inc/keepalive/class-keepalive-installer.php` — runs on every successful AF load. Copies the template into `wp-content/mu-plugins/auctionforge-keepalive.php` if missing or version-bumped. Idempotent: compares `KEEPALIVE_VERSION` headers, only writes on change. Refuses to overwrite a foreign mu-plugin (defensive against name collisions). Failure is non-fatal — install errors are recorded in `wp_options` for wpdeploy visibility but never throw.

**Net effect.** Any site that successfully loads AF 3.7.0.4 or later will have the keepalive permanently installed in mu-plugins. From that point forward, even if a future update hard-fails, the keepalive recovers AF on the next pageview without any manual intervention or filesystem access. Crucially: this works on sites we don't own — the keepalive ships inside the AF zip, gets installed during the first successful update, and lives in mu-plugins thereafter.

**2. Forensic markers**
The keepalive writes three options on each recovery:
- `auctionforge_auto_reactivated_at` — most recent recovery timestamp
- `auctionforge_auto_reactivated_count` — total recoveries
- `auctionforge_auto_reactivated_failed_at` — set when the keepalive saw AF on disk but with no Plugin Name header (genuinely corrupt — needs operator attention)

These get picked up by the AF sync streams and surfaced on the wpdeploy dashboard so you can see which sites have been quietly recovering themselves and whether a particular release is failing more than it should.

**3. Companion: post-update-silence alerts on wpdeploy (server side)**
Wpdeploy's `report-health` route now compares incoming `plugin_version` against the row and writes `last_version_changed_at` + `previous_plugin_version` on change. The `SyncWatchdog` cron then alerts if a site has reported a version change but not sent any heartbeat for 2+ hours since — likely a failed install. Emits `sync_incidents` rows with `kind=post_update_failure` so the existing Telegram fan-out picks them up. Each version-change event alerts at most once.

#### Files Changed
- **Created:** `inc/keepalive/auctionforge-keepalive.template.php`, `inc/keepalive/class-keepalive-installer.php`
- **Modified:** `inc/stats/class-stats-init.php` (call `AF_Keepalive_Installer::maybe_install()` on every plugin load)
- **Modified:** `auctionforge.php` (Version 3.7.0.3 → 3.7.0.4)

Companion server-side changes (already deployed on wpdeploy.smoothbyteit.dev — not in this zip):
- `sites` table: `last_version_changed_at TIMESTAMP NULL`, `previous_plugin_version VARCHAR(20) NULL`
- `api.php` /report-health route detects version changes
- `SyncWatchdog::maybe_alert_post_update_failure()` emits the new alert kind

#### Verification
1. Drop a 3.7.0.4 install on any site. Confirm `wp-content/mu-plugins/auctionforge-keepalive.php` exists post-load.
2. Manually deactivate AF from the database (`DELETE FROM wp_options ...active_plugins...`). Hit the homepage. AF reappears in `active_plugins`; `auctionforge_auto_reactivated_count` increments.
3. Delete `mu-plugins/auctionforge-keepalive.php`. Trigger AF load (any pageview). The file reappears.
4. Bump KEEPALIVE_VERSION in the source template, ship a new release, observe the installed mu-plugin update on next AF load.

#### Operator notes
- Sites currently in the broken state (AF deactivated, no keepalive yet) are NOT auto-rescued by this release — they need a one-time manual reactivation in wp-admin OR a fresh AF install via wp-admin's Upload Plugin. After that, the keepalive is in place and future failures self-heal.
- The post-update-failure alert won't fire for upgrades that happened before this release (no `last_version_changed_at` was recorded). It activates from the first version change wpdeploy sees from each site after this update lands.

---

## [3.7.0.3] — 2026-05-02

### Fix: profile re-sync on login / profile-edit / register (no more empty names)

#### Why
The hourly profile sync uses a `user_registered` watermark — once a user has been pushed once, the watermark advances past them and they're never re-pulled. That meant:

1. Existing users whose first_name/last_name became populated AFTER their first sync stayed empty on wpdeploy forever.
2. BidSpirit-driven sites that don't write WP's standard `first_name`/`last_name` fields shipped empty rows even though the canonical name was visible in `display_name`.

The People view was showing `—` for the name on rows that absolutely had a name available — just not where the sync handler was looking.

#### Fixes (`inc/sync/class-profile-sync.php` + `inc/stats/class-stats-init.php`)
- **`AF_Profile_Sync::push_for_user_id($user_id, $blocking=false)`** — new public method that builds a single user's profile row, normalises it, and POSTs to wpdeploy bypassing the watermark. Non-blocking by default (`wp_remote_post` with `blocking=false, timeout=2s`) so login latency is unaffected.
- **`build_user_row($user_id)`** extracted as a reusable helper. Both the hourly batch and the on-demand push call it. Centralises role-filtering + display_name fallback + usermeta probing.
- **`display_name` fallback.** When `wp_usermeta.first_name` / `last_name` are both empty (typical on BidSpirit-only sites), `build_user_row()` parses `display_name` ("John Smith" → first=John, last=Smith) so we don't ship a row with a blank name when the data is sitting on the user record itself.
- **Three new action hooks** registered in `class-stats-init.php::init()`:
  - `wp_login` → `push_for_user_id($user->ID)` — every login refreshes the row
  - `profile_update` → same — profile edits in wp-admin refresh
  - `user_register` → same — new registrations get pushed instantly (instead of waiting up to 60 min for the next cron tick)

#### Files Changed
- **Modified:** `inc/sync/class-profile-sync.php` (refactor + new method + display_name fallback)
- **Modified:** `inc/stats/class-stats-init.php` (three new action hooks)
- **Modified:** `auctionforge.php` (Version 3.7.0.2 → 3.7.0.3)

#### Verification
1. On a 3.7.0.3 site, find a user whose `wpdeploy.user_profiles.first_name` is empty:
   `SELECT site_id, email, first_name FROM user_profiles WHERE email='something@example.com'`
2. Log in as that user (or have them log in).
3. Within ~2 seconds, re-query — `first_name` should now be populated, either from the standard meta key OR parsed from `display_name`.
4. The non-blocking POST means the user's login experience is unchanged — no spinner, no extra latency.

#### Operator note
Existing wpdeploy rows with empty `first_name`/`last_name` will refresh automatically as users log in or edit their profile. To force a one-shot re-walk of every user on a site (regardless of watermark), reset the watermark there:
`DELETE FROM wp_options WHERE option_name='auctionforge_profile_sync_watermark';`
Next hourly cron will re-pull every non-admin user with the new fallback applied.

---

## [3.7.0.2] — 2026-05-02

### Fix: sync-lots datetime mismatch + idle syncs now heartbeat

#### Why
Two issues surfaced in the wpdeploy Sync Health dashboard:

1. **Every site's `sync-lots` was stuck on `api_error`.** The plugin sends `last_modified` straight from `wp_bp_meta_data.lastUpdate`, which is a **Unix epoch string** (`"1756919754"`). wpdeploy's `lots.last_modified` column is a `DATETIME`, so MariaDB rejects the insert with `SQLSTATE[22007]: Incorrect datetime value`. The handler records `api_error` and the watermark never advances, so every cron tick re-fails on the same batch.

2. **Sites with nothing to sync looked dead.** When a sync handler had an empty batch (e.g. no non-admin users yet) it was returning early without POSTing anything. wpdeploy's `update_sync_health()` only fires on a successful POST, so `sites.sync_health_json` stayed NULL and the dashboard showed grey dots — indistinguishable from a broken cron. WP-Cron was actually firing fine; the watchdog just couldn't tell.

#### Fixes
- **`inc/sync/class-lots-sync.php`** — new `epoch_to_datetime()` helper converts the BidSpirit epoch field to UTC `Y-m-d H:i:s` before shipping. Idempotent: already-formatted datetimes pass through untouched, invalid values become `NULL`.
- **`inc/sync/class-sync-base.php::run()`** — always POST, even when the batch is empty. Empty payload is `{records: []}` and wpdeploy's existing handlers handle it gracefully (loop is skipped, `update_sync_health()` still fires with `synced=0`). This makes the dashboard reflect **cron liveness**, not just **data flow**.

#### Files Changed
- **Modified:** `inc/sync/class-lots-sync.php`
- **Modified:** `inc/sync/class-sync-base.php`
- **Modified:** `auctionforge.php` (Version 3.7.0.1 → 3.7.0.2)

#### Verification
1. On Clumber: `do_action('auctionforge_sync_lots')` — confirm the previous `auctionforge_last_sync-lots_status = api_error` flips to `success(N)` and that `wpdeploy.lots` now contains rows.
2. On a site with no non-admin users: `do_action('auctionforge_sync_user_profile')` — confirm `auctionforge_last_sync-user-profile_status = idle(0)` AND that wpdeploy's Sync Health page now shows a green dot for that cell.

---

## [3.7.0.1] — 2026-05-02

### Fix: marketing data leaks WordPress admins into the people list

#### Why
After the 3.7.0.0 rollout the central `people` view on wpdeploy was showing site administrators alongside real auction-house users — the `sync-user-profile` handler read straight from `wp_users` with no role filter, so any account with administrator/editor/author/contributor/shop_manager capabilities was getting shipped as if it were a buyer. Marketing audiences must contain buyers, not staff.

#### Fixes (`inc/sync/class-profile-sync.php`)
- The `read_batch()` SQL now LEFT JOINs `{$wpdb->usermeta}` on the prefix-aware capabilities key (`{$wpdb->prefix}capabilities`) and filters out any user whose serialized capabilities meta_value contains `administrator`, `editor`, `author`, `contributor`, `shop_manager`, or `super_admin`. Users with `IS NULL` (no roles registered) are still allowed through — those are typically subscribers/buyers on this fleet.
- Watermark on `auctionforge_profile_sync_watermark` is unchanged; the next run after upgrade picks up the same batch with the new filter applied. Operationally the wpdeploy team also wiped the existing admin rows from `user_profiles`, `user_interests`, `user_recent_activity`, `bids_wins`, and `people` to clear the leak server-side — total of 35 rows scrubbed.

#### Files Changed
- **Modified:** `inc/sync/class-profile-sync.php`
- **Modified:** `auctionforge.php` (Version 3.7.0.0 → 3.7.0.1)

#### Verification on Clumber dev
1. Find a logged-in admin: `SELECT u.user_email FROM wp_users u JOIN wp_usermeta um ON um.user_id=u.ID AND um.meta_key='wp_capabilities' WHERE um.meta_value LIKE '%administrator%';`
2. Reset the watermark: `DELETE FROM wp_options WHERE option_name='auctionforge_profile_sync_watermark';`
3. Trigger sync: `do_action('auctionforge_sync_user_profile');`
4. On wpdeploy: confirm those admin emails do NOT appear in `user_profiles` (`SELECT * FROM user_profiles WHERE email='admin@…';` returns zero rows).

#### Privacy / scope
- No API contract changes. The wpdeploy `/api.php/sync-user-profile` route accepts the same payload shape; this is purely a source-side filter narrowing what gets sent.

---

## [3.7.0.0] — 2026-05-02

### Cross-site user data lake — full Phase 2 + Phase 3 build

#### Why
AuctionForge sites were exposing per-lot engagement (views, favourites, bids, wins) keyed only on the anonymous `af_vid` localStorage hash, with no central aggregation. Marketing — even the "collect data now, send later" phase — needs a per-person view across the whole AF network: name + phone + postcode + country + IP + device fingerprint + the keywords they engage with + the bids they place + the lots they win, all rolled up across every site they've used. This release wires every piece needed for that, and keeps it sustainable: per-site aggregates rather than raw event firehose, watermarked syncs with retry, 14/30-day site-side retention, watchdog + Telegram alerts for dead streams.

See `/root/.claude/plans/i-want-to-add-synthetic-goose.md` for the full architecture.

#### New tables (idempotent dbDelta on the existing `plugins_loaded` migration path)
- **`wp_af_stats_lot_keywords`** — per-lot keyword cache. Title + tags + author tokenized (lowercase → drop stop-words → drop ≤2-char → drop pure-digit), one row per (post_id, keyword). Populated on `save_post_lot`.
- **`wp_af_user_interests`** — running tally per `(user_email, dimension, dimension_value)` where dimension ∈ `keyword | category | author | price_band`. UPSERT-keyed so increments are atomic. Bounded by users × distinct interests (typically a few dozen rows per user).
- **`wp_af_user_recent_activity`** — capped per-user activity log (last 50 events per email). Seeds the drill-down timeline on the wpdeploy person view.
- **`wp_af_bid_events`** — bid + win events (auto-created by the bids sync handler). Drained and shipped to wpdeploy hourly.
- **`synced_at` columns** added to `wp_af_stats_pageviews`, `wp_af_stats_sessions`, `wp_af_stats_searches`, `wp_af_stats_outbound`. Powers the durable sync-and-purge lifecycle.
- `af_stats_db_version` bumped 2 → **3**. The existing `AF_Stats_Init::maybe_create_tables()` picks up the new tables on the next admin page load after auto-update.

#### New helper classes
- **`AF_Keyword_Extractor`** (`inc/stats/class-keyword-extractor.php`) — pure tokenizer + cache writer + read-through helper. Hooks `save_post_lot` to refresh on lot changes. Stop-words tunable via `apply_filters('af_keyword_stop_words', ...)`.
- **`AF_User_Interests`** (`inc/stats/class-user-interests.php`) — `record_view / record_favorite / record_bid / record_win`. All idempotent UPSERTs. Calls `AF_Stats_Tracker::should_skip()` first so admins/bots never pollute interest profiles.
- **`AF_Sync_Base`** (`inc/sync/class-sync-base.php`) — abstract durability backbone. Reads `synced_at IS NULL` batches, POSTs, marks rows synced only on a confirmed 200, retries on next cron run if the POST fails. Idempotent UNIQUE keys on the wpdeploy side mean retries never duplicate.
- **`AF_Profile_Sync` / `AF_Interests_Sync` / `AF_Activity_Sync` / `AF_Lots_Sync` / `AF_Bids_Sync`** — five concrete sync streams.
- **`AF_Data_Purge`** (`inc/maintenance/class-data-purge.php`) — daily cron: 14-day floor on synced rows, 30-day hard cap with CRITICAL alert if any unsynced row hits the cap (which would mean wpdeploy has been unreachable for a month).

#### New cron schedules (auto-registered on plugins_loaded if `auctionforge_update_server_url` + `_api_key` are configured)
| Hook | Schedule | Endpoint |
|---|---|---|
| `auctionforge_sync_user_profile` | hourly | `POST /api.php/sync-user-profile` |
| `auctionforge_sync_user_interests` | hourly | `POST /api.php/sync-user-interests` |
| `auctionforge_sync_user_activity` | hourly | `POST /api.php/sync-user-activity` |
| `auctionforge_sync_lots` | every 10 min | `POST /api.php/sync-lots` |
| `auctionforge_sync_bids_wins` | hourly | `POST /api.php/sync-bids-wins` |
| `auctionforge_purge_synced_data` | daily | (purge cron — local) |

All sync handlers are watermarked or `synced_at`-gated; cron mid-run failure is harmless because the next run picks up the same rows.

#### Hooks fired
- `af_stats_pageview_recorded($url, $email, $visitor_hash)` — fires inside `AF_Stats_Ajax::handle_track()` after a logged-in pageview is recorded. Default listener resolves URL → lot post → `AF_User_Interests::record_view()`.
- `af_stats_lot_favorited($email, $post_id)` — fires from the existing `lot_analytics_record_favorite` AJAX handler when a watchlist add happens. Default listener calls `record_favorite()`.

#### Server-side companion (wpdeploy)
This release is paired with wpdeploy changes (handled out-of-band; not in the plugin zip):
- **5 new API routes** matching the sync streams above. All return `synced` + watermark metadata so the plugin can advance / mark rows synced.
- **`update_sync_health()` helper** in wpdeploy — every successful sync POST writes `(stream, last_seen_at, last_synced_count, state)` into `sites.sync_health_json`.
- **`SyncWatchdog`** — 5-minute cron on wpdeploy that scans every (site × stream) cell and runs an `ok → overdue → gone → recovering → ok` state machine. Emits alerts via the existing `sync_incidents` Telegram fan-out.
- **People section** in the wpdeploy admin — `?tab=people` (cross-site rollup with top keywords / lifetime spend), `?tab=person&email=...` (drill-down with timeline + bids), `?tab=people-export` (Google Customer Match + Meta Custom Audience CSV with sha256 hashing per spec).
- **`?tab=sync-health`** — site × stream traffic-light grid showing every sync's state.

#### Files Changed
- **Created:** `inc/stats/class-keyword-extractor.php`, `inc/stats/class-user-interests.php`, `inc/stats/stop-words.php`
- **Created:** `inc/sync/class-sync-base.php`, `inc/sync/class-profile-sync.php`, `inc/sync/class-interests-sync.php`, `inc/sync/class-activity-sync.php`, `inc/sync/class-lots-sync.php`, `inc/sync/class-bids-sync.php`
- **Created:** `inc/maintenance/class-data-purge.php`
- **Modified:** `inc/stats/class-stats-database.php` (DB_VERSION = 3, new dbDelta calls, synced_at column adds)
- **Modified:** `inc/stats/class-stats-init.php` (require new classes, register sync crons, wire `af_stats_pageview_recorded` and `af_stats_lot_favorited` listeners)
- **Modified:** `inc/stats/class-stats-ajax.php` (fire `af_stats_pageview_recorded` after pageview record; fire `af_stats_lot_favorited` on watchlist add)
- **Modified:** `auctionforge.php` (Version: 3.6.4.0 → 3.7.0.0)

#### Verification on Clumber dev
1. After auto-update + first wp-admin page load: `wp_af_stats_lot_keywords`, `wp_af_user_interests`, `wp_af_user_recent_activity` all exist; `af_stats_db_version = 3`.
2. Save a test lot titled `"Pair of Victorian silver candlesticks by Mappin & Webb"` → `wp_af_stats_lot_keywords` has rows for `victorian, silver, candlesticks, mappin, webb` (and **not** `pair, of, by`).
3. Log in as throwaway test user, view 3 of those lots → `wp_af_user_interests` shows `(test@…, keyword, 'victorian', view_count=3)`.
4. Wait one hourly cron, confirm `wpdeploy.user_interests` mirror via the wpdeploy admin → `?tab=people` → search for the test email.
5. Confirm `wpdeploy.sites.sync_health_json` has `user-interests.state = 'ok'` for the Clumber site.
6. Pause the cron, wait 2h, watch the watchdog flip the cell to `overdue` and emit a Telegram alert.

#### Privacy / scope
- Admins and bots are filtered out at write time via `AF_Stats_Tracker::should_skip()`.
- Email is normalized lowercase + trim before storage; phone normalized to E.164 (UK-aware) on the sync side.
- No outbound activation yet — wpdeploy stores everything but doesn't send anything to anyone. Marketing send mechanics (consent flag, suppression list, sender) explicitly deferred.

---

## [3.6.4.0] — 2026-05-02

### Identity stitching: visitor_hash → user_email

#### Why
The `af_stats_*` tables (`pageviews`, `sessions`, `searches`, `outbound`) and the lot-engagement tables (`af_lot_analytics`, `af_lot_shares`) currently store activity keyed only on the anonymous `af_vid` localStorage hash — there is no link from any browsing event to the user's email even when they're logged in. Without that link, the central wpdeploy server can never aggregate behavioural data on a per-person basis, which is the prerequisite for the cross-site user-data lake being built on wpdeploy (see `/root/.claude/plans/i-want-to-add-synthetic-goose.md` Phase 1).

This release adds the bridge: every authenticated tracker hit records a `(visitor_hash, user_email)` pair into a new table. From here on, anonymous browsing can be resolved to an email via JOIN for any session the user was logged in.

#### Changes
- **New table `wp_af_stats_visitor_emails`** — `(visitor_hash, user_email, ip_address, first_seen, last_seen)` with `UNIQUE(visitor_hash, user_email)` + index on `user_email`. Created via `dbDelta` inside the existing `AF_Stats_Database::create_tables()` so it ships through the standard `plugins_loaded` migration path — no manual reactivation needed after auto-update.
- **`af_stats_db_version` bumped 1 → 2.** `AF_Stats_Init::maybe_create_tables()` now compares against the new `AF_Stats_Database::DB_VERSION` constant rather than a hard-coded `< 1`, so future schema bumps (Phase 2 onwards) just require constant edits + new dbDelta calls.
- **Identity record on every authenticated tracker hit.** `AF_Stats_Ajax::handle_track()` now calls `AF_Stats_Visitor_Email_Map::record($visitor_hash, $email, $ip)` whenever `is_user_logged_in()` is true. Trust boundary: the email is read server-side from `wp_get_current_user()` — clients cannot assert who they are.
- **Defensive table-exists guard.** The new helper short-circuits silently if the migration hasn't run yet on a given site (race window on the very first request after auto-update); the next request finds the table and proceeds. No fatals, no missing rows.
- **Email normalised at write time** — lowercase + trim + `is_email()` validation before storage. Marketing audience match-rates downstream depend on consistent casing.

#### Files Changed
- **Created:** `inc/stats/class-visitor-email-map.php`
- **Modified:** `inc/stats/class-stats-database.php` (DB_VERSION constant; new table; drop_tables list)
- **Modified:** `inc/stats/class-stats-init.php` (require new helper; migration check uses constant)
- **Modified:** `inc/stats/class-stats-ajax.php` (record pair in `handle_track`)
- **Modified:** `auctionforge.php` (Version header bump)

#### Verification on Clumber dev
1. After auto-update, load any `wp-admin/*` page once → `wp_af_stats_visitor_emails` exists, `af_stats_db_version = 2`.
2. Log in as a test user, browse 5 lots → exactly one row in `wp_af_stats_visitor_emails` for that `(visitor_hash, email)` pair, with `last_seen` updating on each hit.
3. `SELECT email FROM wp_af_stats_visitor_emails WHERE visitor_hash IN (SELECT visitor_hash FROM wp_af_stats_pageviews WHERE created_at > NOW() - INTERVAL 1 HOUR)` returns the test email — proving the JOIN works.

#### Privacy / scope
- This change writes a `(visitor_hash, email)` pair to a single new table on the AF site. Nothing is sent to wpdeploy yet — the sync stream lands in Phase 2.
- Anonymous (logged-out) browsing is unaffected: no row is created until the user authenticates.
- Bots are still skipped via `AF_Stats_Tracker::is_bot()` before any tracking writes.

---

## [3.6.3.1] — 2026-05-01

### Fix: New lots never processed + Live console improvements

#### Why
When BidSpirit adds new lots to an auction (e.g. items 683-692), the sync pipeline correctly staged all 709 lots into `import_history` but the InsertLotsBS processing loop exited after the first batch of 500 unchanged lots, never reaching the genuinely new lots at the tail of the queue. This caused new lots to remain permanently stuck in staging — synced but never created as WordPress posts.

Separately, the admin Live Console was replaying the entire log history from the beginning on every page load, and showed long silent gaps during API calls with no indication of what the worker was doing.

#### Fixes
- **InsertLotsBS loop break condition** — The stage 5 insert loop in `CatalogSyncWorker::process()` and `processDayEnded()` previously broke when `updated lots === 0`, even if the batch had cleared hundreds of unchanged ("unupdated") lots from the queue. New lots with higher IDs were never reached. Now breaks only when both `updated lots` and `unupdated lots` are 0, meaning the staging queue is truly empty.
- **Live Console starts from current position** — `consoleSinceId` was hardcoded to `0`, causing the console to page through the entire `af_sync_log` table (50 rows at a time) before reaching real-time entries. Now initializes to `SyncLogger::getLatestId()` so only entries created after page load appear.
- **`queueIsActive` declaration order** — Variable was declared after functions that referenced it, causing the console to always start at the slow 3s polling rate even when a worker was active. Moved declaration before first use.
- **Progress logging during API calls** — `LotList::auctionProcessing()` made 2-3 BidSpirit API calls with zero `SyncLogger` entries, creating long silent gaps in the console. Added log entries for API fetch start, response received (with duration), data staged, and API errors.
- **Per-auction progress in bulk runs** — `LotList::run()` now logs `Processing auction X/Y: {id}` for each auction in the bulk loop, and logs skipped auctions.
- **`processDayEnded` insert loop logging** — Added batch progress logging and timeout guard matching the `process()` method pattern. Previously this loop was completely silent.

#### Files Changed
- **Modified:** `inc/sync/CatalogSyncWorker.php`, `inc/import/LotList.php`, `admin/view/sync-status.php`

---

## [3.6.3.0] — 2026-05-01

### Public Auctions API — Token Authentication

#### Why
The `/wp-json/auctionforge/v1/public/auctions` endpoint added in v3.6.2.9 was publicly accessible. Since auction data should only be served to authorized aggregator sites, the endpoint now requires a valid auth token.

#### Changes
- **Token verification** — The `PublicAuctions` REST endpoint now validates an `X-AF-Token` header (or `?token=` query parameter) against the site's existing **Webhook auth token** from AuctionForge settings.
- Returns `401 Unauthorized` for missing/invalid tokens and `403 Forbidden` if no auth token is configured on the site.
- Uses `hash_equals()` for timing-safe comparison.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/api/PublicAuctions.php`

---

## [3.6.2.9] — 2026-05-01

### Public Auctions REST API Endpoint

#### Features
- **New REST endpoint** `GET /wp-json/auctionforge/v1/public/auctions` — Exposes auction list data (title, date, image, state, catalog link) for consumption by the AuctionForge Hub plugin on parent/main sites.
- **Parameters:** `type` (upcoming or past, default: upcoming), `limit` (max results, default: 50).
- Handles multi-day auctions with correct part numbers and catalog links.
- Returns auction metadata including `auction_id`, `source_site`, and `day_index` for deduplication.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/coreIncludes.php`
- **Created:** `inc/api/PublicAuctions.php`

---

## [3.6.2.8] — 2026-04-30

### Suppress alerts for transient retry conditions

#### Why
The "BidSpirit API returned 0 lots — catalog may not be ready yet" message is logged when the BidSpirit webhook fires before the auction catalog is fully published. The safety cron retries the job automatically and it usually succeeds on the next attempt — there's no operator action required, so a Telegram alert is just noise.

#### Fix
- New private helper `SyncLogger::isSuppressedFromAlerts($message, $context)` matches the message against a substring allowlist of known-transient errors. When matched, the row is still inserted into `af_sync_log` (so the in-app sync console still shows the retry chain) but the `auctionforge_sync_error_logged` fan-out action does NOT fire — wpdeploy and Telegram stay quiet.
- Default suppression substrings: `"BidSpirit API returned 0 lots"`, `"catalog may not be ready yet"`.
- Extendable via the new `auctionforge_sync_alert_suppress_patterns` filter — themes/MU plugins can add their own substrings.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/sync/SyncLogger.php`

---

## [3.6.2.7] — 2026-04-30

### Typo fix
- Settings → Connections tab: the placeholder/help text under the **Server** field showed `https://my-accaunt.bidspirit.com/` (extra "a"). Now reads `https://my-account.bidspirit.com/`.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/controllers/Settings.php`

---

## [3.6.2.6] — 2026-04-30

### Fix stale `plugin_version` in reports

#### Why
Sites were reporting their old version to wpdeploy long after they'd been upgraded — e.g. Lonsdale Auctioneers ran v3.6.1.1 but kept telling wpdeploy it was on v2.9.6. Root cause: the constant `AUCTIONFORGE_VERSION` is read from the plugin file's `Version:` header *once at plugin load*, then frozen into `$this->current_version` on the auto-updater instance. After a plugin upgrade replaces the file on disk, existing PHP-FPM workers keep using the cached constant value until they're recycled, so every report from those workers carries the old version.

#### Fix
- New helper `AuctionForge_Auto_Updater::get_live_version()` reads the version directly from the plugin file's header on each call (via `get_file_data()` — uncached).
- `report_health`, `push_sync_error_immediate`, and `retry_sync_errors` now send `get_live_version()` instead of the cached constant.
- The pre-existing iteration through active plugins inside `report_health` already used `get_plugin_data()` per plugin, so secondary plugin entries were already accurate; only the top-level `plugin_version` field was stale.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/class-auto-updater.php`

---

## [3.6.2.5] — 2026-04-30

### Real diagnostics for plugin self-updates

#### Why
The wpdeploy `update_queue` table had a 46% historical failure rate, but every single failure row stored the literal string `"Installation failed"` — collapsing every failure mode into one opaque error with no diagnostic value. Root cause: the `install_update()` method in both clients (AF auto-updater and wpd-client) treated `Plugin_Upgrader::upgrade()` as a boolean, throwing away `WP_Error` objects and skin-emitted error messages.

#### Fixes (`inc/class-auto-updater.php` `install_update()`)
- **Refreshes the `update_plugins` transient before invoking the upgrader.** The upgrader reads from this transient to know what version to download; if WP hasn't checked recently, the upgrader silently returns false (looking like a failure even though there's a real update queued at wpdeploy).
- **Distinguishes `WP_Error`, `false`/`null`, and success.** `WP_Error` was previously treated as truthy → reported as "completed" even on failure. Now extracts the error code and message.
- **Reads `Automatic_Upgrader_Skin::get_errors()`** to surface the real upgrader-emitted error messages.
- **Reads `$upgrader->result`** which holds the final `WP_Error` for some failure paths.
- **Captures PHP errors/warnings emitted during the upgrade** (file-move issues, etc.) via a temporary `set_error_handler`.
- **Detects "no update in transient"** as a distinct failure cause and labels it explicitly so we know it's a transient-cache problem, not an actual install failure.
- Truncates the combined diagnostic to 1000 chars before sending.

The same fix is applied to `wpd-client.php` (the WPD client plugin shipped from `client-plugin/wpd-client.php` on the wpdeploy server).

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/class-auto-updater.php`

---

## [3.6.2.4] — 2026-04-30

### Bulk-sync worker dispatch fix

#### Fixes
- The HTTP-loopback worker (`auctionforge_rest_sync_worker` in `auctionforge.php`) had its own switch statement for job-type dispatch, distinct from the one in `crontasks/syncWorker.php`. The new `full_sync_upcoming` and `full_sync_past` job types were only added to the CLI worker, so the loopback path produced "Unknown job type" errors. Both switches now route those types to `BulkSyncWorker::process`.
- `inc/coreIncludes.php` now `require_once`s `BulkSyncWorker.php` so the class is available wherever sync code runs.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/coreIncludes.php`

---

## [3.6.2.3] — 2026-04-30

### Fixes for end-to-end Telegram round-trip

#### Fixes
- **`verify_api_key` reads the option fresh on every call** (`hash_equals` against `get_option('auctionforge_update_api_key')`) instead of relying on the cached `$this->api_key` from constructor time. Different FPM workers can hold different cached values when the option drifts (e.g. via auto-heal collisions), which previously produced intermittent 401s on REST endpoints.
- **New REST endpoint `POST /wp-json/auctionforge/v1/sync/version`** — wraps the existing `trigger-install` flow with a JSON response (always HTTP 200 with `success` flag). The original endpoint returned `WP_Error('no_update', …, status: 404)` when the plugin was already on the latest version, which nginx's `error_page 404` directive then clobbered with a static HTML 404 page on hosts using aaPanel/BTWAF. Keeping the URL under `/sync/*` matches the pattern that's already proven to pass through host WAFs.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/class-auto-updater.php`

---

## [3.6.2.2] — 2026-04-29

### Catalog-sync kind disambiguation

#### Fix
- `catalog_sync` jobs target a single auction that may be either active or archived. Until now their alerts were always classified as `kind=upcoming`. The classifier now resolves the auction's `auction_state` term meta and routes:
  - `ARCHIVED` / `ENDED` / `POST_AUCTION` → `kind=past` → **Kill + Full Past** buttons
  - anything else (or unresolvable) → `kind=upcoming` → **Kill + Full Upcoming** buttons

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/class-auto-updater.php`

---

## [3.6.2.1] — 2026-04-29

### Telegram Sync Monitoring follow-ups

#### Features
- **Context-aware alert buttons.** Each Telegram alert now shows the action set most relevant to the failing sync: upcoming-sync errors get **Kill + Full Upcoming**, past-sync errors get **Kill + Full Past**, everything else gets **Kill** only. Button choice is driven by a new `kind` field classified at log-write time from the queue's `job_type`.
- **Plugin version in alerts + Update button.** Each push now includes the live `plugin_version`. wpdeploy compares it to the latest `is_stable=1` row in its `versions` table and only renders an **Update plugin** button when the site is behind. Tapping Update calls the existing `POST /wp-json/auctionforge/v1/trigger-install` endpoint to force the upgrade.

#### Architecture
- New private helper `AuctionForge_Auto_Updater::classify_error_kind($jobId)` looks up the job's `job_type` and maps it to `'upcoming'` / `'past'` / `'other'`. Used by both the immediate push and the 1-min retry cron.
- Outbound payloads now include `plugin_version` at the top level; wpdeploy refreshes `sites.plugin_version` on every `/sync-errors` POST.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/class-auto-updater.php`

---

## [3.6.2.0] — 2026-04-29

### Telegram Sync Monitoring & Remote Control

#### Features
- **Instant Telegram alerts on sync errors.** Any `level='error'` row written to `af_sync_log` is pushed (fire-and-forget, non-blocking) to wpdeploy, which fans it out to a configured Telegram group with inline-keyboard action buttons (Kill / Full Upcoming / Full Past / Acknowledge).
- **Remote command surface.** Any group admin can tap a button to:
  - **Kill sync** — flips DB flags via `SyncQueue::cancelAll()`, then SIGTERMs every active worker; a 5-second watchdog escalates to SIGKILL for any survivor.
  - **Full sync upcoming** — full re-import of every active auction and its lots (queued, observable, killable). Replaces the `re-sync?do=importBidSpiritUpcoming` flow with a queued equivalent.
  - **Full sync past** — same, for archived auctions.
- **Safety-net retry cron** (`auctionforge_retry_sync_errors`, every minute) re-pushes recent error rows. wpdeploy dedupes via `UNIQUE(site_id, af_log_id)` so duplicates are silent.

#### Architecture
- **`SyncLogger::log()`** now fires `do_action('auctionforge_sync_error_logged', …)` on `level='error'` so any handler can react. The auto-updater listener does a 2 s non-blocking POST to `/api.php/sync-errors`.
- **New REST endpoint** `POST /wp-json/auctionforge/v1/sync/cancel-all` (X-API-Key auth) — runs `SyncQueue::cancelAll()` + SIGTERM + watchdog. Logs every action through `SyncLogger`.
- **`POST /sync/start` extended** with a `mode` parameter (`upcoming` default, `past` for archived). Bulk re-sync is now a queued job, not a synchronous block.
- **New job types** `full_sync_upcoming` and `full_sync_past` on `SyncQueue`, dispatched to a new `BulkSyncWorker` that wraps the existing `AuctionList::init()` + `LotList::init($upcoming)` pipeline.
- **`syncWorker.php`** installs a SIGTERM handler that flips the in-flight job to `failed` with a "Killed by admin (SIGTERM, cleanup OK)" marker and closes the DB cleanly before exiting. Watchdog escalates to SIGKILL after 5 s grace.
- **`LotList::auctionProcessing()`** now heartbeats the active bulk-sync job between auctions, preventing the safety cron from auto-failing long bulk runs as stale (the 600 s threshold is unchanged).

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/sync/SyncLogger.php`, `inc/sync/SyncQueue.php`, `inc/class-auto-updater.php`, `crontasks/syncWorker.php`, `inc/import/LotList.php`
- **Created:** `inc/sync/BulkSyncWorker.php`

---

## [3.6.1.6] — 2026-04-29

### High-Value Lot Modes for `[bp_lot_list]`

#### Features
- **`high_value_past` mode** — Displays past auction lots ordered by their catalog estimate (`estimatedPriceInt`), highest first. Useful for "Top Lots" or "Highlights" sections.
- **`high_value_sold` mode** — Displays past sold lots ordered by their actual sold price (`soldBid`), highest first. Only includes genuinely sold lots (`soldBid > 0`) and reuses the same false-positive guard as `random_past` to skip lots where `soldBid` was carried over from `startPrice` without real bidding activity.
- **Admin documentation updated** — The Shortcodes reference page in WP Admin now lists both new modes in the `mode` attribute description and includes example shortcode usage.

#### Architecture
- New constants `MODE_HIGH_VALUE_PAST` and `MODE_HIGH_VALUE_SOLD` on `LotsWidget`.
- New method `LotsWidget::getLotListHighValue($mode, $limit)` builds the query, applies the past-auction tax filter, sets `bp_orderby` to the relevant meta field with `DESC` order, and (for the sold variant) filters out unsold-but-stale lots in PHP.
- New filter hook `bp_lot_list_high_value_args_filter` for downstream customization of the WP_Query args.

#### Files Changed
- **Modified:** `inc/widgets/LotsWidget.php`, `inc/controllers/ShortcodesPage.php`

---

## [3.6.0.18] — 2026-04-25

### Brevo SMS Notifications Integration

#### Features
- **Transactional SMS via Brevo API** — The plugin now sends text message alerts through the Brevo transactional SMS service, running alongside existing Firebase push notifications.
- **Four Notification Types:**
  - **New Auction Published** — Broadcast SMS to all opted-in subscribers when an auction is published.
  - **Auction Starting Soon** — Targeted SMS to users registered for an auction when it is about to start.
  - **Favorited Item Live Soon** — Targeted SMS to users who favorited a lot when it is approaching in the auction.
  - **Outbid Notice** — SMS sent when a user's leading bid is surpassed, with a 5-minute per-item cooldown to prevent spam.
- **SMS Subscriber Database** — New `af_sms_subscribers` table stores user phone numbers, country codes, and per-notification-type opt-in preferences (GDPR-ready explicit consent).
- **Admin Settings Tab** — New "SMS Notifications" tab in Settings with:
  - Brevo API Key input
  - SMS Sender Name (11 char max)
  - Master enable/disable toggle
  - Per-notification-type on/off switches
  - Test SMS widget with phone input and send button
  - Live subscriber count display
- **Profile SMS Preferences** — Users can opt into SMS notifications directly from their profile page with phone number entry and granular notification type selection.

#### Architecture
- **BrevoSMS Service** (`inc/services/BrevoSMS.php`) — cURL-based API wrapper with broadcast, targeted, and single-send methods, message builders with 160-char limit awareness, rate limiting, and comprehensive error logging.
- **SMSSubscriber Model** (`inc/model/SMSSubscriber.php`) — CRUD operations, email-to-phone resolution, opt-in filtering, and upsert logic.
- **Webhook Integration** — SMS dispatch hooks added to `AuctionsAPI.php` methods: `leading_bid_surpassed()`, `item_live_soon()`, `auction_starts_soon()`, and `auctionPublishedPush()`.

#### AJAX Handlers
- `auctionforge_sms_save` — Save SMS preferences from profile page
- `auctionforge_sms_load` — Load SMS preferences for profile page
- `auctionforge_sms_test` — Admin-only test SMS endpoint

#### Database
- New table: `af_sms_subscribers` — Phone numbers, country codes, per-notification opt-ins, timestamps

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/coreIncludes.php`, `inc/controllers/AuctionsAPI.php`, `inc/controllers/Settings.php`, `admin/view/settings.php`, `templates/parts/profile-templates.php`
- **Created:** `inc/services/BrevoSMS.php`, `inc/model/SMSSubscriber.php`

---

## [3.6.0.7] — 2026-04-14

### Hotfix

#### Fixes
- **Namespace resolution** — Fixed fatal error in `wp_footer` commission label hook caused by unqualified `SettingsHelper` and `Settings` class references. Now uses fully qualified namespaces.

#### Files Changed
- **Modified:** `auctionforge.php`

---

## [3.6.0.6] — 2026-04-14

### Commission Label Override Fix

#### Fixes
- **Theme template override compatibility** — Moved the commission label JS override from the `single-lot.php` template into `auctionforge.php` via `wp_footer` hook (priority 99). Sites with theme-level template overrides (e.g. `themes/*/auctionforge/single-lot.php`) were not picking up the inline script. The `wp_footer` approach works universally on all single lot pages.

#### Files Changed
- **Modified:** `auctionforge.php`, `templates/single-lot.php`

---

## [3.6.0.5] — 2026-04-14

### Commission Label Override

#### Features
- **Commission Label Setting** — New dropdown in Settings → Appearance allowing admins to choose between "Buyer's Premium" (default) and "Auction House Commission" as the label displayed on lot pages. This overrides the Bidspirit JS client's default label using a MutationObserver that catches asynchronously injected text.

#### Files Changed
- **Modified:** `inc/controllers/Settings.php`, `templates/single-lot.php`

---

## [3.6.0.4] — 2026-04-12

### Auction Approval Modal Redesign

#### Changes
- **Removed BidSpirit Terms of Use** — The generic BidSpirit "Terms of Use" section that appeared at the top of the non-credit-card approval modal has been removed. The modal now shows only the auction house's own legal agreements managed within the plugin.
- **Renamed Modal Title** — Changed "Terms of conditions" to "Terms & Conditions".
- **Larger Scroll Area** — The Terms & Conditions scroll box is now 350px tall (up from 200px) for easier reading.
- **Proportional Section Heights** — Refund & Return Policy and Chargeback Waiver sections use a shorter 260px scroll box to visually distinguish them from the primary Terms & Conditions.

#### Files Changed
- **Modified:** `templates/js-chunks/approval-info.php`, `assets/js/app.js`

---

## [3.6.0.2] — 2026-04-10

### Webhook Token Generator

#### Features
- **Token Generator Widget** — Added a 16-character random token generator directly below the "Webhook auth token" field on the Settings page. Includes a "Generate Token" button and a clipboard copy icon with visual feedback.

#### Files Changed
- **Modified:** `inc/controllers/Settings.php`

---

## [3.6.0.1] — 2026-04-10

### Patch

#### Changes
- Version bump.

---

## [3.6.0.0] — 2026-04-10

### Legal Agreements for Auction Approval

#### Features
- **Terms & Conditions** — A mandatory, scrollable Terms & Conditions document is now displayed during the auction approval process. Bidders must scroll to the bottom and check an agreement box before their approval request is submitted. Always enabled.
- **Refund & Return Policy** — An optional, scrollable Refund & Return Policy can be enabled in Settings. When enabled, bidders must read and accept it during auction approval.
- **Chargeback Waiver** — An optional, scrollable Chargeback Waiver can be enabled in Settings. When enabled, bidders must read and accept it during auction approval.
- **Admin Management** — New "Legal Agreements" page under the Bidspirit admin menu with tabbed TinyMCE editors for each agreement type. Includes automatic version numbering (incremented on content change) and full version history.
- **Consent Logging** — Every agreement acceptance is logged to a dedicated database table (`af_user_agreement_log`) with the agreement type, version, user email, IP address, user agent, auction ID, and timestamp.
- **User Tracking Integration** — Agreement events (`terms_agreement`, `refund_agreement`, `chargeback_waiver`) are also recorded in the existing IP tracking system alongside registration, login, and bid events.
- **Placeholder Content** — Default sample content is seeded on plugin activation for all three agreement types.

#### Settings Added
- **Enable Refund & Return Policy** — Toggle to require bidders to accept the refund policy during auction approval.
- **Enable Chargeback Waiver** — Toggle to require bidders to accept the chargeback waiver during auction approval.

#### Database
- New table: `af_legal_agreements` — Current active agreement content per type
- New table: `af_legal_agreement_versions` — Version history archive
- New table: `af_user_agreement_log` — User consent records

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/controllers/Settings.php`, `inc/controllers/BidspiritViews.php`, `inc/ip-logger.php`, `templates/js-chunks/approval-info.php`, `assets/js/app.js`
- **Created:** `inc/legal/class-legal-agreements.php`, `admin/view/legal-agreements.php`

---

## [3.5.0.6] — 2026-04-08

### Bid Event Tracking

#### Features
- **Bid Tracking** — All successful bids (regular, catalog, pre-sale buyout, post-sale purchase) now fire `afLogIP("bid", bidspiritUser)` to capture the bidder's full identity in the user tracking table.
- **Whitelist Update** — Added `bid` to the allowed `event_type` values in both the local plugin and the central WPDeploy API.

---

## [3.5.0.5] — 2026-04-08

### Self-Healing Database Schema

#### Features
- **Auto-Migration** — The plugin now auto-detects and adds any missing tracking table columns on version upgrade, ensuring sites with older schemas seamlessly migrate without manual SQL.

---

## [3.5.0.4] — 2026-04-08

### API Key Auto-Healing

#### Features
- **Seamless Self-Registration** — The WordPress plugin now autonomously regenerates and saves a fresh API Key whenever WPDeploy rejects a payload with an `api_key_collision` error. This guarantees zero-downtime security handovers when developers clone instances to proxy/staging servers.

---

## [3.5.0.3] — 2026-04-08

### API Key Collision Defense

#### Features
- **Network-Level Quarantine** — Central API dynamically extracts and strictly validates the incoming payload domain against the registered API Key domain, forcefully blocking mismatched traffic (HTTP 403).
- **Local Critical Alert Banner** — Added a persistent crimson warning banner in the WordPress admin panel that intercepts `api_key_collision` errors, directly instructing developers to update cloned keys.

---

## [3.5.0.2] — 2026-04-08

### Modal Trigger Hotfix

#### Fixes
- Restructured internal UI rendering priority to gracefully deploy the inline Modal triggers inside custom IP log view without colliding with cached `z-index` stacks.

---

## [3.5.0.1] — 2026-04-08

### Hotfix

#### Fixes
- **Timed Auction Badge Visibility** — Fixed a strict type-matching bug in the main `auction_list.php` core file that incorrectly hid the "Timed Auction" badge overlay from valid timed/online auctions on the main upcoming/archive views. The badge now displays properly across all manual and Bidspirit-synced objects when toggled on.

#### Files Changed
- **Modified:** `templates/main/auction_list.php`

---

## [3.2.9.1] — 2026-03-30

### Timed Auction Display Enhancements

#### Features
- **Timed Auction Countdown Text Toggle** — Added a WP-Admin setting "Change text to 'Auction will close in'" that conditionally changes the countdown label for timed/online auctions on single lot pages.
- **Shortcode Text Toggle Support** — Extended the new countdown text logic to the `bp_upcoming_wide` shortcodes so "Live bidding starts in:" successfully transitions to "Auction will close in:" for timed auctions.

#### Files Changed
- **Modified:** `inc/controllers/Settings.php`, `templates/single-lot.php`, `templates/shortcodes/upcoming-auction-wide.php`, `templates/shortcodes/upcoming-auction-wide-manual.php`

---

## [3.2.9.0] — 2026-03-29

### Billing & Invoices Polish

#### Fixes
- **Profile Invoice ID Tracking** — Prevented internal auction codes (e.g. `002` or `ai4`) from breaking into the clean hyphenated titles inside the `profile-templates.php` view.
- **Dynamic Payment Statuses** — Replaced Bidspirit's default/cached `NOT PAID` HTML payloads by wiring the `dompdf` generator to directly respect the current `$b.status` string from the API (resolving instances where a paid invoice still printed "NOT PAID" atop the document).
- **Payment Instructions Conditional** — Automatically hide the "Payment Instructions" block from the PDF footer when an invoice is fully paid.
- **Improved Nomenclature** — Changed "Invoice No:" to "Bidder No:" on document output to prevent confusion with static invoice ledger IDs.

---

## [3.2.6.0] — 2026-03-28

### Multi-Day Auction Lot Filtering Fix

#### Fixes
- **Day 2+ showing lots from Day 1 in multi-day auctions** — The `itemIndex` column in `bp_meta_data` is `varchar(55)`, but the day-range filter in `BidspiritQuery::bp_query_where()` was comparing it as a string. With string comparison, lot numbers like `'11'`, `'101'`–`'145'` incorrectly fell between `'1001'` and `'1450'`, causing Day 1 lots to leak into Day 2 results. Fixed by using `CAST(bpMeta.itemIndex AS UNSIGNED)` for numeric comparison and `intval()` on the PHP-side boundary values. Letter lots (e.g. `14A`, `1025A`) are handled correctly — `CAST` strips the suffix, keeping them grouped with their base lot number.

#### Files Changed
- **Modified:** `inc/controllers/BidspiritQuery.php`

---

## [3.2.5.9] — 2026-03-27

### Catalog Page Fix

#### Fixes
- **Duplicate preview hours on catalog pages** — The `displayHours` field was rendered twice: once via the `bp_after_description_auction` hook in `BidspiritViews.php` and once inline in the auction template. Removed the hook-based rendering to eliminate the duplication.

#### Files Changed
- **Modified:** `inc/controllers/BidspiritViews.php`, `templates/main/auction.php`

---

## [3.2.5] — 2026-03-19

### Sync Reliability & Stuck Lot Prevention

#### Fixes
- **CATALOG_PUBLISHED webhook now triggers catalog sync** — Previously only sent push notifications without syncing lots. When the earlier AUCTION_CATALOG_UPDATED fired before the catalog was ready on BidSpirit, lots were never imported. CATALOG_PUBLISHED now calls `auctionCatalogUpdated()` to trigger a full catalog sync when the catalog is actually available.
- **0-lot API results now fail instead of silently succeeding** — When BidSpirit API returns 0 lots (catalog not yet ready), the sync job now fails with an explicit error message, allowing the next webhook to create a fresh retry job.
- **Expanded CDN allowlist in pre_http_request filter** — The HTTP filter during bulk post insertion now allows all `*.bidspirit.com` subdomains and BidSpirit image CDNs (`fastly.net`, `cloudfront.net`). Previously only `bidspirit.com` and `www.bidspirit.com` were allowed, blocking image downloads during sync and causing worker hangs.
- **InsertLotsBS timeout guard** — Stage 5 (InsertLotsBS processing loop) now has a 180-second timeout and logs progress every 2 batches. Prevents indefinite hangs that previously required manual force-kill.
- **fixResult() no longer marks lots as done when postId=0** — When `lotProcessing()` fails to create a WP post, the staging row now keeps `syncFinished=0` so the lot is retried on the next sync pass, instead of being permanently marked as complete with no actual post.
- **lotProcessing() logs error on missing auction term** — Previously returned 0 silently when `Auction::findAuctionById()` failed. Now logs an explicit error that feeds into `fixResult()` to keep the lot retryable.
- **Hourly orphan detection in safety cron** — New step in `syncSafety.php` detects lot posts that exist in `bp_meta_data` but are missing their auction taxonomy assignment (caused by workers killed mid-batch) and auto-repairs them with `wp_set_object_terms()`.

#### Files Changed
- **Modified:** `inc/controllers/AuctionsAPI.php`, `inc/sync/CatalogSyncWorker.php`, `inc/abs/InsertLotsAbstract.php`, `inc/import/InsertLotsBS.php`, `crontasks/syncSafety.php`

---

## [3.2.4] — 2026-03-18

### Sync Worker Hang Fix

#### Fixes
- **Sync workers hanging at InsertLotsBS stage** — Third-party plugins (Smush Pro, SmartCrawl SEO, WPMU DEV Updates) hook into `wp_insert_post()` and make blocking outbound HTTPS calls for every lot processed. With 489+ lots per auction, this caused workers to hang indefinitely on socket reads to WPMU DEV servers (`32.193.94.25`, `32.193.93.106`). Added `WP_IMPORTING` constant at the REST worker entry point and a `pre_http_request` filter in `CatalogSyncWorker` that blocks all non-essential external HTTP during the batch post-insertion phase. Loopback (`127.0.0.1`, `localhost`) and BidSpirit API calls remain allowed.
- **Stuck staging rows after force-kill** — When workers were force-killed mid-sync, staging rows in `import_history` were left with `syncstart=1` and never unblocked. Subsequent sync runs could not see these rows (filtered out by `Lot::getRawLots()`), causing the InsertLotsBS loop to exit immediately with 0 posts processed. Combined with job deduplication (`SyncQueue::enqueue()` skips if a `processing` job exists), this created a deadlock where no new sync could proceed.

#### Files Changed
- **Modified:** `auctionforge.php`, `inc/sync/CatalogSyncWorker.php`

---

## [3.2.2] — 2026-03-17

### Full Sync Auction Discovery Fix

#### Fixes
- **Full Sync finds no auctions on fresh sites** — The v3 `full_sync` action only queried the WordPress database for existing auction terms, but on a freshly deployed site the database has zero auctions. Added `AuctionList::init()` discovery step before querying the DB, so Full Sync now fetches all auctions from the BidSpirit API and creates taxonomy terms first, then enqueues catalog sync jobs for each.

#### Files Changed
- **Modified:** `auctionforge.php`

---

## [3.2.0] — 2026-03-14

### Webhook Pipeline Fixes, Archive Sync & Admin UI Overhaul

#### New Features
- **Archive Sync** — New "Archive Sync" button on Sync Status admin page. Enqueues catalog sync jobs for all ARCHIVED/ENDED auctions. Past auctions now appear in the auction dropdown with an optgroup separator and state label.
- **Sync Tasks v3** — Replaced old v2 task cards (importData, importBidSpirit, lotBidSpiritOld) with v3 queue-based tasks. "Sync Active Auctions" and "Sync Archived Auctions" now enqueue jobs via the queue system. Maintenance tasks (Clean Draft/Trash Lots, Clean Orphaned Meta) remain as direct-execution tasks.
- **How It Works guide rewritten** — Complete rewrite of the admin guide for v3 architecture. Documents webhook-first flow, all 5 job types, queue system mechanics, cron setup (external + WP-Cron), configuration constants, and troubleshooting.

#### Fixes
- **Dual-write removed** — Removed legacy handlers from `auctionCatalogUpdated()`, `auctionDayEnded()`, and `itemsUpdated()` webhook methods. The old handlers were racing with the v3 worker, creating orphaned staging rows in `import_history` that were never processed. All three methods now exclusively use the v3 enqueue → spawn path.
- **ITEMS_UPDATED webhook** — Fixed `itemsUpdated()` failing to enqueue jobs. The `ITEMS_UPDATED` payload has `auctionId` nested in `itemsByLanguage.{lang}[0].item.auctionId`, not at the top level. Added extraction logic to resolve it.
- **ItemUpdateWorker incomplete** — `ItemUpdateWorker::process()` was only calling `Lot::bulkSave()` (staging table) without running `InsertLotsBS` to process staged data into WP posts and `bp_meta_data`. Added the InsertLotsBS processing step with autocommit restore. Item updates now flow: stage → InsertLotsBS → WP post + meta → cache clear.
- **Worker spawn reliability** — Changed `SyncQueue::spawnWorker()` from non-blocking HTTPS to blocking HTTP loopback (`http://127.0.0.1` with explicit `Host` header, 2s timeout). Fixes nginx 403/404 errors when HTTPS loopback hits the default vhost instead of the site's vhost.
- **API token constant** — Plugin expects `AUCTIONFORGE_API_TOKEN` in `wp-config.php` (renamed from `UCO_API_TOKEN` during the plugin rename). Documented in readme.

#### Database
- DB version: 22 → 23

#### Files Changed
- **Modified:** `inc/controllers/AuctionsAPI.php`, `inc/sync/ItemUpdateWorker.php`, `inc/sync/SyncQueue.php`, `auctionforge.php`, `admin/view/sync-status.php`, `readme.txt`

---

## [3.0.0] — 2025-03-14

### New Feature: Webhook-First Sync Architecture (Sync v3)

**Overview:** Complete redesign of the BidSpirit data synchronisation pipeline. Replaces the old two-phase polling system (importBidSpirit every hour + importData every minute) with a webhook-driven job queue that processes data in near real-time.

#### Architecture
- **Webhook-driven sync** — BidSpirit webhooks now enqueue jobs into a dedicated queue table (`af_sync_queue`) instead of relying solely on polling cron tasks. Data flows: webhook → queue → background worker → WordPress posts.
- **Dual-write mode** — During transition, webhooks enqueue jobs AND still run the legacy handlers. Once verified, legacy handlers can be removed cleanly.
- **Job deduplication** — Prevents duplicate work by checking for existing pending/processing jobs with the same auction_id + job_type.

#### New Components
- **Job Queue System** (`inc/sync/SyncQueue.php`) — Priority-based FIFO queue with atomic job claiming, status tracking (pending/processing/completed/failed/skipped), worker PID tracking, and automatic stuck job recovery.
- **Sync Logger** (`inc/sync/SyncLogger.php`) — Real-time log table for admin console polling with level filtering (info/success/warning/error) and incremental cursor-based retrieval.
- **Catalog Sync Worker** (`inc/sync/CatalogSyncWorker.php`) — Processes catalog_sync, full_sync, and day_ended jobs by reusing existing `LotList::singleRun()` logic.
- **Item Update Worker** (`inc/sync/ItemUpdateWorker.php`) — Processes individual item_update jobs with the same logic as the webhook `itemsUpdated` handler.
- **Background Worker** (`crontasks/syncWorker.php`) — Async CLI process spawned by webhooks via `exec()` or by the safety cron. Claims and processes queued jobs with a configurable timeout (default 240s).
- **Safety Net** (`crontasks/syncSafety.php`) — Hourly cron that resets stuck jobs (>10min), spawns workers for pending jobs, runs a 24-hour health check (auto-enqueues full sync if no webhooks received), and purges old data.

#### Admin UI
- **Queue Status Dashboard** — New card on Sync Status page showing pending/processing/completed/failed/skipped counts, recent jobs table with real-time refresh, worker status badge, and action buttons:
  - **Full Sync** — Enqueues catalog sync for all active auctions
  - **Sync Selected** — Enqueue a single auction from dropdown
  - **Spawn Worker** — Manually trigger a background worker process
- **Live Console** — Dark-themed terminal console on the Sync Status page. Polls `af_sync_log` every 1.5s showing timestamped, color-coded log entries from webhooks, workers, queue operations, and the safety cron. Supports pause, clear, and auto-scroll.

#### Cron Changes
- **Removed** `importData` (ran every minute — ~1,440 PHP executions/day)
- **Removed** `importBidSpirit` (ran hourly — ~24 PHP executions/day)
- **Added** `syncSafety` (runs hourly at :10 — 24 PHP executions/day)
- **Net effect:** ~62 PHP executions/hour → 1 PHP execution/hour
- **WP-Cron safety hook** (`auctionforge_sync_safety`) — Always-active hourly event, independent of external cron
- **setup.sh v3** — Updated task definitions, new `migrate` command for interactive v2→v3 transition

#### Database
- New table: `af_sync_queue` — Job queue with status, priority, source, attempts, worker PID, timing columns
- New table: `af_sync_log` — Real-time log entries with context, level, auction_id, job_id
- DB version: 20 → 22

#### Constants Added
| Constant | Default | Description |
|---|---|---|
| `AUCTIONFORGE_SYNC_WORKER_TIMEOUT` | 240 | Worker process timeout in seconds |
| `AUCTIONFORGE_SYNC_STALE_JOB` | 600 | Seconds before a processing job is considered stuck |
| `AUCTIONFORGE_SYNC_HEALTH_CHECK` | 86400 | Seconds without webhook before triggering full sync |
| `AUCTIONFORGE_SYNC_LOG_RETENTION` | 7 | Days to keep log entries |
| `AUCTIONFORGE_SYNC_QUEUE_RETENTION` | 30 | Days to keep completed queue jobs |
| `AUCTIONFORGE_CURL_TIMEOUT` | 30 | BidSpirit API cURL timeout in seconds |
| `AUCTIONFORGE_PHP_BINARY` | /www/server/php/83/bin/php | PHP CLI binary path for spawning workers |

#### AJAX Handlers Added
- `auctionforge_sync_log_poll` — Incremental log polling for live console
- `auctionforge_sync_queue_status` — Queue counts + recent jobs for dashboard
- `auctionforge_sync_enqueue` — Admin-triggered sync actions (full_sync, sync_auction, spawn_worker)

### Fixes
- **cURL timeout** — BidSpiritRequest now enforces a 30-second timeout (was unlimited/0), preventing hung connections from blocking the sync pipeline.

### Files Changed
- **Modified:** `auctionforge.php`, `inc/coreIncludes.php`, `inc/controllers/AuctionsAPI.php`, `inc/BidSpiritRequest.php`, `admin/view/sync-status.php`, `crontasks/setup.sh`
- **Created:** `inc/sync/SyncQueue.php`, `inc/sync/SyncLogger.php`, `inc/sync/CatalogSyncWorker.php`, `inc/sync/ItemUpdateWorker.php`, `crontasks/syncWorker.php`, `crontasks/syncSafety.php`

---

## [2.7.3.0]

### Fixes
- Various stability improvements and bug fixes.

## [2.7.1.2]

### Fixes
- Added missing `vatAndCommission()` function in `loadBid()` — the sales tax display on single lot pages was never being rendered because the code to call `loadTemplate` for `vat-and-commission-template` was missing from `app.js`.

## [2.7.1.1]

### Fixes
- 2 decimal places now only appear in the bid modal (Your max bid, Total Price) via `showDecimals` flag. Start price, increments list, and other prices show whole numbers as before.

## [2.7.1.0]

### Fixes
- Fixed Buyer's Premium value not showing on single lot pages.

## [2.7.0.9]

### Fixes
- Fixed fatal error during plugin install/upgrade: `class-stats-database.php` require failure.

## [2.7.0.0]

### New Features: Advanced Lot Analytics
- Conversion Tracking, Peak Viewing Times, Pre-Sale vs Live Comparison, Category Performance, Share Analytics, Search → View Funnel, Click-Through Tracking, CSV Export, Hot Lot Badge.
- New DB table: `af_lot_shares`. New columns on `af_lot_analytics`. DB version bumped to 20.

## [2.6.0.0]

### New Feature: Lot Analytics
- Comprehensive lot view and favorite tracking system with admin dashboard.

## [2.5.0.0]

### New Features
- **Site Statistics System** — Full website analytics built into the plugin admin.
- **Recently Viewed Items** — Profile page tab showing last 20 viewed lots per user.
