compile one call for the pending `ai` parts -> * strict validation with one bounded targeted retry * (missing/invalid/over its limit/banned-phrase) -> apply each part's own * `missing` policy -> dedupe repeated words across parts (an `ai` part * left as a fragment is dropped) -> join with the * separator (no separator between an immediately-following `brand` + * `product_type` pair) -> enforce the hard character limit by dropping * `overflowDropPartId` and re-checking -> measured checks -> eligibility. * * @package AIPT\Api\ContentStructure\Engine\Generators * @since 2.8.0 */ namespace AIPT\Api\ContentStructure\Engine\Generators; use AIPT\Api\ContentStructure\Engine\AiNoteBlock; use AIPT\Api\ContentStructure\Engine\Checks; use AIPT\Api\ContentStructure\Engine\Context\ProductContextBuilder; use AIPT\Api\ContentStructure\Engine\ExecutionRequest; use AIPT\Api\ContentStructure\Engine\Generators\Formula\FormulaCallRunner; use AIPT\Api\ContentStructure\Engine\Generators\Formula\FormulaChecks; use AIPT\Api\ContentStructure\Engine\Generators\Formula\FormulaText; use AIPT\Api\ContentStructure\Engine\Generators\Support\PromptSpecBuilder; use AIPT\Api\ContentStructure\Engine\LanguageResolver; use AIPT\Api\ContentStructure\Engine\OutputValidator; use AIPT\Api\ContentStructure\Engine\ProviderFailureSupport; use AIPT\Api\ContentStructure\Engine\StructureInstructions; use AIPT\Api\ContentStructure\Engine\StructuredCallerInterface; use AIPT\Api\ContentStructure\Engine\TextMetrics; use AIPT\Core\ContentStructure\Domain\FieldCatalog; use AIPT\Core\ContentStructure\Domain\SectionCatalog; defined( 'ABSPATH' ) || exit; /** * Title formula pipeline orchestrator. */ class TitleGenerator implements GeneratorInterface { /** * Filter for extra instructions in the AI rounds: receives * array{system:string[],user:string[]}, the execution context and the * clamped definition. */ public const PROMPT_EXTRAS_FILTER = 'aipt_content_structure_title_prompt_extras'; /** * Separator enum -> literal joining text. * * @var array */ const SEPARATORS = array( 'dash' => ' – ', 'pipe' => ' | ', 'comma' => ', ', 'space' => ' ', ); /** * A run of Unicode letters at or under this length is treated as a * short acronym or brand code (e.g. "USB", "LED", a two/three-letter * brand) and is never title-cased by the "Avoid ALL CAPS" guard, even * when it is itself all-uppercase. */ const ACRONYM_MAX_LETTERS = 3; /** * The fewest characters an `ai` part without its own maxChars is given. * Squeezed below this, a key feature comes back as a stray word ("1", * "rib"), so the part is left out of the title instead. */ const MIN_AI_PART_CHARS = 10; /** * @var OutputValidator */ private $validator; /** * @var FormulaCallRunner */ private $callRunner; /** * @var PromptSpecBuilder */ private $specBuilder; /** * Ids of the `ai` parts the model answered this run with its permitted * empty string ("nothing specific applies"), reset by run(). * * @var array */ private $noDataPartIds = array(); /** * Whether this run's AI reads only the free title sources (the product * name and description, never tags, categories or attributes): * `ctx.titleSourcesLimited`, set by ExecutionService and copied here by * run(). * * @var bool */ private $titleSourcesLimited = false; public function __construct() { $this->validator = new OutputValidator(); $this->callRunner = new FormulaCallRunner(); $this->specBuilder = new PromptSpecBuilder(); } /** * @inheritDoc */ public function generate( array $ctx, StructuredCallerInterface $caller ): array { return $this->run( $ctx, $caller, null, null ); } /** * @inheritDoc */ public function regenerateUnit( array $ctx, array $previous, string $unit_id, StructuredCallerInterface $caller ): array { $parts = $this->partsOf( $ctx['definition'] ); $part = $this->findPart( $parts, $unit_id ); if ( null === $part || 'ai' !== ( $part['mode'] ?? '' ) || empty( $part['enabled'] ) ) { return $previous; } return $this->run( $ctx, $caller, $unit_id, $previous ); } /** * @param array $ctx Execution context. * @param StructuredCallerInterface $caller Structured AI caller. * @param string|null $only_unit_id Set only when regenerating one part. * @param array|null $previous regenerateUnit()'s previous slice. * @return array{units:array,outputs:array,checks:array,conflicts:array,findings:array,sourcesUsed:array,eligibility:array,usage:array,providerError:array|null} */ private function run( array $ctx, StructuredCallerInterface $caller, ?string $only_unit_id, ?array $previous ): array { $this->noDataPartIds = array(); $this->titleSourcesLimited = ! empty( $ctx['titleSourcesLimited'] ); $definition = $ctx['definition']; $structure = $definition['structure']; $parts = $this->partsOf( $definition ); $separator = (string) ( $structure['separator'] ?? 'dash' ); $max_chars = (int) ( $structure['maxChars'] ?? 60 ); $dedupe_on = ! empty( $structure['dedupe'] ); $overflow_drop_id = $structure['overflowDropPartId'] ?? null; $avoid_sku = (bool) ( $structure['avoidSku'] ?? true ); $avoid_all_caps = (bool) ( $structure['avoidAllCaps'] ?? true ); $fields = new FieldCatalog(); $product = $ctx['product']; $sku = trim( (string) $product->get_sku() ); $allowed_fields = isset( $definition['sources']['productFields'] ) ? array_values( (array) $definition['sources']['productFields'] ) : array(); $product_context = ( new ProductContextBuilder( $fields ) )->build( $product, $allowed_fields ); $extras = $this->promptExtras( $ctx, $definition ); $usage = $this->callRunner->emptyUsage(); $findings = array(); $banned = $this->specBuilder->mergedBanned( $ctx, $definition ); list( $resolved, $pending_specs ) = $this->resolveDeterministicAndCollectPending( $parts, $fields, $product, $only_unit_id, $previous ); $variant_count = null === $only_unit_id ? $this->resolveVariantCount( $ctx ) : 1; $texts_by_id = array(); $caps = $this->aiPartCaps( $definition, $resolved, $pending_specs, $overflow_drop_id ); foreach ( $caps as $id => $cap ) { if ( null === $cap ) { $resolved[ $id ] = $this->result( 'skipped_missing_data', __( 'There is no room left in the title for this part.', 'ai-product-tools' ), '', array() ); unset( $pending_specs[ $id ], $caps[ $id ] ); } } if ( ! empty( $pending_specs ) ) { $title_shape = $this->titleShape( $parts, $resolved, $pending_specs, $separator ); if ( $variant_count > 1 ) { $texts_by_id = $this->runAiRoundVariants( $caller, $ctx, $definition, $product_context, $pending_specs, $caps, $title_shape, $banned, $variant_count, $extras, $resolved, $usage, $findings ); } else { $this->runAiRound( $caller, $ctx, $definition, $product_context, $pending_specs, $caps, $title_shape, $banned, $extras, $resolved, $usage, $findings ); } } $assembled = $this->assemble( $parts, $resolved, $separator, $max_chars, $dedupe_on, $overflow_drop_id, $product_context, $banned, $usage, $findings, $only_unit_id, $avoid_sku, $sku, $previous ); if ( $variant_count > 1 ) { $extra_variants = $this->buildExtraVariants( $parts, $resolved, $texts_by_id, $caps, $separator, $max_chars, $overflow_drop_id, $dedupe_on, $variant_count, $avoid_all_caps, $banned ); $extra = $extra_variants['texts']; $variants = array_values( array_unique( array_merge( array( (string) $assembled['outputs']['title'] ), $extra ) ) ); if ( count( $variants ) > 1 ) { $assembled['outputs']['titleVariants'] = $variants; } $assembled['findings'] = $this->guardNonCanonicalVariants( $assembled['findings'], $extra_variants['allCapsFixed'], $avoid_sku, $sku, $extra ); if ( count( $variants ) < $variant_count ) { $assembled['findings'][] = $this->validator->finding( 'variant_dropped', 'warning', sprintf( /* translators: 1: number of title variants actually generated. 2: number requested. */ __( 'Only %1$d of %2$d requested title variants were generated; the rest were dropped for being too long, empty, using a banned phrase, or duplicating another variant.', 'ai-product-tools' ), count( $variants ), $variant_count ) ); } $assembled['eligibility'] = ( new Checks() )->eligibility( $assembled['findings'], array() ); } return $assembled; } /** * How many title alternatives this generate() call asks the model for * (`ExecutionRequest` already clamps * `runOptions.variants` to 1..MAX_VARIANTS, this only re-asserts the * floor for a ctx built outside that normalizer, e.g. in tests). * * @param array $ctx Execution context. * @return int */ private function resolveVariantCount( array $ctx ): int { $requested = isset( $ctx['runOptions']['variants'] ) ? (int) $ctx['runOptions']['variants'] : 1; return max( 1, min( ExecutionRequest::MAX_VARIANTS, $requested ) ); } /** * Resolve every fixed/data part deterministically and decide, for every * `ai` part, whether it needs a fresh model call (normal generation, or * the one part being regenerated) or can be reused verbatim from * `$previous` (every other `ai` part during a single-unit regenerate). * * @param array[] $parts TitlePart list. * @param FieldCatalog $fields Field catalog. * @param \WC_Product $product Product. * @param string|null $only_unit_id Set only when regenerating one part. * @param array|null $previous regenerateUnit()'s previous slice. * @return array{0:array,1:array} [resolved by id, pending AI part specs by id]. */ private function resolveDeterministicAndCollectPending( array $parts, FieldCatalog $fields, $product, ?string $only_unit_id, ?array $previous ): array { $resolved = array(); $pending = array(); foreach ( $parts as $part ) { $id = (string) $part['id']; if ( empty( $part['enabled'] ) ) { $resolved[ $id ] = $this->result( 'disabled', __( 'This part is turned off.', 'ai-product-tools' ), '', array() ); continue; } if ( 'fixed' === $part['mode'] ) { $resolved[ $id ] = $this->resolveDeterministicValue( $part, trim( (string) $part['text'] ), array() ); continue; } if ( 'data' === $part['mode'] ) { $ref = (string) $part['field']; $value = '' !== $ref ? $fields->productValue( $product, $ref ) : array( 'type' => 'text', 'value' => '', 'empty' => true ); if ( 'product_type' === $part['key'] && 'core:categories' === $ref && 'list' === ( $value['type'] ?? '' ) ) { $remaining = $this->categoriesNotInName( (array) $value['value'], (string) $product->get_name() ); if ( empty( $remaining ) && ! empty( $value['value'] ) ) { $resolved[ $id ] = $this->result( 'skipped_missing_data', __( 'The product name already contains the category.', 'ai-product-tools' ), '', array() ); continue; } $value['value'] = $remaining; } $raw = trim( FormulaText::scalarText( $value ) ); $resolved[ $id ] = $this->resolveDeterministicValue( $part, $raw, '' !== $ref ? array( $ref ) : array() ); continue; } if ( null !== $only_unit_id && $id !== $only_unit_id && null !== $previous ) { $prev_unit = $this->findUnit( (array) $previous['units'], $id ); if ( null !== $prev_unit ) { $resolved[ $id ] = $this->result( $prev_unit['status'], $prev_unit['reason'], $prev_unit['text'], $prev_unit['missingFields'] ); continue; } } $pending[ $id ] = $part; } return array( $resolved, $pending ); } /** * The categories a "product type" part may still add: those whose words * the product's own name does not already contain, so a "Tshirts" * category is not stacked in front of "T-Shirt with Logo". Compared * without case, hyphens or a trailing plural s. * * @param string[] $categories Category names. * @param string $name Product name. * @return string[] */ private function categoriesNotInName( array $categories, string $name ): array { $haystack = ' ' . $this->comparableWords( $name ) . ' '; return array_values( array_filter( $categories, function ( $category ) use ( $haystack ): bool { $needle = $this->comparableWords( (string) $category ); return '' === $needle || false === strpos( $haystack, ' ' . $needle . ' ' ); } ) ); } /** * @param string $text Any text. * @return string Lowercase words without hyphens, each without a trailing plural s, joined by one space. */ private function comparableWords( string $text ): string { $words = preg_split( '/[^\p{L}\p{N}]+/u', str_replace( '-', '', mb_strtolower( $text ) ), -1, PREG_SPLIT_NO_EMPTY ); if ( ! is_array( $words ) ) { return ''; } return implode( ' ', array_map( static function ( string $word ): string { return strlen( $word ) > 3 && 's' === substr( $word, -1 ) ? substr( $word, 0, -1 ) : $word; }, $words ) ); } /** * @param array $part TitlePart. * @param string $raw Trimmed raw value. * @param string[] $missing_fields Field refs this value came from, when empty. * @return array */ private function resolveDeterministicValue( array $part, string $raw, array $missing_fields ): array { if ( '' === $raw ) { return $this->applyMissingPolicy( $part, $missing_fields ); } $clean = FormulaText::cleanOne( $this->validator, $raw ); return $this->result( $clean['ok'] ? 'included' : 'skipped_missing_data', '', $clean['text'], array() ); } /** * Apply a TitlePart's own `missing`/`fallback` (a * flat 'skip'|'fallback' enum plus a sibling `fallback` string - unlike * a BlueprintSection's nested `missing.policy`). * * @param array $part TitlePart. * @param string[] $missing_fields Field refs this value came from. * @return array */ private function applyMissingPolicy( array $part, array $missing_fields ): array { if ( 'fallback' === ( $part['missing'] ?? 'skip' ) ) { $fallback = trim( (string) ( $part['fallback'] ?? '' ) ); if ( '' !== $fallback ) { $clean = FormulaText::cleanOne( $this->validator, $fallback ); return $this->result( 'fallback', __( 'No data was available for this part; the fallback text was used.', 'ai-product-tools' ), $clean['text'], $missing_fields ); } } return $this->result( 'skipped_missing_data', __( 'No data was available for this part.', 'ai-product-tools' ), '', $missing_fields ); } /** * Run the one shared structured call for every pending `ai` part, with * at most one targeted retry for parts missing, empty, or still * containing a banned phrase, then resolve every pending part's final * value into `$resolved` (in place). * * @param StructuredCallerInterface $caller Structured AI caller. * @param array $ctx Execution context. * @param array $definition Normalized BlueprintDefinition. * @param array $product_context ProductContextBuilder::build()'s result. * @param array $pending_specs Pending TitlePart list, keyed by id. * @param array $caps aiPartCaps()'s limit per pending part. * @param string $title_shape titleShape()'s result. * @param string[] $banned Merged banned phrases. * @param array $extras promptExtras()'s result. * @param array &$resolved Resolved-by-id accumulator, updated in place. * @param array &$usage Usage accumulator, updated in place. * @param array &$findings Findings accumulator, updated in place. * @return void */ private function runAiRound( StructuredCallerInterface $caller, array $ctx, array $definition, array $product_context, array $pending_specs, array $caps, string $title_shape, array $banned, array $extras, array &$resolved, array &$usage, array &$findings ): void { $deadline = isset( $ctx['deadline'] ) ? (float) $ctx['deadline'] : ( microtime( true ) + 60.0 ); $budget = isset( $ctx['maxCalls'] ) ? max( 1, (int) $ctx['maxCalls'] ) : 3; $voice = $this->specBuilder->compileVoice( $ctx, array() ); $language = LanguageResolver::resolve( $ctx, $definition ); $ai_note = (string) ( $ctx['aiNote'] ?? '' ); $compiled = $this->compileRequest( $pending_specs, $caps, $title_shape, $product_context, $language, $voice, $banned, $ai_note, array(), $extras, StructureInstructions::enabled( $definition ) ); $first = $this->callRunner->call( $caller, $ctx, $compiled, min( 2, $budget ), $deadline ); $this->callRunner->mergeUsage( $usage, $first ); $calls_used = $first['calls']; $by_id = array(); if ( $first['ok'] ) { $match = $this->validator->matchUnits( $first['decoded']['parts'] ?? array(), array_keys( $pending_specs ) ); $findings = array_merge( $findings, $match['findings'] ); $by_id = $match['byId']; } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $first['error'] ?? array() ) ); } $retry_ids = $this->idsNeedingRetry( $pending_specs, $caps, $by_id, $banned ); $retry_result = null; if ( ! empty( $retry_ids ) && $this->callRunner->canRetry( $budget, $calls_used, $deadline ) ) { $retry_specs = array_intersect_key( $pending_specs, array_flip( $retry_ids ) ); $retry_caps = array_intersect_key( $caps, array_flip( $retry_ids ) ); $retry_notes = array_fill_keys( $retry_ids, __( 'missing, longer than its character limit, or still used a banned phrase', 'ai-product-tools' ) ); $retry_compiled = $this->compileRequest( $retry_specs, $retry_caps, $title_shape, $product_context, $language, $voice, $banned, $ai_note, $retry_notes, $extras, StructureInstructions::enabled( $definition ) ); $retry_result = $this->callRunner->call( $caller, $ctx, $retry_compiled, 1, $deadline, $first['provider'], $first['model'] ); $this->callRunner->mergeUsage( $usage, $retry_result ); if ( $retry_result['ok'] ) { $retry_match = $this->validator->matchUnits( $retry_result['decoded']['parts'] ?? array(), $retry_ids ); $findings = array_merge( $findings, $retry_match['findings'] ); foreach ( $retry_match['byId'] as $id => $raw ) { $by_id[ $id ] = $raw; } } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $retry_result['error'] ?? array() ) ); } } $failure_messages = ProviderFailureSupport::unitFailureMessages( $first, array_keys( $pending_specs ), $retry_result, $retry_ids ); foreach ( $pending_specs as $id => $part ) { $resolved[ $id ] = $this->resolveAiPart( $id, $part, $caps[ $id ], $by_id[ $id ] ?? null, $definition, $banned, $findings, $failure_messages[ $id ] ?? null ); } } /** * Whether an AI answer is over its part's limit (its own maxChars, or * its share of the title), a hard cap. * * @param int $limit aiPartCaps()'s limit for the part. * @param string $text Cleaned part text. * @return bool */ private function overPartLimit( int $limit, string $text ): bool { return $limit > 0 && mb_strlen( $text, 'UTF-8' ) > $limit; } /** * Cut an AI answer still over its part's limit at the last whole word, * the same way an alt text is held to its limit. * * @param int $limit aiPartCaps()'s limit for the part. * @param string $text Cleaned part text. * @return array{text:string,trimmed:bool} */ private function capToPartLimit( int $limit, string $text ): array { return $limit > 0 ? FormulaText::trimToWordBoundary( $text, $limit ) : array( 'text' => $text, 'trimmed' => false ); } /** * @param array $pending_specs Pending TitlePart list, keyed by id. * @param array $caps aiPartCaps()'s limit per pending part. * @param array $by_id Matched raw payloads, keyed by id. * @param string[] $banned Merged banned phrases. * @return string[] */ private function idsNeedingRetry( array $pending_specs, array $caps, array $by_id, array $banned ): array { $retry = array(); foreach ( $pending_specs as $id => $part ) { $raw = $by_id[ $id ] ?? null; if ( null === $raw || ! is_array( $raw ) || ! isset( $raw['text'] ) ) { $retry[] = $id; continue; } if ( $this->isNoDataAnswer( $raw ) ) { continue; } $clean = FormulaText::cleanOne( $this->validator, (string) $raw['text'] ); if ( ! $clean['ok'] || $this->overPartLimit( (int) $caps[ $id ], $clean['text'] ) || ! empty( $this->validator->findBannedPhrases( $clean['text'], $banned ) ) ) { $retry[] = $id; } } return $retry; } /** * Whether a part's raw answer is compileRequest()/ * compileVariantsRequest()'s own permitted "nothing specific applies" * outcome ("write an empty string for it instead of a generic claim ... * or an invented feature, benefit, or offer"), rather than a missing or * malformed answer - mirrors {@see FaqGenerator::isNoDataAnswer()} for * this generator's own single-value part shape. Retrying this id would * tell the model, on the very next call, that the correct empty answer * was a problem to fix, pushing it back toward inventing something. * * @param array $raw Matched raw payload, `{id, text}`. * @return bool */ private function isNoDataAnswer( array $raw ): bool { return is_string( $raw['text'] ) && '' === trim( $raw['text'] ); } /** * {@see self::isNoDataAnswer()} for a variants call's `texts` array * shape: every requested alternative came back the grounding * instruction's own permitted empty string, not a missing or malformed * answer. * * @param array|null $raw Matched raw payload, `{id, texts: string[]}`. * @return bool */ private function isNoDataAnswerVariants( ?array $raw ): bool { if ( null === $raw || ! is_array( $raw['texts'] ?? null ) || empty( $raw['texts'] ) ) { return false; } foreach ( $raw['texts'] as $text ) { if ( ! is_string( $text ) || '' !== trim( $text ) ) { return false; } } return true; } /** * Run the one shared structured call for every pending `ai` part asking * for `$variant_count` alternatives of each (build item 2: "asking the * engine for N alternatives of the AI parts in one call"), with at most * one targeted retry, then resolve each pending part's CANONICAL * (variant 0) value into `$resolved` via the exact same * {@see self::resolveAiPart()} every non-variant run uses, so eligibility, * checks and findings are driven by one real answer, never a fabricated * one. * * @param StructuredCallerInterface $caller Structured AI caller. * @param array $ctx Execution context. * @param array $definition Normalized BlueprintDefinition. * @param array $product_context ProductContextBuilder::build()'s result. * @param array $pending_specs Pending TitlePart list, keyed by id. * @param array $caps aiPartCaps()'s limit per pending part. * @param string $title_shape titleShape()'s result. * @param string[] $banned Merged banned phrases. * @param int $variant_count Alternatives requested per part (>= 2). * @param array $extras promptExtras()'s result. * @param array &$resolved Resolved-by-id accumulator, updated in place. * @param array &$usage Usage accumulator, updated in place. * @param array &$findings Findings accumulator, updated in place. * @return array Cleaned, non-empty alternative texts by part id (never containing more than one entry when the model returned exactly one). */ private function runAiRoundVariants( StructuredCallerInterface $caller, array $ctx, array $definition, array $product_context, array $pending_specs, array $caps, string $title_shape, array $banned, int $variant_count, array $extras, array &$resolved, array &$usage, array &$findings ): array { $deadline = isset( $ctx['deadline'] ) ? (float) $ctx['deadline'] : ( microtime( true ) + 60.0 ); $budget = isset( $ctx['maxCalls'] ) ? max( 1, (int) $ctx['maxCalls'] ) : 3; $voice = $this->specBuilder->compileVoice( $ctx, array() ); $language = LanguageResolver::resolve( $ctx, $definition ); $ai_note = (string) ( $ctx['aiNote'] ?? '' ); $compiled = $this->compileVariantsRequest( $pending_specs, $caps, $title_shape, $product_context, $language, $voice, $banned, $ai_note, array(), $variant_count, $extras, StructureInstructions::enabled( $definition ) ); $first = $this->callRunner->call( $caller, $ctx, $compiled, min( 2, $budget ), $deadline ); $this->callRunner->mergeUsage( $usage, $first ); $calls_used = $first['calls']; $texts_by_id = array(); $raw_by_id = array(); if ( $first['ok'] ) { $match = $this->validator->matchUnits( $first['decoded']['parts'] ?? array(), array_keys( $pending_specs ) ); $findings = array_merge( $findings, $match['findings'] ); $raw_by_id = $match['byId']; foreach ( $raw_by_id as $id => $raw ) { $texts_by_id[ $id ] = $this->extractTexts( $raw ); } } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $first['error'] ?? array() ) ); } $retry_ids = $this->idsNeedingRetryVariants( $pending_specs, $caps, $texts_by_id, $raw_by_id, $banned ); $retry_result = null; if ( ! empty( $retry_ids ) && $this->callRunner->canRetry( $budget, $calls_used, $deadline ) ) { $retry_specs = array_intersect_key( $pending_specs, array_flip( $retry_ids ) ); $retry_caps = array_intersect_key( $caps, array_flip( $retry_ids ) ); $retry_notes = array_fill_keys( $retry_ids, __( 'missing, longer than its character limit, or still used a banned phrase', 'ai-product-tools' ) ); $retry_compiled = $this->compileVariantsRequest( $retry_specs, $retry_caps, $title_shape, $product_context, $language, $voice, $banned, $ai_note, $retry_notes, $variant_count, $extras, StructureInstructions::enabled( $definition ) ); $retry_result = $this->callRunner->call( $caller, $ctx, $retry_compiled, 1, $deadline, $first['provider'], $first['model'] ); $this->callRunner->mergeUsage( $usage, $retry_result ); if ( $retry_result['ok'] ) { $retry_match = $this->validator->matchUnits( $retry_result['decoded']['parts'] ?? array(), $retry_ids ); $findings = array_merge( $findings, $retry_match['findings'] ); foreach ( $retry_match['byId'] as $id => $raw ) { $texts_by_id[ $id ] = $this->extractTexts( $raw ); $raw_by_id[ $id ] = $raw; } } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $retry_result['error'] ?? array() ) ); } } $failure_messages = ProviderFailureSupport::unitFailureMessages( $first, array_keys( $pending_specs ), $retry_result, $retry_ids ); foreach ( $pending_specs as $id => $part ) { $texts = $texts_by_id[ $id ] ?? array(); if ( empty( $texts ) && $this->isNoDataAnswerVariants( $raw_by_id[ $id ] ?? null ) ) { $this->noDataPartIds[ $id ] = true; } $raw0 = isset( $texts[0] ) ? array( 'text' => $texts[0] ) : null; $resolved[ $id ] = $this->resolveAiPart( $id, $part, $caps[ $id ], $raw0, $definition, $banned, $findings, $failure_messages[ $id ] ?? null ); } return $texts_by_id; } /** * @param array|null $raw Matched raw payload, expected shape `{id, texts: string[]}`. * @return string[] Non-empty string alternatives, in the model's order. */ private function extractTexts( ?array $raw ): array { if ( null === $raw || ! is_array( $raw['texts'] ?? null ) ) { return array(); } $texts = array(); foreach ( $raw['texts'] as $text ) { if ( is_string( $text ) && '' !== trim( $text ) ) { $texts[] = $text; } } return $texts; } /** * @param array $pending_specs Pending TitlePart list, keyed by id. * @param array $caps aiPartCaps()'s limit per pending part. * @param array $texts_by_id extractTexts() results by id (blank alternatives already filtered out). * @param array $raw_by_id Matched raw payloads (pre-filter), keyed by id. * @param string[] $banned Merged banned phrases. * @return string[] */ private function idsNeedingRetryVariants( array $pending_specs, array $caps, array $texts_by_id, array $raw_by_id, array $banned ): array { $retry = array(); foreach ( $pending_specs as $id => $part ) { $texts = $texts_by_id[ $id ] ?? array(); if ( empty( $texts ) ) { if ( $this->isNoDataAnswerVariants( $raw_by_id[ $id ] ?? null ) ) { continue; } $retry[] = $id; continue; } $clean = FormulaText::cleanOne( $this->validator, (string) $texts[0] ); if ( ! $clean['ok'] || $this->overPartLimit( (int) $caps[ $id ], $clean['text'] ) || ! empty( $this->validator->findBannedPhrases( $clean['text'], $banned ) ) ) { $retry[] = $id; } } return $retry; } /** * Same request shape as {@see self::compileRequest()}, except every part * answers with a `texts` array of `$variant_count` alternatives instead of * one `text` string. * * @param array[] $parts TitlePart list. * @param array[] $caps Per-part caps for this pending spec set, keyed by id. * @param string $title_shape titleShape()'s result. * @param array $product_context ProductContextBuilder::build()'s result. * @param string $language LanguageResolver::resolve()'s result. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param string[] $banned Merged banned phrases. * @param string $ai_note The subject's merchant AI note, already gated; '' when none or not allowed. * @param array $retry_notes Retry notes, when compiling a targeted retry. * @param int $variant_count Alternatives requested per part. * @param array $extras promptExtras()'s result. * @param string[] $instructions StructureInstructions::enabled()'s result. * @return array{system:string,user:string,schema:array,schemaName:string,validate:callable} */ private function compileVariantsRequest( array $parts, array $caps, string $title_shape, array $product_context, string $language, array $voice, array $banned, string $ai_note, array $retry_notes, int $variant_count, array $extras = array(), array $instructions = array() ): array { $part_catalog = SectionCatalog::titlePartKeys(); $ids = array_keys( $parts ); $lines = array(); /* translators: %d: number of alternative texts requested per part. */ $lines[] = sprintf( __( 'You write short product-title parts for an online store. For each part, provide %d different alternative plain-text values. Answer with ONE JSON object only: no prose before or after it, no Markdown code fence.', 'ai-product-tools' ), $variant_count ); $lines[] = __( 'Use facts only from the block below. Never invent a specification, certification, compliance claim, award, warranty term, or a claim about how the product is delivered, shipped, redeemed, installed or used, or its available amounts or options.', 'ai-product-tools' ); $lines[] = __( 'Every part must name something specific to this product\'s own data. If the data gives nothing specific enough for a part, write an empty string for it instead of a generic claim any similar product could make, or an invented feature, benefit, or offer.', 'ai-product-tools' ); $lines[] = __( 'Write plain text only: no HTML, no Markdown, no trailing punctuation, no quotes around the value. Make the alternatives noticeably different from each other in wording while staying accurate to the product data.', 'ai-product-tools' ); foreach ( $extras['system'] ?? array() as $extra_line ) { $lines[] = $extra_line; } $ai_note_system_line = AiNoteBlock::systemLine( $ai_note ); if ( '' !== $ai_note_system_line ) { $lines[] = $ai_note_system_line; } $language_line = LanguageResolver::instructionLine( $language ); if ( '' !== $language_line ) { $lines[] = $language_line; } if ( '' !== $voice['block'] ) { $lines[] = $voice['block']; } if ( ! empty( $banned ) ) { /* translators: %s: comma-separated banned phrases. */ $lines[] = sprintf( __( 'Never use these words or phrases: %s.', 'ai-product-tools' ), implode( ', ', $banned ) ); } foreach ( StructureInstructions::systemLines( $instructions ) as $instruction_line ) { $lines[] = $instruction_line; } $system = implode( "\n\n", $lines ); $user_parts = array(); $user_parts[] = '' . "\n" . FormulaText::escapeBlock( (string) $product_context['text'] ) . "\n" . ''; foreach ( $extras['user'] ?? array() as $extra_block ) { $user_parts[] = $extra_block; } $ai_note_user_block = AiNoteBlock::userBlock( $ai_note, array( FormulaText::class, 'escapeBlock' ) ); if ( '' !== $ai_note_user_block ) { $user_parts[] = $ai_note_user_block; } $units = array(); foreach ( $parts as $id => $part ) { $label = (string) ( $part_catalog[ $part['key'] ]['label'] ?? $part['key'] ); $units[ $id ] = array( 'id' => $id, 'label' => $label, 'maxChars' => $caps[ $id ], 'variantCount' => $variant_count, ); } $user_parts[] = '' . "\n" . wp_json_encode( array_values( $units ) ) . "\n" . ''; $user_parts[] = $this->titleShapeLine( $title_shape ); /* translators: %d: number of alternative texts requested per part. */ $user_parts[] = sprintf( __( 'For each part above, write %d short plain-text alternatives of AT MOST its maxChars characters that fit its label and the product data, in a "texts" array, or an empty string when nothing specific applies.', 'ai-product-tools' ), $variant_count ); if ( ! empty( $retry_notes ) ) { $note_lines = array( __( 'Your previous answer had problems with these parts. Return the FULL corrected JSON object again, fixing only what is noted below:', 'ai-product-tools' ) ); foreach ( $retry_notes as $id => $note ) { $note_lines[] = '- ' . $id . ': ' . $note; } $user_parts[] = implode( "\n", $note_lines ); } return array( 'system' => $system, 'user' => implode( "\n\n", $user_parts ), 'schema' => $this->buildVariantsSchema( $ids ), 'schemaName' => 'aipt_blueprint_title_part_variants', 'validate' => function ( $decoded ) { return ( is_array( $decoded ) && isset( $decoded['parts'] ) && is_array( $decoded['parts'] ) ) ? array( 'ok' => true, 'errors' => array() ) : array( 'ok' => false, 'errors' => array( __( 'The answer must have a "parts" array.', 'ai-product-tools' ) ) ); }, ); } /** * @param string[] $ids Expected part ids (enum). * @return array JSON Schema. */ private function buildVariantsSchema( array $ids ): array { return array( 'type' => 'object', 'properties' => array( 'parts' => array( 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'id' => empty( $ids ) ? array( 'type' => 'string' ) : array( 'type' => 'string', 'enum' => $ids ), 'texts' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ), ), 'required' => array( 'id', 'texts' ), 'additionalProperties' => false, ), ), ), 'required' => array( 'parts' ), 'additionalProperties' => false, ); } /** * Build title alternatives 1..variantCount-1 (variant 0 is always the * canonical {@see self::assemble()} output, reused verbatim rather than * recomputed, so it is byte-identical to the non-variant result). * Deterministic (fixed/data) parts are identical across every variant; * only each `ai` part's text differs, reusing the model's own * alternatives cyclically when fewer than `$variant_count` came back for * a part (never fabricating a new one). A variant still over the hard * character limit after the configured overflow drop is left out rather * than presented as fitting. The "Avoid ALL CAPS" guard is applied to * each `ai` part's alternative exactly as {@see self::resolveAiPart()} * applies it to variant 0, so a merchant can never pick a still-shouting * alternative from the picker (the SKU-exposure guard is checked by the * caller across the finished variant texts; see * {@see self::guardNonCanonicalVariants()}). * * @param array[] $parts TitlePart list. * @param array $resolved Final resolved-by-id (variant 0's values). * @param array $texts_by_id runAiRoundVariants()'s alternatives by part id. * @param array $caps aiPartCaps()'s limit per AI part that was asked for. * @param string $separator Separator enum. * @param int $max_chars Hard character limit. * @param string|null $overflow_drop_id Part id to drop first on overflow. * @param bool $dedupe_on Whether dedupe is enabled. * @param int $variant_count Total variants requested (>= 2). * @param bool $avoid_all_caps Whether the "Avoid ALL CAPS" guard is on. * @param string[] $banned Merged banned phrases (same list the canonical variant is checked against). * @return array{texts:string[],allCapsFixed:bool} Variants 1..variantCount-1 that fit the hard limit, in order, plus whether any of them needed ALL-CAPS correction. */ private function buildExtraVariants( array $parts, array $resolved, array $texts_by_id, array $caps, string $separator, int $max_chars, ?string $overflow_drop_id, bool $dedupe_on, int $variant_count, bool $avoid_all_caps, array $banned ): array { $extra = array(); $all_caps_fixed = false; for ( $variant_index = 1; $variant_index < $variant_count; $variant_index++ ) { $included = array(); $overlong = false; foreach ( $parts as $part ) { $id = (string) $part['id']; $entry = $resolved[ $id ]; if ( ! in_array( $entry['status'], array( 'included', 'fallback' ), true ) ) { continue; } $value = $entry['value']; if ( 'ai' === $part['mode'] ) { $texts = $texts_by_id[ $id ] ?? array(); if ( ! empty( $texts ) ) { $clean = FormulaText::cleanOne( $this->validator, (string) $texts[ $variant_index % count( $texts ) ] ); if ( $clean['ok'] ) { $shared_cap = null === ( $part['maxChars'] ?? null ); $overlong = $overlong || ( $shared_cap && $this->overPartLimit( (int) ( $caps[ $id ] ?? 0 ), $clean['text'] ) ); $value = $this->capToPartLimit( (int) ( $caps[ $id ] ?? 0 ), $clean['text'] )['text']; if ( $avoid_all_caps ) { $capped = $this->titleCaseShoutyWords( $value ); if ( $capped['changed'] ) { $value = $capped['text']; $all_caps_fixed = true; } } } } } $included[] = array( 'id' => $id, 'key' => $part['key'], 'mode' => (string) $part['mode'], 'value' => $value ); } if ( $overlong ) { continue; } $original_values = array_column( $included, 'value', 'id' ); if ( $dedupe_on ) { $included = $this->dedupeIncludedParts( $included, $original_values )['included']; } $candidate = $this->assembleTitle( $included, $separator ); if ( $candidate['len'] > $max_chars && null !== $overflow_drop_id ) { $without_overflow = array_values( array_filter( $included, static function ( $entry2 ) use ( $overflow_drop_id ) { return $entry2['id'] !== $overflow_drop_id; } ) ); if ( count( $without_overflow ) !== count( $included ) ) { if ( $dedupe_on ) { $without_overflow = $this->dedupeIncludedParts( $without_overflow, $original_values )['included']; } $candidate = $this->assembleTitle( $without_overflow, $separator ); } } if ( '' === $candidate['text'] || $candidate['len'] > $max_chars || ! empty( $this->validator->findBannedPhrases( $candidate['text'], $banned ) ) ) { continue; } $extra[] = $candidate['text']; } return array( 'texts' => $extra, 'allCapsFixed' => $all_caps_fixed ); } /** * Apply the "Avoid ALL CAPS" and "Do not show the SKU" guards to every * non-canonical variant text a merchant can select from the "Generated * title variants" picker (variant 0 already carries both guards via * {@see self::resolveAiPart()} and {@see self::assemble()}). ALL-CAPS * correction already happened in {@see self::buildExtraVariants()} (it * changes the text itself); this only raises the one info finding for it * when variant 0 did not already raise one. The SKU check runs here, * once, over every extra variant's final text, because it cannot be * "corrected" - only flagged for review. * * @param array $findings Findings accumulated so far (variant 0's). * @param bool $all_caps_fixed Whether any extra variant needed ALL-CAPS correction. * @param bool $avoid_sku Whether the "Do not show the SKU" guard is on. * @param string $sku The product's real SKU, trimmed ('' when it has none). * @param string[] $extra_variants Every extra (non-canonical) variant's final text. * @return array Updated findings. */ private function guardNonCanonicalVariants( array $findings, bool $all_caps_fixed, bool $avoid_sku, string $sku, array $extra_variants ): array { $existing_codes = array_column( $findings, 'code' ); if ( $all_caps_fixed && ! in_array( 'all_caps_title_cased', $existing_codes, true ) ) { $findings[] = $this->validator->finding( 'all_caps_title_cased', 'info', __( 'A shouty, ALL CAPS part was changed to title case.', 'ai-product-tools' ) ); } if ( $avoid_sku && '' !== $sku && ! in_array( 'sku_exposed', $existing_codes, true ) ) { foreach ( $extra_variants as $variant_text ) { if ( ! empty( $this->validator->findBannedPhrases( $variant_text, array( $sku ) ) ) ) { $findings[] = $this->validator->finding( 'sku_exposed', 'review', __( 'The title shows the product\'s SKU.', 'ai-product-tools' ) ); break; } } } return $findings; } /** * @param string $id Part id. * @param array $part TitlePart. * @param int $limit aiPartCaps()'s limit for the part. * @param array|null $raw Matched raw payload (post-retry), or null. * @param array $definition Normalized BlueprintDefinition. * @param string[] $banned Merged banned phrases. * @param array &$findings Findings accumulator, updated in place. * @param string|null $provider_message The classified provider message responsible for this part still being missing, when `$raw` is null because its own call failed; null otherwise (see ProviderFailureSupport::unitFailureMessages()). * @return array */ private function resolveAiPart( string $id, array $part, int $limit, ?array $raw, array $definition, array $banned, array &$findings, ?string $provider_message = null ): array { $clean = null !== $raw && isset( $raw['text'] ) ? FormulaText::cleanOne( $this->validator, (string) $raw['text'] ) : array( 'ok' => false, 'text' => '' ); if ( $clean['ok'] ) { $text = $clean['text']; if ( (bool) ( $definition['structure']['avoidAllCaps'] ?? true ) ) { $capped = $this->titleCaseShoutyWords( $text ); if ( $capped['changed'] ) { $findings[] = $this->validator->finding( 'all_caps_title_cased', 'info', __( 'A shouty, ALL CAPS part was changed to title case.', 'ai-product-tools' ), $id ); $text = $capped['text']; } } $within_limit = $this->capToPartLimit( $limit, $text ); if ( $within_limit['trimmed'] ) { if ( null === ( $part['maxChars'] ?? null ) && mb_strlen( $within_limit['text'], 'UTF-8' ) < self::MIN_AI_PART_CHARS ) { return $this->result( 'skipped_missing_data', __( 'This part did not fit in the title, so it was left out.', 'ai-product-tools' ), '', array() ); } /* translators: %d: the title part's character limit. */ $findings[] = $this->validator->finding( 'part_shortened', 'warning', sprintf( __( 'This title part was cut to its %d-character limit.', 'ai-product-tools' ), $limit ), $id ); $text = $within_limit['text']; } $still_banned = $this->validator->findBannedPhrases( $text, $banned ); if ( ! empty( $still_banned ) ) { /* translators: %s: comma-separated banned phrases still present after the retry. */ $findings[] = $this->validator->finding( 'banned_phrase', 'review', sprintf( __( 'This title part still uses a banned phrase: %s.', 'ai-product-tools' ), implode( ', ', $still_banned ) ), $id ); return $this->result( 'needs_review', '', $text, array() ); } return $this->result( 'included', '', $text, array() ); } if ( null !== $raw && isset( $raw['text'] ) && $this->isNoDataAnswer( $raw ) ) { $this->noDataPartIds[ $id ] = true; } $message = ( null === $raw && null !== $provider_message ) ? $provider_message : __( 'The AI did not return this title part.', 'ai-product-tools' ); $required_failure = (string) ( $definition['rules']['requiredFailure'] ?? 'review' ); if ( 'partial' === $required_failure ) { $applied = $this->applyMissingPolicy( $part, array() ); $findings[] = $this->validator->finding( 'unit_failed_dropped', 'warning', $message, $id ); return $applied; } $findings[] = $this->validator->finding( 'unit_failed', 'review', $message, $id ); return $this->result( 'needs_review', $message, '', array() ); } /** * "Avoid ALL CAPS": title-case every run of Unicode letters that is * BOTH longer than {@see self::ACRONYM_MAX_LETTERS} AND entirely * uppercase, leaving everything else untouched - short acronyms/brand * codes ("USB", "LED"), digits, punctuation, spacing, and any word that * is not itself fully uppercase (already-normal casing). Deterministic * and idempotent. Only ever called for an `ai`-mode part's own cleaned * text; merchant-authored fixed text and store data are never passed * here. * * @param string $text Cleaned AI-written part text. * @return array{text:string,changed:bool} */ private function titleCaseShoutyWords( string $text ): array { $pieces = preg_split( '/(\p{L}+)/u', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); if ( ! is_array( $pieces ) ) { return array( 'text' => $text, 'changed' => false ); } $changed = false; $result = ''; foreach ( $pieces as $index => $piece ) { $is_word = 1 === $index % 2 && '' !== $piece; if ( $is_word && mb_strlen( $piece, 'UTF-8' ) > self::ACRONYM_MAX_LETTERS ) { $is_all_upper = $piece === mb_strtoupper( $piece, 'UTF-8' ) && $piece !== mb_strtolower( $piece, 'UTF-8' ); if ( $is_all_upper ) { $piece = mb_strtoupper( mb_substr( $piece, 0, 1, 'UTF-8' ), 'UTF-8' ) . mb_strtolower( mb_substr( $piece, 1, null, 'UTF-8' ), 'UTF-8' ); $changed = true; } } $result .= $piece; } return array( 'text' => $result, 'changed' => $changed ); } /** * Extra system lines and user blocks for this run's AI rounds, from the * `aipt_content_structure_title_prompt_extras` filter (the Business * build adds the current title to improve and the structure's * keywords there). Each system line joins the instructions after the * fixed ones, each user block follows ; without a * registrant the request is the plain product-data request. * * @param array $ctx Execution context. * @param array $definition Clamped definition. * @return array{system:string[],user:string[]} */ private function promptExtras( array $ctx, array $definition ): array { $extras = apply_filters( self::PROMPT_EXTRAS_FILTER, array( 'system' => array(), 'user' => array() ), $ctx, $definition ); $extras = is_array( $extras ) ? $extras : array(); $strings = static function ( $list ): array { return is_array( $list ) ? array_values( array_filter( $list, static function ( $item ): bool { return is_string( $item ) && '' !== $item; } ) ) : array(); }; return array( 'system' => $strings( $extras['system'] ?? array() ), 'user' => $strings( $extras['user'] ?? array() ), ); } /** * @param array[] $parts TitlePart list. * @param array[] $caps Per-part caps for this pending spec set, keyed by id. * @param string $title_shape titleShape()'s result. * @param array $product_context ProductContextBuilder::build()'s result. * @param string $language LanguageResolver::resolve()'s result. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param string[] $banned Merged banned phrases. * @param string $ai_note The subject's merchant AI note, already gated; '' when none or not allowed. * @param array $retry_notes Retry notes, when compiling a targeted retry. * @param array $extras promptExtras()'s result. * @param string[] $instructions StructureInstructions::enabled()'s result. * @return array{system:string,user:string,schema:array,schemaName:string,validate:callable} */ private function compileRequest( array $parts, array $caps, string $title_shape, array $product_context, string $language, array $voice, array $banned, string $ai_note, array $retry_notes, array $extras = array(), array $instructions = array() ): array { $part_catalog = SectionCatalog::titlePartKeys(); $ids = array_keys( $parts ); $lines = array(); $lines[] = 'You write short product-title parts for an online store. Answer with ONE JSON object only: no prose before or after it, no Markdown code fence.'; $lines[] = 'Use facts only from the block below. Never invent a specification, certification, compliance claim, award, warranty term, or a claim about how the product is delivered, shipped, redeemed, installed or used, or its available amounts or options.'; $lines[] = 'Every part must name something specific to this product\'s own data. If the data gives nothing specific enough for a part, write an empty string for it instead of a generic claim any similar product could make, or an invented feature, benefit, or offer.'; $lines[] = 'Write plain text only: no HTML, no Markdown, no trailing punctuation, no quotes around the value.'; foreach ( $extras['system'] ?? array() as $extra_line ) { $lines[] = $extra_line; } $ai_note_system_line = AiNoteBlock::systemLine( $ai_note ); if ( '' !== $ai_note_system_line ) { $lines[] = $ai_note_system_line; } $language_line = LanguageResolver::instructionLine( $language ); if ( '' !== $language_line ) { $lines[] = $language_line; } if ( '' !== $voice['block'] ) { $lines[] = $voice['block']; } if ( ! empty( $banned ) ) { $lines[] = 'Never use these words or phrases: ' . implode( ', ', $banned ) . '.'; } foreach ( StructureInstructions::systemLines( $instructions ) as $instruction_line ) { $lines[] = $instruction_line; } $system = implode( "\n\n", $lines ); $user_parts = array(); $user_parts[] = '' . "\n" . FormulaText::escapeBlock( (string) $product_context['text'] ) . "\n" . ''; foreach ( $extras['user'] ?? array() as $extra_block ) { $user_parts[] = $extra_block; } $ai_note_user_block = AiNoteBlock::userBlock( $ai_note, array( FormulaText::class, 'escapeBlock' ) ); if ( '' !== $ai_note_user_block ) { $user_parts[] = $ai_note_user_block; } $units = array(); foreach ( $parts as $id => $part ) { $label = (string) ( $part_catalog[ $part['key'] ]['label'] ?? $part['key'] ); $units[ $id ] = array( 'id' => $id, 'label' => $label, 'maxChars' => $caps[ $id ], ); } $user_parts[] = '' . "\n" . wp_json_encode( array_values( $units ) ) . "\n" . ''; $user_parts[] = $this->titleShapeLine( $title_shape ); $user_parts[] = 'For each part above, write one short plain-text value of AT MOST its maxChars characters that fits its label and the product data, or an empty string when nothing specific applies.'; if ( ! empty( $retry_notes ) ) { $note_lines = array( 'Your previous answer had problems with these parts. Return the FULL corrected JSON object again, fixing only what is noted below:' ); foreach ( $retry_notes as $id => $note ) { $note_lines[] = '- ' . $id . ': ' . $note; } $user_parts[] = implode( "\n", $note_lines ); } return array( 'system' => $system, 'user' => implode( "\n\n", $user_parts ), 'schema' => $this->buildSchema( $ids ), 'schemaName' => 'aipt_blueprint_title_parts', 'validate' => function ( $decoded ) { return ( is_array( $decoded ) && isset( $decoded['parts'] ) && is_array( $decoded['parts'] ) ) ? array( 'ok' => true, 'errors' => array() ) : array( 'ok' => false, 'errors' => array( __( 'The answer must have a "parts" array.', 'ai-product-tools' ) ) ); }, ); } /** * @param string[] $ids Expected part ids (enum). * @return array JSON Schema. */ private function buildSchema( array $ids ): array { return array( 'type' => 'object', 'properties' => array( 'parts' => array( 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'id' => empty( $ids ) ? array( 'type' => 'string' ) : array( 'type' => 'string', 'enum' => $ids ), 'text' => array( 'type' => 'string' ), ), 'required' => array( 'id', 'text' ), 'additionalProperties' => false, ), ), ), 'required' => array( 'parts' ), 'additionalProperties' => false, ); } /** * The characters left for the pending AI parts together: the title's * own limit, less the parts already resolved, less the separator each * AI part adds when it is inserted among them. Zero or less when the * resolved parts already fill the title. * * @param array $definition Normalized BlueprintDefinition. * @param array $resolved Resolved-by-id so far. * @param string[] $pending_ids AI parts still to write. * @return int */ private function aiPartBudget( array $definition, array $resolved, array $pending_ids ): int { $separator = (string) ( $definition['structure']['separator'] ?? 'dash' ); $deterministic = $this->deterministicAssembledLength( $definition['structure']['parts'], $resolved, $separator, $pending_ids ); $glue = TextMetrics::charCount( self::SEPARATORS[ $separator ] ?? self::SEPARATORS['dash'] ); $pending_count = count( $pending_ids ); $added_glue = ( $deterministic['len'] > 0 ? $pending_count : max( 0, $pending_count - 1 ) ) * $glue; return (int) ( $definition['structure']['maxChars'] ?? 60 ) - $deterministic['len'] - $added_glue; } /** * Each pending AI part's character limit: its own maxChars, or an even * share of what aiPartBudget() leaves. When that share is too small and * the title names an overflow part that is already resolved, the share * is what is left once that part is dropped, as assemble() would drop * it. A shared part whose share still falls under MIN_AI_PART_CHARS gets * null: there is no room for it, so it is left out instead of being * asked for in a stray word (the last such part first, so the others * keep a usable share). * * @param array $definition Normalized BlueprintDefinition. * @param array $resolved Resolved-by-id so far. * @param array $pending_specs Pending TitlePart list, keyed by id. * @param string|null $overflow_drop_id Part id assemble() drops first on overflow. * @return array Limit per pending part id, in order. */ private function aiPartCaps( array $definition, array $resolved, array $pending_specs, ?string $overflow_drop_id = null ): array { $caps = array(); $shared = array(); $reserved = 0; foreach ( $pending_specs as $id => $part ) { $caps[ $id ] = null; if ( null !== ( $part['maxChars'] ?? null ) ) { $caps[ $id ] = (int) $part['maxChars']; $reserved += (int) $part['maxChars']; } else { $shared[] = (string) $id; } } $without_overflow = $resolved; if ( null !== $overflow_drop_id && ! isset( $pending_specs[ $overflow_drop_id ] ) && isset( $resolved[ $overflow_drop_id ] ) ) { $without_overflow[ $overflow_drop_id ]['status'] = 'skipped_missing_data'; } $explicit = array_values( array_diff( array_map( 'strval', array_keys( $pending_specs ) ), $shared ) ); while ( ! empty( $shared ) ) { $ids = array_merge( $explicit, $shared ); $share = intdiv( max( 0, $this->aiPartBudget( $definition, $resolved, $ids ) - $reserved ), count( $shared ) ); if ( $share < self::MIN_AI_PART_CHARS ) { $share = intdiv( max( 0, $this->aiPartBudget( $definition, $without_overflow, $ids ) - $reserved ), count( $shared ) ); } if ( $share >= self::MIN_AI_PART_CHARS ) { foreach ( $shared as $id ) { $caps[ $id ] = $share; } break; } array_pop( $shared ); } return $caps; } /** * The finished title with every pending AI part shown as "[part id]", * so the model writes parts that fit around the rest instead of * repeating it. * * @param array[] $parts TitlePart list. * @param array $resolved Resolved-by-id so far. * @param array $pending_specs Pending TitlePart list, keyed by id. * @param string $separator Separator enum. * @return string */ private function titleShape( array $parts, array $resolved, array $pending_specs, string $separator ): string { $included = array(); foreach ( $parts as $part ) { $id = (string) $part['id']; if ( isset( $pending_specs[ $id ] ) ) { $included[] = array( 'key' => $part['key'], 'value' => '[' . $id . ']' ); continue; } $entry = $resolved[ $id ] ?? null; if ( null !== $entry && in_array( $entry['status'], array( 'included', 'fallback' ), true ) ) { $included[] = array( 'key' => $part['key'], 'value' => $entry['value'] ); } } return $this->assembleTitle( $included, $separator )['text']; } /** * @param string $title_shape titleShape()'s result. * @return string Prompt line placing the parts in the finished title. */ private function titleShapeLine( string $title_shape ): string { return 'The finished title reads: "' . $title_shape . '", with each [part id] replaced by your text. Write each part so it adds information the rest of the title does not give: never repeat a word that is already in it.'; } /** * Assemble the final title string from ONLY the parts already resolved * in `$resolved`, skipping every part still pending an AI call - used * only to size the remaining character budget for pending `ai` parts * BEFORE the call, so this is an approximation when an `ai` part sits * between two resolved parts. * * @param array[] $parts TitlePart list. * @param array $resolved Resolved-so-far by id. * @param string $separator Separator enum. * @param string[] $pending_ids AI parts still to write. * @return array{text:string,len:int} */ private function deterministicAssembledLength( array $parts, array $resolved, string $separator, array $pending_ids ): array { $included = array(); foreach ( $parts as $part ) { $id = (string) $part['id']; if ( in_array( $id, $pending_ids, true ) ) { continue; } $entry = $resolved[ $id ] ?? null; if ( null !== $entry && in_array( $entry['status'], array( 'included', 'fallback' ), true ) ) { $included[] = array( 'key' => $part['key'], 'value' => $entry['value'] ); } } return $this->assembleTitle( $included, $separator ); } /** * Join an ordered list of included parts with the configured separator, * never inserting a separator between an immediately-following * `brand` -> `product_type` pair. * * @param array $included Included parts, in order. * @param string $separator Separator enum. * @return array{text:string,len:int} */ private function assembleTitle( array $included, string $separator ): array { $sep = self::SEPARATORS[ $separator ] ?? self::SEPARATORS['dash']; $text = ''; $previous_key = null; foreach ( $included as $entry ) { if ( '' === trim( (string) $entry['value'] ) ) { continue; } if ( null === $previous_key ) { $text = $entry['value']; } else { $glue = ( 'brand' === $previous_key && 'product_type' === $entry['key'] ) ? ' ' : $sep; $text .= $glue . $entry['value']; } $previous_key = $entry['key']; } return array( 'text' => $text, 'len' => TextMetrics::charCount( $text ) ); } /** * Run {@see FormulaText::dedupeWordsAcross()} over $included, sourcing * every part's text from $original_values rather than $included's own * (possibly already-deduped) value. Both {@see self::assemble()} and * {@see self::buildExtraVariants()} call this twice: once before their * overflow drop, once after (over the surviving parts only) - the * second call always re-sources from the SAME untouched originals, so * dropping the part that "owned" a shared word restores that word to * the part that kept it, instead of leaving it removed. * * The product name is the title's anchor and is deduped first, wherever * it sits: it keeps every word, and a repeated word comes out of the * other part instead of leaving the name as "Hoodie with" or empty. * An `ai` part that loses more than half of its words only repeated the * title, and what is left reads as a fragment ("Chunky rib knit" -> * "rib"), so it is dropped. * * @param array $included Included parts, in order. * @param array $original_values Every part's pre-dedupe value, by id. * @return array{included:array,changed:bool} $included with deduped values, and whether any of them differs from $original_values. */ private function dedupeIncludedParts( array $included, array $original_values ): array { $order = array(); foreach ( $included as $index => $entry ) { if ( 'product_name' === $entry['key'] ) { $order[] = $index; } } foreach ( $included as $index => $entry ) { if ( 'product_name' !== $entry['key'] ) { $order[] = $index; } } $source = array(); foreach ( $order as $index ) { $source[] = $original_values[ $included[ $index ]['id'] ] ?? $included[ $index ]['value']; } $deduped = count( $source ) > 1 ? FormulaText::dedupeWordsAcross( $source ) : $source; $changed = $deduped !== $source; foreach ( $order as $position => $index ) { $value = $deduped[ $position ]; if ( 'ai' === ( $included[ $index ]['mode'] ?? '' ) && $value !== $source[ $position ] ) { if ( TextMetrics::wordCount( $value ) * 2 < TextMetrics::wordCount( $source[ $position ] ) ) { $value = ''; } } $included[ $index ]['value'] = $value; } return array( 'included' => $included, 'changed' => $changed ); } /** * Resolve, dedupe, join, enforce the hard limit, build checks/findings * and assemble the generator-specific GenerationResult slice. * * @param array[] $parts TitlePart list. * @param array $resolved Final resolved-by-id. * @param string $separator Separator enum. * @param int $max_chars Hard character limit. * @param bool $dedupe_on Whether dedupe is enabled. * @param string|null $overflow_drop_id Part id to drop first on overflow. * @param array $product_context For the unsupported-number heuristic. * @param string[] $banned Merged banned phrases. * @param array $usage Usage accumulator. * @param array $findings Findings accumulated during generation. * @param string|null $only_unit_id Set only when regenerating one part. * @param bool $avoid_sku Whether the "Do not show the SKU" guard is on. * @param string $sku The product's real SKU, trimmed ('' when it has none). * @param array|null $previous regenerateUnit()'s previous slice, when regenerating. * @return array{units:array,outputs:array,checks:array,conflicts:array,findings:array,sourcesUsed:array,eligibility:array,usage:array,providerError:array|null} */ private function assemble( array $parts, array $resolved, string $separator, int $max_chars, bool $dedupe_on, ?string $overflow_drop_id, array $product_context, array $banned, array $usage, array $findings, ?string $only_unit_id, bool $avoid_sku, string $sku, ?array $previous = null ): array { $part_catalog = SectionCatalog::titlePartKeys(); $included_ids = array(); $included = array(); foreach ( $parts as $part ) { $id = (string) $part['id']; $entry = $resolved[ $id ]; if ( in_array( $entry['status'], array( 'included', 'fallback' ), true ) ) { $included_ids[] = $id; $included[] = array( 'id' => $id, 'key' => $part['key'], 'mode' => (string) $part['mode'], 'value' => $entry['value'] ); } } $original_values = array_column( $included, 'value', 'id' ); $dedupe_changed = false; if ( $dedupe_on ) { $dedupe_result = $this->dedupeIncludedParts( $included, $original_values ); $included = $dedupe_result['included']; $dedupe_changed = $dedupe_result['changed']; foreach ( $included as $entry ) { $resolved[ $entry['id'] ]['value'] = $entry['value']; } } $assembled = $this->assembleTitle( $included, $separator ); $dropped_id = null; if ( $assembled['len'] > $max_chars && null !== $overflow_drop_id && in_array( $overflow_drop_id, $included_ids, true ) ) { $included = array_values( array_filter( $included, static function ( $entry ) use ( $overflow_drop_id ) { return $entry['id'] !== $overflow_drop_id; } ) ); if ( $dedupe_on ) { $redo_result = $this->dedupeIncludedParts( $included, $original_values ); $included = $redo_result['included']; $dedupe_changed = $redo_result['changed']; foreach ( $included as $entry ) { $resolved[ $entry['id'] ]['value'] = $entry['value']; } } $assembled = $this->assembleTitle( $included, $separator ); $dropped_id = $overflow_drop_id; } $still_over = $assembled['len'] > $max_chars; if ( $still_over ) { $findings[] = $this->validator->finding( 'hard_limit_exceeded', 'blocking', null !== $dropped_id ? __( 'The title is still over its character limit after dropping the configured overflow part.', 'ai-product-tools' ) : __( 'The title is over its character limit.', 'ai-product-tools' ) ); } $units = array(); foreach ( $parts as $part ) { $id = (string) $part['id']; $entry = $resolved[ $id ]; $value = ( null !== $dropped_id && $id === $dropped_id ) ? '' : $entry['value']; $label = (string) ( $part_catalog[ $part['key'] ]['label'] ?? $part['key'] ); if ( 'included' === $entry['status'] && '' === (string) $value && '' !== (string) ( $original_values[ $id ] ?? '' ) && ( null === $dropped_id || $id !== $dropped_id ) ) { $entry['status'] = 'skipped_missing_data'; $entry['reason'] = __( 'Left out: every word of it is already in the title.', 'ai-product-tools' ); } $units[] = array( 'id' => $id, 'kind' => 'part', 'type' => (string) $part['key'], 'name' => $label, 'mode' => (string) $part['mode'], 'format' => 'paragraph', 'status' => ( null !== $dropped_id && $id === $dropped_id ) ? 'skipped_missing_data' : $entry['status'], 'reason' => ( null !== $dropped_id && $id === $dropped_id ) ? __( 'Removed to fit the character limit.', 'ai-product-tools' ) : $entry['reason'], 'heading' => '', 'html' => '', 'text' => $value, 'items' => array(), 'rows' => array(), 'wordCount' => TextMetrics::wordCount( $value ), 'charCount' => TextMetrics::charCount( $value ), 'itemCount' => 0, 'missingFields' => $entry['missingFields'], 'usedFallback' => 'fallback' === $entry['status'], 'regenerated' => null !== $only_unit_id && $id === $only_unit_id, 'sourceRefs' => 'data' === $part['mode'] && '' !== (string) $part['field'] ? array( (string) $part['field'] ) : array(), 'findings' => array(), ); } $checks = array(); $checks[] = FormulaChecks::charLength( 'length', __( 'Length', 'ai-product-tools' ), $assembled['len'], $max_chars, ! $still_over ); foreach ( $units as $unit ) { if ( ! in_array( $unit['status'], array( 'included', 'fallback' ), true ) ) { $checks[] = ( new Checks() )->statusNote( $unit['id'], $unit['name'], $unit['status'], $unit['reason'] ); } } $checks[] = FormulaChecks::row( 'repeated_words', __( 'Repeated words', 'ai-product-tools' ), $dedupe_on ? 'pass' : 'skip', $dedupe_on ? ( $dedupe_changed ? __( 'Repeated words were removed.', 'ai-product-tools' ) : __( 'None left after duplicate removal.', 'ai-product-tools' ) ) : __( 'Not checked - duplicate removal is off.', 'ai-product-tools' ) ); $checker = new Checks(); $checks[] = $checker->bannedPhrases( $this->validator->findBannedPhrases( $assembled['text'], $banned ) ); $unsupported_numbers = $this->validator->findUnsupportedNumbers( $assembled['text'], (array) ( $product_context['numericTokens'] ?? array() ) ); if ( ! empty( $unsupported_numbers ) ) { /* translators: %s: comma-separated numeric tokens not found in the supplied context. */ $findings[] = $this->validator->finding( 'unsupported_number', 'warning', sprintf( __( 'The title mentions a number not found in the provided context: %s.', 'ai-product-tools' ), implode( ', ', $unsupported_numbers ) ) ); } if ( $avoid_sku && '' !== $sku && ! empty( $this->validator->findBannedPhrases( $assembled['text'], array( $sku ) ) ) ) { $findings[] = $this->validator->finding( 'sku_exposed', 'review', __( 'The title shows the product\'s SKU.', 'ai-product-tools' ) ); } $provider_error = ProviderFailureSupport::providerErrorFromFindings( $findings ); $provider_error = ProviderFailureSupport::carryForwardProviderError( $units, $provider_error, $previous ); $findings = ProviderFailureSupport::applyAiOutcomeRules( $units, $findings, $provider_error ); $findings = $this->explainNoDataOnFreeSources( $units, $findings, $provider_error ); $eligibility = $checker->eligibility( $findings, array() ); return array( 'units' => $units, 'outputs' => array( 'title' => $assembled['text'] ), 'checks' => $checks, 'conflicts' => array(), 'findings' => $findings, 'sourcesUsed' => array(), 'eligibility' => $eligibility, 'usage' => $usage, 'providerError' => $provider_error, ); } /** * @param array $definition Normalized BlueprintDefinition. * @return array[] TitlePart list. */ private function partsOf( array $definition ): array { return isset( $definition['structure']['parts'] ) && is_array( $definition['structure']['parts'] ) ? $definition['structure']['parts'] : array(); } /** * @param array[] $parts TitlePart list. * @param string $id Part id. * @return array|null */ private function findPart( array $parts, string $id ): ?array { foreach ( $parts as $part ) { if ( ( $part['id'] ?? '' ) === $id ) { return $part; } } return null; } /** * @param array[] $units Rendered units. * @param string $id Unit id. * @return array|null */ private function findUnit( array $units, string $id ): ?array { foreach ( $units as $unit ) { if ( ( $unit['id'] ?? '' ) === $id ) { return $unit; } } return null; } /** * Without the paid title sources a Title run's AI reads only the * product name and description ({@see self::$titleSourcesLimited}). When * every AI part that came back empty was the model's permitted "nothing * specific" answer, the run's `ai_generation_failed` message says that, * and what to do, instead of the bare "No AI content was produced". It * names the data the template reads rather than the plan, and never * mentions Business. A provider failure keeps its own message, and a * part the model did not answer keeps the plain one. * * @param array $units Final title units. * @param array $findings Findings after ProviderFailureSupport::applyAiOutcomeRules(). * @param array|null $provider_error This run's provider failure, if any. * @return array Findings. */ private function explainNoDataOnFreeSources( array $units, array $findings, ?array $provider_error ): array { if ( ! $this->titleSourcesLimited || null !== $provider_error || empty( $this->noDataPartIds ) ) { return $findings; } foreach ( $units as $unit ) { if ( ! ProviderFailureSupport::countsTowardAiOutcome( $unit ) ) { continue; } if ( '' === (string) ( $unit['text'] ?? '' ) && ! isset( $this->noDataPartIds[ (string) ( $unit['id'] ?? '' ) ] ) ) { return $findings; } } foreach ( $findings as $index => $finding ) { if ( 'ai_generation_failed' === (string) ( $finding['code'] ?? '' ) ) { $findings[ $index ]['message'] = __( 'No AI content was produced for this run. The product details this template reads have nothing specific for the AI to write a title part from. Add more detail to the product description and try again.', 'ai-product-tools' ); } } return $findings; } /** * @param string $status SectionStatus value. * @param string $reason Human-readable reason. * @param string $value Resolved plain-text value. * @param string[] $missing_fields Missing field refs, when relevant. * @return array{status:string,reason:string,value:string,missingFields:string[]} */ private function result( string $status, string $reason, string $value, array $missing_fields ): array { return array( 'status' => $status, 'reason' => $reason, 'value' => $value, 'missingFields' => $missing_fields, ); } }