*/ public static function allowed() { return array( 'accurate', 'outdated', 'inaccurate', 'unverifiable' ); } /** * Severity ranking, worst first. Used for sorting and for picking a winner * when two providers disagree. * * @return array */ public static function severity() { return array( 'inaccurate' => 0, 'outdated' => 1, 'unverifiable' => 2, 'unchecked' => 3, 'accurate' => 4, ); } /** * Coerce a verdict string onto the known set. * * @param string $verdict Raw verdict. * @return string */ public static function normalise( $verdict ) { $verdict = strtolower( trim( (string) $verdict ) ); return in_array( $verdict, self::allowed(), true ) ? $verdict : 'unverifiable'; } /** * The shared instruction block both providers receive. * * @return string */ public static function system_prompt() { return implode( "\n", array( 'You are a fact-checking engine for a publishing workflow. You are given numbered claims taken verbatim from a published article.', 'Search current sources and judge each claim as it stands today.', '', 'Assign exactly one verdict per claim:', '- "accurate": supported by current sources.', '- "outdated": was true previously but has since been superseded. This is the most important category: the article was likely written by a model whose training data predates the change.', '- "inaccurate": contradicted by current sources, or never true.', '- "unverifiable": opinion, prediction, or something no source can settle. Do not guess.', '', 'Rules:', '- Judge only what the claim asserts. Do not penalise a claim for being incomplete.', '- If a claim is time-anchored ("as of 2023...") and was correct for that date but is no longer current, mark it "outdated", not "inaccurate".', '- "correction" must state the current fact in one sentence, or be an empty string when the verdict is "accurate" or "unverifiable".', '- "confidence" is 0-100, reflecting source quality and agreement.', '- "sources" holds up to 3 URLs you actually relied on.', '', 'Respond with a single JSON object and nothing else — no prose, no code fences:', '{"results":[{"index":1,"verdict":"accurate","confidence":90,"correction":"","reasoning":"one short sentence","sources":["https://..."]}]}', ) ); } /** * Build the user-facing prompt listing the claims. * * @param array $claims Claim sentences. * @param array $context Optional title/published date. * @return string */ public static function user_prompt( array $claims, array $context ) { $lines = array(); $lines[] = 'Today is ' . gmdate( 'F j, Y' ) . '.'; if ( ! empty( $context['title'] ) ) { $lines[] = 'Article title: ' . $context['title']; } if ( ! empty( $context['published'] ) ) { $lines[] = 'Article published: ' . $context['published']; } $lines[] = ''; $lines[] = 'Claims to check:'; foreach ( $claims as $i => $claim ) { $lines[] = ( $i + 1 ) . '. ' . $claim; } $lines[] = ''; $lines[] = 'Return one result object per claim, using the same index numbers.'; return implode( "\n", $lines ); } /** * Turn a decoded results array into verdict rows paired back to their claims. * * @param array $rows Decoded "results" array. * @param array $claims Original claims, indexed from zero. * @param string $provider Provider slug for attribution. * @param array $fallback Fallback source URLs when a row carries none. * @return array */ public static function rows_to_verdicts( $rows, array $claims, $provider, array $fallback = array() ) { $out = array(); foreach ( $rows as $row ) { if ( ! is_array( $row ) ) { continue; } $index = isset( $row['index'] ) ? (int) $row['index'] - 1 : count( $out ); if ( ! isset( $claims[ $index ] ) ) { continue; } $sources = self::normalise_sources( $row['sources'] ?? array() ); if ( empty( $sources ) ) { $sources = self::normalise_sources( $fallback ); } $sources = array_slice( $sources, 0, 3 ); $out[] = array( 'claim' => $claims[ $index ], 'verdict' => self::normalise( $row['verdict'] ?? '' ), 'confidence' => isset( $row['confidence'] ) ? max( 0, min( 100, (int) $row['confidence'] ) ) : 0, 'correction' => isset( $row['correction'] ) ? sanitize_text_field( $row['correction'] ) : '', 'reasoning' => isset( $row['reasoning'] ) ? sanitize_text_field( $row['reasoning'] ) : '', 'sources' => $sources, 'provider' => $provider, ); } return $out; } /** * Normalise a mixed list of sources into {url, label} pairs. * * Accepts bare URL strings or arrays carrying a title/domain. The label * matters because Gemini returns grounding redirects on * vertexaisearch.cloud.google.com — every citation would otherwise display * with the same meaningless hostname, even though clicking works fine. * * @param mixed $raw Source list. * @return array */ public static function normalise_sources( $raw ) { if ( ! is_array( $raw ) ) { return array(); } $out = array(); $seen = array(); foreach ( $raw as $item ) { $url = ''; $label = ''; if ( is_string( $item ) ) { $url = $item; } elseif ( is_array( $item ) ) { $url = $item['url'] ?? ''; $label = $item['label'] ?? ''; } $url = esc_url_raw( trim( (string) $url ), array( 'http', 'https' ) ); // esc_url_raw will happily turn "not a url" into "http://notaurl", // so the host is checked rather than trusting a non-empty return. if ( '' === $url || ! self::is_real_url( $url ) || isset( $seen[ $url ] ) ) { continue; } $seen[ $url ] = true; $out[] = array( 'url' => $url, 'label' => sanitize_text_field( $label ) ?: self::host_label( $url ), ); } return array_values( $out ); } /** * Whether a URL points at something that could actually be fetched. * * @param string $url URL. * @return bool */ private static function is_real_url( $url ) { $parts = wp_parse_url( $url ); if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { return false; } if ( ! in_array( strtolower( $parts['scheme'] ), array( 'http', 'https' ), true ) ) { return false; } // A bare word coerced into a URL has no dot in its host. return false !== strpos( $parts['host'], '.' ); } /** * Readable fallback label derived from a URL's host. * * @param string $url URL. * @return string */ private static function host_label( $url ) { $host = wp_parse_url( $url, PHP_URL_HOST ); if ( ! $host ) { return $url; } return preg_replace( '/^www\./i', '', $host ); } /** * Decode JSON that may be wrapped in code fences or trailing prose. * * Search-grounded responses in particular tend to arrive with commentary * attached, because grounding and strict JSON output cannot be combined. * * @param string $content Raw model output. * @return array|null */ public static function decode_loose( $content ) { $content = trim( (string) $content ); $direct = json_decode( $content, true ); if ( is_array( $direct ) ) { return $direct; } // Strip code fences. if ( preg_match( '/```(?:json)?\s*(.+?)```/s', $content, $m ) ) { $fenced = json_decode( trim( $m[1] ), true ); if ( is_array( $fenced ) ) { return $fenced; } } // Fall back to the outermost brace pair. $start = strpos( $content, '{' ); $end = strrpos( $content, '}' ); if ( false !== $start && false !== $end && $end > $start ) { $loose = json_decode( substr( $content, $start, $end - $start + 1 ), true ); if ( is_array( $loose ) ) { return $loose; } } return null; } }