renderer = new Renderer(); $this->checks = new Checks(); $this->validator = new OutputValidator(); $this->sourceContextBuilder = new SourceContextBuilder(); $this->specBuilder = new PromptSpecBuilder(); } /** * @param array $ctx Execution context. * @param array[] $sections Sections. * @param array $plans Final per-section plans. * @param array $subject_context SubjectContextResolver::buildSubjectContext()'s result. * @param array $definition Normalized BlueprintDefinition. * @param array $source_result SourceContextBuilder::build()'s result. * @param string[] $banned Merged banned phrases. * @param array $voice BrandVoiceCompiler::compile()'s result. * @param array $usage Usage accumulator. * @param array $findings Findings accumulated during generation. * @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} */ public function assemble( array $ctx, array $sections, array $plans, array $subject_context, array $definition, array $source_result, array $banned, array $voice, array $usage, array $findings, ?array $previous = null ): array { $heading_level = (string) ( $definition['rules']['headingLevel'] ?? 'h2' ); $blueprint_items = $definition['sources']['items'] ?? array(); $units = array(); $checks = array( $this->checks->sectionOrder( array_column( $sections, 'id' ) ) ); $rendered_texts = array(); $all_text_parts = array(); foreach ( $sections as $section ) { $id = $section['id']; $plan = $plans[ $id ]; $unit = $this->renderUnit( $section, $plan, $heading_level, $blueprint_items ); if ( null !== $previous ) { $unit = $this->reuseOrRender( $previous, $id, $unit, $plan ); } $units[] = $unit; $checks[] = $this->checkForSection( $section, $unit ); if ( in_array( $unit['status'], array( 'included', 'fallback' ), true ) ) { if ( null === SectionTypeExtensions::data( (string) $unit['type'] ) || ! empty( $unit['usedFallback'] ) ) { $rendered_texts[ $unit['id'] ] = $unit['text']; } $all_text_parts[] = $unit['text']; } } $companion_units = $this->renderCompanions( $plans, $all_text_parts, $previous ); foreach ( $companion_units as $companion_unit ) { if ( in_array( $companion_unit['status'], array( 'included', 'fallback' ), true ) ) { $checks[] = $this->checkForCompanion( $companion_unit, $definition ); } else { $checks[] = $this->checks->statusNote( $companion_unit['id'], $companion_unit['name'], $companion_unit['status'], $companion_unit['reason'] ); } } $units = array_merge( $units, $companion_units ); $all_text = implode( ' ', $all_text_parts ); $checks[] = $this->checks->bannedPhrases( $this->validator->findBannedPhrases( $all_text, $banned ) ); $terminology_check = $this->checks->terminology( $this->validator->findPreferredTermHits( $all_text, $voice['preferred'] ?? array() ) ); if ( null !== $terminology_check ) { $checks[] = $terminology_check; } $duplicate_findings = $this->checks->duplicateSentences( $rendered_texts ); $findings = array_merge( $findings, $duplicate_findings ); $provider_error = ProviderFailureSupport::providerErrorFromFindings( $findings ); $provider_error = ProviderFailureSupport::carryForwardProviderError( $units, $provider_error, $previous ); $findings = ProviderFailureSupport::applyAiOutcomeRules( $units, $findings, $provider_error ); $conflicts = $this->computeConflicts( $ctx, $subject_context, $source_result, $definition, $sections, $plans, $blueprint_items ); $eligibility = $this->checks->eligibility( $findings, $conflicts ); $outputs = $this->buildOutputs( (string) ( $ctx['generator'] ?? '' ), $units ); return array( 'units' => $units, 'outputs' => $outputs, 'checks' => $checks, 'conflicts' => $conflicts, 'findings' => $findings, 'sourcesUsed' => $source_result['sourcesUsed'], 'eligibility' => $eligibility, 'usage' => $usage, 'providerError' => $provider_error, ); } /** * @param array $previous regenerateUnit()'s previous slice. * @param string $id Unit id. * @param array $unit Freshly rendered unit (for the one regenerated id). * @param array $plan This unit's plan. * @return array */ private function reuseOrRender( array $previous, string $id, array $unit, array $plan ): array { if ( ! empty( $plan['regenerated'] ) ) { $unit['regenerated'] = true; return $unit; } $previous_unit = $this->findUnitById( (array) ( $previous['units'] ?? array() ), $id ); return null !== $previous_unit ? $previous_unit : $unit; } /** * @param array[] $units Rendered units. * @param string $id Unit id to find. * @return array|null */ private function findUnitById( array $units, string $id ): ?array { foreach ( $units as $unit ) { if ( ( $unit['id'] ?? '' ) === $id ) { return $unit; } } return null; } /** * @param array $section Normalized BlueprintSection. * @param array $plan Final plan for this section. * @param string $heading_level 'h2' | 'h3' | 'h4'. * @param array $blueprint_items BlueprintSourcePolicy.items. * @return array UnitResult-shaped array. */ private function renderUnit( array $section, array $plan, string $heading_level, array $blueprint_items ): array { $status = $plan['status']; $source_refs = $this->sourceContextBuilder->refsForSection( $section['sources'] ?? array( 'inherit' => true, 'refs' => array() ), $blueprint_items ); $base = array( 'id' => $section['id'], 'kind' => 'section', 'type' => $section['type'], 'name' => $section['name'], 'mode' => $section['mode'], 'format' => $section['format'], 'status' => $status, 'reason' => $plan['reason'] ?? '', 'missingFields' => $plan['missingFields'] ?? array(), 'sourceRefs' => $source_refs, 'findings' => array(), 'requestedFromProvider' => (bool) ( $plan['needsModelCall'] ?? false ), ); if ( ! in_array( $status, array( 'included', 'fallback' ), true ) ) { return $base + array( 'heading' => '', 'html' => '', 'text' => '', 'items' => array(), 'rows' => array(), 'wordCount' => 0, 'charCount' => 0, 'itemCount' => 0, 'usedFallback' => false, 'regenerated' => false, ); } $payload = 'fallback' === $status ? array( 'paragraphs' => array( (string) ( $section['missing']['fallbackText'] ?? '' ) ) ) : $this->payloadFor( $section, $plan ); $render_section = 'fallback' === $status ? array( 'format' => 'paragraph' ) + $section : $section; $rendered = $this->renderer->renderSection( $render_section, $payload, $heading_level ); return $base + array( 'heading' => $rendered['heading'], 'html' => $rendered['html'], 'text' => $rendered['text'], 'items' => $rendered['items'], 'rows' => $rendered['rows'], 'wordCount' => TextMetrics::wordCount( $rendered['text'] ), 'charCount' => TextMetrics::charCount( $rendered['text'] ), 'itemCount' => count( $rendered['items'] ) + count( $rendered['rows'] ), 'usedFallback' => 'fallback' === $status, 'regenerated' => ! empty( $plan['regenerated'] ), ); } /** * @param array $section Normalized BlueprintSection. * @param array $plan Final plan for this section. * @return array {heading?,paragraphs?,items?,rows?} */ private function payloadFor( array $section, array $plan ): array { if ( 'ai' === $section['mode'] ) { $clean = $plan['payload'] ?? array( 'heading' => '', 'paragraphs' => array(), 'items' => array(), 'rows' => array() ); $payload = array( 'heading' => $clean['heading'] ?? '', 'paragraphs' => $clean['paragraphs'] ?? array(), 'items' => $clean['items'] ?? array(), 'rows' => $clean['rows'] ?? array() ); if ( is_array( $plan['answerFacts'] ?? null ) ) { $payload['answerFacts'] = $plan['answerFacts']; } return $payload; } if ( null !== SectionTypeExtensions::data( (string) ( $section['type'] ?? '' ) ) ) { return array( 'extension' => is_array( $plan['extensionData'] ?? null ) ? $plan['extensionData'] : array() ); } $resolved = $plan['resolvedFields'] ?? array(); if ( 'table' === $section['format'] ) { return array( 'rows' => $this->dataRows( $resolved ) ); } return array( 'items' => $this->dataItems( $resolved ) ); } /** * @param array $resolved_fields ref => {type,value,empty,label?}. * @return array */ private function dataRows( array $resolved_fields ): array { $rows = array(); foreach ( $resolved_fields as $resolved ) { if ( ! empty( $resolved['empty'] ) ) { continue; } $rows[] = array( 'label' => (string) ( $resolved['label'] ?? '' ), 'value' => $this->scalarText( $resolved ) ); } return $rows; } /** * @param array $resolved_fields ref => {type,value,empty,label?}. * @return string[] */ private function dataItems( array $resolved_fields ): array { $items = array(); foreach ( $resolved_fields as $resolved ) { if ( ! empty( $resolved['empty'] ) ) { continue; } $items[] = trim( ( $resolved['label'] ?? '' ) . ': ' . $this->scalarText( $resolved ) ); } return $items; } /** * @param array $resolved {type,value,empty}. * @return string */ private function scalarText( array $resolved ): string { if ( 'list' === ( $resolved['type'] ?? '' ) ) { return implode( ', ', array_map( 'strval', (array) $resolved['value'] ) ); } if ( 'pairs' === ( $resolved['type'] ?? '' ) ) { return $this->pairsText( (array) ( $resolved['value'] ?? array() ) ); } return (string) ( $resolved['value'] ?? '' ); } /** * Render a FieldCatalog `pairs` value (e.g. `core:attributes`, * `term:common_attributes`) as "label: value" facts, the same join * `FieldContextTrait::composeFieldContext()` already uses for the * AI-facing context — without this, `(string) $resolved['value']` casts * the pairs array to the literal string "Array". * * @param array $pairs Array<{label,value}>. * @return string */ private function pairsText( array $pairs ): string { $parts = array(); foreach ( $pairs as $pair ) { $pair_label = is_array( $pair ) ? (string) ( $pair['label'] ?? '' ) : ''; $pair_value = is_array( $pair ) ? (string) ( $pair['value'] ?? '' ) : ''; if ( '' === $pair_label || '' === $pair_value ) { continue; } $parts[] = $pair_label . ': ' . $pair_value; } return implode( ', ', $parts ); } /** * A companion (Short description, Tags) only gets a plan entry when the * current round actually requested it (`PromptSpecBuilder:: * companionSpecs()`/`GenerationRoundRunner::applyCompanionResults()`). * `regenerateUnit()` never requests companions for its single-section * round, so without this reuse path they would silently vanish from the * result the client then saves over the previous one * (`retry-companions-dropped`). When a plan key IS present (a full * `generate()` run, with or without companions requested this time), * behavior is unchanged from before. * * @param array $plans Final plans (including synthetic companion entries). * @param string[] &$all_text_parts Accumulator of renderable plain text, updated in place. * @param array|null $previous regenerateUnit()'s previous slice, when regenerating. * @return array[] */ private function renderCompanions( array $plans, array &$all_text_parts, ?array $previous ): array { $units = array(); if ( isset( $plans['companion_short_description'] ) ) { $units[] = $this->renderShortDescriptionCompanion( $plans['companion_short_description'], $all_text_parts ); } elseif ( null !== $previous ) { $reused = $this->reusePreviousCompanion( $previous, 'companion_short_description', $all_text_parts ); if ( null !== $reused ) { $units[] = $reused; } } if ( isset( $plans['companion_tags'] ) ) { $units[] = $this->renderTagsCompanion( $plans['companion_tags'] ); } elseif ( null !== $previous ) { $reused = $this->findUnitById( (array) ( $previous['units'] ?? array() ), 'companion_tags' ); if ( null !== $reused ) { $units[] = $reused; } } return $units; } /** * Reuse a previous run's Short description companion verbatim, feeding * its text back into the duplicate-sentence/banned-phrase text pool the * same way a freshly rendered one would (`renderShortDescriptionCompanion()`): * a regenerate must stay indistinguishable from "this companion simply * was not touched this time". * * @param array $previous regenerateUnit()'s previous slice. * @param string $id Companion unit id. * @param string[] &$all_text_parts Accumulator of renderable plain text, updated in place. * @return array|null */ private function reusePreviousCompanion( array $previous, string $id, array &$all_text_parts ): ?array { $reused = $this->findUnitById( (array) ( $previous['units'] ?? array() ), $id ); if ( null === $reused ) { return null; } if ( 'included' === ( $reused['status'] ?? '' ) ) { $all_text_parts[] = $reused['text']; } return $reused; } /** * @param array $plan The `companion_short_description` plan entry. * @param string[] &$all_text_parts Accumulator of renderable plain text, updated in place. * @return array UnitResult-shaped array. */ private function renderShortDescriptionCompanion( array $plan, array &$all_text_parts ): array { $payload = $plan['payload'] ?? array( 'paragraphs' => array(), 'items' => array() ); $text = ! empty( $payload['paragraphs'] ) ? implode( "\n\n", $payload['paragraphs'] ) : implode( "\n", (array) ( $payload['items'] ?? array() ) ); if ( 'included' === $plan['status'] ) { $all_text_parts[] = $text; } return array( 'id' => 'companion_short_description', 'kind' => 'companion', 'type' => 'short_description', 'name' => __( 'Short description', 'ai-product-tools' ), 'mode' => 'ai', 'format' => ! empty( $payload['items'] ) ? 'bullets' : 'paragraph', 'status' => $plan['status'], 'reason' => $plan['reason'] ?? '', 'heading' => '', 'html' => '', 'text' => $text, 'items' => (array) ( $payload['items'] ?? array() ), 'rows' => array(), 'wordCount' => TextMetrics::wordCount( $text ), 'charCount' => TextMetrics::charCount( $text ), 'itemCount' => count( (array) ( $payload['items'] ?? array() ) ), 'missingFields' => array(), 'usedFallback' => false, 'regenerated' => false, 'sourceRefs' => array( 'product' ), 'findings' => array(), 'requestedFromProvider' => (bool) ( $plan['needsModelCall'] ?? true ), ); } /** * @param array $plan The `companion_tags` plan entry. * @return array UnitResult-shaped array. */ private function renderTagsCompanion( array $plan ): array { $tags = $plan['payload']['tags'] ?? array(); return array( 'id' => 'companion_tags', 'kind' => 'companion', 'type' => 'tags', 'name' => __( 'Tags', 'ai-product-tools' ), 'mode' => 'ai', 'format' => 'bullets', 'status' => $plan['status'], 'reason' => $plan['reason'] ?? '', 'heading' => '', 'html' => '', 'text' => implode( ', ', $tags ), 'items' => $tags, 'rows' => array(), 'wordCount' => 0, 'charCount' => 0, 'itemCount' => count( $tags ), 'missingFields' => array(), 'usedFallback' => false, 'regenerated' => false, 'sourceRefs' => array( 'product' ), 'findings' => array(), 'requestedFromProvider' => (bool) ( $plan['needsModelCall'] ?? true ), ); } /** * Build this section's measured check against its OWN configured * target/limit (not the unit's already-measured value against itself, * which would trivially always pass). * * @param array $section Normalized BlueprintSection. * @param array $unit Its rendered UnitResult-shaped array. * @return array MeasuredCheck. */ private function checkForSection( array $section, array $unit ): array { if ( 'included' !== $unit['status'] ) { return $this->checks->statusNote( $unit['id'], $unit['name'], $unit['status'], $unit['reason'] ); } if ( 'fixed' === $section['mode'] ) { return $this->checks->fixedTextIdentity( $unit['id'], $unit['name'] ); } if ( 'data' === $section['mode'] ) { $present = $unit['itemCount']; $total = $present + count( $unit['missingFields'] ); return $this->checks->dataFields( $unit['id'], $unit['name'], $present, $total, array() ); } if ( 'paragraph' === $section['format'] ) { return $this->checks->wordTarget( $unit['id'], $unit['name'], $unit['wordCount'], (int) $section['length']['targetMin'], (int) $section['length']['targetMax'] ); } return $this->checks->itemLimit( $unit['id'], $unit['name'], $unit['itemCount'], (int) $section['items']['max'] ); } /** * A companion's own measured check on success, the same kind of row an * ordinary section gets from `checkForSection()`: a paragraph short * description against its configured word target, a bullet one and the * tags against their configured item limit (the prompt asks for bullets * by count, not by words). Companions never carry a 'fallback' status * (see `renderCompanions()`'s docblock), so this only ever runs for * 'included'. * * @param array $companion_unit Rendered companion UnitResult. * @param array $definition Normalized BlueprintDefinition. * @return array MeasuredCheck. */ private function checkForCompanion( array $companion_unit, array $definition ): array { $companions = isset( $definition['structure']['companions'] ) && is_array( $definition['structure']['companions'] ) ? $definition['structure']['companions'] : array(); if ( 'short_description' === $companion_unit['type'] ) { $short = isset( $companions['shortDescription'] ) && is_array( $companions['shortDescription'] ) ? $companions['shortDescription'] : array(); if ( 'bullets' === ( $short['format'] ?? 'paragraph' ) ) { return $this->checks->itemLimit( $companion_unit['id'], $companion_unit['name'], $companion_unit['itemCount'], (int) ( $short['items']['max'] ?? 0 ) ); } $length = isset( $short['length'] ) && is_array( $short['length'] ) ? $short['length'] : array(); return $this->checks->wordTarget( $companion_unit['id'], $companion_unit['name'], $companion_unit['wordCount'], (int) ( $length['targetMin'] ?? 0 ), (int) ( $length['targetMax'] ?? 0 ) ); } $max = (int) ( $companions['tags']['max'] ?? 0 ); return $this->checks->itemLimit( $companion_unit['id'], $companion_unit['name'], $companion_unit['itemCount'], $max ); } /** * @param string $generator Generator key. * @param array[] $units Rendered units. * @return array */ private function buildOutputs( string $generator, array $units ): array { $html_parts = array(); $short_text = ''; $tags = array(); foreach ( $units as $unit ) { if ( ! in_array( $unit['status'], array( 'included', 'fallback' ), true ) ) { continue; } if ( 'companion' === $unit['kind'] && 'short_description' === $unit['type'] ) { $short_text = $unit['text']; continue; } if ( 'companion' === $unit['kind'] && 'tags' === $unit['type'] ) { $tags = $unit['items']; continue; } $html_parts[] = $unit['html']; } $body = implode( '', $html_parts ); if ( Generators::TAXONOMY === $generator ) { return array( 'termDescription' => $body ); } $outputs = array( 'description' => $body ); if ( '' !== $short_text ) { $outputs['shortDescription'] = $short_text; } if ( ! empty( $tags ) ) { $outputs['tags'] = $tags; } return $outputs; } /** * @param array $ctx Execution context. * @param array $subject_context SubjectContextResolver::buildSubjectContext()'s result. * @param array $source_result SourceContextBuilder::build()'s result. * @param array $definition Normalized BlueprintDefinition. * @param array[] $sections Sections. * @param array $plans Final plans. * @param array $blueprint_items BlueprintSourcePolicy.items. * @return array[] SourceConflict list. */ private function computeConflicts( array $ctx, array $subject_context, array $source_result, array $definition, array $sections, array $plans, array $blueprint_items ): array { $resolution = $this->specBuilder->resolveConflicts( $ctx, $subject_context, $source_result['blocks'], $definition, $blueprint_items ); $conflicts = $resolution['conflicts']; foreach ( $conflicts as $index => $conflict ) { $conflicts[ $index ]['usedByUnits'] = $this->unitsUsingField( $sections, $plans, $blueprint_items ); } return $conflicts; } /** * Units "using" a resolved field: every rendered unit whose allowed * sources include `'product'` and which is not itself skipped/disabled. * This is a labelled heuristic, not an exact trace of which words a * model actually used. * * @param array[] $sections Sections. * @param array $plans Final plans. * @param array $blueprint_items BlueprintSourcePolicy.items. * @return string[] */ private function unitsUsingField( array $sections, array $plans, array $blueprint_items ): array { $used_ids = array(); foreach ( $sections as $section ) { $plan = $plans[ $section['id'] ] ?? array( 'status' => 'disabled' ); if ( ! in_array( $plan['status'], array( 'included', 'fallback', 'needs_review' ), true ) ) { continue; } $refs = $this->sourceContextBuilder->refsForSection( $section['sources'] ?? array( 'inherit' => true, 'refs' => array() ), $blueprint_items ); if ( in_array( 'product', $refs, true ) ) { $used_ids[] = $section['id']; } } return $used_ids; } }