*/ private const USAGE_TOOL_IDS = array( Generators::DESCRIPTION => 'advanced_desc', Generators::TITLE => 'title', Generators::SEO_META => 'seo_meta', Generators::FAQ => 'faq', Generators::TAXONOMY => 'taxonomy', Generators::IMAGE_ALT => 'image_alt', ); /** * Engine factory (test seam). * * @var callable|null fn(): ExecutionService */ private static $service_factory = null; /** * Run pin service factory (test seam). * * @var callable|null fn(): RunPinService */ private static $pin_factory = null; /** * Replace the collaborators (tests only). * * @param callable|null $service_factory fn(): ExecutionService-like object with generateForRun(). * @param callable|null $pin_factory fn(): RunPinService-like object with loadRunPin(). * @return void */ public static function setFactoriesForTesting( ?callable $service_factory, ?callable $pin_factory ): void { self::$service_factory = $service_factory; self::$pin_factory = $pin_factory; } /** * Trusted per-job facts for the Automation job currently being executed. * * Set ONLY by JobExecutor, immediately before it calls a generator's * Blueprint-aware entry point, and cleared again right after (finally * block). This is the ONLY source `executionPath()`/`usesBlueprint()` * may treat as `$trusted['jobMode']`/`$trusted['legacyPrompts']` for an * Automation job: it is never derived from, or merged with, * request-shaped `$options`, so a REST request (the bulk generate * endpoints, Product Editor, the metabox) has no way to reach it and * can never change which path a direct call runs. * * @var array{jobMode?:string,legacyPrompts?:bool} */ private static $job_trusted_facts = array(); /** * Set (or clear, with an empty array) this call's trusted Automation * job facts. JobExecutor is the only production caller; also the test * seam every generator's own Blueprint-fork test uses to simulate an * Automation job's saved "Content structure" choice. * * @param array $facts Same shape executionPath() documents for $trusted. * @return void */ public static function setJobTrustedFacts( array $facts ): void { self::$job_trusted_facts = $facts; } /** * This call's trusted Automation job facts, or an empty array outside * an Automation job run (REST bulk generate, Product Editor, the * metabox, Abilities): those origins have no per-job choice to read, * so they keep resolving purely from the plugin-wide ExecutionModeRegistry * content mode, exactly as before this fix. * * @return array */ public static function jobTrustedFacts(): array { return self::$job_trusted_facts; } /** * Acting user id for the Automation job currently being executed — that * job's `created_by`, set (and cleared) by JobExecutor for the same * single-call window as {@see $job_trusted_facts}, never derived from a * request. WP-Cron runs Automation with no logged-in user, so `run()` * uses this id (via ExecutionRequest's userId) instead of * `get_current_user_id()` when nothing more specific was given, and * `ExecutionContextBuilder::checkObjectPermission()` checks THAT user's * capability rather than the nonexistent current one. Null outside an * Automation job run. * * @var int|null */ private static $job_actor_user_id = null; /** * Set (or clear, with null) this call's acting user id. * * @param int|null $user_id Automation job's created_by, or null outside a job run. * @return void */ public static function setJobActorUserId( ?int $user_id ): void { self::$job_actor_user_id = $user_id; } /** * This call's acting user id, or null outside an Automation job run. * * @return int|null */ public static function jobActorUserId(): ?int { return self::$job_actor_user_id; } /** * Whether the Automation job currently being executed is guaranteed to * route its results through a human review step before anything is * written ({@see \AIPT\Api\AutomationJobs\Services\JobEntitlementGuard::reviewGuaranteed()}), * or null outside an Automation job run. Kept as its own scalar channel, * separate from {@see $job_trusted_facts}: unlike `jobMode`/ * `legacyPrompts`, `executionPath()`/`usesBlueprint()` never read this * value, so it never widens what `$trusted` means there. * * @var bool|null */ private static $job_review_guaranteed = null; /** * Set (or clear, with null) this call's trusted "will this job's results * reach review" fact. JobExecutor is the only production caller, for the * same single-call window as {@see setJobActorUserId()}. * * @param bool|null $guaranteed Job-uniform reviewGuaranteed(), or null to clear. * @return void */ public static function setJobReviewGuaranteed( ?bool $guaranteed ): void { self::$job_review_guaranteed = $guaranteed; } /** * This call's trusted reviewGuaranteed fact, or null outside an * Automation job run (REST bulk generate, Product Editor, the metabox, * Abilities, and Test & preview): those origins have no job-level review * routing to read, so `EntitlementPolicy::apply()`'s automation-only * clamp never fires for them. * * @return bool|null */ public static function jobReviewGuaranteed(): ?bool { return self::$job_review_guaranteed; } /** * Sanitize the request options from a raw options array. * * Unknown values fall back to safe defaults; nothing here grants access. * * @param array $raw Raw request options (already decoded JSON/params). * @return array{blueprintRun:int,blueprintId:int,overwrite:string} */ public static function sanitizeOptions( array $raw ): array { $overwrite = isset( $raw['overwrite'] ) ? (string) $raw['overwrite'] : 'replace'; return array( 'blueprintRun' => isset( $raw['blueprintRun'] ) ? max( 0, (int) $raw['blueprintRun'] ) : 0, 'blueprintId' => isset( $raw['blueprintId'] ) ? max( 0, (int) $raw['blueprintId'] ) : 0, 'overwrite' => 'empty_only' === $overwrite ? 'empty_only' : 'replace', ); } /** * Decide which execution path runs for a generator. * * `$trusted` must only carry server-side facts, never raw client input: * - `jobMode` 'blueprint'|'advanced'|'' : an automation job's stored settings.blueprint.mode. * - `legacyPrompts` bool : the run carries legacy per-run prompt overrides * from server-side settings (Automation custom prompts). * * Precedence — an explicit per-job choice always wins over leftover * prompt text, in BOTH directions: * 1. `jobMode` 'advanced' -> advanced (`job_custom_prompts`). * 2. `jobMode` 'blueprint' -> blueprint (`job_blueprint`), even when * `legacyPrompts` is true. A merchant who explicitly switches a job * from "Custom prompts (Advanced)" to "Use Blueprint assignments" * must have that choice stick even though the old prompt text is * still sitting in settings (it is never cleared on switch) — * otherwise the job would keep running custom prompts forever. * 3. No job choice at all (`jobMode` empty/missing) AND * `legacyPrompts` true -> advanced (`legacy_prompts`). This is the * fallback for a job that predates content structure: it has no * settings.blueprint key (the wizard never persists one unless the * user saves a structure choice), so it keeps running on its * existing prompts. * 4. Otherwise -> the plugin-wide content mode every generator shares * (ExecutionModeRegistry, `generator_mode`): one stored mode, not a * per-generator choice (2.8.0 had a per-generator map; 2.8.1 replaced * it with this single setting). Non-Automation callers (bulk generate * REST, Product Editor, the metabox, Abilities) never carry `jobMode`, * so they resolve through rule 3 (Description's per-run prompt * overrides) or this rule. * * @param string $generator Blueprint generator key. * @param array $trusted Server-side facts about the run. * @return array{path:string,reason:string} */ public static function executionPath( string $generator, array $trusted = array() ): array { if ( ! Generators::isValid( $generator ) ) { return array( 'path' => self::PATH_ADVANCED, 'reason' => 'unknown_generator' ); } $job_mode = isset( $trusted['jobMode'] ) ? (string) $trusted['jobMode'] : ''; if ( self::PATH_ADVANCED === $job_mode ) { return array( 'path' => self::PATH_ADVANCED, 'reason' => 'job_custom_prompts' ); } if ( self::PATH_BLUEPRINT === $job_mode ) { return array( 'path' => self::PATH_BLUEPRINT, 'reason' => 'job_blueprint' ); } if ( ! empty( $trusted['legacyPrompts'] ) ) { return array( 'path' => self::PATH_ADVANCED, 'reason' => 'legacy_prompts' ); } if ( ExecutionModeRegistry::isBlueprint( $generator ) ) { return array( 'path' => self::PATH_BLUEPRINT, 'reason' => 'generator_mode' ); } return array( 'path' => self::PATH_ADVANCED, 'reason' => 'generator_mode' ); } /** * Convenience: true when the Blueprint path runs. * * @param string $generator Blueprint generator key. * @param array $trusted Server-side facts (see executionPath()). * @return bool */ public static function usesBlueprint( string $generator, array $trusted = array() ): bool { $decision = self::executionPath( $generator, $trusted ); return self::PATH_BLUEPRINT === $decision['path']; } /** * Verify a run pin exists and belongs to the generator. * * @param int $pin_id Run pin id (kind='run' snapshot id). * @param string $generator Blueprint generator key. * @return true|WP_Error */ public static function validatePin( int $pin_id, string $generator ) { $pin = self::pins()->loadRunPin( $pin_id ); if ( ! is_array( $pin ) ) { return new WP_Error( 'aipt_blueprint_pin_invalid', __( 'The pinned run could not be found. Start the run again.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( (string) ( $pin['generator'] ?? '' ) !== $generator ) { return new WP_Error( 'aipt_blueprint_pin_invalid', __( 'The pinned run belongs to a different content type.', 'ai-product-tools' ), array( 'status' => 400 ) ); } return true; } /** * Run the engine for one subject. * * @param string $generator Blueprint generator key. * @param array $subject array{type:string,id:int,productId?:int}. * @param array $options Options (raw or sanitized; sanitized again here). * @param array $run_options ExecutionRequest run options (companions, language, provider, model, * allowExistingDescription, preserveContentImages, overwrite, variants, attachmentIds). * @param string $origin 'bulk' | 'automation' | 'editor' | 'metabox' | 'ability' | 'ability_run'. * @param array $extra array{deadline?: float, maxCalls?: int, userId?: int}. * @return array|WP_Error GenerationResult or an error. */ public static function run( string $generator, array $subject, array $options, array $run_options, string $origin, array $extra = array() ) { if ( ! Generators::isValid( $generator ) ) { return new WP_Error( 'aipt_blueprint_generator_invalid', __( 'Unknown generator.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( 'bulk' === $origin && ! empty( self::jobTrustedFacts() ) ) { $origin = 'automation'; } $clean = self::sanitizeOptions( $options ); if ( $clean['blueprintRun'] > 0 ) { $valid = self::validatePin( $clean['blueprintRun'], $generator ); if ( is_wp_error( $valid ) ) { return $valid; } } if ( ! isset( $run_options['overwrite'] ) ) { $run_options['overwrite'] = $clean['overwrite']; } $actor_user_id = self::jobActorUserId(); $user_id = isset( $extra['userId'] ) ? (int) $extra['userId'] : ( null !== $actor_user_id ? $actor_user_id : ( function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0 ) ); $review_guaranteed = self::jobReviewGuaranteed(); $automation_context = null !== $review_guaranteed ? array( 'reviewGuaranteed' => $review_guaranteed ) : array(); $request = ExecutionRequest::fromArray( array( 'generator' => $generator, 'subject' => $subject, 'mode' => 'run', 'draft' => null, 'blueprintId' => $clean['blueprintRun'] > 0 ? null : ( $clean['blueprintId'] > 0 ? $clean['blueprintId'] : null ), 'runPin' => $clean['blueprintRun'] > 0 ? $clean['blueprintRun'] : null, 'runOptions' => $run_options, 'deadline' => isset( $extra['deadline'] ) ? (float) $extra['deadline'] : ( microtime( true ) + self::DEFAULT_RUN_SECONDS ), 'maxCalls' => isset( $extra['maxCalls'] ) ? (int) $extra['maxCalls'] : 3, 'origin' => $origin, 'userId' => $user_id, 'automationContext' => $automation_context, ) ); $result = self::service()->generateForRun( $request ); if ( ! is_wp_error( $result ) && isset( self::USAGE_TOOL_IDS[ $generator ] ) ) { UsageTracker::increment( self::USAGE_TOOL_IDS[ $generator ], 'generated_blueprint' ); } return $result; } /** * Per-item response fields for a Blueprint result. * * @param array $result GenerationResult. * @return array{executionPath:string,blueprint:array|null,findings:array,eligibility:array,appliedFreeDefaults:array,resultKey:string,providerError:array|null} */ public static function responseFields( array $result ): array { $blueprint = isset( $result['blueprint'] ) && is_array( $result['blueprint'] ) ? $result['blueprint'] : array(); $findings = array(); foreach ( (array) ( $result['findings'] ?? array() ) as $finding ) { if ( is_array( $finding ) && in_array( (string) ( $finding['severity'] ?? '' ), array( 'warning', 'review', 'blocking' ), true ) ) { $findings[] = $finding; } } return array( 'executionPath' => self::PATH_BLUEPRINT, 'blueprint' => array( 'id' => isset( $blueprint['id'] ) ? $blueprint['id'] : null, 'name' => (string) ( $blueprint['name'] ?? '' ), 'revision' => isset( $blueprint['revision'] ) ? $blueprint['revision'] : null, 'builtin' => ! empty( $blueprint['builtin'] ), ), 'findings' => $findings, 'eligibility' => self::eligibility( $result ), 'appliedFreeDefaults' => isset( $result['appliedFreeDefaults'] ) && is_array( $result['appliedFreeDefaults'] ) ? array_values( $result['appliedFreeDefaults'] ) : array(), 'resultKey' => isset( $result['resultKey'] ) ? (string) $result['resultKey'] : '', 'providerError' => isset( $result['providerError'] ) && is_array( $result['providerError'] ) ? $result['providerError'] : null, ); } /** * Per-item response fields for the legacy (advanced) path. * * @return array{executionPath:string,blueprint:null,findings:array,eligibility:null,appliedFreeDefaults:array,providerError:null} */ public static function advancedResponseFields(): array { return array( 'executionPath' => self::PATH_ADVANCED, 'blueprint' => null, 'findings' => array(), 'eligibility' => null, 'appliedFreeDefaults' => array(), 'providerError' => null, ); } /** * Whether a result must be held back for a destination. * * - preview: never held back (the user sees it with its findings). * - review: held back only when a blocker exists (a review-required * result may be staged: staging IS the review). * - apply: held back when it cannot be applied or still needs review. * * @param array $result GenerationResult. * @param string $destination One of the DESTINATION_* constants. * @return bool */ public static function isHeldBack( array $result, string $destination ): bool { $eligibility = self::eligibility( $result ); if ( self::DESTINATION_PREVIEW === $destination ) { return false; } if ( self::DESTINATION_REVIEW === $destination ) { return ! $eligibility['canApply']; } return ! $eligibility['canApply'] || $eligibility['requiresReview']; } /** * Map a generationMode (client_preview | server_review | immediate) to a destination. * * @param string $generation_mode Effective (already enforced/downgraded) generation mode. * @return string */ public static function destinationForMode( string $generation_mode ): string { if ( 'immediate' === $generation_mode ) { return self::DESTINATION_APPLY; } if ( 'server_review' === $generation_mode ) { return self::DESTINATION_REVIEW; } return self::DESTINATION_PREVIEW; } /** * User-facing reason a held-back result was not written. * * @param array $result GenerationResult. * @return string */ public static function heldBackMessage( array $result ): string { $eligibility = self::eligibility( $result ); foreach ( $eligibility['blockers'] as $blocker ) { if ( is_array( $blocker ) && '' !== (string) ( $blocker['message'] ?? '' ) ) { return (string) $blocker['message']; } } if ( $eligibility['requiresReview'] ) { return __( 'This result needs a review before it can be applied. Nothing was written.', 'ai-product-tools' ); } return __( 'This result cannot be applied. Nothing was written.', 'ai-product-tools' ); } /** * Normalized eligibility block of a result. * * @param array $result GenerationResult. * @return array{canApply:bool,requiresReview:bool,blockers:array} */ private static function eligibility( array $result ): array { $raw = isset( $result['eligibility'] ) && is_array( $result['eligibility'] ) ? $result['eligibility'] : array(); return array( 'canApply' => ! empty( $raw['canApply'] ), 'requiresReview' => ! empty( $raw['requiresReview'] ), 'blockers' => isset( $raw['blockers'] ) && is_array( $raw['blockers'] ) ? array_values( $raw['blockers'] ) : array(), ); } /** * @return ExecutionService */ private static function service() { if ( null !== self::$service_factory ) { return call_user_func( self::$service_factory ); } return ExecutionService::withSourcesAndDecisions(); } /** * @return RunPinService */ private static function pins() { if ( null !== self::$pin_factory ) { return call_user_func( self::$pin_factory ); } return new RunPinService(); } }