sourceContextBuilder = new SourceContextBuilder(); $this->conflictDetector = new ConflictDetector(); } /** * @param array[] $sections Sections. * @param array $plans SubjectContextResolver::planSections()'s result. * @param array $blueprint_items BlueprintSourcePolicy.items. * @return array Pending AI unit specs, keyed by id, in definition order. */ public function pendingUnitSpecs( array $sections, array $plans, array $blueprint_items ): array { $specs = array(); foreach ( $sections as $section ) { $id = $section['id']; if ( 'ai' === ( $section['mode'] ?? '' ) && 'pending' === $plans[ $id ]['status'] ) { $specs[ $id ] = $this->unitSpecFor( $section, $blueprint_items ); } } return $specs; } /** * @param array $section Normalized BlueprintSection. * @param array $blueprint_items BlueprintSourcePolicy.items. * @return array */ public function unitSpecFor( array $section, array $blueprint_items ): array { $catalog_entry = SectionCatalog::get( $section['type'] ); return array( 'id' => $section['id'], 'type' => $section['type'], 'purpose' => null !== $catalog_entry ? $catalog_entry['description'] : $section['name'], 'focus' => $section['focus'], 'format' => $section['format'], 'words' => array( 'min' => (int) ( $section['length']['targetMin'] ?? 0 ), 'max' => (int) ( $section['length']['targetMax'] ?? 0 ), 'limit' => $section['length']['hardMax'] ?? null, ), 'maxItems' => (int) ( $section['items']['max'] ?? 0 ), 'heading' => 'ai' === ( $section['heading']['mode'] ?? 'none' ) ? 'write' : 'none', 'detail' => $section['detail'], 'tone' => $section['tone'], 'instruction' => $this->instructionFor( $section ), 'sources' => $this->sourceContextBuilder->refsForSection( $section['sources'], $blueprint_items ), ); } /** * A unit's own `instruction` text. Every type reads the merchant's own * saved instruction unchanged, except an isolated type an extension * writes: its output rules are never merchant-authored, so they come * first, ahead of whatever the merchant may have written, every time * its isolated call compiles. * * @param array $section Normalized BlueprintSection. * @return string */ private function instructionFor( array $section ): string { $extension = SectionTypeExtensions::isolated( (string) ( $section['type'] ?? '' ) ); if ( null === $extension ) { return $section['instruction']; } $rules = $extension->outputRules(); $merchant_instruction = trim( (string) $section['instruction'] ); return '' !== $merchant_instruction ? $rules . ' ' . $merchant_instruction : $rules; } /** * @param array $ctx Execution context. * @param array $definition Normalized BlueprintDefinition. * @return array{short:array|null,tags:array|null} */ public function companionSpecs( array $ctx, array $definition ): array { if ( Generators::DESCRIPTION !== ( $ctx['generator'] ?? '' ) ) { return array( 'short' => null, 'tags' => null ); } $companions = $definition['structure']['companions'] ?? array(); $wanted = $ctx['runOptions']['companions'] ?? array(); $short = null; if ( ! empty( $wanted['shortDescription'] ) && isset( $companions['shortDescription'] ) ) { $short_def = $companions['shortDescription']; $short = array( 'format' => $short_def['format'], 'words' => array( 'min' => (int) ( $short_def['length']['targetMin'] ?? 0 ), 'max' => (int) ( $short_def['length']['targetMax'] ?? 0 ), 'limit' => $short_def['length']['hardMax'] ?? null ), 'maxItems' => (int) ( $short_def['items']['max'] ?? 0 ), ); } $tags = null; if ( ! empty( $wanted['tags'] ) && isset( $companions['tags'] ) ) { $tags = array( 'max' => (int) ( $companions['tags']['max'] ?? 10 ), 'existingTags' => $this->existingProductTags( $ctx['product'] ?? null ), ); } return array( 'short' => $short, 'tags' => $tags ); } /** * The product's current tag names, for the tags companion's * "do not duplicate these" context. * * @param mixed $product Loaded product from ctx (a WC_Product for the * description generator's product subject), or * anything else when none is loaded. * @return string[] */ private function existingProductTags( $product ): array { if ( ! is_object( $product ) || ! is_callable( array( $product, 'get_id' ) ) ) { return array(); } $terms = function_exists( 'wp_get_post_terms' ) ? wp_get_post_terms( (int) $product->get_id(), 'product_tag', array( 'fields' => 'names' ) ) : array(); return is_array( $terms ) ? array_values( array_filter( array_map( 'strval', $terms ) ) ) : array(); } /** * @param array $ctx Execution context. * @param array $definition Normalized BlueprintDefinition. * @return string[] Profile avoid list + blueprint-local list (Business, * {@see StructureBannedPhrases}), deduplicated. */ public function mergedBanned( array $ctx, array $definition ): array { $profile_avoid = isset( $ctx['brandProfile']['avoidPhrases'] ) && is_array( $ctx['brandProfile']['avoidPhrases'] ) ? $ctx['brandProfile']['avoidPhrases'] : array(); $rule_banned = StructureBannedPhrases::of( $definition ); return array_values( array_unique( array_merge( $profile_avoid, $rule_banned ) ) ); } /** * @param array $ctx Execution context. * @param array[] $sections Sections. * @return array BrandVoiceCompiler::compile()'s result. */ public function compileVoice( array $ctx, array $sections ): array { $tones = array(); foreach ( $sections as $section ) { if ( '' !== ( $section['tone'] ?? '' ) ) { $tones[] = $section['tone']; } } $voice_overrides = isset( $ctx['definition']['voice'] ) && is_array( $ctx['definition']['voice'] ) ? $ctx['definition']['voice'] : array( 'expression' => null, 'note' => '' ); return ( new BrandVoiceCompiler() )->compile( $ctx['brandProfile'] ?? null, $voice_overrides, array( 'sectionTones' => array_unique( $tones ) ) ); } /** * @param array $ctx Execution context. * @param array $subject_context SubjectContextResolver::buildSubjectContext()'s result. * @param array $reference_blocks Usable reference blocks for the units in play. * @param array $units Pending AI unit specs. * @param array $companions companionSpecs() (or a reduced retry subset). * @param array $voice BrandVoiceCompiler::compile()'s result. * @param string[] $banned Merged banned phrases. * @param array $definition Normalized BlueprintDefinition. * @param array $retry_notes Retry notes, when compiling a targeted retry. * @param array $conflict_resolution resolveConflicts()'s result, computed once per subject. * @return array PromptCompiler::compile()'s input spec. */ public function compilerSpec( array $ctx, array $subject_context, array $reference_blocks, array $units, array $companions, array $voice, array $banned, array $definition, array $retry_notes, array $conflict_resolution ): array { $generator = (string) ( $ctx['generator'] ?? Generators::DESCRIPTION ); $conflicts = is_array( $conflict_resolution['conflicts'] ?? null ) ? $conflict_resolution['conflicts'] : array(); $resolved_facts = is_array( $conflict_resolution['facts'] ?? null ) ? $conflict_resolution['facts'] : array(); $dropped = $this->droppedConflictCandidates( $conflicts, $resolved_facts ); $product_facts = is_array( $subject_context['facts'] ?? null ) ? $subject_context['facts'] : array(); $product_text = $this->filterConflictingProductLines( (string) ( $subject_context['text'] ?? '' ), $this->droppedProductFactTexts( $conflicts, $resolved_facts, $product_facts ) ); $filtered_blocks = $this->filterConflictingBlockFacts( $reference_blocks, $dropped ); return array( 'language' => LanguageResolver::resolve( $ctx, $definition ), 'headingLevel' => (string) ( $definition['rules']['headingLevel'] ?? 'h2' ), 'voiceBlock' => (string) ( $voice['block'] ?? '' ), 'bannedPhrases' => $banned, 'ruleInstructions' => $this->enabledInstructions( $definition ), 'aiNote' => (string) ( $ctx['aiNote'] ?? '' ), 'taxonomyLabel' => $this->taxonomyLabel( $ctx ), 'taxonomy' => $this->taxonomySlug( $ctx ), 'conflictInstructions' => $this->conflictInstructionLines( $conflicts, $resolved_facts ), 'productText' => $product_text, 'referenceBlocks' => array_map( static function ( $block ) { return array( 'ref' => $block['ref'], 'name' => $block['name'], 'priority' => $block['priority'], 'text' => $block['text'], 'facts' => isset( $block['facts'] ) && is_array( $block['facts'] ) ? $block['facts'] : array(), ); }, $filtered_blocks ), 'units' => $units, 'companions' => $companions, 'schemaName' => 'aipt_blueprint_' . $generator . '_sections', 'retryNotes' => $retry_notes, ); } /** * The taxonomy slug a term run writes for; '' for a product run. * * @param array $ctx Execution context. * @return string */ private function taxonomySlug( array $ctx ): string { if ( Generators::TAXONOMY !== ( $ctx['generator'] ?? '' ) || ! is_object( $ctx['term'] ?? null ) ) { return ''; } return (string) ( $ctx['term']->taxonomy ?? '' ); } /** * The singular label of the taxonomy a term run writes for; '' for a * product run. Product categories and tags use fixed English names: the * fact labels in the prompt are English and the registered label follows * the admin's locale, which can differ from the content language. Any other * taxonomy uses its registered label. * * @param array $ctx Execution context. * @return string */ private function taxonomyLabel( array $ctx ): string { $taxonomy = $this->taxonomySlug( $ctx ); if ( '' === $taxonomy ) { return ''; } if ( 'product_cat' === $taxonomy ) { return 'Category'; } if ( 'product_tag' === $taxonomy ) { return 'Tag'; } $object = function_exists( 'get_taxonomy' ) ? get_taxonomy( $taxonomy ) : false; $labels = is_object( $object ) && isset( $object->labels ) ? $object->labels : null; foreach ( array( 'singular_name', 'name' ) as $key ) { if ( is_object( $labels ) && ! empty( $labels->$key ) ) { return (string) $labels->$key; } } return $taxonomy; } /** * Resolve product-vs-source fact conflicts for one subject via the * ctx-injected detector (`$ctx['conflictDetector']`), using the FULL, * un-round-filtered source blocks — conflicts must not depend on which * refs a given AI unit happens to select. A pure, side-effect-free * computation over its inputs: `ResultAssembler` calls this exact same * method with the exact same inputs after generation for its own * findings, so prompt-time filtering and post-generation reporting can * never disagree. * * @param array $ctx Execution context (`conflictDetector` callable, `decisions`). * @param array $subject_context SubjectContextResolver::buildSubjectContext()'s result (reads 'facts'). * @param array $source_blocks SourceContextBuilder::build()'s 'blocks' (full, not round-filtered). * @param array $definition Normalized BlueprintDefinition (reads sources.conflictPolicy). * @param array $blueprint_items BlueprintSourcePolicy.items (priority order). * @return array{conflicts:array>,facts:array>} */ public function resolveConflicts( array $ctx, array $subject_context, array $source_blocks, array $definition, array $blueprint_items ): array { $detector = $ctx['conflictDetector'] ?? null; if ( ! is_callable( $detector ) ) { return array( 'conflicts' => array(), 'facts' => array() ); } $product_facts = isset( $subject_context['facts'] ) && is_array( $subject_context['facts'] ) ? $subject_context['facts'] : array(); $source_facts = $this->sourceContextBuilder->flattenFacts( $source_blocks ); $priority = array_column( $blueprint_items, 'ref' ); $policy = (string) ( $definition['sources']['conflictPolicy'] ?? 'review' ); $result = call_user_func( $detector, $product_facts, $source_facts, $priority, $policy, $ctx['decisions'] ?? array() ); return array( 'conflicts' => is_array( $result['conflicts'] ?? null ) ? $result['conflicts'] : array(), 'facts' => is_array( $result['facts'] ?? null ) ? $result['facts'] : array(), ); } /** * "ref|normalizedLabel" => true for every candidate that must not reach * the model for a conflicting label: every losing candidate always, and * every candidate at all when the label resolved to no authoritative * value (the `skip` policy — `$facts` simply has no entry for it). * * @param array $conflicts ConflictDetector::detect()-shaped `conflicts`. * @param array $facts The SAME call's resolved `facts` dictionary. * @return array */ private function droppedConflictCandidates( array $conflicts, array $facts ): array { $dropped = array(); foreach ( $conflicts as $conflict ) { $field = (string) ( $conflict['field'] ?? '' ); $winner = isset( $facts[ $field ]['ref'] ) ? (string) $facts[ $field ]['ref'] : ''; foreach ( (array) ( $conflict['values'] ?? array() ) as $candidate ) { $ref = is_array( $candidate ) ? (string) ( $candidate['ref'] ?? '' ) : ''; if ( '' === $ref || $ref === $winner ) { continue; } $dropped[ $ref . '|' . $field ] = true; } } return $dropped; } /** * Exact "Label: value" text (verbatim, including any embedded line * breaks) for every PRODUCT candidate that lost or was skipped * entirely out of a detected conflict. Composed from the conflict's own * candidate list and the raw product facts those candidates came from * (`rawProductFactTexts()`), never re-derived by re-parsing the * flattened `subject_context['text']` a physical line at a time: that * re-parsing cannot tell a dropped value's own embedded line break * from the boundary between two different facts, and cannot tell a * label that itself contains "': '" (e.g. a merchant-named "Size: * International" attribute) from the real label/value separator. * * @param array $conflicts ConflictDetector::detect()-shaped `conflicts`. * @param array $facts The SAME call's resolved `facts` dictionary. * @param array $product_facts The subject context's own raw `facts`. * @return string[] */ private function droppedProductFactTexts( array $conflicts, array $facts, array $product_facts ): array { $texts = array(); foreach ( $conflicts as $conflict ) { $field = (string) ( $conflict['field'] ?? '' ); $winner = isset( $facts[ $field ]['ref'] ) ? (string) $facts[ $field ]['ref'] : ''; foreach ( (array) ( $conflict['values'] ?? array() ) as $candidate ) { $ref = is_array( $candidate ) ? (string) ( $candidate['ref'] ?? '' ) : ''; if ( 'product' !== $ref || $ref === $winner ) { continue; } $texts = array_merge( $texts, $this->rawProductFactTexts( $product_facts, (string) ( $candidate['label'] ?? '' ), (string) ( $candidate['value'] ?? '' ) ) ); } } return $texts; } /** * The composed text of one dropped product candidate, plus the exact * composed text of every raw product fact it came from. ConflictDetector * trims each candidate's label and value, while the product text was * composed from the untrimmed fact * (`FieldContextTrait::composeFieldContext()`), so a value with * surrounding whitespace only matches when composed from the raw fact. * * @param array $product_facts The subject context's own raw `facts`. * @param string $label The candidate's label. * @param string $value The candidate's value. * @return string[] */ private function rawProductFactTexts( array $product_facts, string $label, string $value ): array { $label = trim( $label ); $value = trim( $value ); if ( '' === $label || '' === $value ) { return array(); } $texts = array( $label . ': ' . $value ); foreach ( $product_facts as $fact ) { $raw_label = is_array( $fact ) ? (string) ( $fact['label'] ?? '' ) : ''; $raw_value = is_array( $fact ) ? (string) ( $fact['value'] ?? '' ) : ''; if ( trim( $raw_label ) === $label && trim( $raw_value ) === $value ) { $texts[] = $raw_label . ': ' . $raw_value; } } return $texts; } /** * Drop every dropped product fact's exact composed text from the * product/term context, as a whole, line-bounded block, matched * verbatim against `droppedProductFactTexts()`'s own candidate data, * never by scanning each physical line for its label/value boundary. * * @param string $product_text Subject context's product/term text. * @param string[] $dropped_product_facts droppedProductFactTexts()'s result. * @return string */ private function filterConflictingProductLines( string $product_text, array $dropped_product_facts ): string { if ( '' === $product_text || empty( $dropped_product_facts ) ) { return $product_text; } foreach ( $dropped_product_facts as $fact_text ) { $product_text = $this->removeExactFactText( $product_text, $fact_text ); } return $product_text; } /** * Remove one exact fact's composed text from a larger newline-joined * block of text, only when it occupies the WHOLE text, a line-bounded * prefix, a line-bounded suffix, or a line-bounded infix, never a * partial-line match. The needle itself may contain embedded line * breaks (a multi-paragraph value composed from one fact). * * @param string $text Composed product/term text. * @param string $fact_text Exact "Label: value" text to remove. * @return string */ private function removeExactFactText( string $text, string $fact_text ): string { if ( '' === $fact_text || '' === $text ) { return $text; } if ( $text === $fact_text ) { return ''; } $prefix = $fact_text . "\n"; if ( 0 === strpos( $text, $prefix ) ) { return substr( $text, strlen( $prefix ) ); } $suffix = "\n" . $fact_text; if ( strlen( $suffix ) <= strlen( $text ) && substr( $text, -strlen( $suffix ) ) === $suffix ) { return substr( $text, 0, strlen( $text ) - strlen( $suffix ) ); } $infix = "\n" . $fact_text . "\n"; if ( false !== strpos( $text, $infix ) ) { return str_replace( $infix, "\n", $text ); } return $text; } /** * Drop a source's own fact line for a label it lost (or that was * skipped entirely), leaving its other, non-conflicting facts and its * prose text untouched — free-text contradictions are out of scope, * matching `ConflictDetector`'s own "labeled facts only" boundary. * * @param array $blocks Reference blocks (each with a 'facts' list). * @param array $dropped droppedConflictCandidates()'s result. * @return array */ private function filterConflictingBlockFacts( array $blocks, array $dropped ): array { if ( empty( $dropped ) ) { return $blocks; } return array_map( function ( $block ) use ( $dropped ) { $ref = (string) ( $block['ref'] ?? '' ); $block['facts'] = array_values( array_filter( (array) ( $block['facts'] ?? array() ), function ( $fact ) use ( $ref, $dropped ) { $normalized = $this->conflictDetector->normalizeLabelForMatching( (string) ( $fact['label'] ?? '' ) ); return ! isset( $dropped[ $ref . '|' . $normalized ] ); } ) ); return $block; }, $blocks ); } /** * "Use only this value" instruction lines for every conflict that DID * resolve to one authoritative value (`prefer`, and `review` both * before and after a human decision). A `skip` conflict has no entry in * `$facts`, so it gets no instruction line: the conflicting label is * simply absent from what the model reads * (`filterConflictingProductLines()`/`filterConflictingBlockFacts()` * already handled that). * * @param array $conflicts ConflictDetector::detect()-shaped `conflicts`. * @param array $facts The SAME call's resolved `facts` dictionary. * @return string[] */ private function conflictInstructionLines( array $conflicts, array $facts ): array { $lines = array(); foreach ( $conflicts as $conflict ) { $field = (string) ( $conflict['field'] ?? '' ); if ( ! isset( $facts[ $field ] ) ) { continue; } $winning_ref = isset( $facts[ $field ]['ref'] ) ? (string) $facts[ $field ]['ref'] : ''; if ( 'product' !== $winning_ref ) { continue; } $label = (string) ( $facts[ $field ]['label'] ?? $field ); $value = (string) ( $facts[ $field ]['value'] ?? '' ); if ( '' === $value ) { continue; } /* translators: 1: field label. 2: the single authoritative value to use for it. */ $lines[] = sprintf( __( 'For %1$s, use only this value: %2$s.', 'ai-product-tools' ), $label, $value ); } return $lines; } /** * @param array $definition Normalized BlueprintDefinition. * @return string[] */ private function enabledInstructions( array $definition ): array { return StructureInstructions::enabled( $definition ); } }