* feat(cost): persist run_id on generated posts + back-populate for v0.8.1 reaper
The orphan-research-row reaper (upcoming commit) needs a cheap way to
answer "which posts belong to this run_id?" when amortizing a stranded
`llm_research` row back to its siblings. Relying on the generation_log
post_id column is circular: if the pipeline died before amortize_research
ran, we'd trust the same table we're trying to repair.
- `Publisher::build_meta()` now accepts `?string $run_id` and writes
`_prautoblogger_run_id => $run_id` when non-empty. Null/empty preserves
existing null-safe legacy behaviour.
- `Publisher::create_post()` forwards the $run_id it already receives
into build_meta — one-line plumbing, no new parameters at call sites.
- `Activator::backpopulate_run_id_meta_v081()` runs once per site,
gated by `prautoblogger_migrated_run_id_meta_v081` option. Walks
`wp_prautoblogger_generation_log`, pairs (post_id, min(run_id)),
writes `_prautoblogger_run_id` on any post that doesn't already have
it. Uses `metadata_exists()` so it's a no-op on re-run.
- Activator also schedules the new daily `prautoblogger_reap_orphan_research_rows`
cron at 03:15 — 15 min after the primary generation cron — so live
pipelines have time to finish amortizing cleanly before the reaper scans.
- Deactivator unschedules the new hook alongside the existing cron hooks.
No user-visible behaviour change yet. The reaper handler ships in the
next commit; this one just ensures it will have the data + schedule it
needs when it lands.
Part of the v0.8.1 bundle (thread research-cost-reaper).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(cost): daily reaper for orphan llm_research rows
Implements the orphan-research-row reaper per thread research-cost-reaper
seq 1. When a pipeline dies between post creation and
`Post_Assembler::amortize_research_costs()` (Hostinger exec kill, OOM,
LiteSpeed cut, fatal), the shared research row stays in
`wp_prautoblogger_generation_log` with `post_id = NULL` and sibling
articles' cost popovers understate their true spend.
New class `PRAutoBlogger_Research_Reaper` owns:
- `on_cron()` — WP-Cron entrypoint hooked to the daily
`prautoblogger_reap_orphan_research_rows` event (already scheduled
by the Activator in the previous commit at 03:15).
- `reap()` — returns a `{reaped, deleted, skipped}` summary. For each
orphan `llm_research` row older than 1 hour (grace window for live
pipelines):
- `_prautoblogger_run_id` post_meta primary lookup.
- Falls back to distinct post_ids in gen_log with the same run_id.
- If ≥1 post found → delegate to the existing idempotent
`Post_Assembler::amortize_research_costs()`. That method inserts
the per-article rows and deletes the original orphan in one pass,
so the reaper is idempotent on re-run.
- If 0 posts found AND orphan is >7 days old → delete outright as
sunk cost with nothing to attribute to.
- Else → skip; try again the next day.
- Never throws. DB errors caught and logged WARNING.
New WP-CLI command `wp prautoblogger reap-research` registered in the
main loader when `WP_CLI` is defined — manual ops trigger that prints
the same summary.
Departure from the CTO's spec: the reap logic lives on
`Research_Reaper` instead of `Post_Assembler`. Placing it on
Post_Assembler pushed that file to 391 lines, over the 300-line cap.
Moving it to the thin class colocates the attribution logic with the
cron/CLI plumbing that triggers it. `amortize_research_costs()` stays
on Post_Assembler — the reaper delegates to it unchanged. Flagged for
CTO review.
Part of the v0.8.1 bundle (thread research-cost-reaper).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(cost): ResearchReaperTest — five cases per spec
Covers the five scenarios from convo thread research-cost-reaper seq 1:
- test_reaps_orphan_with_matching_run_id_posts — meta lookup returns
two post IDs; reaper delegates to amortize_research_costs which
inserts two rows and deletes the orphan.
- test_skips_orphan_within_grace_period — the SELECT's
`created_at < now - 1h` clause filters fresh orphans at the DB; the
reaper's stats stay zero and no side effects fire.
- test_deletes_orphan_with_no_articles_after_7_days — orphan is 8 days
old, zero siblings via meta or gen_log; reaper deletes outright.
- test_falls_back_to_gen_log_when_post_meta_missing — meta returns
empty (legacy pre-v0.8.1 post); gen_log has two distinct post_ids;
amortize still runs.
- test_idempotent_on_repeat_run — second pass on a cleaned state
returns 0/0/0 with no inserts or deletes.
All DB interaction mocked via $wpdb stub — no real DB round-trips.
Fixtures are driven by property mutations in the test methods so
PHPUnit's "one stub per method" restriction on mocks doesn't bite.
Part of the v0.8.1 bundle.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(v0.8.1): version bump + CHANGELOG + ARCHITECTURE.md for reaper
Bump plugin header and PRAUTOBLOGGER_VERSION 0.8.0 → 0.8.1. Patch
bump — the reaper is internal infrastructure; no user-visible UX
change.
CHANGELOG:
- Fixed: orphan `llm_research` rows now reaped daily.
- Added: WP-CLI `wp prautoblogger reap-research`; `_prautoblogger_run_id`
post_meta is now written by Publisher on every post.
ARCHITECTURE.md:
- Decision #13 (Run-ID based log linking) cross-refs the new post_meta.
- New Decision #19 documents the reaper's scan/amortize/delete policy,
the 1-hour grace window, the 7-day stale cutoff, and the one-shot
activator back-populate migration.
DB schema unchanged — no PRAUTOBLOGGER_DB_VERSION bump.
Final commit of the v0.8.1 bundle.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(cost): widen $wpdb mock so ResearchReaperTest actually runs
BaseTestCase::create_mock_wpdb() only adds methods
[prepare, get_var, get_results, insert, query, get_row, update] — the
reaper and amortize_research_costs also call `delete` and `get_col`,
which the default mock can't stub. CI on PR #100 fired all five new
ResearchReaperTest cases as errors at the first `->method('delete')`
call during setUp.
Fix: build a bespoke $wpdb mock in this file's setUp with the full
superset of methods it needs. Self-contained; no change to
BaseTestCase so existing tests aren't affected.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(cost): filter gen_log inserts from event_log inserts in reaper tests
CI on ec1efee showed the two reap-and-amortize tests failing because
`assertCount(2, $this->inserted_rows)` was seeing 4 rows, not 2. Root
cause: the Logger singleton writes INFO lines via `$wpdb->insert` into
the event_log table — the reaper logs once ("Reaped...") and amortize
logs once ("Amortized LLM research cost...") before the two per-post
gen_log inserts, so the capture ended up with 4 total rows.
Add a `gen_log_inserts()` helper that filters the capture down to rows
whose `__table` contains "generation_log" — the assertions on
attribution count should only measure the actual cost inserts, not
incidental log writes. Two tests updated; logic unchanged.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(admin): correct misleading GA4 Property ID description
The GA4 client at includes/core/class-ga4-client.php:85 already wraps the
property_id option with "properties/" in the outbound URL path. The admin
description told users to enter "properties/XXXXXXXXX" — which would have
produced a double-prefixed URL (properties/properties/XXXXXXXXX) and a
guaranteed 404 from the Data API. Description now asks for digits only,
matching actual code behavior.
No code logic change — UX copy + CHANGELOG only. Flagged by CEO while
inspecting the Analytics tab; folded into the in-flight v0.8.1 PR per
CTO call rather than cutting a separate patch.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: peptiderepo <peptiderepo@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
291 lines
13 KiB
PHP
291 lines
13 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Main orchestrator for the PRAutoBlogger plugin.
|
|
*
|
|
* Registers all WordPress hooks (actions and filters) and wires up dependencies.
|
|
* This is the ONLY place hooks are registered — individual classes contain only
|
|
* business logic, not hook registration.
|
|
*
|
|
* Triggered by: prautoblogger() singleton in prautoblogger.php, called on `plugins_loaded`.
|
|
* Dependencies: All other plugin classes (loaded via autoloader), PRAutoBlogger_Executor.
|
|
*
|
|
* @see prautoblogger.php — Plugin bootstrap that instantiates this class.
|
|
* @see class-executor.php — Cron/AJAX handlers for generation, model registry.
|
|
* @see class-ajax-handlers.php — Non-generation AJAX endpoints (images, models, test).
|
|
* @see class-generation-lock.php — DB mutex for single-writer generation.
|
|
* @see core/class-pipeline-runner.php — Executes the generation pipeline.
|
|
* @see ARCHITECTURE.md — Data flow diagram showing how classes interact.
|
|
* @see CONVENTIONS.md — Hook naming conventions.
|
|
*/
|
|
class PRAutoBlogger {
|
|
|
|
private bool $initialized = false;
|
|
|
|
/** @var PRAutoBlogger_Executor Handles generation cron/AJAX, model registry. */
|
|
private PRAutoBlogger_Executor $executor;
|
|
|
|
/** @var PRAutoBlogger_Ajax_Handlers Handles non-generation AJAX (images, models, test). */
|
|
private PRAutoBlogger_Ajax_Handlers $ajax_handlers;
|
|
|
|
/**
|
|
* Register all hooks and initialize the plugin.
|
|
* Called once on `plugins_loaded`. Idempotent.
|
|
*
|
|
* Side effects: registers WordPress actions and filters.
|
|
*/
|
|
public function run(): void {
|
|
if ( $this->initialized ) {
|
|
return;
|
|
}
|
|
$this->initialized = true;
|
|
$this->executor = new PRAutoBlogger_Executor();
|
|
$this->ajax_handlers = new PRAutoBlogger_Ajax_Handlers( $this->executor->get_model_registry() );
|
|
|
|
add_action( 'admin_init', [ $this, 'on_check_db_version' ] );
|
|
add_filter( 'cron_schedules', [ $this, 'filter_add_cron_schedules' ] );
|
|
|
|
if ( is_admin() ) {
|
|
$this->register_admin_hooks();
|
|
}
|
|
|
|
$this->register_cron_hooks();
|
|
$this->register_frontend_hooks();
|
|
$this->register_ajax_hooks();
|
|
|
|
/** Fires after PRAutoBlogger has finished registering all hooks. */
|
|
do_action( 'prautoblogger_loaded' );
|
|
}
|
|
|
|
/** Register admin-only hooks (settings, notices, metabox, dashboard widget). */
|
|
private function register_admin_hooks(): void {
|
|
$admin_page = new PRAutoBlogger_Admin_Page();
|
|
add_action( 'admin_menu', [ $admin_page, 'on_register_menu' ] );
|
|
add_action( 'admin_init', [ $admin_page, 'on_register_settings' ] );
|
|
add_action( 'admin_enqueue_scripts', [ $admin_page, 'on_enqueue_assets' ] );
|
|
|
|
add_action( 'admin_notices', [ new PRAutoBlogger_Admin_Notices(), 'on_display_notices' ] );
|
|
add_action( 'add_meta_boxes', [ new PRAutoBlogger_Post_Metabox(), 'on_register_metabox' ] );
|
|
add_action( 'admin_menu', [ new PRAutoBlogger_Metrics_Page(), 'on_register_menu' ] );
|
|
add_action( 'wp_dashboard_setup', [ new PRAutoBlogger_Dashboard_Widget(), 'on_register_widget' ] );
|
|
|
|
$review_queue = new PRAutoBlogger_Review_Queue();
|
|
add_action( 'admin_menu', [ $review_queue, 'on_register_menu' ] );
|
|
|
|
$ideas_browser = new PRAutoBlogger_Ideas_Browser();
|
|
add_action( 'admin_menu', [ $ideas_browser, 'on_register_menu' ] );
|
|
add_action( 'admin_menu', [ new PRAutoBlogger_Log_Viewer(), 'on_register_menu' ] );
|
|
|
|
( new PRAutoBlogger_Post_List_Columns() )->register();
|
|
|
|
// Block false update notifications — our slug collides with another plugin.
|
|
add_filter( 'site_transient_update_plugins', [ $this, 'filter_block_false_updates' ] );
|
|
}
|
|
|
|
/** Register frontend hooks (shortcode, REST, typography). */
|
|
private function register_frontend_hooks(): void {
|
|
$posts_widget = new PRAutoBlogger_Posts_Widget();
|
|
add_action( 'init', [ $posts_widget, 'on_register_shortcode' ] );
|
|
add_action( 'rest_api_init', [ $posts_widget, 'on_register_rest_route' ] );
|
|
|
|
$typography = new PRAutoBlogger_Article_Typography();
|
|
add_action( 'wp_head', [ $typography, 'on_wp_head' ] );
|
|
add_action( 'wp_enqueue_scripts', [ $typography, 'on_enqueue_fonts' ] );
|
|
add_filter( 'the_content', [ $typography, 'on_wrap_tables' ], 99 );
|
|
}
|
|
|
|
/** Register cron-triggered hooks for scheduled generation and metrics. */
|
|
private function register_cron_hooks(): void {
|
|
add_action( 'prautoblogger_daily_generation', [ $this->executor, 'on_daily_generation' ] );
|
|
add_action( 'prautoblogger_collect_metrics', [ $this->executor, 'on_collect_metrics' ] );
|
|
|
|
// Manual "Generate Now" runs as a one-shot cron event to avoid
|
|
// Hostinger's 120-second web-server connection timeout.
|
|
add_action( 'prautoblogger_manual_generation', [ $this->executor, 'on_manual_generation' ] );
|
|
|
|
// Chained article generation — each queued article fires as its own
|
|
// cron event so it gets a fresh PHP process and execution time budget.
|
|
add_action(
|
|
PRAutoBlogger_Pipeline_Runner::CRON_ACTION,
|
|
[ $this->executor, 'on_process_article_queue' ]
|
|
);
|
|
|
|
$registry = $this->executor->get_model_registry();
|
|
add_action( 'prautoblogger_refresh_model_registry', [ $registry, 'refresh' ] );
|
|
|
|
// Single-idea generation from the Ideas browser page.
|
|
add_action( 'prautoblogger_generate_from_idea', [ 'PRAutoBlogger_Ideas_Browser', 'on_cron_generate_from_idea' ] );
|
|
|
|
// v0.8.1: daily reaper for orphan `llm_research` rows (when a
|
|
// pipeline dies before amortize_research_costs runs).
|
|
add_action( 'prautoblogger_reap_orphan_research_rows', [ 'PRAutoBlogger_Research_Reaper', 'on_cron' ] );
|
|
|
|
// v0.8.1: WP-CLI manual trigger for the reaper. Only registers when
|
|
// WP-CLI is present; no-op in normal HTTP requests.
|
|
if ( defined( 'WP_CLI' ) && WP_CLI ) {
|
|
\WP_CLI::add_command( 'prautoblogger reap-research', static function (): void {
|
|
$stats = PRAutoBlogger_Research_Reaper::reap();
|
|
\WP_CLI::success( sprintf(
|
|
'Reaped %d, deleted %d (stale), skipped %d.',
|
|
(int) $stats['reaped'],
|
|
(int) $stats['deleted'],
|
|
(int) $stats['skipped']
|
|
) );
|
|
} );
|
|
}
|
|
}
|
|
|
|
/** Register AJAX handlers for admin actions. */
|
|
private function register_ajax_hooks(): void {
|
|
// Generation AJAX (start + status polling) stays on executor.
|
|
add_action( 'wp_ajax_prautoblogger_generate_now', [ $this->executor, 'on_ajax_generate_now' ] );
|
|
add_action( 'wp_ajax_prautoblogger_generation_status', [ $this->executor, 'on_ajax_generation_status' ] );
|
|
|
|
// Non-generation AJAX (images, models, test) on dedicated handler.
|
|
add_action( 'wp_ajax_prautoblogger_generate_image', [ $this->ajax_handlers, 'on_ajax_generate_image' ] );
|
|
add_action( 'wp_ajax_prautoblogger_test_connection', [ $this->ajax_handlers, 'on_ajax_test_connection' ] );
|
|
add_action( 'wp_ajax_prautoblogger_get_models', [ $this->ajax_handlers, 'on_ajax_get_models' ] );
|
|
|
|
$review_queue = new PRAutoBlogger_Review_Queue();
|
|
add_action( 'wp_ajax_prautoblogger_approve_post', [ $review_queue, 'on_ajax_approve_post' ] );
|
|
add_action( 'wp_ajax_prautoblogger_reject_post', [ $review_queue, 'on_ajax_reject_post' ] );
|
|
|
|
add_action( 'wp_ajax_prautoblogger_clear_logs', [ new PRAutoBlogger_Log_Viewer(), 'on_ajax_clear_logs' ] );
|
|
|
|
$ideas = new PRAutoBlogger_Ideas_Browser();
|
|
add_action( 'wp_ajax_prautoblogger_generate_from_idea', [ $ideas, 'on_ajax_generate_from_idea' ] );
|
|
add_action( 'wp_ajax_prautoblogger_idea_gen_status', [ $ideas, 'on_ajax_idea_gen_status' ] );
|
|
}
|
|
|
|
/**
|
|
* Check if database needs migration after plugin update.
|
|
* Compares stored DB version with PRAUTOBLOGGER_DB_VERSION; re-runs activation if different.
|
|
*
|
|
* Side effects: may update database schema and db_version option.
|
|
*/
|
|
public function on_check_db_version(): void {
|
|
$stored_version = get_option( 'prautoblogger_db_version', '0' );
|
|
if ( version_compare( $stored_version, PRAUTOBLOGGER_DB_VERSION, '<' ) ) {
|
|
PRAutoBlogger_Activator::activate();
|
|
}
|
|
|
|
// One-time migration: switch to Gemini 2.5 Flash Lite for cost/speed.
|
|
if ( ! get_option( 'prautoblogger_migrated_gemini_flash_lite' ) ) {
|
|
update_option( 'prautoblogger_analysis_model', PRAUTOBLOGGER_DEFAULT_ANALYSIS_MODEL );
|
|
update_option( 'prautoblogger_writing_model', PRAUTOBLOGGER_DEFAULT_WRITING_MODEL );
|
|
update_option( 'prautoblogger_editor_model', PRAUTOBLOGGER_DEFAULT_EDITOR_MODEL );
|
|
update_option( 'prautoblogger_migrated_gemini_flash_lite', '1' );
|
|
}
|
|
|
|
// One-time migration (v0.8.0): the admin no longer has an independent
|
|
// Image Provider dropdown; provider is derived from the image model on
|
|
// save. Auto-heal any existing site where the saved provider doesn't
|
|
// match the saved model's provider (the root cause of posts 650/657
|
|
// silently missing their featured image on 2026-04-20). Runs once.
|
|
if ( ! get_option( 'prautoblogger_migrated_image_provider_v080' ) ) {
|
|
$saved_model = (string) get_option( 'prautoblogger_image_model', '' );
|
|
$provider = PRAutoBlogger_Image_Model_Registry::provider_for( $saved_model );
|
|
if ( '' !== $provider ) {
|
|
update_option( 'prautoblogger_image_provider', $provider );
|
|
}
|
|
update_option( 'prautoblogger_migrated_image_provider_v080', '1' );
|
|
}
|
|
|
|
// One-time migration (v3): switch to single-panel newspaper comic style.
|
|
// Replaces both the old infomercial pastiche and the short-lived premium
|
|
// photography style. Force-update unless the user has a truly custom value.
|
|
if ( ! get_option( 'prautoblogger_migrated_style_suffix_v3' ) ) {
|
|
$known_old_prefixes = [
|
|
'Style: a screengrab from a 1995', // v1: infomercial.
|
|
'Style: premium scientific lifestyle', // v2: photography.
|
|
];
|
|
$current = get_option( 'prautoblogger_image_style_suffix', '' );
|
|
$is_old = ( '' === $current );
|
|
foreach ( $known_old_prefixes as $prefix ) {
|
|
if ( false !== strpos( $current, $prefix ) ) {
|
|
$is_old = true;
|
|
break;
|
|
}
|
|
}
|
|
if ( $is_old ) {
|
|
update_option( 'prautoblogger_image_style_suffix', PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX );
|
|
}
|
|
update_option( 'prautoblogger_migrated_style_suffix_v3', '1' );
|
|
}
|
|
|
|
// One-time migration (v4): remove caption-in-image instruction from style suffix.
|
|
// Captions are now inserted as HTML below the image, not baked into the image.
|
|
if ( ! get_option( 'prautoblogger_migrated_style_suffix_v4' ) ) {
|
|
$current = get_option( 'prautoblogger_image_style_suffix', '' );
|
|
// Detect v3 style suffix (contains "caption text" instruction).
|
|
if ( false !== strpos( $current, 'caption text in a clean sans-serif font below the panel' ) ) {
|
|
update_option( 'prautoblogger_image_style_suffix', PRAUTOBLOGGER_DEFAULT_IMAGE_STYLE_SUFFIX );
|
|
}
|
|
update_option( 'prautoblogger_migrated_style_suffix_v4', '1' );
|
|
}
|
|
|
|
// One-time migration: re-wrap existing encrypted values with "enc:" prefix.
|
|
if ( ! get_option( 'prautoblogger_migrated_enc_prefix' ) ) {
|
|
$enc_options = [ 'prautoblogger_openrouter_api_key', 'prautoblogger_ga4_credentials_json' ];
|
|
foreach ( $enc_options as $opt ) {
|
|
$val = get_option( $opt, '' );
|
|
if ( '' !== $val && ! PRAutoBlogger_Encryption::is_encrypted( $val ) ) {
|
|
delete_option( $opt );
|
|
}
|
|
}
|
|
update_option( 'prautoblogger_migrated_enc_prefix', '1' );
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Add custom cron schedules (six-hourly for metrics collection).
|
|
*
|
|
* @param array<string, array{interval: int, display: string}> $schedules Existing schedules.
|
|
* @return array<string, array{interval: int, display: string}>
|
|
*/
|
|
public function filter_add_cron_schedules( array $schedules ): array {
|
|
$schedules['prautoblogger_six_hours'] = [
|
|
'interval' => 6 * HOUR_IN_SECONDS,
|
|
'display' => __( 'Every Six Hours', 'prautoblogger' ),
|
|
];
|
|
return $schedules;
|
|
}
|
|
|
|
/**
|
|
* Block false update notifications from wordpress.org.
|
|
* Our plugin slug may collide with a different plugin in the directory.
|
|
*
|
|
* @param object $transient The update_plugins transient data.
|
|
* @return object Modified transient.
|
|
*/
|
|
public function filter_block_false_updates( $transient ) {
|
|
if ( isset( $transient->response[ PRAUTOBLOGGER_PLUGIN_BASENAME ] ) ) {
|
|
unset( $transient->response[ PRAUTOBLOGGER_PLUGIN_BASENAME ] );
|
|
}
|
|
return $transient;
|
|
}
|
|
|
|
/** Expose the executor for external access (e.g., model registry). */
|
|
public function get_executor(): PRAutoBlogger_Executor {
|
|
return $this->executor;
|
|
}
|
|
|
|
// ── Backward-compatible proxies ──
|
|
|
|
/** @see PRAutoBlogger_Executor::on_daily_generation() */
|
|
public function on_daily_generation(): void { $this->executor->on_daily_generation(); }
|
|
|
|
/** @see PRAutoBlogger_Executor::on_collect_metrics() */
|
|
public function on_collect_metrics(): void { $this->executor->on_collect_metrics(); }
|
|
|
|
/** @see PRAutoBlogger_Executor::on_ajax_generate_now() */
|
|
public function on_ajax_generate_now(): void { $this->executor->on_ajax_generate_now(); }
|
|
|
|
/** @see PRAutoBlogger_Ajax_Handlers::on_ajax_test_connection() */
|
|
public function on_ajax_test_connection(): void { $this->ajax_handlers->on_ajax_test_connection(); }
|
|
|
|
/** @see PRAutoBlogger_Executor::get_model_registry() */
|
|
public function get_model_registry(): PRAutoBlogger_OpenRouter_Model_Registry { return $this->executor->get_model_registry(); }
|
|
}
|