method. The label names the step in the * log line and in run()'s failure message. * * @var array */ private const STEPS = array( 'mode decision' => 'upgradeModeAndNotice', 'description prompt options' => 'upgradeDescriptionPrompts', 'automation job prompts' => 'upgradeAutomationJobs', 'local template prompts' => 'upgradeLocalTemplates', ); /** * Run every step. Safe to call more than once: every step only fills in * a value that does not already exist. Each step is isolated in its own * try/catch so a failure in one (e.g. a transient DB error while * scanning Automation jobs) never blocks the others. A failed step is * still reported once every step has run: Migration writes its * permanent guard only when this method returns, so the throw leaves * the guard unset and its next (throttled) pass retries the whole run. * * @return void * @throws \RuntimeException When at least one step failed; the first * step's error is the previous exception. */ public static function run(): void { $failed = array(); $first = null; foreach ( self::STEPS as $label => $method ) { try { self::$method(); } catch ( \Throwable $e ) { self::logStepError( $label, $e ); $failed[] = $label; $first = $first ?? $e; } } if ( array() !== $failed ) { $message = 'Content mode upgrade incomplete (' . implode( ', ', $failed ) . '); it will be retried.'; throw new \RuntimeException( $message, 0, $first ); } } /** * Log one step's failure. Never throws itself. * * @param string $label Human-readable step name for the log line. * @param \Throwable $e The caught error. * @return void */ private static function logStepError( string $label, \Throwable $e ): void { } /** * Decide the plugin-wide content mode once, only when the site does not * already have one: a prior run of this method, a fresh activation * ({@see \AIPT\Core\Activator}'s own seed), or a merchant's own Settings * choice must never be overwritten. * * @return void */ private static function upgradeModeAndNotice(): void { if ( false !== get_option( ExecutionModeRegistry::OPTION ) ) { return; } $ran_custom_prompts = self::sitePreviouslyRanCustomPrompts(); self::addMissingOption( ExecutionModeRegistry::OPTION, ExecutionModeRegistry::BLUEPRINT, true ); if ( $ran_custom_prompts ) { update_option( self::NOTICE_OPTION, '1', false ); } } /** * Whether the site ran custom prompts before this upgrade: the 2.8.0 * per-generator map says so directly when it exists (any generator * `advanced`); a site that predates even that map (2.7.x) is read * through {@see CustomizationDetector} instead — the same live-prompt * comparison 2.8.0's own upgrade used to make that same per-generator * decision. * * @return bool */ private static function sitePreviouslyRanCustomPrompts(): bool { $legacy_map = get_option( ExecutionModeRegistry::LEGACY_OPTION, null ); if ( is_array( $legacy_map ) ) { return in_array( ExecutionModeRegistry::ADVANCED, $legacy_map, true ); } $detector = new CustomizationDetector(); foreach ( Generators::all() as $generator ) { if ( $detector->isCustomized( $generator ) ) { return true; } } return false; } /** * Pre-seed `aipt_short_custom_prompt` / `aipt_full_custom_prompt` from * whatever pre-2.8.1 prompt options the site had, for every type that * does not already have one. * * @return void */ private static function upgradeDescriptionPrompts(): void { foreach ( CustomPrompts::types() as $type ) { $option = CustomPrompts::optionName( $type ); if ( false !== get_option( $option ) ) { continue; } self::addMissingOption( $option, CustomPrompts::mergedFromLegacyOptions( $type ), false ); } } /** * Add an option the caller just found missing. add_option() returns * false for a missing option only when the write itself failed, which * must not pass silently: the run would end, the guard would be written * and the value would never be seeded. * * @param string $option Option name, known to be missing. * @param mixed $value Value to store. * @param bool $autoload Whether to autoload the option. * @return void * @throws \RuntimeException When the option could not be stored. */ private static function addMissingOption( string $option, $value, bool $autoload ): void { if ( ! add_option( $option, $value, '', $autoload ) ) { throw new \RuntimeException( "Could not store the {$option} option." ); } } /** * Merge every Automation job's saved per-job prompt override into the * `prompts.{type}.custom_prompt` shape {@see CustomPrompts::runOverride()} * reads first, keeping every old key untouched (a downgrade must still * find its original system/user prompts). Skips entirely when the * table does not exist yet (defensive only — Migration always creates * it before this runs). * * @return void */ private static function upgradeAutomationJobs(): void { global $wpdb; $table = $wpdb->prefix . 'aipt_automation_jobs'; if ( ! self::tableExists( $table ) ) { return; } $last_id = 0; do { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, settings FROM {$table} WHERE id > %d AND settings LIKE %s ORDER BY id ASC LIMIT %d", $last_id, '%' . $wpdb->esc_like( 'prompt' ) . '%', self::BATCH_SIZE ), ARRAY_A ); if ( empty( $rows ) ) { break; } foreach ( $rows as $row ) { $last_id = (int) $row['id']; self::upgradeJobRow( $table, $row ); } } while ( count( $rows ) === self::BATCH_SIZE ); } /** * Merge one Automation job row's prompt override, writing it back only * when at least one prompt type actually changed. Invalid JSON is * skipped, not repaired. * * @param string $table Automation jobs table name. * @param array $row `id` + raw `settings` JSON. * @return void */ private static function upgradeJobRow( string $table, array $row ): void { $settings = json_decode( (string) $row['settings'], true ); if ( ! is_array( $settings ) ) { return; } $changed = false; foreach ( CustomPrompts::types() as $type ) { $entry = isset( $settings['prompts'][ $type ] ) && is_array( $settings['prompts'][ $type ] ) ? $settings['prompts'][ $type ] : array(); if ( isset( $entry['custom_prompt'] ) && is_string( $entry['custom_prompt'] ) && '' !== trim( $entry['custom_prompt'] ) ) { continue; } $system = is_string( $entry['system_prompt'] ?? null ) ? $entry['system_prompt'] : (string) ( $settings[ $type . '_system_prompt' ] ?? '' ); $user = is_string( $entry['user_prompt'] ?? null ) ? $entry['user_prompt'] : (string) ( $settings[ $type . '_user_prompt' ] ?? '' ); $merged = CustomPrompts::merge( $system, $user ); if ( '' === $merged ) { continue; } $entry['custom_prompt'] = $merged; $settings['prompts'][ $type ] = $entry; $changed = true; } if ( ! $changed ) { return; } global $wpdb; $wpdb->update( $table, array( 'settings' => wp_json_encode( $settings ) ), array( 'id' => (int) $row['id'] ), array( '%s' ), array( '%d' ) ); } /** * Merge every local Description prompt template's (including a legacy * 'standard' one's) system/user * prompt into `prompt_data.custom_prompt`, keeping the old keys. Skips * entirely when the table does not exist yet (defensive only). * * @return void */ private static function upgradeLocalTemplates(): void { global $wpdb; $table = $wpdb->prefix . 'aipt_prompt_templates'; if ( ! self::tableExists( $table ) ) { return; } $last_id = 0; do { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, prompt_data FROM {$table} WHERE id > %d AND generator_type IN (%s, %s) ORDER BY id ASC LIMIT %d", $last_id, Generators::DESCRIPTION, self::LEGACY_STANDARD_TEMPLATE_TYPE, self::BATCH_SIZE ), ARRAY_A ); if ( empty( $rows ) ) { break; } foreach ( $rows as $row ) { $last_id = (int) $row['id']; self::upgradeTemplateRow( $table, $row ); } } while ( count( $rows ) === self::BATCH_SIZE ); } /** * Merge one local template row's prompt_data, writing it back only when * it gained a custom_prompt. Invalid JSON is skipped, not repaired. * * @param string $table Prompt templates table name. * @param array $row `id` + raw `prompt_data` JSON. * @return void */ private static function upgradeTemplateRow( string $table, array $row ): void { $prompt_data = json_decode( (string) $row['prompt_data'], true ); if ( ! is_array( $prompt_data ) ) { return; } if ( isset( $prompt_data['custom_prompt'] ) && is_string( $prompt_data['custom_prompt'] ) && '' !== trim( $prompt_data['custom_prompt'] ) ) { return; } $system = is_string( $prompt_data['system_prompt'] ?? null ) ? $prompt_data['system_prompt'] : ''; $user = is_string( $prompt_data['user_prompt'] ?? null ) ? $prompt_data['user_prompt'] : ''; $merged = CustomPrompts::merge( $system, $user ); if ( '' === $merged ) { return; } $prompt_data['custom_prompt'] = $merged; global $wpdb; $wpdb->update( $table, array( 'prompt_data' => wp_json_encode( $prompt_data ) ), array( 'id' => (int) $row['id'] ), array( '%s' ), array( '%d' ) ); } /** * Whether a table exists, via the established `SHOW TABLES LIKE` * pattern (mirrors {@see \AIPT\Premium\ContentStructure\CatalogWatch\CatalogWatchStore::exists()}). * * @param string $table Fully-prefixed table name. * @return bool */ private static function tableExists( string $table ): bool { global $wpdb; return $table === $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ); } }