* 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>
288 lines
10 KiB
PHP
Executable File
288 lines
10 KiB
PHP
Executable File
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Handles plugin activation: creates database tables, sets default options,
|
|
* and schedules the initial cron job.
|
|
*
|
|
* Triggered by: WordPress `register_activation_hook` in prautoblogger.php.
|
|
* Dependencies: WordPress $wpdb, dbDelta().
|
|
*
|
|
* @see class-deactivator.php — Reverses transient/cron setup on deactivation.
|
|
* @see ARCHITECTURE.md — Database schema definitions.
|
|
*/
|
|
class PRAutoBlogger_Activator {
|
|
|
|
/**
|
|
* Run activation tasks.
|
|
*
|
|
* Creates custom database tables if they don't exist, sets default option
|
|
* values (without overwriting existing ones), and schedules the daily
|
|
* generation cron event.
|
|
*
|
|
* Side effects: writes to wp_options, creates database tables, schedules WP-Cron event.
|
|
*
|
|
* @return void
|
|
*/
|
|
public static function activate(): void {
|
|
self::create_tables();
|
|
self::set_default_options();
|
|
self::schedule_cron();
|
|
self::backpopulate_run_id_meta_v081();
|
|
|
|
// Store the DB version so we can run migrations on future updates.
|
|
update_option( 'prautoblogger_db_version', PRAUTOBLOGGER_DB_VERSION, false );
|
|
}
|
|
|
|
/**
|
|
* Create all custom database tables using dbDelta.
|
|
*
|
|
* Side effects: creates/updates four database tables.
|
|
*
|
|
* @return void
|
|
*/
|
|
private static function create_tables(): void {
|
|
global $wpdb;
|
|
|
|
$charset_collate = $wpdb->get_charset_collate();
|
|
$prefix = $wpdb->prefix . 'prautoblogger_';
|
|
|
|
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
|
|
|
|
// Source data — raw posts/comments from social platforms.
|
|
$sql_source_data = "CREATE TABLE {$prefix}source_data (
|
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
source_type VARCHAR(50) NOT NULL,
|
|
source_id VARCHAR(255) NOT NULL,
|
|
subreddit VARCHAR(255) DEFAULT NULL,
|
|
title TEXT DEFAULT NULL,
|
|
content LONGTEXT DEFAULT NULL,
|
|
author VARCHAR(255) DEFAULT NULL,
|
|
score INT DEFAULT 0,
|
|
comment_count INT DEFAULT 0,
|
|
permalink VARCHAR(500) DEFAULT NULL,
|
|
collected_at DATETIME NOT NULL,
|
|
metadata_json LONGTEXT DEFAULT NULL,
|
|
PRIMARY KEY (id),
|
|
UNIQUE KEY source_unique (source_type, source_id),
|
|
KEY source_collected (source_type, collected_at)
|
|
) {$charset_collate};";
|
|
|
|
// Analysis results — detected patterns from source data.
|
|
$sql_analysis = "CREATE TABLE {$prefix}analysis_results (
|
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
analysis_type VARCHAR(50) NOT NULL,
|
|
topic VARCHAR(500) NOT NULL,
|
|
summary TEXT DEFAULT NULL,
|
|
frequency INT DEFAULT 1,
|
|
relevance_score FLOAT DEFAULT 0,
|
|
source_ids_json LONGTEXT DEFAULT NULL,
|
|
analyzed_at DATETIME NOT NULL,
|
|
metadata_json LONGTEXT DEFAULT NULL,
|
|
PRIMARY KEY (id),
|
|
KEY type_relevance (analysis_type, relevance_score),
|
|
KEY analyzed_at (analyzed_at)
|
|
) {$charset_collate};";
|
|
|
|
// Generation log — every API call with cost tracking.
|
|
// run_id groups all log entries from a single pipeline execution so
|
|
// link_generation_logs() can accurately attribute costs to a post.
|
|
$sql_generation_log = "CREATE TABLE {$prefix}generation_log (
|
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
post_id BIGINT UNSIGNED DEFAULT NULL,
|
|
run_id VARCHAR(36) DEFAULT NULL,
|
|
stage VARCHAR(50) NOT NULL,
|
|
provider VARCHAR(50) NOT NULL,
|
|
model VARCHAR(100) NOT NULL,
|
|
prompt_tokens INT DEFAULT 0,
|
|
completion_tokens INT DEFAULT 0,
|
|
estimated_cost DECIMAL(10,6) DEFAULT 0,
|
|
request_json LONGTEXT DEFAULT NULL,
|
|
response_status VARCHAR(20) NOT NULL DEFAULT 'success',
|
|
error_message TEXT DEFAULT NULL,
|
|
created_at DATETIME NOT NULL,
|
|
PRIMARY KEY (id),
|
|
KEY post_id (post_id),
|
|
KEY run_id (run_id),
|
|
KEY created_at (created_at),
|
|
KEY stage (stage)
|
|
) {$charset_collate};";
|
|
|
|
// Content scores — post performance metrics for self-improvement.
|
|
$sql_content_scores = "CREATE TABLE {$prefix}content_scores (
|
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
post_id BIGINT UNSIGNED NOT NULL,
|
|
pageviews INT DEFAULT 0,
|
|
avg_time_on_page FLOAT DEFAULT 0,
|
|
bounce_rate FLOAT DEFAULT 0,
|
|
comment_count INT DEFAULT 0,
|
|
composite_score FLOAT DEFAULT 0,
|
|
score_factors_json LONGTEXT DEFAULT NULL,
|
|
measured_at DATETIME NOT NULL,
|
|
PRIMARY KEY (id),
|
|
KEY post_id (post_id),
|
|
KEY measured_at (measured_at),
|
|
KEY composite_score (composite_score)
|
|
) {$charset_collate};";
|
|
|
|
// Event log — structured application log entries for the admin log viewer.
|
|
$sql_event_log = "CREATE TABLE {$prefix}event_log (
|
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
level VARCHAR(10) NOT NULL DEFAULT 'info',
|
|
context VARCHAR(100) DEFAULT NULL,
|
|
message TEXT NOT NULL,
|
|
meta_json LONGTEXT DEFAULT NULL,
|
|
created_at DATETIME NOT NULL,
|
|
PRIMARY KEY (id),
|
|
KEY level (level),
|
|
KEY created_at (created_at),
|
|
KEY level_created (level, created_at)
|
|
) {$charset_collate};";
|
|
|
|
dbDelta( $sql_source_data );
|
|
dbDelta( $sql_analysis );
|
|
dbDelta( $sql_generation_log );
|
|
dbDelta( $sql_content_scores );
|
|
dbDelta( $sql_event_log );
|
|
}
|
|
|
|
/**
|
|
* Set default option values without overwriting existing ones.
|
|
*
|
|
* Uses add_option() which is a no-op if the option already exists.
|
|
*
|
|
* Side effects: writes to wp_options.
|
|
*
|
|
* @return void
|
|
*/
|
|
private static function set_default_options(): void {
|
|
$defaults = [
|
|
'prautoblogger_analysis_model' => PRAUTOBLOGGER_DEFAULT_ANALYSIS_MODEL,
|
|
'prautoblogger_writing_model' => PRAUTOBLOGGER_DEFAULT_WRITING_MODEL,
|
|
'prautoblogger_editor_model' => PRAUTOBLOGGER_DEFAULT_EDITOR_MODEL,
|
|
'prautoblogger_daily_article_target' => 1,
|
|
'prautoblogger_writing_pipeline' => 'multi_step',
|
|
'prautoblogger_niche_description' => '',
|
|
'prautoblogger_target_subreddits' => '[]',
|
|
'prautoblogger_monthly_budget_usd' => 50.00,
|
|
'prautoblogger_tone' => 'informational',
|
|
'prautoblogger_min_word_count' => 800,
|
|
'prautoblogger_max_word_count' => 2000,
|
|
'prautoblogger_topic_exclusions' => '[]',
|
|
'prautoblogger_enabled_sources' => '["reddit"]',
|
|
'prautoblogger_article_font_family' => 'default',
|
|
'prautoblogger_article_font_size' => 0,
|
|
'prautoblogger_table_borders' => '1',
|
|
'prautoblogger_schedule_time' => '03:00',
|
|
'prautoblogger_log_level' => 'info',
|
|
];
|
|
|
|
foreach ( $defaults as $key => $value ) {
|
|
add_option( $key, $value );
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Schedule the daily generation cron event if not already scheduled.
|
|
*
|
|
* The custom 'prautoblogger_six_hours' schedule is normally registered via
|
|
* the `cron_schedules` filter in class-prautoblogger.php. However, activation
|
|
* runs before `plugins_loaded`, so the filter may not be registered yet.
|
|
* We register it inline here to ensure it exists at scheduling time.
|
|
*
|
|
* Side effects: registers a WP-Cron event, may register a cron schedule.
|
|
*
|
|
* @return void
|
|
*/
|
|
private static function schedule_cron(): void {
|
|
if ( ! wp_next_scheduled( 'prautoblogger_daily_generation' ) ) {
|
|
// Schedule for the configured time tomorrow.
|
|
$time_str = get_option( 'prautoblogger_schedule_time', '03:00' );
|
|
$parts = explode( ':', $time_str );
|
|
$hour = isset( $parts[0] ) ? absint( $parts[0] ) : 3;
|
|
$minute = isset( $parts[1] ) ? absint( $parts[1] ) : 0;
|
|
$timestamp = strtotime( "tomorrow {$hour}:{$minute}" );
|
|
|
|
if ( false !== $timestamp ) {
|
|
wp_schedule_event( $timestamp, 'daily', 'prautoblogger_daily_generation' );
|
|
}
|
|
}
|
|
|
|
// Ensure the six-hour schedule exists before referencing it.
|
|
// Activation can fire before plugins_loaded, so the cron_schedules filter
|
|
// in class-prautoblogger.php may not be hooked yet.
|
|
$schedules = wp_get_schedules();
|
|
if ( ! isset( $schedules['prautoblogger_six_hours'] ) ) {
|
|
add_filter( 'cron_schedules', static function ( array $scheds ): array {
|
|
$scheds['prautoblogger_six_hours'] = [
|
|
'interval' => 6 * HOUR_IN_SECONDS,
|
|
'display' => __( 'Every Six Hours', 'prautoblogger' ),
|
|
];
|
|
return $scheds;
|
|
} );
|
|
}
|
|
|
|
// Schedule a separate metrics collection job (runs every 6 hours).
|
|
if ( ! wp_next_scheduled( 'prautoblogger_collect_metrics' ) ) {
|
|
wp_schedule_event( time() + HOUR_IN_SECONDS, 'prautoblogger_six_hours', 'prautoblogger_collect_metrics' );
|
|
}
|
|
|
|
// v0.8.1: daily reaper for orphan `llm_research` rows. Pinned to
|
|
// 03:15 so it runs 15 min after the primary generation cron, giving
|
|
// any live pipeline time to finish and call amortize_research_costs
|
|
// cleanly before the reaper scans.
|
|
if ( ! wp_next_scheduled( 'prautoblogger_reap_orphan_research_rows' ) ) {
|
|
$tomorrow = strtotime( 'tomorrow 03:15' );
|
|
if ( false !== $tomorrow ) {
|
|
wp_schedule_event( $tomorrow, 'daily', 'prautoblogger_reap_orphan_research_rows' );
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* One-shot v0.8.1 migration — back-populate `_prautoblogger_run_id`
|
|
* post_meta for existing posts from their gen-log rows.
|
|
*
|
|
* Lets the orphan-research-row reaper (v0.8.1+) attribute historic
|
|
* orphan rows to sibling posts via post_meta lookup, without having
|
|
* to walk the generation_log table. Gated by
|
|
* `prautoblogger_migrated_run_id_meta_v081` so it runs exactly once
|
|
* per site.
|
|
*
|
|
* Side effects: adds post_meta rows for existing PRAutoBlogger posts
|
|
* that don't already have `_prautoblogger_run_id`.
|
|
*
|
|
* @return void
|
|
*/
|
|
private static function backpopulate_run_id_meta_v081(): void {
|
|
if ( get_option( 'prautoblogger_migrated_run_id_meta_v081' ) ) {
|
|
return;
|
|
}
|
|
|
|
global $wpdb;
|
|
$gen_log = $wpdb->prefix . 'prautoblogger_generation_log';
|
|
|
|
// For each (post_id, run_id) pair present in the gen-log, write
|
|
// the run_id meta if it's not already set. Uses the first run_id
|
|
// seen per post — in practice each post is linked to exactly one run.
|
|
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
|
$pairs = $wpdb->get_results(
|
|
"SELECT post_id, MIN(run_id) AS run_id FROM {$gen_log}
|
|
WHERE post_id IS NOT NULL AND run_id IS NOT NULL AND run_id != ''
|
|
GROUP BY post_id"
|
|
);
|
|
|
|
if ( is_array( $pairs ) ) {
|
|
foreach ( $pairs as $row ) {
|
|
$post_id = (int) ( $row->post_id ?? 0 );
|
|
$run_id = (string) ( $row->run_id ?? '' );
|
|
if ( $post_id > 0 && '' !== $run_id && ! metadata_exists( 'post', $post_id, '_prautoblogger_run_id' ) ) {
|
|
update_post_meta( $post_id, '_prautoblogger_run_id', $run_id );
|
|
}
|
|
}
|
|
}
|
|
|
|
update_option( 'prautoblogger_migrated_run_id_meta_v081', '1' );
|
|
}
|
|
}
|