call -> validate (pass 1) -> * at most one targeted retry -> validate (final pass), for the * description/taxonomy SectionGenerator pipeline. * * Split out of SectionGenerator to keep each file within the repository's * file-size guidance; this remains an internal collaborator, not part of * the per-generator file list, so it lives under a `Support` sub-namespace. * * @package AIPT\Api\ContentStructure\Engine\Generators\Support * @since 2.8.0 */ namespace AIPT\Api\ContentStructure\Engine\Generators\Support; use AIPT\Api\ContentStructure\Engine\Context\SourceContextBuilder; use AIPT\Api\ContentStructure\Engine\Extension\ContextualIsolatedSectionExtension; use AIPT\Api\ContentStructure\Engine\Extension\IsolatedSectionExtension; use AIPT\Api\ContentStructure\Engine\Extension\SectionTypeExtensions; use AIPT\Api\ContentStructure\Engine\OutputValidator; use AIPT\Api\ContentStructure\Engine\ProviderFailureSupport; use AIPT\Api\ContentStructure\Engine\PromptCompiler; use AIPT\Api\ContentStructure\Engine\StructuredCallerInterface; use AIPT\Api\ContentStructure\Engine\TextMetrics; use AIPT\Utils\TagListSanitizer; defined( 'ABSPATH' ) || exit; /** * One generation round: whole-batch call, optional targeted retry, final * per-unit resolution. */ class GenerationRoundRunner { /** * No retry may start with less than this many seconds left before the * deadline (mirrors StructuredCaller's own rule). */ const MIN_RETRY_SECONDS = 15.0; /** * @var OutputValidator */ private $validator; /** * @var SourceContextBuilder */ private $sourceContextBuilder; /** * @var PromptSpecBuilder */ private $specBuilder; public function __construct() { $this->validator = new OutputValidator(); $this->sourceContextBuilder = new SourceContextBuilder(); $this->specBuilder = new PromptSpecBuilder(); } /** * Run the whole-batch call, the optional targeted retry, and update * `$plans`/`$usage`/`$findings` in place. * * @param StructuredCallerInterface $caller Structured AI caller. * @param array $ctx Execution context. * @param array $subject_context SubjectContextResolver::buildSubjectContext()'s result. * @param array $source_result SourceContextBuilder::build()'s result. * @param array $pending_specs Pending AI unit specs. * @param array $companions PromptSpecBuilder::companionSpecs()'s result. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param string[] $banned Merged banned phrases. * @param array $definition Normalized BlueprintDefinition. * @param array &$plans Section plans, updated in place. * @param array &$usage Usage accumulator, updated in place. * @param array &$findings Findings accumulator, updated in place. * @param bool $isolated Whether $pending_specs is an isolated-unit-type round * (SectionCatalog::isIsolatedUnit()) rather than the normal * batch: the type's extension adds its own output contract * (one retry, then its own findings), alongside the * banned-phrase check every round already applies. * @return void */ public function run( StructuredCallerInterface $caller, array $ctx, array $subject_context, array $source_result, array $pending_specs, array $companions, array $voice, array $banned, array $definition, array &$plans, array &$usage, array &$findings, bool $isolated = false ): void { $deadline = isset( $ctx['deadline'] ) ? (float) $ctx['deadline'] : ( microtime( true ) + 60.0 ); $budget = isset( $ctx['maxCalls'] ) ? max( 1, (int) $ctx['maxCalls'] ) : 3; $want_short = null !== $companions['short']; $want_tags = null !== $companions['tags']; $blueprint_items = $definition['sources']['items'] ?? array(); $conflict_resolution = $this->specBuilder->resolveConflicts( $ctx, $subject_context, $source_result['blocks'], $definition, $blueprint_items ); $relevant_refs = array(); foreach ( $pending_specs as $spec ) { $relevant_refs = array_merge( $relevant_refs, $spec['sources'] ); } $relevant_refs = array_unique( $relevant_refs ); $usable_blocks = $this->sourceContextBuilder->usableBlocksForRefs( $source_result['blocks'], $relevant_refs ); $compiled = ( new PromptCompiler() )->compile( $this->specBuilder->compilerSpec( $ctx, $subject_context, $usable_blocks, $pending_specs, $companions, $voice, $banned, $definition, array(), $conflict_resolution ) ); $first = $this->callOnce( $caller, $compiled, $ctx, min( 2, $budget ), $deadline ); $this->mergeUsage( $usage, $first ); $calls_used = $first['calls']; $decoded_by_id = array(); $decoded_short = null; $decoded_tags = null; $retryable_companions = array(); if ( $first['ok'] ) { $decoded = $first['decoded']; $match = $this->validator->matchUnits( $decoded['sections'] ?? array(), array_keys( $pending_specs ) ); $findings = array_merge( $findings, $match['findings'] ); $decoded_by_id = $match['byId']; if ( $want_short ) { $decoded_short = is_array( $decoded['shortDescription'] ?? null ) ? $decoded['shortDescription'] : null; } if ( $want_tags ) { $decoded_tags = is_array( $decoded['tags'] ?? null ) ? $decoded['tags'] : null; } } else { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $first['error'] ?? array() ) ); } list( $sanitized, $retry_ids ) = $this->validateFirstPass( $pending_specs, $decoded_by_id, $banned, $isolated, $subject_context ); if ( $want_short && ( null === $decoded_short || ! $this->isUsableShortDescription( $decoded_short, $companions ) ) ) { $retryable_companions['short'] = true; } if ( $want_tags && null === $decoded_tags ) { $retryable_companions['tags'] = true; } $remaining_budget = $budget - $calls_used; $time_left = $deadline - microtime( true ); $retry_result = null; $retried_ids = $retry_ids; if ( isset( $retryable_companions['short'] ) ) { $retried_ids[] = 'companion_short_description'; } if ( isset( $retryable_companions['tags'] ) ) { $retried_ids[] = 'companion_tags'; } if ( ( ! empty( $retry_ids ) || ! empty( $retryable_companions ) ) && $remaining_budget >= 1 && $time_left >= self::MIN_RETRY_SECONDS ) { $retry_result = $this->runTargetedRetry( $caller, $ctx, $subject_context, $source_result, $pending_specs, $companions, $voice, $banned, $definition, $conflict_resolution, $retry_ids, $retryable_companions, $sanitized, $relevant_refs, $first, $deadline, $usage, $findings, $decoded_by_id, $decoded_short, $decoded_tags, $isolated ); } $all_ids = array_keys( $pending_specs ); if ( $want_short ) { $all_ids[] = 'companion_short_description'; } if ( $want_tags ) { $all_ids[] = 'companion_tags'; } $failure_messages = ProviderFailureSupport::unitFailureMessages( $first, $all_ids, $retry_result, $retried_ids ); $this->validateFinalPass( $pending_specs, $decoded_by_id, $banned, $voice, $subject_context, $source_result, $plans, $findings, $definition, $failure_messages, $isolated ); $this->applyCompanionResults( $decoded_short, $decoded_tags, $companions, $plans, $findings, $banned, $want_short, $want_tags, $failure_messages ); } /** * @param StructuredCallerInterface $caller Structured AI caller. * @param array $ctx Execution context. * @param array $subject_context SubjectContextResolver::buildSubjectContext()'s result. * @param array $source_result SourceContextBuilder::build()'s result. * @param array $pending_specs Pending AI unit specs. * @param array $companions PromptSpecBuilder::companionSpecs()'s result. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param string[] $banned Merged banned phrases. * @param array $definition Normalized BlueprintDefinition. * @param array $conflict_resolution PromptSpecBuilder::resolveConflicts()'s result (reused unchanged from the main round). * @param string[] $retry_ids Unit ids needing the targeted retry. * @param array $retryable_companions {short?,tags?} flags. * @param array $sanitized First-pass sanitizeUnit() results by id. * @param string[] $relevant_refs Source refs in play across the pending units. * @param array $first The first call()'s result (for provider/model reuse). * @param float $deadline Unix deadline. * @param array &$usage Usage accumulator, updated in place. * @param array &$findings Findings accumulator, updated in place. * @param array &$decoded_by_id Matched raw payloads, updated in place. * @param array|null &$decoded_short Decoded shortDescription, updated in place. * @param array|null &$decoded_tags Decoded tags, updated in place. * @param bool $isolated Whether this round is an isolated-unit-type round (see {@see run()}). * @return array The retry call()'s own result, so the caller can attribute a still-missing unit's final message to it (see ProviderFailureSupport::unitFailureMessages()). */ private function runTargetedRetry( StructuredCallerInterface $caller, array $ctx, array $subject_context, array $source_result, array $pending_specs, array $companions, array $voice, array $banned, array $definition, array $conflict_resolution, array $retry_ids, array $retryable_companions, array $sanitized, array $relevant_refs, array $first, float $deadline, array &$usage, array &$findings, array &$decoded_by_id, &$decoded_short, &$decoded_tags, bool $isolated = false ): array { $retry_specs = array_intersect_key( $pending_specs, array_flip( $retry_ids ) ); $retry_companions = array( 'short' => isset( $retryable_companions['short'] ) ? $companions['short'] : null, 'tags' => isset( $retryable_companions['tags'] ) ? $companions['tags'] : null, ); $retry_notes = $this->retryNotesFor( $retry_ids, $sanitized, $pending_specs, $isolated, $subject_context ); $retry_usable = $this->sourceContextBuilder->usableBlocksForRefs( $source_result['blocks'], $relevant_refs ); $retry_compiled = ( new PromptCompiler() )->compile( $this->specBuilder->compilerSpec( $ctx, $subject_context, $retry_usable, $retry_specs, $retry_companions, $voice, $banned, $definition, $retry_notes, $conflict_resolution ) ); $retry_result = $this->callOnce( $caller, $retry_compiled, $ctx, 1, $deadline, $first['provider'] ?? '', $first['model'] ?? '' ); $this->mergeUsage( $usage, $retry_result ); if ( ! $retry_result['ok'] ) { $findings = ProviderFailureSupport::recordTerminalFailure( $findings, (array) ( $retry_result['error'] ?? array() ) ); return $retry_result; } $retry_decoded = $retry_result['decoded']; $retry_match = $this->validator->matchUnits( $retry_decoded['sections'] ?? array(), array_keys( $retry_specs ) ); $findings = array_merge( $findings, $retry_match['findings'] ); foreach ( $retry_match['byId'] as $id => $raw ) { $decoded_by_id[ $id ] = $raw; } if ( isset( $retryable_companions['short'] ) && is_array( $retry_decoded['shortDescription'] ?? null ) ) { $decoded_short = $retry_decoded['shortDescription']; } if ( isset( $retryable_companions['tags'] ) && is_array( $retry_decoded['tags'] ?? null ) ) { $decoded_tags = $retry_decoded['tags']; } return $retry_result; } /** * @param StructuredCallerInterface $caller Structured AI caller. * @param array $compiled PromptCompiler::compile()'s result. * @param array $ctx Execution context. * @param int $max_calls Provider-call budget for this call(). * @param float $deadline Unix deadline. * @param string $provider Provider override (retry call reuses the first call's resolved provider). * @param string $model Model override. * @return array StructuredCallerInterface::call()'s result. */ private function callOnce( StructuredCallerInterface $caller, array $compiled, array $ctx, int $max_calls, float $deadline, string $provider = '', string $model = '' ): array { $request = array( 'provider' => '' !== $provider ? $provider : (string) ( $ctx['runOptions']['provider'] ?? '' ), 'model' => '' !== $model ? $model : (string) ( $ctx['runOptions']['model'] ?? '' ), 'system' => $compiled['system'], 'user' => $compiled['user'], 'schema' => $compiled['schema'], 'schemaName' => $compiled['schemaName'], 'maxCalls' => $max_calls, 'deadline' => $deadline, 'validate' => function ( $decoded ) { return $this->schemaLevelValidate( $decoded ); }, ); return $caller->call( $request ); } /** * Minimal schema-level check used only to decide StructuredCaller's own * whole-answer repair retry. Unit-level checks happen afterward via * OutputValidator. * * @param mixed $decoded Decoded JSON. * @return array{ok:bool,errors:string[]} */ private function schemaLevelValidate( $decoded ): array { if ( ! is_array( $decoded ) || ! isset( $decoded['sections'] ) || ! is_array( $decoded['sections'] ) ) { return array( 'ok' => false, 'errors' => array( __( 'The answer must have a "sections" array.', 'ai-product-tools' ) ) ); } return array( 'ok' => true, 'errors' => array() ); } /** * @param array &$usage Accumulator. * @param array $call_result StructuredCallerInterface::call()'s result. * @return void */ private function mergeUsage( array &$usage, array $call_result ): void { $usage['aiCalls'] += $call_result['calls']; $usage['nativeStructuredOutput'] = $usage['nativeStructuredOutput'] || ! empty( $call_result['native'] ); $usage['provider'] = $call_result['provider']; $usage['model'] = $call_result['model']; $usage['durationMs'] += $call_result['durationMs']; } /** * First validation pass (not final): shape + hard-limit + banned-phrase * checks, collecting which unit ids need the one allowed targeted * retry. Never trims or sentence-cuts here. * * @param array $pending_specs Pending AI unit specs. * @param array $decoded_by_id Matched raw payloads, keyed by id. * @param string[] $banned Merged banned phrases. * @param bool $isolated Whether this round is an isolated-unit-type round (see {@see run()}). * @param array $subject_context This round's subject context (an isolated round's is its type's own context). * @return array{0:array,1:string[]} [sanitized by id, retry ids]. */ private function validateFirstPass( array $pending_specs, array $decoded_by_id, array $banned, bool $isolated = false, array $subject_context = array() ): array { $sanitized = array(); $retry_ids = array(); foreach ( $pending_specs as $id => $spec ) { $raw = $decoded_by_id[ $id ] ?? null; if ( null === $raw ) { $retry_ids[] = $id; continue; } $clean = $this->validator->sanitizeUnit( $raw, $spec['format'] ); $sanitized[ $id ] = $clean; if ( ! $clean['ok'] ) { $retry_ids[] = $id; continue; } if ( 'paragraph' === $spec['format'] ) { $limit = $this->validator->checkHardLimit( $clean['paragraphs'], array( 'targetMin' => $spec['words']['min'], 'targetMax' => $spec['words']['max'], 'hardMax' => $spec['words']['limit'] ), false ); if ( $limit['needsRetry'] ) { $retry_ids[] = $id; continue; } } $plain = $this->plainTextOf( $clean ); if ( ! empty( $this->validator->findBannedPhrases( $plain, $banned ) ) ) { $retry_ids[] = $id; } if ( $isolated && $this->breaksIsolatedContract( (string) ( $spec['type'] ?? '' ), $plain, $subject_context ) ) { $retry_ids[] = $id; } } return array( $sanitized, array_values( array_unique( $retry_ids ) ) ); } /** * Whether an isolated unit's first-pass answer already breaks its type * extension's output contract, worth the same one targeted retry a * banned phrase already gets, before the extension's own findings on * the final pass. * * @param string $type Section type. * @param string $plain Plain text of the (pre-limit) unit. * @param array $subject_context The isolated round's own context. * @return bool */ private function breaksIsolatedContract( string $type, string $plain, array $subject_context ): bool { $extension = $this->isolatedExtension( $type, $subject_context ); return null !== $extension && $extension->breaksContract( $plain, $this->validator ); } /** * The isolated extension for $type, bound to this round's context facts * when it reads them ({@see ContextualIsolatedSectionExtension}). * * @param string $type Section type. * @param array $subject_context The isolated round's own context. * @return IsolatedSectionExtension|null */ private function isolatedExtension( string $type, array $subject_context ): ?IsolatedSectionExtension { $extension = SectionTypeExtensions::isolated( $type ); if ( $extension instanceof ContextualIsolatedSectionExtension ) { return $extension->withFacts( (array) ( $subject_context['facts'] ?? array() ) ); } return $extension; } /** * Final validation pass for every pending unit: resolves each one to * its final plan status/payload, applying list/row trimming, the * hard-limit sentence-trim-or-review fallback, and the still-banned * review finding. * * @param array $pending_specs Pending AI unit specs. * @param array $decoded_by_id Matched raw payloads (post-retry), keyed by id. * @param string[] $banned Merged banned phrases. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param array $subject_context SubjectContextResolver::buildSubjectContext()'s result. * @param array $source_result SourceContextBuilder::build()'s result. * @param array &$plans Section plans, updated in place. * @param array &$findings Findings accumulator, updated in place. * @param array $definition Normalized BlueprintDefinition. * @param array $failure_messages Unit id => the classified provider message responsible for it still being missing (ProviderFailureSupport::unitFailureMessages()); absent for an id whose non-presence is not a classified provider failure. * @param bool $isolated Whether this round is an isolated-unit-type round (see {@see run()}). * @return void */ private function validateFinalPass( array $pending_specs, array $decoded_by_id, array $banned, array $voice, array $subject_context, array $source_result, array &$plans, array &$findings, array $definition, array $failure_messages = array(), bool $isolated = false ): void { foreach ( $pending_specs as $id => $spec ) { $raw = $decoded_by_id[ $id ] ?? null; if ( null === $raw ) { $reason = $failure_messages[ $id ] ?? __( 'The AI provider did not return this section.', 'ai-product-tools' ); $this->resolveFailedUnit( $id, $plans, $findings, $definition, $reason ); continue; } $clean = $this->validator->sanitizeUnit( $raw, $spec['format'] ); if ( ! $clean['ok'] ) { $this->resolveFailedUnit( $id, $plans, $findings, $definition, __( 'The AI answer for this section was not usable.', 'ai-product-tools' ) ); continue; } $findings = array_merge( $findings, $clean['findings'] ); $clean = $this->applyLimits( $id, $spec, $clean, $plans, $findings ); $plain = $this->plainTextOf( $clean ); $this->appendMeasuredFindings( $id, $plain, $spec, $banned, $voice, $subject_context, $source_result, $findings, $isolated ); if ( 'needs_review' !== $plans[ $id ]['status'] ) { $plans[ $id ]['status'] = 'included'; } $plans[ $id ]['payload'] = $clean; if ( $isolated && SectionTypeExtensions::isolated( (string) ( $spec['type'] ?? '' ) ) instanceof ContextualIsolatedSectionExtension ) { $plans[ $id ]['answerFacts'] = (array) ( $subject_context['facts'] ?? array() ); } } } /** * Apply the deterministic item/row trim or the paragraph hard-limit * resolution for one unit, updating `$plans[$id]['status']` to * `needs_review` when the hard limit could not be resolved. * * @param string $id Unit id. * @param array $spec Pending AI unit spec. * @param array $clean sanitizeUnit()'s result. * @param array &$plans Section plans, updated in place. * @param array &$findings Findings accumulator, updated in place. * @return array The (possibly trimmed) clean payload. */ private function applyLimits( string $id, array $spec, array $clean, array &$plans, array &$findings ): array { if ( 'bullets' === $spec['format'] || 'numbered' === $spec['format'] ) { $trim = $this->validator->trimToMax( $clean['items'], $spec['maxItems'] ); $clean['items'] = $trim['values']; if ( $trim['trimmed'] ) { /* translators: %1$d: configured item limit. %2$d: number of items the model actually returned. */ $findings[] = $this->validator->finding( 'items_trimmed', 'warning', sprintf( __( 'Kept the first %1$d of %2$d items the model returned.', 'ai-product-tools' ), $spec['maxItems'], $trim['available'] ), $id ); } } elseif ( 'table' === $spec['format'] && $spec['maxItems'] > 0 ) { $trim = $this->validator->trimToMax( $clean['rows'], $spec['maxItems'] ); $clean['rows'] = $trim['values']; if ( $trim['trimmed'] ) { /* translators: %1$d: configured row limit. %2$d: number of rows the model actually returned. */ $findings[] = $this->validator->finding( 'items_trimmed', 'warning', sprintf( __( 'Kept the first %1$d of %2$d rows the model returned.', 'ai-product-tools' ), $spec['maxItems'], $trim['available'] ), $id ); } } elseif ( 'paragraph' === $spec['format'] ) { $limit = $this->validator->checkHardLimit( $clean['paragraphs'], array( 'targetMin' => $spec['words']['min'], 'targetMax' => $spec['words']['max'], 'hardMax' => $spec['words']['limit'] ), true ); $clean['paragraphs'] = $limit['paragraphs']; foreach ( $limit['findings'] as $finding ) { $finding['unitId'] = $id; $findings[] = $finding; } if ( $limit['overLimit'] ) { $plans[ $id ]['status'] = 'needs_review'; } } return $clean; } /** * @param string $id Unit id. * @param string $plain Plain text of the (post-limit) unit. * @param array $spec Pending AI unit spec. * @param string[] $banned Merged banned phrases. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param array $subject_context SubjectContextResolver::buildSubjectContext()'s result. * @param array $source_result SourceContextBuilder::build()'s result. * @param array &$findings Findings accumulator, updated in place. * @param bool $isolated Whether this round is an isolated-unit-type round (see {@see run()}): its type extension's findings replace the normal warning-only number check. * @return void */ private function appendMeasuredFindings( string $id, string $plain, array $spec, array $banned, array $voice, array $subject_context, array $source_result, array &$findings, bool $isolated = false ): void { $still_banned = $this->validator->findBannedPhrases( $plain, $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 section still uses a banned phrase: %s.', 'ai-product-tools' ), implode( ', ', $still_banned ) ), $id ); } $preferred_hits = $this->validator->findPreferredTermHits( $plain, $voice['preferred'] ?? array() ); if ( ! empty( $preferred_hits ) ) { $pair = $preferred_hits[0]; /* translators: %1$s: the preferred term. %2$s: the term to avoid. */ $findings[] = $this->validator->finding( 'terminology', 'warning', sprintf( __( 'Use "%1$s" instead of "%2$s".', 'ai-product-tools' ), $pair['use'], $pair['insteadOf'] ), $id ); } $extension = $isolated ? $this->isolatedExtension( (string) ( $spec['type'] ?? '' ), $subject_context ) : null; if ( null !== $extension ) { foreach ( $extension->findings( $id, $plain, $this->validator ) as $finding ) { $findings[] = $finding; } return; } $available_numbers = array_merge( $subject_context['numericTokens'], $this->numericTokensFor( $spec['sources'], $source_result['blocks'] ) ); $unsupported = $this->validator->findUnsupportedNumbers( $plain, $available_numbers ); if ( ! empty( $unsupported ) ) { /* translators: %s: comma-separated numeric tokens not found in the supplied context. */ $findings[] = $this->validator->finding( 'unsupported_number', 'warning', sprintf( __( 'This section mentions a number not found in the provided context: %s.', 'ai-product-tools' ), implode( ', ', $unsupported ) ), $id ); } } /** * @param string $id Unit id. * @param array &$plans Section plans, updated in place. * @param array &$findings Findings accumulator, updated in place. * @param array $definition Normalized BlueprintDefinition. * @param string $reason Human-readable reason. * @return void */ private function resolveFailedUnit( string $id, array &$plans, array &$findings, array $definition, string $reason ): void { $required_failure = $definition['rules']['requiredFailure'] ?? 'review'; $section_missing = $plans[ $id ]['sectionMissingPolicy'] ?? null; if ( 'partial' === $required_failure && 'skip' === $section_missing ) { $plans[ $id ]['status'] = 'skipped_missing_data'; $plans[ $id ]['reason'] = $reason; $findings[] = $this->validator->finding( 'unit_failed_dropped', 'warning', $reason, $id ); return; } $plans[ $id ]['status'] = 'failed'; $plans[ $id ]['reason'] = $reason; $findings[] = $this->validator->finding( 'unit_failed', 'review', $reason, $id ); } /** * @param string[] $retry_ids Unit ids needing the targeted retry. * @param array $sanitized sanitizeUnit() results by id (first pass). * @param array $pending_specs Pending AI unit specs by id. * @param bool $isolated Whether this round is an isolated-unit-type round, whose * retry can also come from its type extension's contract. * @param array $subject_context This round's subject context (an isolated round's is its type's own context). * @return array Unit id => short reason, for the retry prompt. */ private function retryNotesFor( array $retry_ids, array $sanitized, array $pending_specs, bool $isolated = false, array $subject_context = array() ): array { $notes = array(); foreach ( $retry_ids as $id ) { $clean = $sanitized[ $id ] ?? null; $type = (string) ( $pending_specs[ $id ]['type'] ?? '' ); $extension = $isolated ? $this->isolatedExtension( $type, $subject_context ) : null; if ( null === $clean || empty( $clean['ok'] ) ) { $notes[ $id ] = __( 'missing or in the wrong shape', 'ai-product-tools' ); } elseif ( null !== $extension && $extension->breaksContract( $this->plainTextOf( $clean ), $this->validator ) ) { $notes[ $id ] = $extension->retryNote(); } else { $notes[ $id ] = __( 'over its hard word limit or still used a banned phrase', 'ai-product-tools' ); } } return $notes; } /** * @param array $clean sanitizeUnit()'s (post-limit) result. * @return string */ private function plainTextOf( array $clean ): string { if ( ! empty( $clean['paragraphs'] ) ) { return implode( ' ', $clean['paragraphs'] ); } if ( ! empty( $clean['items'] ) ) { return implode( ' ', $clean['items'] ); } if ( ! empty( $clean['rows'] ) ) { return implode( ' ', array_map( static function ( $row ) { return ( $row['label'] ?? '' ) . ' ' . ( $row['value'] ?? '' ); }, $clean['rows'] ) ); } return ''; } /** * @param string[] $refs A unit's allowed source refs. * @param array $source_blocks SourceContextBuilder::build()'s `blocks`. * @return string[] */ private function numericTokensFor( array $refs, array $source_blocks ): array { $tokens = array(); foreach ( $this->sourceContextBuilder->usableBlocksForRefs( $source_blocks, $refs ) as $block ) { $tokens = array_merge( $tokens, TextMetrics::numericTokens( (string) $block['text'] ) ); } return $tokens; } /** * Apply the decoded companion payloads (shortDescription/tags) into a * synthetic plan entry each, so rendering/outputs treat them uniformly. * * @param array|null $decoded_short Decoded shortDescription object, or null. * @param array|null $decoded_tags Decoded tags array, or null. * @param array $companions PromptSpecBuilder::companionSpecs()'s result. * @param array &$plans Section plans, updated in place (adds synthetic entries). * @param array &$findings Findings accumulator, updated in place. * @param string[] $banned Merged banned phrases. * @param bool $want_short Whether a short description was requested. * @param bool $want_tags Whether tags were requested. * @param array $failure_messages Unit id => the classified provider message responsible for it still being missing (ProviderFailureSupport::unitFailureMessages()); see validateFinalPass(). * @return void */ private function applyCompanionResults( ?array $decoded_short, ?array $decoded_tags, array $companions, array &$plans, array &$findings, array $banned, bool $want_short, bool $want_tags, array $failure_messages = array() ): void { if ( $want_short ) { $this->applyShortDescriptionResult( $decoded_short, $companions, $plans, $findings, $banned, $failure_messages['companion_short_description'] ?? null ); } if ( $want_tags ) { $this->applyTagsResult( $decoded_tags, $companions, $plans, $findings, $failure_messages['companion_tags'] ?? null ); } } /** * Whether a decoded short description passes the unit check that * applyShortDescriptionResult() applies to the final answer. * * @param array $decoded_short Decoded shortDescription object. * @param array $companions PromptSpecBuilder::companionSpecs()'s result. * @return bool */ private function isUsableShortDescription( array $decoded_short, array $companions ): bool { $clean = $this->validator->sanitizeUnit( array( 'heading' => '' ) + $decoded_short, $companions['short']['format'] ?? 'paragraph' ); return (bool) $clean['ok']; } /** * @param array|null $decoded_short Decoded shortDescription object, or null. * @param array $companions PromptSpecBuilder::companionSpecs()'s result. * @param array &$plans Section plans, updated in place. * @param array &$findings Findings accumulator, updated in place. * @param string[] $banned Merged banned phrases. * @param string|null $provider_message The classified provider message responsible for this companion still being missing, when `$decoded_short` is null because its own call failed; null otherwise. * @return void */ private function applyShortDescriptionResult( ?array $decoded_short, array $companions, array &$plans, array &$findings, array $banned, ?string $provider_message = null ): void { $spec_format = $companions['short']['format'] ?? 'paragraph'; if ( null === $decoded_short ) { $reason = $provider_message ?? __( 'The AI did not return a short description.', 'ai-product-tools' ); $plans['companion_short_description'] = array( 'status' => 'failed', 'reason' => $reason, 'needsModelCall' => true ); $findings[] = $this->validator->finding( 'unit_failed', 'review', $reason, 'companion_short_description' ); return; } $clean = $this->validator->sanitizeUnit( array( 'heading' => '' ) + $decoded_short, $spec_format ); if ( ! $clean['ok'] ) { $plans['companion_short_description'] = array( 'status' => 'failed', 'reason' => __( 'The short description answer was not usable.', 'ai-product-tools' ), 'needsModelCall' => true ); $findings[] = $this->validator->finding( 'unit_failed', 'review', __( 'The short description answer was not usable.', 'ai-product-tools' ), 'companion_short_description' ); return; } $banned_hit = $this->validator->findBannedPhrases( $this->plainTextOf( $clean ), $banned ); if ( ! empty( $banned_hit ) ) { /* translators: %s: comma-separated banned phrases still present in the short description. */ $findings[] = $this->validator->finding( 'banned_phrase', 'review', sprintf( __( 'The short description still uses a banned phrase: %s.', 'ai-product-tools' ), implode( ', ', $banned_hit ) ), 'companion_short_description' ); } $plans['companion_short_description'] = array( 'status' => 'included', 'reason' => '', 'needsModelCall' => true, 'payload' => $clean ); } /** * @param array|null $decoded_tags Decoded tags array, or null. * @param array $companions PromptSpecBuilder::companionSpecs()'s result. * @param array &$plans Section plans, updated in place. * @param array &$findings Findings accumulator, updated in place. * @param string|null $provider_message The classified provider message responsible for these tags still being missing, when `$decoded_tags` is null because its own call failed; null otherwise. * @return void */ private function applyTagsResult( ?array $decoded_tags, array $companions, array &$plans, array &$findings, ?string $provider_message = null ): void { if ( null === $decoded_tags ) { $reason = $provider_message ?? __( 'The AI did not return tags.', 'ai-product-tools' ); $plans['companion_tags'] = array( 'status' => 'failed', 'reason' => $reason, 'needsModelCall' => true ); $findings[] = $this->validator->finding( 'unit_failed', 'review', $reason, 'companion_tags' ); return; } $existing_tags = isset( $companions['tags']['existingTags'] ) && is_array( $companions['tags']['existingTags'] ) ? $companions['tags']['existingTags'] : array(); $plans['companion_tags'] = array( 'status' => 'included', 'reason' => '', 'needsModelCall' => true, 'payload' => array( 'tags' => TagListSanitizer::sanitize( $decoded_tags, (int) ( $companions['tags']['max'] ?? 10 ), $existing_tags ) ) ); } }