results = $results ?? new ResultStore(); $this->reviewStager = $reviewStager ?? new ReviewStager(); $this->contextBuilder = $contextBuilder ?? new ExecutionContextBuilder(); $this->clock = $clock ?? static function () { return microtime( true ); }; $this->adapterFactory = $adapterFactory ?? array( ApplyAdapterFactory::class, 'forGenerator' ); $this->seoGuard = $seoGuard ?? new ProductScreenSeoGuard(); $this->seoPluginDetector = $seoPluginDetector ?? array( SeoPluginDetector::class, 'detect' ); } /** * @param string $resultKey Stored result's result_key. * @param array $params { * @type string $expectedDefinitionHash Required; must match the stored result. * @type string $overwrite 'replace' | 'empty_only'. Default 'replace'. * @type string $destination 'apply' | 'review'. Default 'apply'. * @type bool $confirmReview Required true to apply a result that requiresReview. * } * @param int $userId Acting user id. * @return array{status:string,fields:array,snapshotTaken:bool,message:string}|WP_Error */ public function apply( string $resultKey, array $params, int $userId ) { $row = $this->results->get( $resultKey ); if ( null === $row ) { return new WP_Error( 'aipt_blueprint_result_not_found', __( 'This result no longer exists.', 'ai-product-tools' ), array( 'status' => 404 ) ); } if ( (int) $row['createdBy'] !== $userId && ! current_user_can( self::CAP_MANAGE ) ) { return new WP_Error( 'aipt_blueprint_forbidden', __( 'You do not have permission to apply this result.', 'ai-product-tools' ), array( 'status' => 403 ) ); } $subject_error = $this->contextBuilder->checkObjectPermission( array( 'type' => (string) $row['subjectType'], 'id' => (int) $row['subjectId'] ) ); if ( null !== $subject_error ) { return $subject_error; } if ( in_array( $row['status'], array( 'applied', 'staged', 'apply_failed' ), true ) ) { return $this->storedOutcome( $row ); } if ( 'applying' === $row['status'] ) { return $this->storedOutcome( $row ); } $expected_hash = (string) ( $params['expectedDefinitionHash'] ?? '' ); if ( '' === $expected_hash || $expected_hash !== (string) $row['definitionHash'] ) { return new WP_Error( 'aipt_blueprint_result_stale', __( 'This template has changed since this result was generated. Run a new test.', 'ai-product-tools' ), array( 'status' => 409 ) ); } if ( $this->isExpired( $row ) ) { return new WP_Error( 'aipt_blueprint_result_stale', __( 'This result has expired. Run a new test.', 'ai-product-tools' ), array( 'status' => 409 ) ); } $payload = is_array( $row['payload'] ) ? $row['payload'] : array(); $eligibility = is_array( $payload['eligibility'] ?? null ) ? $payload['eligibility'] : array( 'canApply' => false, 'requiresReview' => true, 'blockers' => array() ); if ( empty( $eligibility['canApply'] ) ) { return new WP_Error( 'aipt_blueprint_result_not_eligible', __( 'This result cannot be applied yet. Resolve the blocking issues and test again.', 'ai-product-tools' ), array( 'status' => 409, 'blockers' => $eligibility['blockers'] ?? array() ) ); } $destination = 'review' === ( $params['destination'] ?? 'apply' ) ? 'review' : 'apply'; $overwrite = 'empty_only' === ( $params['overwrite'] ?? 'replace' ) ? 'empty_only' : 'replace'; $confirm_review = ! empty( $params['confirmReview'] ); $generator = (string) $row['generator']; $stored_outputs = is_array( $payload['outputs'] ?? null ) ? $payload['outputs'] : array(); $outputs_override = null; if ( array_key_exists( 'outputs', $params ) && null !== $params['outputs'] ) { if ( ! is_array( $params['outputs'] ) ) { return new WP_Error( 'aipt_blueprint_invalid_outputs', __( 'This output selection is invalid.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $validated_outputs = OutputsOverrideValidator::validate( $generator, $params['outputs'], $stored_outputs ); if ( is_wp_error( $validated_outputs ) ) { return $validated_outputs; } $outputs_override = $validated_outputs; } if ( 'apply' === $destination && ! empty( $eligibility['requiresReview'] ) && ! $confirm_review ) { return new WP_Error( 'aipt_blueprint_review_required', __( 'This result needs review before it can be applied. Confirm to continue.', 'ai-product-tools' ), array( 'status' => 409 ) ); } if ( 'review' === $destination && Generators::TAXONOMY === $generator ) { return new WP_Error( 'aipt_blueprint_taxonomy_no_review', __( 'Category descriptions do not go through review.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( 'review' === $destination ) { $gate_error = $this->reviewStager->gateError(); if ( null !== $gate_error ) { return $gate_error; } } if ( ! $this->results->claimForApply( $resultKey ) ) { $fresh = $this->results->get( $resultKey ); return $this->storedOutcome( null !== $fresh ? $fresh : $row ); } $changed = $this->hasContextChanged( $row, $payload ); if ( is_wp_error( $changed ) ) { $this->results->releaseApply( $resultKey, (string) $row['status'] ); return $changed; } if ( $changed ) { $this->results->releaseApply( $resultKey, (string) $row['status'] ); return new WP_Error( 'aipt_blueprint_apply_conflict', __( 'This product has changed since this result was generated. Run a new test.', 'ai-product-tools' ), array( 'status' => 409, 'reason' => 'changed' ) ); } $blueprint = is_array( $payload['blueprint'] ?? null ) ? $payload['blueprint'] : array(); $context = array( 'productId' => (int) $row['productId'], 'termId' => 'term' === $row['subjectType'] ? (int) $row['subjectId'] : 0, 'taxonomy' => (string) ( $payload['subject']['taxonomy'] ?? ( 'term' === $row['subjectType'] ? 'product_cat' : '' ) ), 'overwrite' => $overwrite, 'userId' => $userId, 'blueprintId' => isset( $blueprint['id'] ) ? $blueprint['id'] : null, 'blueprintName' => isset( $blueprint['name'] ) ? (string) $blueprint['name'] : '', 'blueprintRevision' => isset( $blueprint['revision'] ) ? $blueprint['revision'] : null, 'blueprintBuiltin' => ! empty( $blueprint['builtin'] ), 'sectionNotices' => StoreSectionsPolicy::sectionNoticesFrom( is_array( $payload['appliedFreeDefaults'] ?? null ) ? $payload['appliedFreeDefaults'] : array() ), 'existingAlt' => is_array( $stored_outputs['existingAlt'] ?? null ) ? $stored_outputs['existingAlt'] : array(), ); $outputs = $outputs_override ?? $stored_outputs; $screen = (string) ( $params['screen'] ?? '' ); $seo_guard_state = ( 'product_edit' === $screen && Generators::SEO_META === $generator && 'apply' === $destination ) ? $this->seoScreenGuardBefore( (int) $row['productId'] ) : null; try { $outcome = ( 'review' === $destination ) ? $this->reviewStager->stage( $generator, $outputs, $context ) : $this->dispatchApply( $generator, $outputs, $context ); } catch ( \Throwable $e ) { $sanitized_message = ErrorHandler::sanitize_error_for_logging( $e->getMessage() ); $sanitized_trace = ErrorHandler::sanitize_error_for_logging( $e->getTraceAsString() ); error_log( sprintf( '[AIPT ContentStructure] apply(%s) threw %s: %s; trace: %s', $generator, get_class( $e ), $sanitized_message, $sanitized_trace ) ); $outcome = array( 'status' => 'skipped', 'fields' => array( array( 'field' => $generator, 'outcome' => 'failed' ) ), 'message' => __( 'The write did not complete.', 'ai-product-tools' ), ); } if ( null !== $seo_guard_state && ( 'applied' === $outcome['status'] || $this->hasWrittenField( $outcome['fields'] ) ) ) { $this->recordSeoScreenGuard( (int) $row['productId'], $seo_guard_state, $outputs, $outcome['fields'] ); } return $this->finish( $resultKey, $row, $outcome, 'review' === $destination ); } /** * Read the product's current SEO meta values and the active plugin's * slug, BEFORE any write — the revert guard's "before" snapshot. Null * when no SEO plugin is detected (nothing to guard). * * @param int $productId Product id. * @return array{pluginSlug:string,before:array{title:string,description:string,focus:string}}|null */ private function seoScreenGuardBefore( int $productId ): ?array { $plugin = call_user_func( $this->seoPluginDetector ); $plugin_slug = is_array( $plugin ) ? (string) ( $plugin['plugin_slug'] ?? '' ) : ''; if ( '' === $plugin_slug ) { return null; } $info = SeoPluginDetector::get_seo_info( $productId, $plugin, false ); return array( 'pluginSlug' => $plugin_slug, 'before' => array( 'title' => (string) ( $info['meta_title'] ?? '' ), 'description' => (string) ( $info['meta_description'] ?? '' ), 'focus' => (string) ( $info['focus_keyword'] ?? '' ), ), ); } /** * Whether the apply wrote at least one field. * * @param array $fields Per-field outcomes from the apply. * @return bool */ private function hasWrittenField( array $fields ): bool { foreach ( $fields as $field ) { if ( 'written' === ( $field['outcome'] ?? '' ) ) { return true; } } return false; } /** * @param int $productId Product id. * @param array{pluginSlug:string,before:array} $guardState seoScreenGuardBefore()'s result. * @param array $outputsUsed The outputs actually dispatched. * @param array $fields Per-field outcomes from the apply. * @return void */ private function recordSeoScreenGuard( int $productId, array $guardState, array $outputsUsed, array $fields ): void { $written = array(); foreach ( $fields as $field ) { if ( 'written' === ( $field['outcome'] ?? '' ) ) { $written[ (string) ( $field['field'] ?? '' ) ] = true; } } $before = $guardState['before']; $map = array( 'title' => 'metaTitle', 'description' => 'metaDescription', 'focus' => 'focusKeyword' ); $after = array(); foreach ( $map as $short_key => $output_key ) { $after[ $short_key ] = isset( $written[ $output_key ] ) ? (string) ( $outputsUsed[ $output_key ] ?? '' ) : $before[ $short_key ]; } $this->seoGuard->record( $productId, $before, $after, (string) $guardState['pluginSlug'] ); } /** * @param string $generator Generator key. * @param array $outputs GenerationResult.outputs. * @param array $context Apply context (see ApplyAdapterInterface). * @return array{status:string,fields:array,message:string} */ private function dispatchApply( string $generator, array $outputs, array $context ): array { $adapter = call_user_func( $this->adapterFactory, $generator ); if ( null === $adapter ) { return array( 'status' => 'skipped', 'fields' => array(), 'message' => __( 'This generator does not support applying yet.', 'ai-product-tools' ) ); } return $adapter->apply( $outputs, $context ); } /** * Decide the final outcome from the adapter/stager result, releasing or * finishing the apply claim accordingly. * * @param string $result_key Stored result's result_key. * @param array $row Stored row (pre-claim). * @param array $outcome {status,fields,message} from the adapter/stager. * @param bool $is_review Whether this was a 'review' destination call. * @return array|WP_Error */ private function finish( string $result_key, array $row, array $outcome, bool $is_review ) { $fields = $outcome['fields']; if ( 'applied' === $outcome['status'] || 'staged' === $outcome['status'] ) { $final = 'staged' === $outcome['status'] || $is_review ? 'staged' : 'applied'; $this->results->finishApply( $result_key, $final ); $snapshot_taken = 'applied' === $final && SnapshotStore::historyCaptureEnabled(); return array( 'status' => $final, 'fields' => $fields, 'snapshotTaken' => $snapshot_taken, 'message' => $outcome['message'] ); } if ( $this->isNotEmptyConflict( $fields ) ) { $this->results->releaseApply( $result_key, (string) $row['status'] ); return new WP_Error( 'aipt_blueprint_apply_conflict', __( 'The existing content is no longer empty. Nothing was changed.', 'ai-product-tools' ), array( 'status' => 409, 'reason' => 'not_empty', 'fields' => $fields ) ); } if ( ! empty( $outcome['retryable'] ) ) { $this->results->releaseApply( $result_key, (string) $row['status'] ); return new WP_Error( 'aipt_blueprint_apply_retryable', '' !== (string) $outcome['message'] ? (string) $outcome['message'] : __( 'The result could not be applied right now. Please retry.', 'ai-product-tools' ), array( 'status' => 503, 'reason' => 'retryable', 'fields' => $fields ) ); } if ( $this->hasFailedField( $fields ) ) { $this->results->finishApply( $result_key, 'apply_failed' ); return array( 'status' => 'apply_failed', 'fields' => $fields, 'snapshotTaken' => false, 'message' => $outcome['message'] ); } $this->results->releaseApply( $result_key, (string) $row['status'] ); return array( 'status' => 'skipped', 'fields' => $fields, 'snapshotTaken' => false, 'message' => $outcome['message'] ); } /** * @param array $fields Field outcomes. * @return bool Whether every present field was skipped for being non-empty. */ private function isNotEmptyConflict( array $fields ): bool { if ( empty( $fields ) ) { return false; } foreach ( $fields as $field ) { if ( 'skipped_not_empty' !== ( $field['outcome'] ?? '' ) ) { return false; } } return true; } /** * @param array $fields Field outcomes. * @return bool */ private function hasFailedField( array $fields ): bool { foreach ( $fields as $field ) { if ( 'failed' === ( $field['outcome'] ?? '' ) ) { return true; } } return false; } /** * Re-derive the stored outcome for an already-decided (or in-flight) * result, without writing again. * * @param array $row Stored row. * @return array{status:string,fields:array,snapshotTaken:bool,message:string} */ private function storedOutcome( array $row ): array { $status = (string) $row['status']; if ( 'applying' === $status ) { return array( 'status' => 'skipped', 'fields' => array(), 'snapshotTaken' => false, 'message' => __( 'This result is already being applied.', 'ai-product-tools' ) ); } return array( 'status' => in_array( $status, array( 'applied', 'staged', 'apply_failed' ), true ) ? $status : 'skipped', 'fields' => array(), 'snapshotTaken' => false, 'message' => __( 'This result was already decided.', 'ai-product-tools' ), ); } /** * @param array $row Stored row. * @return bool */ private function isExpired( array $row ): bool { $expires_at = (string) ( $row['expiresAt'] ?? '' ); if ( '' === $expires_at ) { return false; } $timestamp = strtotime( $expires_at . ' UTC' ); return false !== $timestamp && $timestamp <= (int) $this->now(); } /** * Recompute the subject's current context (product concurrency token, * sources) and compare it against the hash taken at generation time * (the "changed product context" check). * * @param array $row Stored row. * @param array $payload Stored GenerationResult payload. * @return bool|WP_Error */ private function hasContextChanged( array $row, array $payload ) { $subject = array( 'type' => (string) $row['subjectType'], 'id' => (int) $row['subjectId'], ); if ( (int) $row['productId'] > 0 ) { $subject['productId'] = (int) $row['productId']; } $subject_data = $this->contextBuilder->loadSubject( $subject ); if ( is_wp_error( $subject_data ) ) { return $subject_data; } $sources_used = is_array( $payload['sourcesUsed'] ?? null ) ? $payload['sourcesUsed'] : array(); $fresh_hash = $this->contextBuilder->computeContextHash( array( 'product' => $subject_data['product'], 'subject' => $payload['subject'] ?? array() ), $sources_used ); return $fresh_hash !== (string) $row['contextHash']; } /** * @return float */ private function now(): float { return (float) call_user_func( $this->clock ); } }