resolve definition + brand profile * + assignment (draft | manual pick | run pin | live default) -> load the * subject (product/term/attachment) and its allowed field/source context -> * resolve the generator class via {@see GeneratorRegistry} -> run its * generate()/regenerateUnit() pipeline with a {@see StructuredCallerInterface} * -> wrap the generator-specific slice into the full GenerationResult shape * -> persist test/bulk/regenerate-origin results * through {@see \AIPT\Core\ContentStructure\Storage\ResultStore} (24h for a * test/preview result, 7 days for a real bulk-generate run; a regenerate * keeps its parent row's own class). * * @package AIPT\Api\ContentStructure\Engine * @since 2.8.0 */ namespace AIPT\Api\ContentStructure\Engine; use AIPT\Api\ContentStructure\Engine\Generators\GeneratorRegistry; use AIPT\Api\ContentStructure\Engine\Policy\EntitlementPolicy; use AIPT\Core\ContentStructure\Domain\Generators; use WP_Error; defined( 'ABSPATH' ) || exit; /** * The shared content structure generation engine. * * Orchestration only: subject permission/loading, the sources/decisions * bundle and ctx assembly live in {@see ExecutionContextBuilder}; the draft * > manual > run pin > live definition precedence lives in * {@see ExecutionDefinitionResolver}. */ class ExecutionService { /** * MANAGE capability, required to act on another user's test result. */ const CAP_MANAGE = 'manage_aipt_settings'; /** * USE capability, required to test an unsaved draft (anyone who can * generate may test a structure before saving it). */ const CAP_USE = 'manage_woocommerce'; /** * Test/preview result lifetime, in seconds: a quick throwaway check, * kept only long enough for the editor session that produced it. */ const RESULT_TTL_SECONDS = 86400; /** * Real bulk-run result lifetime, in seconds: long enough for a merchant * to open a finished batch and repair one section without the row * already being gone. */ const RESULT_TTL_SECONDS_BULK = 604800; /** * Origins {@see persist()} ever stores verbatim. Anything else (a * malformed/legacy value) falls back to the 'test' class — the * shorter-lived, fail-safe default — the same instinct * {@see \AIPT\Core\ContentStructure\Storage\ResultStore::create()}'s own * "missing expiresAt defaults to now" already applies. * * 'ability_run' (since 2.8.0) is the confirm-content-run Ability's own * synchronous per-product run: persisted so {@see * \AIPT\Api\ContentStructure\Apply\ResultApplier::apply()} can be reused * unchanged for History snapshots, attribution, idempotency and the * changed-product guard, at the 24h 'test'-class TTL (see * {@see ttlSecondsForOrigin()}) — a confirm run is a one-time action, not * a batch a merchant returns to days later like a 'bulk' row. */ private const PERSISTABLE_ORIGINS = array( 'test', 'bulk', 'regenerate', 'ability_run' ); /** * @var ExecutionDefinitionResolver */ private $definitionResolver; /** * @var ExecutionContextBuilder */ private $contextBuilder; /** * Engine entitlement policy: clamps the resolved definition to this * site's Free/Business entitlements, the same way for every mode and * every origin. * * @var EntitlementPolicy */ private $entitlementPolicy; /** * Duck-typed ResultStore ({@see \AIPT\Core\ContentStructure\Storage\ResultStore}). * * @var object */ private $results; /** * fn(): StructuredCallerInterface — test seam. * * @var callable */ private $callerFactory; /** * fn(): float — injectable clock for deterministic tests. * * @var callable */ private $clock; /** * @param ExecutionDefinitionResolver|null $definitionResolver Definition resolver; a default instance is constructed when omitted. * @param ExecutionContextBuilder|null $contextBuilder Context builder; a default instance (no external sources/decisions) is constructed when omitted. * @param object|null $results ResultStore-shaped collaborator; a default \AIPT\Core\ContentStructure\Storage\ResultStore is constructed when omitted. * @param callable|null $callerFactory fn(): StructuredCallerInterface; defaults to `new StructuredCaller()`. * @param callable|null $clock fn(): float; defaults to microtime(true). * @param EntitlementPolicy|null $entitlementPolicy Entitlement policy; a default instance is constructed when omitted. */ public function __construct( ?ExecutionDefinitionResolver $definitionResolver = null, ?ExecutionContextBuilder $contextBuilder = null, $results = null, ?callable $callerFactory = null, ?callable $clock = null, ?EntitlementPolicy $entitlementPolicy = null ) { $this->definitionResolver = $definitionResolver ?? new ExecutionDefinitionResolver(); $this->contextBuilder = $contextBuilder ?? new ExecutionContextBuilder(); $this->results = $results ?? new \AIPT\Core\ContentStructure\Storage\ResultStore(); $this->callerFactory = $callerFactory ?? static function () { return new StructuredCaller(); }; $this->clock = $clock ?? static function () { return microtime( true ); }; $this->entitlementPolicy = $entitlementPolicy ?? new EntitlementPolicy(); } /** * The engine every real run uses: its context reads the blueprint's * sources and the stored conflict decisions, exactly like Test and * preview. Bulk runs, automation, the Product Editor and Abilities must * not silently skip the sources a merchant attached to a blueprint. * Web page sources are read by the Business build's service * ({@see \AIPT\Api\ContentStructure\Sources\WebSourceServices}); without * one, a run reads product data only. * * @since 2.8.0 * @return self */ public static function withSourcesAndDecisions(): self { $source_content = \AIPT\Api\ContentStructure\Sources\WebSourceServices::get(); return new self( null, new ExecutionContextBuilder( $source_content, new \AIPT\Core\ContentStructure\Storage\DecisionStore() ) ); } /** * Run a generation and persist it through ResultStore (test/regenerate * origins). * * @param ExecutionRequest $request Execution request. * @return array|WP_Error GenerationResult, or an error. */ public function generate( ExecutionRequest $request ) { $resolved = $this->resolveExecution( $request ); if ( is_wp_error( $resolved ) ) { return $resolved; } $slice = $this->runGenerator( $resolved['generatorInstance'], $resolved['ctx'] ); $slice = $this->contextBuilder->applyPreserveContentImages( $request->getGenerator(), $request->getRunOptions(), $resolved['ctx']['product'], $slice ); $result = $this->wrapResult( $request->getGenerator(), $request->getClientVersion(), $resolved, $slice, $request->getOrigin(), $request->getRunOptions() ); return $this->persist( $result, $request, $resolved ); } /** * Run a generation for an integration caller (bulk/automation/editor/ * metabox/ability). A bulk-generate run (origin 'bulk') is persisted * through ResultStore exactly like {@see generate()} does for a test * run, so a merchant can come back to one row of a finished batch and * repair a single section. A confirm-content-run Ability's own * synchronous per-product run (origin 'ability_run', since 2.8.0) is * persisted the same way, at the 24h TTL, so its result can be applied * through the existing {@see \AIPT\Api\ContentStructure\Apply\ResultApplier}. * Every other caller (editor, metabox, the plain 'ability' origin used by * generate-*, automation) gets an empty resultKey and no row is written: * the generator owns continuing into its own existing apply/review path. * BlueprintIntegration::run() is what tells an Automation job's calls * apart from the bulk pages, by giving them the 'automation' origin. * * @param ExecutionRequest $request Execution request. * @return array|WP_Error GenerationResult (persisted for a real bulk run or an 'ability_run' confirm run, an empty resultKey otherwise), or an error. */ public function generateForRun( ExecutionRequest $request ) { $resolved = $this->resolveExecution( $request ); if ( is_wp_error( $resolved ) ) { return $resolved; } $slice = $this->runGenerator( $resolved['generatorInstance'], $resolved['ctx'] ); $slice = $this->contextBuilder->applyPreserveContentImages( $request->getGenerator(), $request->getRunOptions(), $resolved['ctx']['product'], $slice ); $result = $this->wrapResult( $request->getGenerator(), $request->getClientVersion(), $resolved, $slice, $request->getOrigin(), $request->getRunOptions() ); if ( $this->shouldPersistForRun( $request ) ) { return $this->persist( $result, $request, $resolved ); } return $result; } /** * Whether a `generateForRun()` call must be persisted: a bulk-generate * run, or a confirm-content-run Ability's own synchronous per-product run * (origin 'ability_run', since 2.8.0 — it carries its own acting user, so * it has an owner from the start, unlike an Automation run). Automation * runs are not persisted yet: the request's userId now carries the job's * creator (BlueprintIntegration::run(), for the object-permission check), * but that alone does not make a persisted row's retention/History * behavior meaningful for a job the merchant never opens one result of — * persisting Automation runs is a separate decision, not made here. * * @param ExecutionRequest $request Execution request. * @return bool */ private function shouldPersistForRun( ExecutionRequest $request ): bool { return in_array( $request->getOrigin(), array( 'bulk', 'ability_run' ), true ); } /** * Re-run exactly one AI unit of a stored result and persist a new result * row (`POST results/{key}/regenerate`). * * @param string $resultKey Stored result's result_key. * @param string $unitId Unit id to regenerate. * @param array|null $draft Fresh unsaved draft definition `{definition, brandProfileId}`, or null to reuse the stored snapshot. * @param int $userId Acting user id. * @return array|WP_Error New GenerationResult, or an error. */ public function regenerateSection( string $resultKey, string $unitId, ?array $draft, 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 regenerate this result.', 'ai-product-tools' ), array( 'status' => 403 ) ); } $generator = (string) $row['generator']; $definition_result = $this->definitionResolver->forRegenerate( $row, $draft ); if ( is_wp_error( $definition_result ) ) { return $definition_result; } $policy_result = $this->entitlementPolicy->apply( $generator, $definition_result['definition'] ); $definition_result['definition'] = $policy_result['definition']; $voice_result = $this->entitlementPolicy->clampBrandProfile( $definition_result['brandProfileData'] ); $definition_result['brandProfileData'] = $voice_result['profile']; $subject = array( 'type' => (string) $row['subjectType'], 'id' => (int) $row['subjectId'], ); if ( (int) $row['productId'] > 0 ) { $subject['productId'] = (int) $row['productId']; } $permission_error = $this->contextBuilder->checkObjectPermission( $subject ); if ( null !== $permission_error ) { return $permission_error; } $subject_data = $this->contextBuilder->loadSubject( $subject ); if ( is_wp_error( $subject_data ) ) { return $subject_data; } $stored_run_options = is_array( $row['payload']['runOptions'] ?? null ) ? $row['payload']['runOptions'] : array(); $pre_clamp_run_options = ExecutionRequest::fromArray( array( 'generator' => $generator, 'subject' => $subject, 'runOptions' => $stored_run_options ) )->getRunOptions(); $run_options = $this->clampSeoMetaVariants( $generator, $pre_clamp_run_options ); $run_options = $this->clampTitleImproveExisting( $generator, $run_options ); $definition = $this->contextBuilder->applyAllowExistingDescription( $generator, $run_options, $definition_result['definition'] ); $deadline = $this->now() + 60.0; $source_bundle = $this->contextBuilder->buildSourcesAndDecisions( $definition, $subject['type'], (int) $row['subjectId'], $deadline, (int) ( $definition_result['blueprintMeta']['id'] ?? 0 ) ); $generator_instance = GeneratorRegistry::create( $generator ); if ( null === $generator_instance ) { return new WP_Error( 'aipt_blueprint_generator_unavailable', __( 'This generator is not available right now.', 'ai-product-tools' ), array( 'status' => 500 ) ); } $ctx = $this->contextBuilder->buildCtx( $generator, $definition, $definition_result['brandProfileData'], $subject_data, $source_bundle, $run_options, $deadline, 3 ); $ctx = $this->withTitleSourcesLimit( $generator, $ctx ); $previous_slice = $this->sliceFromPayload( is_array( $row['payload'] ) ? $row['payload'] : array() ); if ( null === $this->findUnitById( $previous_slice['units'], $unitId ) ) { return new WP_Error( 'aipt_blueprint_section_not_found', __( 'This section no longer exists in the template.', 'ai-product-tools' ), array( 'status' => 404 ) ); } $caller = $this->runCaller(); $slice = $generator_instance->regenerateUnit( $ctx, $previous_slice, $unitId, $caller ); $slice = $this->contextBuilder->applyPreserveContentImages( $generator, $run_options, $ctx['product'], $slice ); $stored_resolution = is_array( $row['payload']['resolution'] ?? null ) ? $row['payload']['resolution'] : null; $resolved = array( 'ctx' => $ctx, 'blueprintMeta' => $definition_result['blueprintMeta'], 'brandProfileMeta' => $definition_result['brandProfileMeta'], 'resolution' => $stored_resolution, 'subjectMeta' => $subject_data['meta'], 'snapshotId' => $definition_result['snapshotId'], 'definitionHash' => $definition_result['definitionHash'], 'appliedFreeDefaults' => $this->withExtraSlotsFreeDefault( $this->withTitleImproveExistingFreeDefault( $this->withSeoMetaVariantsFreeDefault( $this->withAiNoteFreeDefault( $this->withImageAltGalleryFreeDefault( $this->withVoiceSamplesFreeDefault( $policy_result['appliedFreeDefaults'], $voice_result['dropped'] ), $ctx ), $ctx, $generator ), $generator, $pre_clamp_run_options ), $generator, $pre_clamp_run_options ), $stored_resolution ), ); $origin = (string) ( $row['origin'] ?? 'test' ); $result = $this->wrapResult( $generator, null, $resolved, $slice, $origin, $pre_clamp_run_options ); $request = ExecutionRequest::fromArray( array( 'generator' => $generator, 'subject' => $subject, 'origin' => $origin, 'userId' => $userId, ) ); return $this->persist( $result, $request, $resolved ); } /** * Whether a subject type is valid for a generator. Image alt also runs * on a product: every image of that product in one call * (ExecutionContextBuilder::imagesFor()), which Test & preview and the * Image alt page use. * * @param string $generator Generator key. * @param string $type Subject type. * @return bool */ private function acceptsSubjectType( string $generator, string $type ): bool { if ( Generators::subjectType( $generator ) === $type ) { return true; } return Generators::IMAGE_ALT === $generator && 'product' === $type; } /** * @param ExecutionRequest $request Execution request. * @return array|WP_Error {ctx, generatorInstance, blueprintMeta, brandProfileMeta, resolution, subjectMeta, snapshotId, definitionHash}. */ private function resolveExecution( ExecutionRequest $request ) { $generator = $request->getGenerator(); if ( ! Generators::isValid( $generator ) ) { return new WP_Error( 'aipt_blueprint_invalid_generator', __( 'Unknown content type.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $subject = $request->getSubject(); if ( ! $this->acceptsSubjectType( $generator, (string) ( $subject['type'] ?? '' ) ) || (int) ( $subject['id'] ?? 0 ) <= 0 ) { return new WP_Error( 'aipt_blueprint_invalid_subject', __( 'This subject is not valid for this generator.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( null !== $request->getDraft() && ! current_user_can( self::CAP_USE ) ) { return new WP_Error( 'aipt_blueprint_forbidden', __( 'You do not have permission to test an unsaved draft.', 'ai-product-tools' ), array( 'status' => 403 ) ); } $actor_user_id = 'automation' === $request->getOrigin() ? $request->getUserId() : null; $permission_error = $this->contextBuilder->checkObjectPermission( $subject, $actor_user_id ); if ( null !== $permission_error ) { return $permission_error; } $subject_data = $this->contextBuilder->loadSubject( $subject ); if ( is_wp_error( $subject_data ) ) { return $subject_data; } $definition_result = $this->definitionResolver->resolve( $request ); if ( is_wp_error( $definition_result ) ) { return $definition_result; } $policy_result = $this->entitlementPolicy->apply( $generator, $definition_result['definition'], $request->getAutomationContext() ); $definition_result['definition'] = $policy_result['definition']; $voice_result = $this->entitlementPolicy->clampBrandProfile( $definition_result['brandProfileData'] ); $definition_result['brandProfileData'] = $voice_result['profile']; $generator_instance = GeneratorRegistry::create( $generator ); if ( null === $generator_instance ) { return new WP_Error( 'aipt_blueprint_generator_unavailable', __( 'This generator is not available right now.', 'ai-product-tools' ), array( 'status' => 500 ) ); } $run_options = $this->clampSeoMetaVariants( $generator, $request->getRunOptions() ); $run_options = $this->clampTitleImproveExisting( $generator, $run_options ); $definition = $this->contextBuilder->applyAllowExistingDescription( $generator, $run_options, $definition_result['definition'] ); $source_bundle = $this->contextBuilder->buildSourcesAndDecisions( $definition, $subject['type'], (int) $subject['id'], $request->getDeadline(), (int) ( $definition_result['blueprintMeta']['id'] ?? 0 ) ); $ctx = $this->contextBuilder->buildCtx( $generator, $definition, $definition_result['brandProfileData'], $subject_data, $source_bundle, $run_options, $request->getDeadline(), $request->getMaxCalls() ); $ctx = $this->withTitleSourcesLimit( $generator, $ctx ); $applied_free_defaults = $this->withVoiceSamplesFreeDefault( $policy_result['appliedFreeDefaults'], $voice_result['dropped'] ); $applied_free_defaults = $this->withImageAltGalleryFreeDefault( $applied_free_defaults, $ctx ); $applied_free_defaults = $this->withAiNoteFreeDefault( $applied_free_defaults, $ctx, $generator ); $applied_free_defaults = $this->withSeoMetaVariantsFreeDefault( $applied_free_defaults, $generator, $request->getRunOptions() ); $applied_free_defaults = $this->withTitleImproveExistingFreeDefault( $applied_free_defaults, $generator, $request->getRunOptions() ); $applied_free_defaults = $this->withExtraSlotsFreeDefault( $applied_free_defaults, $definition_result['resolution'] ); return array( 'ctx' => $ctx, 'generatorInstance' => $generator_instance, 'blueprintMeta' => $definition_result['blueprintMeta'], 'brandProfileMeta' => $definition_result['brandProfileMeta'], 'resolution' => $definition_result['resolution'], 'subjectMeta' => $subject_data['meta'], 'snapshotId' => $definition_result['snapshotId'], 'definitionHash' => $definition_result['definitionHash'], 'appliedFreeDefaults' => $applied_free_defaults, ); } /** * Tell a Title run whether its AI reads only the free title sources (the * product name and description), so TitleGenerator can say why a run * that found nothing specific in them produced no title. False for * every other generator and for a site with the paid title sources. * * @param string $generator Generator key. * @param array $ctx ExecutionContextBuilder::buildCtx()'s context. * @return array */ private function withTitleSourcesLimit( string $generator, array $ctx ): array { $ctx['titleSourcesLimited'] = Generators::TITLE === $generator && ! $this->entitlementPolicy->titleAdvancedSourcesAllowed(); return $ctx; } /** * Append the voice writing-samples free-default entry when * `EntitlementPolicy::clampBrandProfile()` withheld this run's samples. * * @param array $applied Accumulated appliedFreeDefaults entries so far. * @param bool $dropped Whether the voice's samples were withheld. * @return array */ private function withVoiceSamplesFreeDefault( array $applied, bool $dropped ): array { if ( $dropped ) { $applied[] = $this->entitlementPolicy->voiceSamplesFreeDefault(); } return $applied; } /** * Append the image-alt gallery free-default entry, but only when THIS * run's ctx actually says a gallery image was left out * (`ExecutionContextBuilder::imagesFor()` is the only place that knows * that — see its own docblock — since `EntitlementPolicy::apply()` runs * before any subject/image data exists). Keeps * `appliedFreeDefaults` additive and in definition order either way: * every definition-level entry `EntitlementPolicy::apply()` already * found, plus this one context-level entry when it applies. * * @param array $applied EntitlementPolicy::apply()'s appliedFreeDefaults so far. * @param array $ctx GeneratorInterface context (buildCtx()'s result). * @return array */ private function withImageAltGalleryFreeDefault( array $applied, array $ctx ): array { if ( ! empty( $ctx['imageAltGalleryDropped'] ) ) { $applied[] = $this->entitlementPolicy->imageAltGalleryFreeDefault(); } return $applied; } /** * Append the AI note free-default entry, but only when THIS run's ctx * actually says a note was withheld * (`ExecutionContextBuilder::buildCtx()`'s `aiNoteDropped` is the only * place that knows that, since `EntitlementPolicy::apply()` runs before * any subject/product data exists) - the same pattern as * {@see withImageAltGalleryFreeDefault()} just above. * * @param array $applied Accumulated appliedFreeDefaults entries so far. * @param array $ctx GeneratorInterface context (buildCtx()'s result). * @param string $generator Generator key. * @return array */ private function withAiNoteFreeDefault( array $applied, array $ctx, string $generator ): array { if ( ! empty( $ctx['aiNoteDropped'] ) ) { $applied[] = $this->entitlementPolicy->aiNoteFreeDefault( $generator ); } return $applied; } /** * Append the SEO meta alternatives free-default entry, but only when * THIS run's requested `runOptions.variants` actually exceeded * {@see EntitlementPolicy::seoMetaMaxVariants()} - the same additive, * only-when-it-mattered pattern as {@see withImageAltGalleryFreeDefault()} * and {@see withAiNoteFreeDefault()} just above. Takes the PRE-clamp run * options (never the already-clamped result {@see clampSeoMetaVariants()} * returns), since clamped-vs-requested is exactly the comparison this * reports. * * @param array $applied Accumulated appliedFreeDefaults entries so far. * @param string $generator Generator key. * @param array $run_options ExecutionRequest run options, BEFORE clampSeoMetaVariants() runs. * @return array */ private function withSeoMetaVariantsFreeDefault( array $applied, string $generator, array $run_options ): array { if ( Generators::SEO_META !== $generator ) { return $applied; } $requested = (int) ( $run_options['variants'] ?? 1 ); if ( $requested > $this->entitlementPolicy->seoMetaMaxVariants() ) { $applied[] = $this->entitlementPolicy->seoMetaVariantsFreeDefault(); } return $applied; } /** * Clamp `runOptions.variants` to this site's SEO meta entitlement, for * SEO meta only — Title stays unclamped. Applied at both places * `$run_options` is read (the normal resolution pipeline and a stored * result's regenerate), so every origin (bulk, automation, editor, * metabox, ability, Test and preview, regenerate) is capped the same way. * * @param string $generator Generator key. * @param array $run_options ExecutionRequest run options. * @return array $run_options, with `variants` clamped for SEO meta only. */ private function clampSeoMetaVariants( string $generator, array $run_options ): array { if ( Generators::SEO_META !== $generator ) { return $run_options; } $run_options['variants'] = min( (int) ( $run_options['variants'] ?? 1 ), $this->entitlementPolicy->seoMetaMaxVariants() ); return $run_options; } /** * Clamp `runOptions.improveExisting` to this site's Title entitlement, * for Title only. Applied at both places `$run_options` is read (the * normal resolution pipeline and a stored result's regenerate), so every * origin (bulk, automation, editor, metabox, ability, Test and preview, * regenerate) is capped the same way - the same pattern * {@see clampSeoMetaVariants()} already uses. * * @param string $generator Generator key. * @param array $run_options ExecutionRequest run options. * @return array $run_options, with `improveExisting` forced false for Title when not entitled. */ private function clampTitleImproveExisting( string $generator, array $run_options ): array { if ( Generators::TITLE !== $generator ) { return $run_options; } if ( ! empty( $run_options['improveExisting'] ) && ! $this->entitlementPolicy->titleImproveExistingAllowed() ) { $run_options['improveExisting'] = false; } return $run_options; } /** * Append the Title "Improve existing text" free-default entry, but only * when THIS run's requested `runOptions.improveExisting` was actually * true and this site is not entitled - the same additive, * only-when-it-mattered pattern as {@see withSeoMetaVariantsFreeDefault()}. * Takes the PRE-clamp run options (never {@see clampTitleImproveExisting()}'s * already-clamped result), since requested-vs-entitled is exactly the * comparison this reports. * * @param array $applied Accumulated appliedFreeDefaults entries so far. * @param string $generator Generator key. * @param array $run_options ExecutionRequest run options, BEFORE clampTitleImproveExisting() runs. * @return array */ private function withTitleImproveExistingFreeDefault( array $applied, string $generator, array $run_options ): array { if ( Generators::TITLE !== $generator ) { return $applied; } if ( ! empty( $run_options['improveExisting'] ) && ! $this->entitlementPolicy->titleImproveExistingAllowed() ) { $applied[] = $this->entitlementPolicy->titleImproveExistingFreeDefault(); } return $applied; } /** * Append the content structure extra-slots free-default entry when this * run's Resolution shows its 'category' step — an ordered category * exception (product generators), or Category descriptions' Product * tags structure — as 'locked': the assignment exists * ({@see \AIPT\Core\ContentStructure\Assignment\AssignmentResolver::resolve()}) * but this plan does not apply it, so the store default (or the * built-in template) was used instead. * * @param array $applied Accumulated appliedFreeDefaults entries so far. * @param array|null $resolution AssignmentResolver::resolve()'s Resolution, or null (an unsaved draft, or a stored row saved before Resolution was recorded, carries none). * @return array */ private function withExtraSlotsFreeDefault( array $applied, ?array $resolution ): array { if ( null !== $resolution && $this->hasLockedCategoryStep( $resolution ) ) { $applied[] = $this->entitlementPolicy->extraSlotsFreeDefault(); } return $applied; } /** * @param array $resolution Resolution. * @return bool Whether its 'category' step reports state 'locked'. */ private function hasLockedCategoryStep( array $resolution ): bool { foreach ( (array) ( $resolution['steps'] ?? array() ) as $step ) { if ( 'category' === ( $step['key'] ?? '' ) ) { return 'locked' === ( $step['state'] ?? '' ); } } return false; } /** * @param \AIPT\Api\ContentStructure\Engine\Generators\GeneratorInterface $generator_instance Resolved generator. * @param array $ctx GeneratorInterface context. * @return array Generator-specific GenerationResult slice. */ private function runGenerator( $generator_instance, array $ctx ): array { return $generator_instance->generate( $ctx, $this->runCaller() ); } /** * A fresh caller for one run, wrapped so a provider that rejected the * key, ran out of quota, kept limiting or could not be reached is not * called again for the rest of that run. * * @return StructuredCallerInterface */ private function runCaller(): StructuredCallerInterface { return new RunScopedCaller( call_user_func( $this->callerFactory ) ); } /** * Reconstruct a generator-specific slice from a stored GenerationResult * payload, so `regenerateUnit()` can reuse every other unit verbatim. * * @param array $payload Stored GenerationResult payload. * @return array{units:array,outputs:array,checks:array,conflicts:array,findings:array,sourcesUsed:array,eligibility:array,usage:array,providerError:array|null} */ private function sliceFromPayload( array $payload ): array { return array( 'units' => is_array( $payload['units'] ?? null ) ? $payload['units'] : array(), 'outputs' => is_array( $payload['outputs'] ?? null ) ? $payload['outputs'] : array(), 'checks' => is_array( $payload['checks'] ?? null ) ? $payload['checks'] : array(), 'conflicts' => is_array( $payload['conflicts'] ?? null ) ? $payload['conflicts'] : array(), 'findings' => is_array( $payload['findings'] ?? null ) ? $payload['findings'] : array(), 'sourcesUsed' => is_array( $payload['sourcesUsed'] ?? null ) ? $payload['sourcesUsed'] : array(), 'eligibility' => is_array( $payload['eligibility'] ?? null ) ? $payload['eligibility'] : array( 'canApply' => false, 'requiresReview' => true, 'blockers' => array() ), 'usage' => is_array( $payload['usage'] ?? null ) ? $payload['usage'] : array( 'aiCalls' => 0, 'nativeStructuredOutput' => false, 'provider' => '', 'model' => '', 'durationMs' => 0 ), 'providerError' => is_array( $payload['providerError'] ?? null ) ? $payload['providerError'] : null, ); } /** * @param array[] $units Stored result's own unit list ({@see sliceFromPayload()}'s `units`). * @param string $id Unit id to find. * @return array|null */ private function findUnitById( array $units, string $id ): ?array { foreach ( $units as $unit ) { if ( ( $unit['id'] ?? '' ) === $id ) { return $unit; } } return null; } /** * Wrap a generator-specific slice into the full GenerationResult shape. * `resultKey` is left empty; {@see persist()} fills it in for persisted * results. * * @param string $generator Generator key. * @param int|null $client_version Client-side staleness counter. * @param array $resolved resolveExecution()'s (or the regenerate path's) metadata. * @param array $slice GeneratorInterface::generate()/regenerateUnit()'s result. * @param string $origin Request origin (or, for a regenerate, the parent row's own origin) — decides the `expiresAt` shown here, matching what {@see persist()} actually stores when this result is persisted. * @param array $run_options The run's normalized options (pre entitlement clamp, no secrets), stored so a section regenerate can restore them. * @return array GenerationResult. */ private function wrapResult( string $generator, ?int $client_version, array $resolved, array $slice, string $origin, array $run_options ): array { $now = $this->now(); $created_at = gmdate( 'c', (int) $now ); $expires_at = gmdate( 'c', (int) $now + $this->ttlSecondsForOrigin( $origin ) ); return array( 'resultKey' => '', 'generator' => $generator, 'executionPath' => 'blueprint', 'subject' => $resolved['subjectMeta'], 'blueprint' => $resolved['blueprintMeta'], 'brandProfile' => $resolved['brandProfileMeta'], 'resolution' => $resolved['resolution'], 'outputs' => $slice['outputs'], 'units' => $slice['units'], 'checks' => $slice['checks'], 'conflicts' => $slice['conflicts'], 'findings' => $slice['findings'], 'sourcesUsed' => $slice['sourcesUsed'], 'eligibility' => $slice['eligibility'], 'usage' => $slice['usage'], 'providerError' => is_array( $slice['providerError'] ?? null ) ? $slice['providerError'] : null, 'contextHash' => $this->contextBuilder->computeContextHash( $resolved['ctx'], $slice['sourcesUsed'] ), 'appliedFreeDefaults' => isset( $resolved['appliedFreeDefaults'] ) && is_array( $resolved['appliedFreeDefaults'] ) ? $resolved['appliedFreeDefaults'] : array(), 'runOptions' => $run_options, 'clientVersion' => $client_version, 'createdAt' => $created_at, 'expiresAt' => $expires_at, ); } /** * Persist a test/bulk/regenerate GenerationResult through ResultStore. * * The result_key is generated here, up front, and baked into `payload` * (via `$result['resultKey']`) before the one and only write — unlike a * two-phase INSERT-then-UPDATE, ResultStore::create() accepts this * pre-generated key and writes the row once. * * @param array $result Assembled GenerationResult (resultKey still empty). * @param ExecutionRequest $request Originating request. * @param array $resolved resolveExecution()'s metadata. * @return array|WP_Error The result with its resultKey filled in, or an error when persistence failed. */ private function persist( array $result, ExecutionRequest $request, array $resolved ) { $subject = $request->getSubject(); $origin = in_array( $request->getOrigin(), self::PERSISTABLE_ORIGINS, true ) ? $request->getOrigin() : 'test'; $key = bin2hex( random_bytes( 16 ) ); $result['resultKey'] = $key; $created = $this->results->create( array( 'resultKey' => $key, 'generator' => $request->getGenerator(), 'subjectType' => (string) $subject['type'], 'subjectId' => (int) $subject['id'], 'productId' => $this->resolvedProductId( $resolved['ctx']['product'] ?? null ), 'origin' => $origin, 'blueprintId' => (int) ( $resolved['blueprintMeta']['id'] ?? 0 ), 'snapshotId' => (int) $resolved['snapshotId'], 'definitionHash' => (string) $resolved['definitionHash'], 'contextHash' => (string) $result['contextHash'], 'status' => $this->resultStatus( $result['eligibility'] ), 'eligible' => (bool) $result['eligibility']['canApply'], 'payload' => $result, 'createdBy' => $request->getUserId(), 'expiresAt' => gmdate( 'Y-m-d H:i:s', (int) $this->now() + $this->ttlSecondsForOrigin( $origin ) ), ) ); if ( '' === $created ) { return new WP_Error( 'aipt_blueprint_result_save_failed', __( 'The result could not be saved. Please try again.', 'ai-product-tools' ), array( 'status' => 500 ) ); } return $result; } /** * The stored row's display `status`: distinct from `eligible` (which * carries `canApply` alone) so a reader of `status` by itself can never * mistake a blocked result for a fine one. `canApply` false takes * precedence over `requiresReview` - a run with no usable AI content is * blocked outright, not merely flagged for review. * * @param array{canApply?:bool,requiresReview?:bool} $eligibility GenerationResult eligibility. * @return string 'blocked' | 'needs_review' | 'ok'. */ private function resultStatus( array $eligibility ): string { if ( empty( $eligibility['canApply'] ) ) { return 'blocked'; } return ! empty( $eligibility['requiresReview'] ) ? 'needs_review' : 'ok'; } /** * Seconds a persisted result of this origin's class may live before * expiring. 'bulk' is the only class that gets the week-long window; a * regenerate of a bulk row is also 'bulk' by the time this is called * (see regenerateSection()), so it gets the same week. Anything else * ('test', or a malformed/legacy value) gets the 24h default. * * @param string $origin One of self::PERSISTABLE_ORIGINS (or any other value, treated as 'test'). * @return int */ private function ttlSecondsForOrigin( string $origin ): int { return 'bulk' === $origin ? self::RESULT_TTL_SECONDS_BULK : self::RESULT_TTL_SECONDS; } /** * @param mixed $product Resolved subject product, or null. * @return int */ private function resolvedProductId( $product ): int { return ( $product instanceof \WC_Product ) ? (int) $product->get_id() : 0; } /** * @return float */ private function now(): float { return (float) call_user_func( $this->clock ); } }