session = Context::load_json( self::SESSION_FILE ) ?: []; } /** Save current session data. */ private function save_session(): void { Context::save_json( self::SESSION_FILE, $this->session ); } /** Prepare headers for streaming AJAX responses. */ private function stream_setup(): void { $prev = ini_get( 'zlib.output_compression' ); if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } while ( ob_get_level() ) { @ob_end_flush(); } header( 'Content-Type: text/plain; charset=utf-8' ); $this->session['prev_zlib'] = $prev; } /* ===== Public entry point ======================================= */ /** * Execute full post generation pipeline and return the created post ID. * * @return int Generated post ID. */ public function generate_post(): int { list( $allowed, $msg ) = Limits::can_generate(); if ( ! $allowed ) { throw new \RuntimeException( esc_html( $msg ) ); } $this->run_stage( fn() => $this->generate_draft(), 'draft' ); $this->run_stage( fn() => $this->run_qa_stage(), 'qa' ); $this->run_stage( fn() => $this->finalize_post(), 'final' ); return $this->run_stage( fn() => $this->generate_image(), 'image' ); } /** * Manual trigger for post generation, used by REST endpoints or AJAX. * * @return int Generated post ID. */ public static function manual_run(): int { $generator = new self(); return $generator->generate_post(); } /** * Generate list of topics suggestions. * * @return array{thread_id:string,vector_id:string,topics:array} */ public static function suggest_topics(): array { $generator = new self(); return $generator->with_retry( fn() => $generator->generate_topic_suggestions() ); } /** * Launch topic suggestion generation asynchronously. * * @return string Job identifier for polling. */ public static function start_async_topic_job(): string { $job_id = wp_generate_uuid4(); $session = [ 'job_id' => $job_id, 'job_status' => 'queued', 'progress' => '', 'retries' => 0, 'last_update'=> time(), ]; Context::save_json( self::TOPIC_SESSION_FILE, $session ); if ( ! wp_next_scheduled( 'aipub_process_topic_job', [ $job_id ] ) ) { wp_schedule_single_event( time(), 'aipub_process_topic_job', [ $job_id ] ); } if ( ! wp_doing_cron() ) { function_exists( 'spawn_cron' ) ? spawn_cron() : wp_cron(); } return $job_id; } /** * Generate a post based on a selected topic. * * @param string $thread_id Existing thread ID from suggest_topics(). * @param string $vector_id Existing vector store ID from suggest_topics(). * @param string $topic Chosen topic text. * @param string[] $keywords Associated keywords. * @return int Generated post ID. */ public static function manual_run_with_topic( string $thread_id, string $vector_id, string $topic, array $keywords ): int { $generator = new self(); return $generator->generate_post_with_topic( $thread_id, $vector_id, $topic, $keywords ); } /** * Launch post generation asynchronously via WP-Cron. * * Stores the job ID and optional topic info in session.json and * schedules the cron event that will execute the generation. * * @param string $thread_id Optional thread ID for selected topic. * @param string $vector_id Optional vector store ID for selected topic. * @param string $topic Optional topic text. * @param string[] $keywords Optional keywords. * @return string Generated job ID used for polling. */ public static function start_async_generation( string $thread_id = '', string $vector_id = '', string $topic = '', array $keywords = [] ): string { list( $allowed, $msg ) = Limits::can_generate(); if ( ! $allowed ) { throw new \RuntimeException( esc_html( $msg ) ); } $job_id = wp_generate_uuid4(); $session = [ 'job_id' => $job_id, 'job_status' => 'queued', 'progress' => '', ]; if ( $topic ) { $session['topic_text'] = $topic; $session['topic_keys'] = $keywords; } if ( $thread_id && $vector_id ) { $session['topic_thread'] = $thread_id; $session['topic_vector'] = $vector_id; } Context::save_json( self::SESSION_FILE, $session ); if ( ! wp_next_scheduled( 'aipub_process_post_job', [ $job_id ] ) ) { wp_schedule_single_event( time(), 'aipub_process_post_job', [ $job_id ] ); } if ( ! wp_doing_cron() ) { function_exists( 'spawn_cron' ) ? spawn_cron() : wp_cron(); } return $job_id; } /** * Cron callback to process an async post generation job. * * @param string $job_id Job identifier from start_async_generation(). * @return void */ public static function process_async_job( string $job_id ): void { ignore_user_abort( true ); aipub_with_time_limit( Brand_Strategy::TIMEOUT_SECS, function () use ( $job_id ) { $gen = new self(); $gen->load_session(); if ( ( $gen->session['job_id'] ?? '' ) !== $job_id ) { return; // Unknown job. } list( $allowed, $msg ) = Limits::can_generate(); if ( ! $allowed ) { $gen->session['job_status'] = 'error'; $gen->session['error'] = $msg; $gen->save_session(); return; } $gen->session['job_status'] = 'running'; $gen->session['progress'] = 'draft'; $gen->save_session(); $attempts = $gen->session['retries'] ?? 0; try { if ( isset( $gen->session['topic_thread'], $gen->session['topic_vector'], $gen->session['topic_text'] ) ) { $post_id = $gen->generate_post_with_topic( $gen->session['topic_thread'], $gen->session['topic_vector'], $gen->session['topic_text'], $gen->session['topic_keys'] ?? [] ); } elseif ( isset( $gen->session['topic_text'] ) ) { $post_id = $gen->generate_post_from_topic_text( $gen->session['topic_text'], $gen->session['topic_keys'] ?? [] ); } else { $gen->generate_draft(); $gen->session['progress'] = 'qa'; $gen->save_session(); $gen->run_qa_stage(); $gen->session['progress'] = 'final'; $gen->save_session(); $gen->finalize_post(); $gen->session['progress'] = 'image'; $gen->save_session(); $post_id = $gen->generate_image(); } Cron::maybe_reschedule(); $gen->session['job_status'] = 'done'; $gen->session['progress'] = 'done'; $gen->session['result'] = [ 'post_id' => $post_id, 'post_edit' => admin_url( 'post.php?post=' . $post_id . '&action=edit' ), 'post_view' => get_permalink( $post_id ), ]; $gen->save_session(); } catch ( \Throwable $e ) { $attempts++; if ( $attempts < self::MAX_RETRIES ) { $gen->session['retries'] = $attempts; $gen->session['job_status'] = 'running'; $gen->save_session(); if ( ! wp_next_scheduled( 'aipub_process_post_job', [ $job_id ] ) ) { wp_schedule_single_event( time() + 30, 'aipub_process_post_job', [ $job_id ] ); } return; } $gen->session['job_status'] = 'error'; $gen->session['error'] = $e->getMessage(); $gen->save_session(); $gen->cleanup_openai( [], $gen->session['vector_id'] ?? '', $gen->session['thread_id'] ?? '' ); } } ); } /** * Cron callback to process async topic suggestion job. * * @param string $job_id Job identifier from start_async_topic_job(). * @return void */ public static function process_async_topic_job( string $job_id ): void { ignore_user_abort( true ); aipub_with_time_limit( Brand_Strategy::TIMEOUT_SECS, function () use ( $job_id ) { $session = Context::load_json( self::TOPIC_SESSION_FILE ) ?: []; if ( ( $session['job_id'] ?? '' ) !== $job_id ) { return; } $session['job_status'] = 'running'; $session['last_update'] = time(); Context::save_json( self::TOPIC_SESSION_FILE, $session ); $attempts = $session['retries'] ?? 0; try { $gen = new self(); $data = $gen->generate_topic_suggestions(); $session['job_status'] = 'done'; $session['progress'] = 'done'; $session['result'] = $data; $session['last_update'] = time(); Context::save_json( self::TOPIC_SESSION_FILE, $session ); } catch ( \Throwable $e ) { $attempts++; if ( $attempts < self::MAX_RETRIES ) { $session['retries'] = $attempts; $session['job_status'] = 'running'; $session['error'] = $e->getMessage(); $session['last_update'] = time(); Context::save_json( self::TOPIC_SESSION_FILE, $session ); if ( ! wp_next_scheduled( 'aipub_process_topic_job', [ $job_id ] ) ) { wp_schedule_single_event( time() + 30, 'aipub_process_topic_job', [ $job_id ] ); } return; } $session['job_status'] = 'error'; $session['error'] = $e->getMessage(); $session['last_update'] = time(); Context::save_json( self::TOPIC_SESSION_FILE, $session ); } } ); } /** Generate the draft stage and persist context. */ public function generate_draft( bool $stream = false ): void { $this->assert_setup_complete(); $this->load_session(); if ( $stream ) { $this->stream_setup(); echo wp_json_encode( [ 'msg' => 'drafting' ] ) . "\n"; @flush(); } $thread_id = $this->create_thread(); $ctx_files = $this->collect_all_context_files(); $vector_store_id = $this->create_vector_store( $ctx_files ); $publisher_id = $this->create_publisher_assistant( $vector_store_id ); $this->with_retry( fn() => $this->draft_post( $thread_id, $publisher_id ) ); $this->add_files_to_vector_store( $vector_store_id, [ Context::dir() . 'draft-post.json' ] ); $this->session = array_merge( $this->session, [ 'thread_id' => $thread_id, 'vector_id' => $vector_store_id, 'publisher_id' => $publisher_id, ] ); $this->save_session(); if ( $stream ) { echo wp_json_encode( [ 'success' => true ] ) . "\n"; if ( function_exists( 'ini_set' ) && isset( $old_zlib ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- restore previous compression setting @ini_set( 'zlib.output_compression', $old_zlib ); unset( $old_zlib ); } } } /** Run QA against the draft post. */ public function run_qa_stage( bool $stream = false ): void { $this->load_session(); if ( empty( $this->session['thread_id'] ) || empty( $this->session['vector_id'] ) ) { throw new \RuntimeException( 'Session not initialized.' ); } if ( $stream ) { $old_zlib = ini_get( 'zlib.output_compression' ); if ( function_exists( 'ini_set' ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- disable compression for this stream @ini_set( 'zlib.output_compression', 'Off' ); } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } while ( ob_get_level() ) { @ob_end_flush(); } header( 'Content-Type: text/plain; charset=utf-8' ); $this->session['prev_zlib'] = $old_zlib; echo wp_json_encode( [ 'msg' => 'qa' ] ) . "\n"; @flush(); } $qa_id = $this->create_qa_assistant( $this->session['vector_id'] ); $draft = Context::load_json( 'draft-post.json' ) ?: []; $pass = $this->with_retry( fn() => $this->run_qa( $this->session['thread_id'], $qa_id, $draft ) ); $this->add_files_to_vector_store( $this->session['vector_id'], [ Context::dir() . 'post-qa.json' ] ); $this->session['qa_id'] = $qa_id; $this->session['qa_pass'] = $pass; $this->save_session(); if ( $stream ) { echo wp_json_encode( [ 'pass' => $pass, 'success' => true ] ) . "\n"; if ( function_exists( 'ini_set' ) && isset( $old_zlib ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- restore previous compression setting @ini_set( 'zlib.output_compression', $old_zlib ); unset( $old_zlib ); } } } /** Apply revisions if QA failed and save final-post.json. */ public function finalize_post( bool $stream = false ): void { $this->load_session(); if ( empty( $this->session['thread_id'] ) || empty( $this->session['vector_id'] ) ) { throw new \RuntimeException( 'Session not initialized.' ); } if ( $stream ) { $old_zlib = ini_get( 'zlib.output_compression' ); if ( function_exists( 'ini_set' ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- disable compression for this stream @ini_set( 'zlib.output_compression', 'Off' ); } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } while ( ob_get_level() ) { @ob_end_flush(); } header( 'Content-Type: text/plain; charset=utf-8' ); $this->session['prev_zlib'] = $old_zlib; echo wp_json_encode( [ 'msg' => 'finalizing' ] ) . "\n"; @flush(); } $draft = Context::load_json( 'draft-post.json' ) ?: []; if ( empty( $this->session['qa_pass'] ) ) { $assistant_id = $this->create_publisher_final_assistant( $this->session['vector_id'] ); $this->session['final_id'] = $assistant_id; $final_post = $this->with_retry( fn() => $this->revise_post( $this->session['thread_id'], $assistant_id, $draft ) ); } else { $final_post = $draft; } try { Context::save_json( 'final-post.json', $final_post ); } catch ( \Throwable $e ) { throw $e; } $this->save_session(); if ( $stream ) { echo wp_json_encode( [ 'success' => true ] ) . "\n"; if ( function_exists( 'ini_set' ) && isset( $old_zlib ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- restore previous compression setting @ini_set( 'zlib.output_compression', $old_zlib ); unset( $old_zlib ); } } } /** Generate image, insert the post and cleanup. */ public function generate_image( bool $stream = false ): int { $this->load_session(); if ( empty( $this->session['thread_id'] ) || empty( $this->session['vector_id'] ) ) { throw new \RuntimeException( 'Session not initialized.' ); } if ( $stream ) { $old_zlib = ini_get( 'zlib.output_compression' ); if ( function_exists( 'ini_set' ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- disable compression for this stream @ini_set( 'zlib.output_compression', 'Off' ); } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } while ( ob_get_level() ) { @ob_end_flush(); } header( 'Content-Type: text/plain; charset=utf-8' ); $this->session['prev_zlib'] = $old_zlib; echo wp_json_encode( [ 'msg' => 'image' ] ) . "\n"; @flush(); } $final_post = Context::load_json( 'final-post.json' ) ?: []; $prompt_vs_id = $this->create_vector_store([ Context::dir() . 'brand-strategy.json', Context::dir() . 'final-post.json', ]); $img_prompt_assistant = $this->create_image_prompt_assistant( $prompt_vs_id ); $prompt_thread = $this->create_thread(); $prompts = self::load_post_generation_prompts(); $img_block = $prompts['TransformX Image Prompt Generator']; $img_prompt = $this->with_retry( function() use ( $prompt_thread, $img_prompt_assistant, $img_block ) { $this->add_user_message( $prompt_thread, $img_block['user_message'] ); $this->run_assistant( $prompt_thread, $img_prompt_assistant, $img_block['assistant_instructions'] ); return trim( $this->wait_for_assistant_message( $prompt_thread ) ); } ); Context::save_json( 'image-prompt.json', [ 'prompt' => $img_prompt ] ); $this->cleanup_openai( [ $img_prompt_assistant ], $prompt_vs_id, $prompt_thread ); $img_id = $this->with_retry( fn() => $this->create_featured_image( $final_post, $img_prompt ) ); $post_id = $this->with_retry( fn() => $this->insert_wp_post( $final_post, $img_id ) ); // After insertion, update final-post.json with URL and resolved category names. $final_post['url'] = get_permalink( $post_id ); $final_post['categories'] = array_map( 'trim', wp_list_pluck( get_the_category( $post_id ), 'name' ) ); $target = Context::dir() . 'final-post.json'; try { Context::save_json( 'final-post.json', $final_post ); } catch ( \Throwable $e ) { aipub_debug_log( 'TransformX: failed to save final-post.json to ' . $target . ' - ' . $e->getMessage() ); } $assistant_ids = [ $this->session['publisher_id'] ?? '', $this->session['qa_id'] ?? '' ]; if ( ! empty( $this->session['final_id'] ) ) { $assistant_ids[] = $this->session['final_id']; } $this->cleanup_openai( array_filter( $assistant_ids ), $this->session['vector_id'], $this->session['thread_id'] ); Context::delete_file( self::SESSION_FILE ); Limits::record_generation(); // FAQPage schema generation triggered after post insertion. if ( $stream ) { $response = [ 'success' => true, 'post_id' => $post_id, 'post_edit' => admin_url( 'post.php?post=' . $post_id . '&action=edit' ), 'post_view' => get_permalink( $post_id ), ]; echo wp_json_encode( $response ) . "\n"; if ( function_exists( 'ini_set' ) && isset( $old_zlib ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- restore previous compression setting @ini_set( 'zlib.output_compression', $old_zlib ); unset( $old_zlib ); } } return $post_id; } /** * Scheduled trigger for post generation (via Cron). * * @return void */ public static function scheduled_run(): void { ( new self() )->generate_post(); } /** * Remove the persisted session file. */ public static function cleanup_session(): void { Context::delete_file( self::SESSION_FILE ); } /* ===== Setup guard ============================================= */ private function assert_setup_complete(): void { if ( ! get_option( 'aipub_openai_api_key' ) ) throw new \RuntimeException( 'OpenAI key missing.' ); if ( ! Brand_Strategy::is_complete() ) throw new \RuntimeException( 'Brand strategy missing.' ); if ( ! Context::load_json( 'keywords.json' ) ) throw new \RuntimeException( 'Keywords missing.' ); // Ensure post-generation prompts configuration is available. self::load_post_generation_prompts(); } /* ===== Thread & Vector-store =================================== */ private function create_thread(): string { return $this->post_json( 'https://api.openai.com/v1/threads', (object) [] )['id']; } private function generate_topic_suggestions(): array { $this->assert_setup_complete(); $thread_id = $this->create_thread(); $ctx_files = $this->collect_all_context_files(); $vector_store_id = $this->create_vector_store( $ctx_files ); $assistant_id = $this->create_topic_generation_assistant( $vector_store_id ); $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Topic Generation)']; $this->add_user_message( $thread_id, $block['user_message'] ); $this->run_assistant( $thread_id, $assistant_id, $block['assistant_instructions'] ); $resp = $this->wait_for_assistant_message( $thread_id ); $path = Context::dir() . 'topic-suggestions.json'; if ( false === file_put_contents( $path, $resp ) ) { throw new \RuntimeException( 'Failed to write topic suggestions file.' ); } $data = $this->parse_json_generic( $resp, 'topic-suggestions' ); if ( isset( $data['topics'] ) && is_array( $data['topics'] ) ) { $topics = $data['topics']; } elseif ( isset( $data[0] ) ) { $topics = $data; } else { $topics = []; } foreach ( $topics as &$t ) { if ( isset( $t['keywords'] ) && is_string( $t['keywords'] ) ) { $t['keywords'] = array_map( 'trim', preg_split( '/,\s*/', $t['keywords'] ) ); } } unset( $t ); // Remove the topic generation assistant once we have the response. OpenAI::delete_assistant( $assistant_id ); return [ 'thread_id' => $thread_id, 'vector_id' => $vector_store_id, 'topics' => $topics, ]; } private function generate_post_from_topic_text( string $topic, array $keywords ): int { $thread_id = $this->create_thread(); $ctx_files = $this->collect_all_context_files(); $vector_store_id = $this->create_vector_store( $ctx_files ); return $this->generate_post_with_topic( $thread_id, $vector_store_id, $topic, $keywords ); } private function generate_post_with_topic( string $thread_id, string $vector_id, string $topic, array $keywords ): int { $this->assert_setup_complete(); $this->load_session(); if ( ! OpenAI::vector_store_exists( $vector_id ) ) { $ctx_files = $this->collect_all_context_files(); $vector_id = $this->create_vector_store( $ctx_files ); $this->session['vector_id'] = $vector_id; $this->save_session(); } $this->session = array_merge( $this->session, [ 'thread_id' => $thread_id, 'vector_id' => $vector_id, ] ); $this->save_session(); $assistant_id = ''; $draft_post = $this->run_stage( function() use ( $thread_id, $vector_id, $topic, $keywords, &$assistant_id ) { $assistant_id = $this->create_topic_assistant( $vector_id ); $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Topic)']; $user = str_replace( [ '$topic', '$keywords' ], [ $topic, implode( ', ', $keywords ) ], $block['user_message'] ); $this->add_user_message( $thread_id, $user ); $this->run_assistant( $thread_id, $assistant_id, $block['assistant_instructions'] ); $post = $this->with_retry( fn() => $this->decode_post_json( $this->wait_for_assistant_message( $thread_id ), 'draft-post.json' ) ); $this->add_files_to_vector_store( $vector_id, [ Context::dir() . 'draft-post.json' ] ); return $post; }, 'draft' ); $this->session['progress'] = 'qa'; $this->save_session(); $qa_id = ''; $qa_pass = $this->run_stage( function() use ( $thread_id, $vector_id, $draft_post, $topic, $keywords, &$qa_id ) { $qa_id = $this->create_topic_qa_assistant( $vector_id ); $pass = $this->with_retry( fn() => $this->run_qa_topic( $thread_id, $qa_id, $draft_post, $topic, $keywords ) ); $this->add_files_to_vector_store( $vector_id, [ Context::dir() . 'post-qa.json' ] ); return $pass; }, 'qa' ); $this->session['progress'] = 'final'; $this->save_session(); $publisher_final_id = null; $final_post = $this->run_stage( function() use ( $thread_id, $vector_id, $draft_post, $topic, $keywords, $qa_pass, &$publisher_final_id ) { if ( ! $qa_pass ) { $publisher_final_id = $this->create_topic_assistant( $vector_id ); return $this->with_retry( fn() => $this->revise_post_topic( $thread_id, $publisher_final_id, $draft_post, $topic, $keywords ) ); } return $draft_post; }, 'final' ); try { Context::save_json( 'final-post.json', $final_post ); } catch ( \Throwable $e ) { throw $e; } $this->session['progress'] = 'image'; $this->save_session(); $post_id = $this->run_stage( function() use ( $final_post, $thread_id, $vector_id, $assistant_id, $qa_id, $publisher_final_id ) { $prompt_vs_id = $this->create_vector_store([ Context::dir() . 'brand-strategy.json', Context::dir() . 'final-post.json', ]); $img_prompt_assistant = $this->create_image_prompt_assistant( $prompt_vs_id ); $prompt_thread = $this->create_thread(); $prompts = self::load_post_generation_prompts(); $img_block = $prompts['TransformX Image Prompt Generator']; $img_prompt = $this->with_retry( function() use ( $prompt_thread, $img_prompt_assistant, $img_block ) { $this->add_user_message( $prompt_thread, $img_block['user_message'] ); $this->run_assistant( $prompt_thread, $img_prompt_assistant, $img_block['assistant_instructions'] ); return trim( $this->wait_for_assistant_message( $prompt_thread ) ); } ); Context::save_json( 'image-prompt.json', [ 'prompt' => $img_prompt ] ); $this->cleanup_openai( [ $img_prompt_assistant ], $prompt_vs_id, $prompt_thread ); $img_id = $this->with_retry( fn() => $this->create_featured_image( $final_post, $img_prompt ) ); $post_id = $this->with_retry( fn() => $this->insert_wp_post( $final_post, $img_id ) ); // After insertion, update final-post.json with URL and resolved category names. $final_post['url'] = get_permalink( $post_id ); $final_post['categories'] = array_map( 'trim', wp_list_pluck( get_the_category( $post_id ), 'name' ) ); $target = Context::dir() . 'final-post.json'; try { Context::save_json( 'final-post.json', $final_post ); } catch ( \Throwable $e ) { aipub_debug_log( 'TransformX: failed to save final-post.json to ' . $target . ' - ' . $e->getMessage() ); } $assistant_ids = [ $assistant_id, $qa_id ]; if ( ! empty( $publisher_final_id ) ) { $assistant_ids[] = $publisher_final_id; } $this->cleanup_openai( $assistant_ids, $vector_id, $thread_id ); return $post_id; }, 'image' ); return $post_id; } /** * Collect the core context files to seed the AI session. * * Includes brand strategy, keywords, pages snapshot (if available) and * a sitemap generated from existing posts and pages. * * @return string[] List of absolute file paths. */ private function collect_all_context_files(): array { $dir = Context::dir(); $files = [ $dir . 'brand-strategy.json', $dir . 'keywords.json', ]; // Optional: include pages snapshot if available if ( file_exists( $dir . 'pages.json' ) ) { $files[] = $dir . 'pages.json'; } // Generate sitemap.json from current posts and pages $smap_data = [ 'posts' => [], 'pages' => [] ]; $posts = \get_posts([ 'post_type' => 'post', 'post_status' => 'publish', 'numberposts' => -1, ]); foreach ( $posts as $p ) { $smap_data['posts'][] = [ 'title' => get_the_title( $p ), 'url' => get_permalink( $p ), 'tags' => \wp_get_post_tags( $p->ID, [ 'fields' => 'names' ] ), ]; } $pages = \get_posts([ 'post_type' => 'page', 'post_status' => 'publish', 'numberposts' => -1, ]); foreach ( $pages as $pg ) { $smap_data['pages'][] = [ 'title' => get_the_title( $pg ), 'url' => get_permalink( $pg ), ]; } $files[] = Context::save_json( 'sitemap.json', $smap_data ); // Include categories: export taxonomy definitions for assistant lookups. $terms = \get_terms( [ 'taxonomy' => 'category', 'hide_empty' => false ] ); $cat_data = []; foreach ( $terms as $term ) { $cat_data[] = [ 'term_id' => $term->term_id, 'name' => $term->name, 'slug' => $term->slug, ]; } $files[] = Context::save_json( 'categories.json', $cat_data ); return $files; } private function create_vector_store( array $files ): string { $file_ids = array_map( fn ( $f ) => $this->upload_file( $f ), $files ); return $this->post_json( 'https://api.openai.com/v1/vector_stores', [ 'name' => 'aipub_' . time(), 'file_ids' => $file_ids ] )['id']; } /** * Add additional files to an existing vector store. * * @param string $vs_id Vector store ID. * @param string[] $files Local file paths to add. * @return void */ private function add_files_to_vector_store( string $vs_id, array $files ): void { $file_ids = array_map( fn ( $f ) => $this->upload_file( $f ), $files ); OpenAI::add_files_to_vector_store( $vs_id, $file_ids ); } /* ===== Assistants ============================================== */ private function publisher_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX Publisher']['system_message']; } private function qa_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX QA']['system_message']; } /** Retrieve QA instructions for topic based generation. */ private function qa_topic_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX QA Topic']['system_message']; } private function topic_generation_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX Publisher (Topic Generation)']['system_message']; } private function topic_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX Publisher (Topic)']['system_message']; } private function create_publisher_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX Publisher', 'instructions' => $this->publisher_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'high'; } else { $payload['temperature'] = 0.4; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } private function create_topic_generation_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX Publisher (Topic Generation)', 'instructions' => $this->topic_generation_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'high'; } else { $payload['temperature'] = 0.4; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } private function create_topic_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX Publisher (Topic)', 'instructions' => $this->topic_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'high'; } else { $payload['temperature'] = 0.4; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } private function create_qa_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX QA', 'instructions' => $this->qa_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'medium'; } else { $payload['temperature'] = 0; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } /** Create QA assistant using topic specific prompts. */ private function create_topic_qa_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX QA Topic', 'instructions' => $this->qa_topic_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'medium'; } else { $payload['temperature'] = 0; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } /* ===== Draft, QA, Revise ======================================= */ private function draft_post( string $thread_id, string $assistant_id ): array { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher']; $this->add_user_message( $thread_id, $block['user_message'] ); $this->run_assistant( $thread_id, $assistant_id, $block['assistant_instructions'] ); return $this->decode_post_json( $this->wait_for_assistant_message( $thread_id ), 'draft-post.json' ); } private function run_qa( string $thread_id, string $qa_id, array $draft ): bool { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX QA']; $this->add_user_message( $thread_id, $block['user_message'] ); $this->add_user_message( $thread_id, 'DRAFT_JSON:' . wp_json_encode( $draft ) ); $this->run_assistant( $thread_id, $qa_id, $block['assistant_instructions'] ); $report = json_decode( $this->wait_for_assistant_message( $thread_id ), true ); Context::save_json( 'post-qa.json', $report ); return isset( $report['result'] ) && 'pass' === $report['result']; } /** Run QA using topic specific prompts. */ private function run_qa_topic( string $thread_id, string $qa_id, array $draft, string $topic, array $keywords ): bool { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX QA Topic']; $user = str_replace( [ '$topic', '$keywords' ], [ $topic, implode( ', ', $keywords ) ], $block['user_message'] ); $this->add_user_message( $thread_id, $user ); $this->add_user_message( $thread_id, 'DRAFT_JSON:' . wp_json_encode( $draft ) ); $this->run_assistant( $thread_id, $qa_id, $block['assistant_instructions'] ); $report = json_decode( $this->wait_for_assistant_message( $thread_id ), true ); Context::save_json( 'post-qa.json', $report ); return isset( $report['result'] ) && 'pass' === $report['result']; } private function revise_post( string $thread, string $assistant, array $draft ): array { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Final)']; $this->add_user_message( $thread, $block['user_message'] ); $this->add_user_message( $thread, 'DRAFT_JSON:' . wp_json_encode( $draft ) ); $this->add_user_message( $thread, 'POST_QA_JSON:' . wp_json_encode( Context::load_json( 'post-qa.json' ) ) ); $this->run_assistant( $thread, $assistant, $block['assistant_instructions'] ); return $this->decode_post_json( $this->wait_for_assistant_message( $thread ), 'final-post.json' ); } /** Revise using topic prompts and QA feedback. */ private function revise_post_topic( string $thread, string $assistant, array $draft, string $topic, array $keywords ): array { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Topic)']; $user = str_replace( [ '$topic', '$keywords' ], [ $topic, implode( ', ', $keywords ) ], $block['user_message'] ); $this->add_user_message( $thread, $user ); $this->add_user_message( $thread, 'DRAFT_JSON:' . wp_json_encode( $draft ) ); $this->add_user_message( $thread, 'POST_QA_JSON:' . wp_json_encode( Context::load_json( 'post-qa.json' ) ) ); $this->run_assistant( $thread, $assistant, $block['assistant_instructions'] ); return $this->decode_post_json( $this->wait_for_assistant_message( $thread ), 'final-post.json' ); } private function decode_post_json( string $json, string $fname ): array { // Normalize output: strip code fences or surrounding text, then extract JSON block. $raw = trim( $json ); // Remove fenced code block if present. if ( preg_match( '/^```(?:json)?\s*([\s\S]*)\s*```$/im', $raw, $m ) ) { $raw = trim( $m[1] ); } // If still not pure JSON, extract the first {...} block. if ( '' !== $raw && ( $raw[0] !== '{' || substr( $raw, -1 ) !== '}' ) ) { if ( preg_match( '/\{[\s\S]*\}$/', $raw, $m2 ) ) { $raw = trim( $m2[0] ); } } $data = is_string( $raw ) ? json_decode( $raw, true ) : null; if ( ! is_array( $data ) ) { $data = []; } $content_md = $data['content'] ?? $data['markdown_content'] ?? ''; $content_html = $data['html_content'] ?? $data['post_content'] ?? ''; if ( '' === $content_html && '' !== $content_md ) { $content_html = Markdown::to_html( $content_md ); } if ( 'final-post.json' === $fname ) { $content_html = $this->add_heading_ids( $content_html ); } $content_html = OpenAI::clean_text( $content_html ); $post = [ 'title' => trim( OpenAI::clean_text( $data['title'] ?? $data['post_title'] ?? '' ) ) ?: 'no data', 'excerpt' => trim( OpenAI::clean_text( $data['excerpt'] ?? $data['post_excerpt'] ?? '' ) ) ?: 'no data', 'categories' => array_values( isset( $data['categories'] ) && is_array( $data['categories'] ) ? $data['categories'] : [] ), 'tags' => array_values( isset( $data['tags'] ) && is_array( $data['tags'] ) ? $data['tags'] : [] ), 'content' => $content_html ?: 'no data', ]; Context::save_json( $fname, $post ); return $post; } /** * Decode a generic JSON string, handling fenced blocks and extra text. * * @param string $json Raw JSON text from OpenAI. * @param string $label Context label for error reporting. * @return array Decoded data array or empty array on failure. */ private function parse_json_generic( string $json, string $label ): array { $raw = trim( $json ); if ( preg_match( '/^```(?:json)?\s*([\s\S]*?)\s*```$/i', $raw, $m ) ) { $raw = trim( $m[1] ); } if ( '' !== $raw && ! in_array( $raw[0], [ '{', '[' ], true ) ) { if ( preg_match( '/(\{[\s\S]*\})|(\[[\s\S]*\])/', $raw, $m2 ) ) { $raw = trim( $m2[0] ); } } $data = is_string( $raw ) ? json_decode( $raw, true ) : null; if ( ! is_array( $data ) ) { $data = []; } return $data; } /** * Add sanitized id attributes to all h2 and h3 elements. */ private function add_heading_ids( string $html ): string { if ( '' === trim( $html ) ) { return $html; } $doc = new \DOMDocument(); libxml_use_internal_errors( true ); $doc->loadHTML( '