feat: M4 chained-cron checkpoint generation + board button (v0.21.0)
## Board 'New Article' button
- templates/admin/board-page.php: add #prab-board-generate-now button + status div
- includes/admin/class-board-page.php: inject generateNonce + i18n strings into prabBoard;
enqueue companion board-generate.js
- assets/js/board-generate.js: NEW – board button AJAX handler (fires
prautoblogger_generate_now, resets board backoff on success)
- assets/js/board.js: applySnapshot() re-enables button when no active runs
## Chained-cron checkpoint machine (retires SSH workaround)
- includes/core/class-generation-checkpoint-runner.php: NEW (295 lines)
Tick 1 (prautoblogger_gen_orchestrate): orchestrate_only() → persist queue → schedule Tick 2
Tick 2..N (prautoblogger_gen_tick): pop one idea → Article_Worker → reschedule or finalize
Budget/halt contract + lock release on all exit paths
- includes/class-executor.php: on_manual_generation() replaced with 1-line delegate to
Generation_Checkpoint_Runner::on_orchestrate_tick() (SSH workaround retired)
- includes/class-prautoblogger.php: register ORCHESTRATE_ACTION + GENERATE_ACTION hooks
- includes/core/class-pipeline-runner.php: expose orchestrate_only() public wrapper
- includes/core/class-pipeline-status.php: add write_initial() + write_error() helpers
## WP-CLI command
- includes/admin/class-wp-cli-commands.php: wp prautoblogger generate → kick_off()
## IA / perf pass (settings-backed pagination + DB indexes)
- includes/admin/class-board-data-provider.php: replace hardcoded posts_per_page=20 with
get_option('prautoblogger_board_column_limit', DEFAULT)
- includes/admin/class-board-gen-log-query.php: replace LIMIT 10/20 literals with settings-backed values
- includes/admin/class-ideas-browser-query.php: NEW – query helpers extracted from Ideas_Browser
(300-line rule split): query_ideas(), get_type_counts(), load_idea_data(),
find_post_by_run_id(), update_idea_stage()
- includes/admin/class-ideas-browser.php: delegates all query work to Ideas_Browser_Query
- includes/class-activator.php: set_default_options() adds board_column_limit + ideas_per_page
- includes/admin/class-admin-page.php: add new settings to numeric sanitization list
- prautoblogger.php: PRAUTOBLOGGER_DEFAULT_BOARD_COLUMN_LIMIT=20, PRAUTOBLOGGER_DEFAULT_IDEAS_PER_PAGE=30
- includes/class-schema-installer.php: indexes on generation_log + analysis_results (db 1.4.0)
- includes/class-pipeline-schema-installer.php: KEY started_at on runs table
## Guard P2s
- scripts/check-constants.php: --self-test mode + inline CONSTANTS_GUARD_WINDOW comment
- .github/workflows/ci.yml: check-constants-self-test step after main constants check
## PHPUnit test
- tests/unit/Core/GenerationCheckpointRunnerTest.php: NEW (227 lines)
4 tests: kick_off schedules+transient, empty-queue finalizes, halted-run aborts+cleanup,
multi-idea pops-one-and-reschedules
## Docs + version
- prautoblogger.php: Version 0.21.0, PRAUTOBLOGGER_DB_VERSION 1.4.0
- ARCHITECTURE.md: §25 Chained-Cron Checkpoint Generation Path
- CHANGELOG.md: v0.21.0 entry
- INFORMATION-ARCHITECTURE.md: NEW – admin pages, entry points, DB tables, options, CLI
- uninstall.php: purge prautoblogger_gen_orchestrate + prautoblogger_gen_tick cron hooks
Agent-Session: phase2-admin-m4-20260614
This commit is contained in:
295
includes/core/class-generation-checkpoint-runner.php
Normal file
295
includes/core/class-generation-checkpoint-runner.php
Normal file
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
|
||||
*
|
||||
* Chained-cron checkpoint runner for in-admin manual article generation (v0.21.0, M4).
|
||||
*
|
||||
* What: Replaces the monolithic on_manual_generation() path with a two-tick
|
||||
* checkpoint machine so Hostinger's background-PHP-process kill cannot
|
||||
* abort a mid-pipeline run:
|
||||
* Tick 1 (ORCHESTRATE): collect sources -> analyze patterns -> score ideas ->
|
||||
* persist idea queue to option -> schedule Tick 2.
|
||||
* Tick 2..N (GENERATE): pop one idea from queue -> Article_Worker ->
|
||||
* update transient -> schedule next tick or finalize.
|
||||
*
|
||||
* Why separate from Rerun_Executor: Rerun_Executor targets existing run_stages
|
||||
* rows (replay/rebuild). This class creates a brand-new run from scratch.
|
||||
*
|
||||
* SSH retirement (v0.21.0): the former `wp eval 'do_action("prautoblogger_manual_generation")'`
|
||||
* workaround fired on_manual_generation() synchronously in one PHP process --
|
||||
* bypassing the nonce and running the full pipeline without checkpoints.
|
||||
* That path is retired: Executor::on_manual_generation() now delegates here,
|
||||
* and `wp prautoblogger generate` queues via kick_off() (see ARCHITECTURE.md ss25).
|
||||
*
|
||||
* Cost governor: Run_State::ceiling_setting() is applied per-run; a halted run
|
||||
* aborts all remaining ticks (same guarantee as Pipeline_Runner's queued-article path).
|
||||
*
|
||||
* Who triggers it: PRAutoBlogger_Executor::on_manual_generation() (cron),
|
||||
* PRAutoBlogger_WP_CLI_Commands (wp prautoblogger generate).
|
||||
* Dependencies: Pipeline_Runner (orchestration), Run_State (run ledger),
|
||||
* Pipeline_Status (transient), Generation_Lock, Cost_Tracker, Logger.
|
||||
*
|
||||
* @see includes/class-executor.php -- Cron/AJAX entry points.
|
||||
* @see core/class-pipeline-runner.php -- Orchestration + article worker.
|
||||
* @see core/class-run-state.php -- Per-run ledger (cost governor).
|
||||
* @see core/class-pipeline-status.php -- Transient broadcast helpers.
|
||||
* @see ARCHITECTURE.md ss25 -- Checkpoint generation path design.
|
||||
*/
|
||||
class PRAutoBlogger_Generation_Checkpoint_Runner {
|
||||
|
||||
/** Option key for the checkpoint queue (shared with Pipeline_Runner article queue). */
|
||||
private const QUEUE_KEY = 'prautoblogger_article_queue';
|
||||
|
||||
/** Option key for the in-progress run UUID (generation tick). */
|
||||
private const RUN_ID_KEY = 'prautoblogger_checkpoint_run_id';
|
||||
|
||||
/** WP-Cron action for the orchestration tick. */
|
||||
public const ORCHESTRATE_ACTION = 'prautoblogger_gen_orchestrate';
|
||||
|
||||
/** WP-Cron action for each article-generation tick. */
|
||||
public const GENERATE_ACTION = 'prautoblogger_gen_tick';
|
||||
|
||||
/**
|
||||
* Schedule the orchestration tick and write the initial status transient.
|
||||
* Called by on_ajax_generate_now() (via Executor) and by the WP-CLI command.
|
||||
* Returns immediately -- ALL pipeline work happens in cron.
|
||||
*
|
||||
* Side effects: cron scheduling, transient write.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function kick_off(): void {
|
||||
if ( wp_next_scheduled( self::ORCHESTRATE_ACTION ) ) {
|
||||
return; // Idempotent: already queued.
|
||||
}
|
||||
wp_schedule_single_event( time(), self::ORCHESTRATE_ACTION );
|
||||
PRAutoBlogger_Pipeline_Status::write_initial();
|
||||
self::fire_cron_now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cron Tick 1: collect -> analyze -> score. Persists ideas, creates run row,
|
||||
* schedules Tick 2 for the first article, then returns.
|
||||
*
|
||||
* Side effects: source/analysis DB writes, run row insert, option write,
|
||||
* status transient update, cron scheduling.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function on_orchestrate_tick(): void {
|
||||
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
|
||||
@ignore_user_abort( true );
|
||||
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
|
||||
@set_time_limit( 300 );
|
||||
|
||||
if ( ! PRAutoBlogger_Generation_Lock::acquire() ) {
|
||||
PRAutoBlogger_Pipeline_Status::write_error(
|
||||
__( 'Could not acquire generation lock. Another run may be in progress.', 'prautoblogger' )
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
$run_id = wp_generate_uuid4();
|
||||
update_option( self::RUN_ID_KEY, $run_id, false );
|
||||
PRAutoBlogger_Run_State::ensure_run( $run_id );
|
||||
|
||||
$cost_tracker = new PRAutoBlogger_Cost_Tracker();
|
||||
$cost_tracker->set_run_id( $run_id );
|
||||
|
||||
try {
|
||||
if ( $cost_tracker->is_budget_exceeded() ) {
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
|
||||
PRAutoBlogger_Pipeline_Status::write_error(
|
||||
__( 'Monthly API budget exceeded. Generation halted.', 'prautoblogger' )
|
||||
);
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
return;
|
||||
}
|
||||
|
||||
PRAutoBlogger_Pipeline_Status::broadcast( __( 'Collecting sources…', 'prautoblogger' ) );
|
||||
$runner = ( new PRAutoBlogger_Pipeline_Runner() )->set_skip_dedup( true );
|
||||
$ideas = $runner->orchestrate_only( $cost_tracker );
|
||||
|
||||
if ( empty( $ideas ) ) {
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'done' );
|
||||
PRAutoBlogger_Pipeline_Status::write_final(
|
||||
array( 'generated' => 0, 'published' => 0, 'rejected' => 0, 'cost' => 0.0 )
|
||||
);
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
delete_option( self::RUN_ID_KEY );
|
||||
return;
|
||||
}
|
||||
|
||||
$serialized = array_map(
|
||||
static fn( PRAutoBlogger_Article_Idea $i ) => $i->to_array(),
|
||||
$ideas
|
||||
);
|
||||
update_option(
|
||||
self::QUEUE_KEY,
|
||||
array(
|
||||
'run_id' => $run_id,
|
||||
'ideas' => $serialized,
|
||||
'results' => array( 'generated' => 0, 'published' => 0, 'rejected' => 0, 'cost' => 0.0 ),
|
||||
),
|
||||
false
|
||||
);
|
||||
|
||||
PRAutoBlogger_Pipeline_Status::broadcast(
|
||||
sprintf(
|
||||
/* translators: %d: number of ideas found */
|
||||
__( 'Found %d idea(s) — starting generation…', 'prautoblogger' ),
|
||||
count( $ideas )
|
||||
)
|
||||
);
|
||||
|
||||
if ( ! wp_next_scheduled( self::GENERATE_ACTION ) ) {
|
||||
wp_schedule_single_event( time(), self::GENERATE_ACTION );
|
||||
}
|
||||
self::fire_cron_now();
|
||||
|
||||
} catch ( \Throwable $e ) {
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
sprintf( 'Orchestrate tick %s: %s', get_class( $e ), $e->getMessage() ),
|
||||
'pipeline'
|
||||
);
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
|
||||
PRAutoBlogger_Pipeline_Status::write_error( $e->getMessage() );
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
delete_option( self::RUN_ID_KEY );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cron Tick 2..N: generate one article, persist totals, reschedule or finalize.
|
||||
*
|
||||
* Side effects: LLM API calls, DB writes, post creation, transient updates,
|
||||
* cron scheduling.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function on_generate_tick(): void {
|
||||
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
|
||||
@ignore_user_abort( true );
|
||||
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
|
||||
@set_time_limit( 300 );
|
||||
|
||||
$queue = get_option( self::QUEUE_KEY );
|
||||
if ( ! is_array( $queue ) || empty( $queue['ideas'] ) ) {
|
||||
self::finalize( array( 'generated' => 0, 'published' => 0, 'rejected' => 0, 'cost' => 0.0 ) );
|
||||
return;
|
||||
}
|
||||
|
||||
$run_id = (string) ( $queue['run_id'] ?? '' );
|
||||
$run_status = PRAutoBlogger_Run_State::get_status( $run_id );
|
||||
if ( in_array( $run_status, array( 'halted', 'failed' ), true ) ) {
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
sprintf( 'Generate tick: run %s is %s -- aborting.', $run_id, $run_status ),
|
||||
'pipeline'
|
||||
);
|
||||
self::cleanup_queue();
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
return;
|
||||
}
|
||||
|
||||
$idea_data = array_shift( $queue['ideas'] );
|
||||
$idea = new PRAutoBlogger_Article_Idea( $idea_data );
|
||||
$cost_tracker = new PRAutoBlogger_Cost_Tracker();
|
||||
$cost_tracker->set_run_id( $run_id );
|
||||
|
||||
if ( $cost_tracker->is_budget_exceeded() ) {
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
|
||||
self::cleanup_queue();
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
PRAutoBlogger_Pipeline_Status::write_error(
|
||||
__( 'Monthly API budget exceeded. Generation halted.', 'prautoblogger' )
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Persist consumed queue BEFORE generating (prevents orphan-recovery duplication).
|
||||
if ( ! empty( $queue['ideas'] ) ) {
|
||||
update_option( self::QUEUE_KEY, $queue, false );
|
||||
} else {
|
||||
delete_option( self::QUEUE_KEY );
|
||||
}
|
||||
|
||||
try {
|
||||
$worker = new PRAutoBlogger_Article_Worker( $cost_tracker );
|
||||
$result = $worker->generate( $idea );
|
||||
|
||||
$queue['results']['generated'] += $result['generated'];
|
||||
$queue['results']['published'] += $result['published'];
|
||||
$queue['results']['rejected'] += $result['rejected'];
|
||||
$queue['results']['cost'] += $result['cost'];
|
||||
|
||||
if ( ! empty( $queue['ideas'] ) ) {
|
||||
update_option( self::QUEUE_KEY, $queue, false );
|
||||
PRAutoBlogger_Pipeline_Status::update_queue_progress( $queue );
|
||||
if ( ! wp_next_scheduled( self::GENERATE_ACTION ) ) {
|
||||
wp_schedule_single_event( time(), self::GENERATE_ACTION );
|
||||
}
|
||||
self::fire_cron_now();
|
||||
} else {
|
||||
PRAutoBlogger_Post_Assembler::amortize_research_costs( $run_id );
|
||||
self::finalize( $queue['results'], $run_id );
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
sprintf( 'Generate tick %s for run %s: %s', get_class( $e ), $run_id, $e->getMessage() ),
|
||||
'pipeline'
|
||||
);
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
|
||||
self::cleanup_queue();
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
PRAutoBlogger_Pipeline_Status::write_error( $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
// -- Private helpers --------------------------------------------------
|
||||
|
||||
/**
|
||||
* Finalize a completed run: write final transient, mark run done, release lock.
|
||||
*
|
||||
* @param array $results Generation counters (generated/published/rejected/cost).
|
||||
* @param string $run_id Run UUID (read from option if blank).
|
||||
* @return void
|
||||
*/
|
||||
private static function finalize( array $results, string $run_id = '' ): void {
|
||||
if ( '' === $run_id ) {
|
||||
$run_id = (string) get_option( self::RUN_ID_KEY, '' );
|
||||
}
|
||||
if ( '' !== $run_id ) {
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'done' );
|
||||
}
|
||||
PRAutoBlogger_Pipeline_Status::write_final( $results );
|
||||
PRAutoBlogger_Pipeline_Status::log_summary( $results );
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
delete_option( self::RUN_ID_KEY );
|
||||
}
|
||||
|
||||
/** Remove the persistent queue and run-id option on abort paths. */
|
||||
private static function cleanup_queue(): void {
|
||||
delete_option( self::QUEUE_KEY );
|
||||
delete_option( self::RUN_ID_KEY );
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-blocking loopback to fire cron events immediately.
|
||||
* Mirrors Pipeline_Runner::schedule_next() exactly.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function fire_cron_now(): void {
|
||||
spawn_cron();
|
||||
wp_remote_post(
|
||||
site_url( 'wp-cron.php?doing_wp_cron=' . sprintf( '%.22F', microtime( true ) ) ),
|
||||
array(
|
||||
'timeout' => 0.01,
|
||||
'blocking' => false,
|
||||
'sslverify' => false,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,19 @@ class PRAutoBlogger_Pipeline_Runner {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Public wrapper for orchestrate(): collect -> analyze -> score.
|
||||
* Used by Generation_Checkpoint_Runner (Tick 1) so orchestration and
|
||||
* article generation happen in separate cron ticks.
|
||||
*
|
||||
* @param PRAutoBlogger_Cost_Tracker $cost_tracker
|
||||
* @return PRAutoBlogger_Article_Idea[]
|
||||
*/
|
||||
public function orchestrate_only( PRAutoBlogger_Cost_Tracker $cost_tracker ): array {
|
||||
return $this->orchestrate( $cost_tracker );
|
||||
}
|
||||
|
||||
// ── Private helpers ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -103,4 +103,42 @@ class PRAutoBlogger_Pipeline_Status {
|
||||
'pipeline'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write an initial "running" status before the first tick fires.
|
||||
* Mirrors the shape on_ajax_generate_now() already writes so the poller
|
||||
* sees a consistent "running" state whether triggered from board or settings page.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function write_initial(): void {
|
||||
set_transient(
|
||||
self::KEY,
|
||||
array(
|
||||
'status' => 'running',
|
||||
'stage' => __( 'Starting generation…', 'prautoblogger' ),
|
||||
'started' => time(),
|
||||
'last_updated' => time(),
|
||||
),
|
||||
self::TTL
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a terminal "error" status.
|
||||
*
|
||||
* @param string $message Operator-facing error description.
|
||||
* @return void
|
||||
*/
|
||||
public static function write_error( string $message ): void {
|
||||
set_transient(
|
||||
self::KEY,
|
||||
array(
|
||||
'status' => 'error',
|
||||
'message' => $message,
|
||||
),
|
||||
self::TTL
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user