$code, 'severity' => 'review', 'message' => $message, ); if ( null !== $unit_id ) { $finding['unitId'] = $unit_id; } $finding['data'] = array( 'providerFailure' => true, 'dedupeKey' => $dedupe, 'reason' => $reason, 'provider' => (string) ( $error['provider'] ?? '' ), ); $findings[] = $finding; return $findings; } /** * The merchant-facing message to show for the ONE unit a classified * provider failure actually broke, instead of a generator's own generic * "the AI did not return X" sentence - the real cause (e.g. "Your Gemini * account has no quota or credit left. Check your billing with the * provider.") rather than a restatement that the answer was missing. * Null for anything that is NOT a classified provider failure - a * successful call, or a failure whose `reason` is empty, a bare copy of * `code`, or the classifier's own 'internal_error' fallback - so the * caller keeps its own generic text. * * @param array|null $error StructuredCallerInterface::call()'s `error` shape, or null when the call succeeded. * @return string|null */ public static function classifiedFailureMessage( ?array $error ): ?string { if ( null === $error ) { return null; } $reason = (string) ( $error['reason'] ?? '' ); if ( ! ProviderCallException::isKnownReason( $reason ) ) { return null; } $message = (string) ( $error['message'] ?? '' ); return '' !== $message ? $message : null; } /** * Attribute every id in `$ids` to the classified provider message * responsible for it STILL having no usable content, from one * generation round's call shape: one whole-batch `$first` call covering * every id, then, only for ids still unresolved after it, at most one * targeted `$retry` covering exactly `$retried_ids`. Every formula * generator's round, and GenerationRoundRunner's, shares this exact * shape; a single image's own one-call-plus-retry in * ImageAltGenerator's vision path fits it too, with both id lists * holding just that one image's own unit id. * * An id's OWN LAST ATTEMPT wins: the retry's outcome for an id * `$retried_ids` covers (attributing the retry's own classified message, * or clearing any attribution the first call left behind because the * retry succeeded), the first call's otherwise. An id left out of the * returned map had no classified failure attributable to it, so the * caller keeps its own generic "the AI did not return X" text for it. * * @param array $first The round's first StructuredCallerInterface::call() result. * @param string[] $ids Every id `$first` was asked to resolve. * @param array|null $retry The round's targeted retry call() result, or null when no retry was attempted. * @param string[] $retried_ids Ids actually covered by `$retry` (a subset of `$ids`); ignored when `$retry` is null. * @return array id => merchant message. */ public static function unitFailureMessages( array $first, array $ids, ?array $retry = null, array $retried_ids = array() ): array { $messages = array(); $first_message = ! empty( $first['ok'] ) ? null : self::classifiedFailureMessage( (array) ( $first['error'] ?? array() ) ); if ( null !== $first_message ) { foreach ( $ids as $id ) { $messages[ $id ] = $first_message; } } if ( null === $retry ) { return $messages; } $retry_message = ! empty( $retry['ok'] ) ? null : self::classifiedFailureMessage( (array) ( $retry['error'] ?? array() ) ); foreach ( $retried_ids as $id ) { if ( null !== $retry_message ) { $messages[ $id ] = $retry_message; } else { unset( $messages[ $id ] ); } } return $messages; } /** * The run's top-level `providerError`: the first terminal provider * failure {@see recordTerminalFailure()} recorded this run, or null. * * `runWide` is true when later calls to the same provider would fail the * same way (ProviderCallException::RUN_WIDE_REASONS), so a page running * a batch stops instead of sending the next product. `helpUrl` is the * documentation section for the reason (ProviderCallException::helpUrl()). * * @param array $findings Findings accumulated for this run. * @return array{code:string,reason:string,message:string,provider:string,runWide:bool,helpUrl:string}|null */ public static function providerErrorFromFindings( array $findings ): ?array { foreach ( $findings as $finding ) { if ( ! empty( $finding['data']['providerFailure'] ) ) { $reason = (string) ( $finding['data']['reason'] ?? '' ); return array( 'code' => (string) ( $finding['code'] ?? '' ), 'reason' => $reason, 'message' => (string) ( $finding['message'] ?? '' ), 'provider' => (string) ( $finding['data']['provider'] ?? '' ), 'runWide' => ProviderCallException::isRunWideReason( $reason ), 'helpUrl' => ProviderCallException::helpUrl( $reason ), ); } } return null; } /** * Apply the shared all-AI-failed rule and the regenerate-safe "still * unresolved" backstop, from a generator's OWN finished `units`. * * Reading the FINAL status of every unit (whether freshly resolved this * round or reused verbatim from a previous result) rather than * re-deriving it from this round's pending ids means a * `regenerateUnit()` call's fresh, round-local `$findings` can never lose * the eligibility effect of a reused sibling that is still not usable. * * The "still needs review" backstop runs over EVERY unit regardless of * `mode`: a `data`- or `fixed`-mode unit stuck at `needs_review` by the * merchant's own "flag for review" policy is just as unresolved as a * failed AI call, and must not go unflagged merely because it was never * AI-sourced. The AI_MODES filter instead scopes the SEPARATE * requested/succeeded tally that drives the all-AI-failed rule, since * that count is specifically about AI-sourced content. * * @param array $units Final rendered UnitResult-shaped units (every kind: sections, companions, tokens, parts, groups, images). * @param array $findings Findings accumulated so far. * @param array|null $provider_error {@see providerErrorFromFindings()}'s result, appended to the blocking message when known. * @return array Findings, with a backstop review finding per still-unresolved unit and, when every unit the model was actually asked for failed, one `ai_generation_failed` blocking finding. */ public static function applyAiOutcomeRules( array $units, array $findings, ?array $provider_error ): array { foreach ( $units as $unit ) { if ( self::isExcludedStatus( $unit ) || self::hasUsableContent( $unit ) ) { continue; } $findings = self::flagUnresolvedUnit( $unit, $findings ); } $requested = 0; $succeeded = 0; foreach ( $units as $unit ) { if ( ! self::countsTowardAiOutcome( $unit ) ) { continue; } ++$requested; if ( self::hasUsableContent( $unit ) ) { ++$succeeded; } } if ( $requested > 0 && 0 === $succeeded ) { $findings[] = self::allAiFailedFinding( $provider_error ); } return $findings; } /** * Whether a unit counts toward a run's AI outcome: an AI-mode unit, in a * status that did not opt out of generation, that the model was actually * asked for. Exactly the units applyAiOutcomeRules() weighs before it * reports that no AI content was produced, so a generator explaining * that finding looks at the same units. * * A unit the model was never asked for this run (a data-starved AI * section already resolved by its missing-data policy before any call, * or an image whose attachment never resolved to a URL) cannot have * "failed" the provider: counting it would let the merchant's choice of * missing-data policy alone hard-block an otherwise fine run. * * @param array $unit UnitResult-shaped array. * @return bool */ public static function countsTowardAiOutcome( array $unit ): bool { return in_array( (string) ( $unit['mode'] ?? '' ), self::AI_MODES, true ) && ! self::isExcludedStatus( $unit ) && self::wasRequestedFromProvider( $unit ); } /** * Keep a regenerate from silently losing the previous run's provider * diagnosis: when this round's own findings record no fresh terminal * failure, but the final (reconciled) units still include one the model * was actually asked for and that has no usable content, the run is * still, in effect, suffering the same unresolved failure the merchant * already saw - carry the previous run's `providerError` forward instead * of silently dropping it. * * @param array $units Final rendered units (this round's, reconciled with $previous when regenerating). * @param array|null $current_provider_error This round's own {@see providerErrorFromFindings()} result. * @param array|null $previous regenerateUnit()'s previous slice, when regenerating; null for a full generate(). * @return array|null */ public static function carryForwardProviderError( array $units, ?array $current_provider_error, ?array $previous ): ?array { if ( null !== $current_provider_error || null === $previous ) { return $current_provider_error; } $previous_error = $previous['providerError'] ?? null; if ( null === $previous_error ) { return null; } foreach ( $units as $unit ) { if ( ! in_array( (string) ( $unit['mode'] ?? '' ), self::AI_MODES, true ) ) { continue; } if ( self::isExcludedStatus( $unit ) || self::hasUsableContent( $unit ) ) { continue; } if ( ! self::wasRequestedFromProvider( $unit ) ) { continue; } return $previous_error; } return null; } /** * @param array $unit UnitResult-shaped array. * @return bool Whether this unit's status opted out before (or instead * of) ever producing, or failing to produce, a usable * answer - see {@see EXCLUDED_STATUSES}. */ private static function isExcludedStatus( array $unit ): bool { return in_array( (string) ( $unit['status'] ?? '' ), self::EXCLUDED_STATUSES, true ); } /** * @param array $unit UnitResult-shaped array. * @return bool Whether this unit already has a usable answer: its status * is one `renderUnit()`/the final join step treats as * content-bearing, or it carries non-empty text regardless * (e.g. a flagged-but-has-text unit). */ private static function hasUsableContent( array $unit ): bool { return in_array( (string) ( $unit['status'] ?? '' ), self::CONTENT_STATUSES, true ) || '' !== trim( (string) ( $unit['text'] ?? '' ) ); } /** * Whether the model was actually asked for this unit this run. Absent on * a unit built before this signal existed (every Formula generator * except Image Alt never sets it), which always means "yes" - those * generators have no path where an `ai`-mode unit reaches this far * without a call ever being attempted. * * @param array $unit UnitResult-shaped array. * @return bool */ private static function wasRequestedFromProvider( array $unit ): bool { return (bool) ( $unit['requestedFromProvider'] ?? true ); } /** * Ensure a unit with no usable content carries at least one * review/blocking-severity finding scoped to its id, so eligibility * (which only ever reads `$findings`) can never miss a failure a reused, * round-local unit's own status already records. * * @param array $unit UnitResult-shaped array. * @param array $findings Findings accumulated so far. * @return array */ private static function flagUnresolvedUnit( array $unit, array $findings ): array { $unit_id = (string) ( $unit['id'] ?? '' ); foreach ( $findings as $finding ) { if ( $unit_id === (string) ( $finding['unitId'] ?? '' ) && in_array( (string) ( $finding['severity'] ?? '' ), array( 'review', 'blocking' ), true ) ) { return $findings; } } $reason = '' !== (string) ( $unit['reason'] ?? '' ) ? (string) $unit['reason'] : __( 'This unit needs review before it can be applied.', 'ai-product-tools' ); $findings[] = array( 'code' => 'unit_failed', 'severity' => 'review', 'message' => $reason, 'unitId' => $unit_id, ); return $findings; } /** * @param array|null $provider_error {@see providerErrorFromFindings()}'s result. * @return array */ private static function allAiFailedFinding( ?array $provider_error ): array { $message = __( 'No AI content was produced for this run.', 'ai-product-tools' ); if ( null !== $provider_error && '' !== (string) ( $provider_error['message'] ?? '' ) ) { /* translators: %s: the AI provider's own error message. */ $message = sprintf( __( 'No AI content was produced for this run: %s', 'ai-product-tools' ), (string) $provider_error['message'] ); } return array( 'code' => 'ai_generation_failed', 'severity' => 'blocking', 'message' => $message, ); } }