benefit -> key_feature/custom until the text fits. * * @var array */ const DROP_PRIORITY = array( array( 'cta' ), array( 'benefit' ), array( 'key_feature', 'custom' ) ); /** * Token keys dropped, whatever their mode, when a field is still over * its hard limit after every `ai` tier: the store name is the least * essential part of a meta title (search results show the site name on * their own), so a long product name never blocks the title. * * @var string[] */ const LAST_RESORT_DROP = array( 'store_name' ); /** * Title-separator enum -> literal joining text. * * @var array */ const TITLE_SEPARATORS = array( 'pipe' => ' | ', 'dash' => ' - ', 'colon' => ': ', ); /** * @param array $pending_title Pending title tokens, keyed by id. * @param array $pending_desc Pending description tokens, keyed by id. * @param string $keyword_instruction The AI keyword source's instruction, which also requests `focusKeyword`; '' requests none. * @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 string[] $instructions StructureInstructions::enabled()'s result. * @param string[] $length_lines SeoMetaLength::promptLine() per field this call writes. * @return array{system:string,user:string,schema:array,schemaName:string,validate:callable} */ public static function compileRequest( array $pending_title, array $pending_desc, string $keyword_instruction, array $product_context, string $language, array $voice, array $banned, string $ai_note, array $retry_notes, array $instructions = array(), array $length_lines = array() ): array { $want_keyword = '' !== $keyword_instruction; $token_catalog = SectionCatalog::seoTokenKeys(); $lines = array(); $lines[] = 'You write SEO meta title and meta description fragments 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 token\'s value must name something specific to this product\'s own data. If the data gives nothing specific enough for a token, 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 surrounding quotes.'; $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 ) . '.'; } if ( $want_keyword ) { $lines[] = $keyword_instruction; } 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" . ''; $ai_note_user_block = AiNoteBlock::userBlock( $ai_note, array( FormulaText::class, 'escapeBlock' ) ); if ( '' !== $ai_note_user_block ) { $user_parts[] = $ai_note_user_block; } if ( ! empty( $pending_title ) ) { $user_parts[] = '' . "\n" . wp_json_encode( self::tokenHints( $pending_title, $token_catalog ) ) . "\n" . ''; } if ( ! empty( $pending_desc ) ) { $user_parts[] = '' . "\n" . wp_json_encode( self::tokenHints( $pending_desc, $token_catalog ) ) . "\n" . ''; } $user_parts[] = empty( $length_lines ) ? 'For each listed token, write one short plain-text value that fits its label and the product data, or an empty string when nothing specific applies.' : 'For each listed token, write one plain-text value that fits its label, the product data and the length below, or an empty string when nothing specific applies.'; foreach ( $length_lines as $length_line ) { $user_parts[] = $length_line; } if ( ! empty( $retry_notes ) ) { $note_lines = array( 'Your previous answer had problems with these tokens. 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' => self::buildSchema( array_keys( $pending_title ), array_keys( $pending_desc ), $want_keyword ), 'schemaName' => 'aipt_blueprint_seo_meta', 'validate' => function ( $decoded ) { return ( is_array( $decoded ) && isset( $decoded['title'] ) && isset( $decoded['description'] ) && is_array( $decoded['title'] ) && is_array( $decoded['description'] ) ) ? array( 'ok' => true, 'errors' => array() ) : array( 'ok' => false, 'errors' => array( __( 'The answer must have "title" and "description" arrays.', 'ai-product-tools' ) ) ); }, ); } /** * Same request shape as {@see self::compileRequest()}, except every * token answers with a `texts` array of `$variant_count` alternatives * instead of one `text` string: this asks the engine for N alternatives * of the AI parts in one call. `focusKeyword` * (when requested) stays a single value, exactly as in the non-variant * request: every variant shares the same resolved keyword. * * @param array $pending_title Pending title tokens, keyed by id. * @param array $pending_desc Pending description tokens, keyed by id. * @param string $keyword_instruction The AI keyword source's instruction, which also requests `focusKeyword`; '' requests none. * @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 token (>= 2). * @param string[] $instructions StructureInstructions::enabled()'s result. * @param string[] $length_lines SeoMetaLength::promptLine() per field this call writes. * @return array{system:string,user:string,schema:array,schemaName:string,validate:callable} */ public static function compileVariantsRequest( array $pending_title, array $pending_desc, string $keyword_instruction, array $product_context, string $language, array $voice, array $banned, string $ai_note, array $retry_notes, int $variant_count, array $instructions = array(), array $length_lines = array() ): array { $want_keyword = '' !== $keyword_instruction; $token_catalog = SectionCatalog::seoTokenKeys(); $lines = array(); /* translators: %d: number of alternative texts requested per token. */ $lines[] = sprintf( __( 'You write SEO meta title and meta description fragments for an online store. For each token, 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 token\'s value must name something specific to this product\'s own data. If the data gives nothing specific enough for a token, 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 surrounding quotes. Make the alternatives noticeably different from each other in wording while staying accurate to the product data.', 'ai-product-tools' ); $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 ) ); } if ( $want_keyword ) { $lines[] = $keyword_instruction; } 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" . ''; $ai_note_user_block = AiNoteBlock::userBlock( $ai_note, array( FormulaText::class, 'escapeBlock' ) ); if ( '' !== $ai_note_user_block ) { $user_parts[] = $ai_note_user_block; } if ( ! empty( $pending_title ) ) { $user_parts[] = '' . "\n" . wp_json_encode( self::tokenVariantHints( $pending_title, $token_catalog, $variant_count ) ) . "\n" . ''; } if ( ! empty( $pending_desc ) ) { $user_parts[] = '' . "\n" . wp_json_encode( self::tokenVariantHints( $pending_desc, $token_catalog, $variant_count ) ) . "\n" . ''; } $user_parts[] = empty( $length_lines ) /* translators: %d: number of alternative texts requested per token. */ ? sprintf( __( 'For each listed token, write %d short plain-text alternatives that fit its label and the product data, in a "texts" array.', 'ai-product-tools' ), $variant_count ) /* translators: %d: number of alternative texts requested per token. */ : sprintf( __( 'For each listed token, write %d plain-text alternatives that fit its label, the product data and the length below, in a "texts" array.', 'ai-product-tools' ), $variant_count ); foreach ( $length_lines as $length_line ) { $user_parts[] = $length_line; } if ( ! empty( $retry_notes ) ) { $note_lines = array( __( 'Your previous answer had problems with these tokens. 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' => self::buildVariantsSchema( array_keys( $pending_title ), array_keys( $pending_desc ), $want_keyword ), 'schemaName' => 'aipt_blueprint_seo_meta_variants', 'validate' => function ( $decoded ) { return ( is_array( $decoded ) && isset( $decoded['title'] ) && isset( $decoded['description'] ) && is_array( $decoded['title'] ) && is_array( $decoded['description'] ) ) ? array( 'ok' => true, 'errors' => array() ) : array( 'ok' => false, 'errors' => array( __( 'The answer must have "title" and "description" arrays.', 'ai-product-tools' ) ) ); }, ); } /** * @param string[] $title_ids Expected title token ids (enum). * @param string[] $desc_ids Expected description token ids (enum). * @param bool $want_keyword Whether `focusKeyword` is required. * @return array JSON Schema. */ public static function buildVariantsSchema( array $title_ids, array $desc_ids, bool $want_keyword ): array { $properties = array( 'title' => self::tokenTextsArraySchema( $title_ids ), 'description' => self::tokenTextsArraySchema( $desc_ids ), ); $required = array( 'title', 'description' ); if ( $want_keyword ) { $properties['focusKeyword'] = array( 'type' => 'string' ); $required[] = 'focusKeyword'; } return array( 'type' => 'object', 'properties' => $properties, 'required' => $required, 'additionalProperties' => false ); } /** * @param string[] $ids Expected ids (enum); an empty list still produces a valid (always-empty) array schema. * @return array */ public static function tokenTextsArraySchema( array $ids ): array { $id_schema = empty( $ids ) ? array( 'type' => 'string' ) : array( 'type' => 'string', 'enum' => $ids ); return array( 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'id' => $id_schema, 'texts' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ) ), 'required' => array( 'id', 'texts' ), 'additionalProperties' => false, ), ); } /** * @param array $pending Pending SeoToken list, keyed by id. * @param array $token_catalog SectionCatalog::seoTokenKeys(). * @return array[] */ public static function tokenHints( array $pending, array $token_catalog ): array { $hints = array(); foreach ( $pending as $id => $token ) { $hints[] = array( 'id' => $id, 'label' => (string) ( $token_catalog[ $token['key'] ]['label'] ?? $token['key'] ) ); } return $hints; } /** * {@see self::tokenHints()}, with the requested alternative count * attached to every hint (mirrors `TitleGenerator::compileVariantsRequest()`'s * per-part `variantCount` field) so the model sees it both in the * instruction text and per-token. * * @param array $pending Pending SeoToken list, keyed by id. * @param array $token_catalog SectionCatalog::seoTokenKeys(). * @param int $variant_count Alternatives requested per token. * @return array[] */ public static function tokenVariantHints( array $pending, array $token_catalog, int $variant_count ): array { $hints = array(); foreach ( $pending as $id => $token ) { $hints[] = array( 'id' => $id, 'label' => (string) ( $token_catalog[ $token['key'] ]['label'] ?? $token['key'] ), 'variantCount' => $variant_count, ); } return $hints; } /** * @param string[] $title_ids Expected title token ids (enum). * @param string[] $desc_ids Expected description token ids (enum). * @param bool $want_keyword Whether `focusKeyword` is required. * @return array JSON Schema. */ public static function buildSchema( array $title_ids, array $desc_ids, bool $want_keyword ): array { $properties = array( 'title' => self::tokenArraySchema( $title_ids ), 'description' => self::tokenArraySchema( $desc_ids ), ); $required = array( 'title', 'description' ); if ( $want_keyword ) { $properties['focusKeyword'] = array( 'type' => 'string' ); $required[] = 'focusKeyword'; } return array( 'type' => 'object', 'properties' => $properties, 'required' => $required, 'additionalProperties' => false ); } /** * @param string[] $ids Expected ids (enum); an empty list still produces a valid (always-empty) array schema. * @return array */ public static function tokenArraySchema( array $ids ): array { $id_schema = empty( $ids ) ? array( 'type' => 'string' ) : array( 'type' => 'string', 'enum' => $ids ); return array( 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'id' => $id_schema, 'text' => array( 'type' => 'string' ) ), 'required' => array( 'id', 'text' ), 'additionalProperties' => false, ), ); } /** * Try joining $resolved's included tokens; while over $hard_max, pick the * best-fitting combination of whole DROP_PRIORITY tiers to drop, then, as * a last resort, the store name (LAST_RESORT_DROP). * * Every tier is tried either fully kept or fully dropped (tokens inside * one tier always move together, as the class docblock documents), but * EVERY combination of tiers is compared rather than only the fixed * cta -> benefit -> key_feature/custom prefix: dropping just the tier * that is actually too long can fit without also discarding a shorter * tier the fixed order would have dropped first. Among every combination * that fits $hard_max, one landing inside [$target_min, $target_max] wins * over one that merely fits; the longest (fewest tiers dropped) wins the * rest of the time, so content is never discarded beyond what is needed. * * @param array[] $tokens SeoToken list, in order. * @param array $resolved Final resolved-by-id. * @param int $hard_max Hard character limit. * @param callable $join fn( array $includedOrdered ): array{text:string,len:int}. * @param int $target_min Field's target minimum characters; 0 when the caller has none to prefer. * @param int $target_max Field's target maximum characters; PHP_INT_MAX when the caller has none to prefer. * @return array{text:string,len:int,droppedIds:string[],stillOver:bool} */ public static function fitWithinHardMax( array $tokens, array $resolved, int $hard_max, callable $join, int $target_min = 0, int $target_max = PHP_INT_MAX ): array { $current = array(); foreach ( $tokens as $token ) { $id = (string) $token['id']; $entry = $resolved[ $id ] ?? null; if ( null !== $entry && in_array( $entry['status'], array( 'included', 'fallback' ), true ) ) { $current[] = array( 'id' => $id, 'key' => $token['key'], 'mode' => $token['mode'], 'value' => $entry['value'] ); } } $full = call_user_func( $join, $current ); if ( $full['len'] <= $hard_max ) { return array( 'text' => $full['text'], 'len' => $full['len'], 'droppedIds' => array(), 'stillOver' => false ); } $best = self::bestTierFit( $current, $hard_max, $join, $target_min, $target_max ); if ( null !== $best ) { return array( 'text' => $best['text'], 'len' => $best['len'], 'droppedIds' => $best['droppedIds'], 'stillOver' => false ); } $leanest_kept = array(); $leanest_dropped = array(); foreach ( $current as $entry ) { if ( 'ai' === $entry['mode'] ) { $leanest_dropped[] = $entry['id']; continue; } $leanest_kept[] = $entry; } $leanest = call_user_func( $join, $leanest_kept ); if ( $leanest['len'] <= $hard_max ) { return array( 'text' => $leanest['text'], 'len' => $leanest['len'], 'droppedIds' => $leanest_dropped, 'stillOver' => false ); } $store_ids = array(); $without_store = array(); foreach ( $current as $entry ) { if ( in_array( $entry['key'], self::LAST_RESORT_DROP, true ) ) { $store_ids[] = $entry['id']; continue; } $without_store[] = $entry; } if ( empty( $store_ids ) ) { return array( 'text' => $leanest['text'], 'len' => $leanest['len'], 'droppedIds' => $leanest_dropped, 'stillOver' => true ); } $best = self::bestTierFit( $without_store, $hard_max, $join, $target_min, $target_max ); if ( null !== $best ) { return array( 'text' => $best['text'], 'len' => $best['len'], 'droppedIds' => array_merge( $best['droppedIds'], $store_ids ), 'stillOver' => false ); } $kept = array_values( array_filter( $leanest_kept, static function ( $entry ) { return ! in_array( $entry['key'], self::LAST_RESORT_DROP, true ); } ) ); $leanest = call_user_func( $join, $kept ); return array( 'text' => $leanest['text'], 'len' => $leanest['len'], 'droppedIds' => array_values( array_unique( array_merge( $leanest_dropped, $store_ids ) ) ), 'stillOver' => $leanest['len'] > $hard_max ); } /** * The best combination of whole DROP_PRIORITY tiers to drop from * $current so it fits $hard_max: one inside [$target_min, $target_max] * over one that merely fits, then the longest, then the one dropping * fewer tiers. Null when no combination fits. * * @param array[] $current Included entries, in order. * @param int $hard_max Hard character limit. * @param callable $join fn( array $includedOrdered ): array{text:string,len:int}. * @param int $target_min Field's target minimum characters. * @param int $target_max Field's target maximum characters. * @return array{text:string,len:int,droppedIds:string[],inRange:bool,tiersCut:int}|null */ private static function bestTierFit( array $current, int $hard_max, callable $join, int $target_min, int $target_max ): ?array { $best = null; $tier_count = count( self::DROP_PRIORITY ); for ( $mask = 0; $mask < ( 1 << $tier_count ); $mask++ ) { $dropped_keys = array(); for ( $tier = 0; $tier < $tier_count; $tier++ ) { if ( 0 !== ( $mask & ( 1 << $tier ) ) ) { $dropped_keys = array_merge( $dropped_keys, self::DROP_PRIORITY[ $tier ] ); } } $kept = array(); $dropped_ids = array(); foreach ( $current as $entry ) { if ( 'ai' === $entry['mode'] && in_array( $entry['key'], $dropped_keys, true ) ) { $dropped_ids[] = $entry['id']; continue; } $kept[] = $entry; } $result = call_user_func( $join, $kept ); if ( $result['len'] > $hard_max ) { continue; } $in_range = $result['len'] >= $target_min && $result['len'] <= $target_max; $tiers_cut = substr_count( decbin( $mask ), '1' ); $is_better = null === $best || ( $in_range && ! $best['inRange'] ) || ( $in_range === $best['inRange'] && $result['len'] > $best['len'] ) || ( $in_range === $best['inRange'] && $result['len'] === $best['len'] && $tiers_cut < $best['tiersCut'] ); if ( $is_better ) { $best = array( 'text' => $result['text'], 'len' => $result['len'], 'droppedIds' => $dropped_ids, 'inRange' => $in_range, 'tiersCut' => $tiers_cut ); } } return $best; } /** * @param string $separator Separator enum. * @return callable fn( array $includedOrdered ): array{text:string,len:int}. */ public static function titleJoiner( string $separator ): callable { $sep = self::TITLE_SEPARATORS[ $separator ] ?? self::TITLE_SEPARATORS['pipe']; return function ( array $included ) use ( $sep ) { $values = array_filter( array_column( $included, 'value' ), static function ( $value ): bool { return '' !== trim( (string) $value ); } ); $text = implode( $sep, $values ); return array( 'text' => $text, 'len' => TextMetrics::charCount( $text ) ); }; } /** * Assemble description tokens into readable sentences: each token's * text becomes its own clause, trailing punctuation is normalized so * clauses never double up ("..") and the whole string ends with exactly * one terminal mark (description tokens joined as sentences: a * deterministic interpretation since the tokens themselves are * independently generated phrases, not a single model-authored * paragraph). * * @param array $included Included tokens, in order. * @return array{text:string,len:int} */ public static function joinDescriptionTokens( array $included ): array { $clauses = array(); foreach ( $included as $entry ) { $clause = rtrim( trim( (string) $entry['value'] ), " \t\n\r.!?" ); if ( '' !== $clause ) { $clauses[] = self::sentenceStart( $clause ); } } $text = implode( '. ', $clauses ); if ( '' !== $text && 0 === preg_match( '/[.!?]$/u', $text ) ) { $text .= '.'; } return array( 'text' => $text, 'len' => TextMetrics::charCount( $text ) ); } /** * A clause joined after a full stop starts with a capital letter. A * leading "i" is left alone: mb_strtoupper() would give "I" where * Turkish needs "İ", and the prompt already asks for capitalized * sentences in the run's own language. * * @param string $clause Trimmed clause. * @return string */ private static function sentenceStart( string $clause ): string { $first = mb_substr( $clause, 0, 1, 'UTF-8' ); if ( 'i' === $first || $first === mb_strtoupper( $first, 'UTF-8' ) ) { return $clause; } return mb_strtoupper( $first, 'UTF-8' ) . mb_substr( $clause, 1, null, 'UTF-8' ); } /** * @param string $id Check id. * @param string $label Check label. * @param int $len Measured character count. * @param int $target_min Target minimum characters. * @param int $target_max Target maximum characters. * @param int $hard_max Hard character limit. * @param bool $ok Whether the final length is within the hard limit. * @return array */ public static function lengthCheck( string $id, string $label, int $len, int $target_min, int $target_max, int $hard_max, bool $ok ): array { if ( ! $ok ) { /* translators: %1$d: measured character count. %2$d: configured hard character limit. */ return FormulaChecks::row( $id, $label, 'fail', sprintf( __( '%1$d characters - over the %2$d character limit.', 'ai-product-tools' ), $len, $hard_max ) ); } $in_range = $len >= $target_min && $len <= $target_max; /* translators: %1$d: measured character count. %2$d: target minimum characters. %3$d: target maximum characters. %4$d: hard character limit. */ $detail = sprintf( __( '%1$d characters - target %2$d-%3$d, limit %4$d.', 'ai-product-tools' ), $len, $target_min, $target_max, $hard_max ); return FormulaChecks::row( $id, $label, $in_range ? 'pass' : 'warn', $detail ); } /** * @param string $keyword Resolved focus keyword. * @param bool $once_rule Whether the "use once" rule is active. * @param string $title_text The assembled meta title (the rule reads "Use it once, early in the title"). * @return array */ public static function keywordUsageCheck( string $keyword, bool $once_rule, string $title_text ): array { if ( '' === $keyword ) { return FormulaChecks::row( 'keyword_usage', __( 'Keyword usage', 'ai-product-tools' ), 'skip', __( 'No keyword configured.', 'ai-product-tools' ) ); } $count = self::countOccurrences( $title_text, $keyword ); if ( ! $once_rule ) { /* translators: %d: measured occurrence count. */ return FormulaChecks::row( 'keyword_usage', __( 'Keyword usage', 'ai-product-tools' ), 'pass', sprintf( _n( 'Used %d time. The "use once" rule is off.', 'Used %d times. The "use once" rule is off.', $count, 'ai-product-tools' ), $count ) ); } $ok = 1 === $count; /* translators: %d: measured occurrence count. */ $detail = sprintf( _n( 'Used %d time - target once.', 'Used %d times - target once.', $count, 'ai-product-tools' ), $count ); return FormulaChecks::row( 'keyword_usage', __( 'Keyword usage', 'ai-product-tools' ), $ok ? 'pass' : 'warn', $detail ); } /** * Case-insensitive, Unicode word-boundary occurrence count of $needle in * $haystack (mirrors `OutputValidator::findBannedPhrases()`'s own * matching rule, counting instead of presence-only). * * @param string $haystack Text to search. * @param string $needle Phrase to count. * @return int */ public static function countOccurrences( string $haystack, string $needle ): int { $normalized = TextMetrics::normalizeForCompare( $haystack ); $needle = trim( mb_strtolower( $needle, 'UTF-8' ) ); if ( '' === $needle ) { return 0; } $pattern = '/(?