* manual pick > run pin > live precedence that resolves a normalized * definition, compiled brand profile data, and display metadata for one * request. * * @package AIPT\Api\ContentStructure\Engine * @since 2.8.0 */ namespace AIPT\Api\ContentStructure\Engine; use AIPT\Core\ContentStructure\Assignment\AssignmentResolver; use AIPT\Core\ContentStructure\Domain\DefinitionHasher; use AIPT\Core\ContentStructure\Domain\DefinitionNormalizer; use AIPT\Core\ContentStructure\Domain\FieldCatalog; use AIPT\Core\ContentStructure\Execution\RunPinService; use AIPT\Core\ContentStructure\Storage\BrandProfileStore; use AIPT\Core\ContentStructure\Storage\SourceStore; use WP_Error; defined( 'ABSPATH' ) || exit; /** * Resolves a request's effective definition + brand profile + Resolution. */ class ExecutionDefinitionResolver { /** * @var AssignmentResolver */ private $assignmentResolver; /** * @var RunPinService */ private $runPinService; /** * @var BrandProfileStore */ private $brandProfiles; /** * @var DefinitionNormalizer */ private $normalizer; /** * @var SourceStore */ private $sourceStore; /** * @param AssignmentResolver|null $assignmentResolver Assignment resolver; a default instance is constructed when omitted. * @param RunPinService|null $runPinService Run pin service; a default instance is constructed when omitted. * @param BrandProfileStore|null $brandProfiles Brand profile store; a default instance is constructed when omitted. * @param DefinitionNormalizer|null $normalizer Definition normalizer; a default instance is constructed when omitted. * @param SourceStore|null $sourceStore Source store (for the normalizer's knownSourceIds); a default instance is constructed when omitted. */ public function __construct( ?AssignmentResolver $assignmentResolver = null, ?RunPinService $runPinService = null, ?BrandProfileStore $brandProfiles = null, ?DefinitionNormalizer $normalizer = null, ?SourceStore $sourceStore = null ) { $this->assignmentResolver = $assignmentResolver ?? new AssignmentResolver(); $this->runPinService = $runPinService ?? new RunPinService(); $this->brandProfiles = $brandProfiles ?? new BrandProfileStore(); $this->normalizer = $normalizer ?? new DefinitionNormalizer(); $this->sourceStore = $sourceStore ?? new SourceStore(); } /** * @param ExecutionRequest $request Execution request. * @return array|WP_Error {definition, brandProfileData, blueprintMeta, brandProfileMeta, resolution, snapshotId, definitionHash}. */ public function resolve( ExecutionRequest $request ) { $generator = $request->getGenerator(); $draft = $request->getDraft(); if ( null !== $draft ) { return $this->resolveDraftDefinition( $generator, $draft ); } $run_pin_input = $request->getRunPin(); if ( null !== $run_pin_input ) { return $this->resolvePinnedDefinition( $generator, $request->getSubject(), $run_pin_input, $request->getBlueprintId(), $request->getUserId() ); } $manual_id = $request->getBlueprintId(); if ( null !== $manual_id ) { return $this->resolveManualDefinition( $generator, $request->getSubject(), $manual_id, $request->getUserId() ); } return $this->resolveLiveDefinition( $generator, $request->getSubject(), $request->getUserId() ); } /** * @param string $generator Generator key. * @param array $draft {definition, brandProfileId, name}. * @return array|WP_Error */ public function resolveDraftDefinition( string $generator, array $draft ) { if ( ! array_key_exists( 'definition', $draft ) || ! is_array( $draft['definition'] ) ) { return new WP_Error( 'aipt_blueprint_draft_invalid', __( 'This draft is missing its "definition" object.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $raw_definition = $draft['definition']; $normalized = $this->normalizer->normalize( $generator, $raw_definition, $this->normalizerContext( $raw_definition ) ); if ( ! empty( $normalized['errors'] ) ) { return new WP_Error( 'aipt_blueprint_invalid_definition', __( 'This draft has validation errors and cannot be tested.', 'ai-product-tools' ), array( 'status' => 400, 'errors' => $normalized['errors'] ) ); } $definition = $normalized['definition']; $definition_hash = DefinitionHasher::hash( $definition ); $brand_profile_id = (int) ( $draft['brandProfileId'] ?? 0 ); $brand_profile_data = null; $brand_profile_meta = null; if ( $brand_profile_id > 0 ) { $profile_row = $this->brandProfiles->get( $brand_profile_id ); if ( null !== $profile_row ) { $brand_profile_data = $profile_row['profile']; $brand_profile_meta = array( 'id' => (int) $profile_row['id'], 'name' => (string) $profile_row['name'], 'revision' => (int) $profile_row['revision'] ); } } return array( 'definition' => $definition, 'brandProfileData' => $brand_profile_data, 'blueprintMeta' => array( 'id' => null, 'name' => (string) ( $draft['name'] ?? '' ), 'revision' => null, 'draft' => true, 'definitionHash' => $definition_hash, 'builtin' => false ), 'brandProfileMeta' => $brand_profile_meta, 'resolution' => null, 'snapshotId' => 0, 'definitionHash' => $definition_hash, ); } /** * @param string $generator Generator key. * @param array $subject Subject. * @param int|string $run_pin Snapshot id or hash. * @param int|null $manual_id Manual pick, when the caller supplies one. * @param int $user_id Acting user id. * @return array|WP_Error */ private function resolvePinnedDefinition( string $generator, array $subject, $run_pin, ?int $manual_id, int $user_id ) { $pin = $this->runPinService->loadRunPin( $run_pin ); if ( null === $pin || $pin['generator'] !== $generator ) { return new WP_Error( 'aipt_blueprint_pin_invalid', __( 'This run pin does not exist or is for a different generator.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $resolution = $this->assignmentResolver->resolve( $generator, $subject, $manual_id, $pin['payload'] ); if ( is_wp_error( $resolution ) ) { return $resolution; } if ( null !== $resolution['conflict'] ) { return $this->assignmentConflictError( $resolution ); } return $this->snapshotFromResolution( $resolution, $pin['payload'], $user_id, true ); } /** * @param string $generator Generator key. * @param array $subject Subject. * @param int $manual_id Manual pick. * @param int $user_id Acting user id. * @return array|WP_Error */ private function resolveManualDefinition( string $generator, array $subject, int $manual_id, int $user_id ) { $resolution = $this->assignmentResolver->resolve( $generator, $subject, $manual_id, null ); if ( is_wp_error( $resolution ) ) { return $resolution; } return $this->snapshotFromResolution( $resolution, null, $user_id, false ); } /** * @param string $generator Generator key. * @param array $subject Subject. * @param int $user_id Acting user id. * @return array|WP_Error */ private function resolveLiveDefinition( string $generator, array $subject, int $user_id ) { $resolution = $this->assignmentResolver->resolve( $generator, $subject, null, null ); if ( is_wp_error( $resolution ) ) { return $resolution; } if ( null !== $resolution['conflict'] ) { return $this->assignmentConflictError( $resolution ); } return $this->snapshotFromResolution( $resolution, null, $user_id, false ); } /** * The shared "two or more Blueprints tied at the same priority" error, * used by both live and pinned resolution so a pinned run can never * silently fall back to the built-in default when its frozen assignment * rows conflict. * * @param array $resolution Resolution carrying the conflict. * @return WP_Error */ private function assignmentConflictError( array $resolution ): WP_Error { return new WP_Error( 'aipt_blueprint_assignment_conflict', __( 'Two or more category exceptions share the same priority for this product. Reorder them on 1 ยท Content template to continue.', 'ai-product-tools' ), array( 'status' => 409, 'resolution' => $resolution ) ); } /** * Resolve a Resolution's winning blueprint (or the built-in default) to * its definition snapshot, either from a run pin's frozen map or by * pinning the current live revision. * * @param array $resolution Resolution. * @param array|null $run_pin Pinned payload, or null for live. * @param int $user_id Acting user id. * @param bool $is_pinned Whether this resolution ran against a run pin. * @return array|WP_Error */ private function snapshotFromResolution( array $resolution, ?array $run_pin, int $user_id, bool $is_pinned ) { $blueprint_id = $resolution['blueprintId']; if ( null === $blueprint_id ) { if ( $is_pinned && null !== $run_pin ) { $snapshot_id = (int) ( $run_pin['builtinDefault']['definitionSnapshotId'] ?? 0 ); $snapshot = $this->runPinService->definitionSnapshot( $snapshot_id ); } else { $snapshot = $this->runPinService->builtinSnapshot( $resolution['generator'], $user_id ); } } elseif ( $is_pinned && null !== $run_pin ) { $snapshot_id = isset( $run_pin['definitionSnapshots'][ (string) $blueprint_id ] ) ? (int) $run_pin['definitionSnapshots'][ (string) $blueprint_id ] : 0; $snapshot = $this->runPinService->definitionSnapshot( $snapshot_id ); } else { $snapshot = $this->runPinService->snapshotForBlueprint( $blueprint_id, $user_id ); } if ( is_wp_error( $snapshot ) ) { return $snapshot; } return $this->metaFromSnapshotPayload( $snapshot['payload'], (int) $snapshot['id'], $resolution ); } /** * @param array $row Stored ResultStore row. * @param array|null $draft Fresh draft, or null to reuse the stored snapshot. * @return array|WP_Error {definition, brandProfileData, blueprintMeta, brandProfileMeta, snapshotId, definitionHash}. */ public function forRegenerate( array $row, ?array $draft ) { if ( null !== $draft ) { $resolved = $this->resolveDraftDefinition( (string) $row['generator'], $draft ); if ( is_wp_error( $resolved ) ) { return $resolved; } if ( $resolved['definitionHash'] !== (string) $row['definitionHash'] ) { return new WP_Error( 'aipt_blueprint_result_stale', __( 'This draft has changed since this result was generated. Run a new test.', 'ai-product-tools' ), array( 'status' => 409 ) ); } return $resolved; } $snapshot_id = (int) $row['snapshotId']; if ( $snapshot_id <= 0 ) { return new WP_Error( 'aipt_blueprint_result_stale', __( 'This result was generated from an unsaved draft. Send the draft again to regenerate a section.', 'ai-product-tools' ), array( 'status' => 409 ) ); } $snapshot_row = $this->runPinService->definitionSnapshot( $snapshot_id ); if ( is_wp_error( $snapshot_row ) ) { return $snapshot_row; } return $this->metaFromSnapshotPayload( $snapshot_row['payload'], $snapshot_id, null ); } /** * @param array $payload Definition snapshot payload. * @param int $snapshot_id Snapshot id. * @param array|null $resolution Resolution to carry through, or null (regenerate path fills this in from the stored row itself). * @return array */ private function metaFromSnapshotPayload( array $payload, int $snapshot_id, ?array $resolution ): array { $blueprint_row = $payload['blueprint']; $has_id = null !== $blueprint_row['id'] && $blueprint_row['id'] > 0; return array( 'definition' => is_array( $blueprint_row['definition'] ) ? $blueprint_row['definition'] : array(), 'brandProfileData' => is_array( $payload['brandProfile']['profile'] ?? null ) ? $payload['brandProfile']['profile'] : null, 'blueprintMeta' => array( 'id' => $has_id ? (int) $blueprint_row['id'] : null, 'name' => (string) $blueprint_row['name'], 'revision' => $has_id ? (int) $blueprint_row['revision'] : null, 'draft' => false, 'definitionHash' => (string) $blueprint_row['definitionHash'], 'builtin' => ! $has_id, ), 'brandProfileMeta' => isset( $payload['brandProfile']['id'] ) ? array( 'id' => (int) $payload['brandProfile']['id'], 'name' => (string) $payload['brandProfile']['name'], 'revision' => (int) $payload['brandProfile']['revision'] ) : null, 'resolution' => $resolution, 'snapshotId' => $snapshot_id, 'definitionHash' => (string) $blueprint_row['definitionHash'], ); } /** * @param array $definition Raw submitted (not yet validated) BlueprintDefinition, used to find every 'src:' it references. * @return array{knownSourceIds:int[],allowCustomFields:bool} */ private function normalizerContext( array $definition = array() ): array { return array( 'knownSourceIds' => $this->knownSourceIds( $definition ), 'allowCustomFields' => ( new FieldCatalog() )->customFieldsAllowed(), ); } /** * Ids valid for a 'src:' reference: SourceStore::list()'s first 500 * rows sorted by name (an existing, bounded "known sources" baseline) * plus every id the submitted definition itself references, checked * directly against the store โ€” so a draft referencing a source outside * that first page is still recognized as known instead of rejected as * "Unknown source reference" (mirrors BlueprintController's and * StructureController's own knownSourceIds()). * * @param array $definition Raw submitted BlueprintDefinition. * @return int[] */ private function knownSourceIds( array $definition ): array { $first_page = array_map( static function ( array $source ): int { return (int) $source['id']; }, $this->sourceStore->list( array(), 500 ) ); $referenced = $this->sourceStore->existingIds( self::referencedSourceIds( $definition ) ); return array_values( array_unique( array_merge( $first_page, $referenced ) ) ); } /** * Every id referenced as 'src:' anywhere in a raw (not yet * validated) BlueprintDefinition โ€” the structure's per-section source * selections and the top-level source policy alike โ€” without depending * on DefinitionNormalizer's own traversal of that shape. * * @param array $definition Raw submitted BlueprintDefinition. * @return int[] */ private static function referencedSourceIds( array $definition ): array { $ids = array(); array_walk_recursive( $definition, static function ( $value ) use ( &$ids ): void { if ( is_string( $value ) && 1 === preg_match( '/^src:(\d+)$/', $value, $match ) ) { $ids[] = (int) $match[1]; } } ); return array_values( array_unique( $ids ) ); } }