Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
1b6892d
feat: update the system instructions to generate a comment value score
priyanshuhaldar007 Jun 8, 2026
5631c28
feat: add value score to comment analysis and enhance context retrieval
priyanshuhaldar007 Jun 8, 2026
aeabc2c
feat: add value score functionality to comment moderation to display …
priyanshuhaldar007 Jun 8, 2026
63e112c
feat: enhance comment analysis by adding value score badge and displa…
priyanshuhaldar007 Jun 8, 2026
e724be1
fix: resolve lint and phpcs issues
priyanshuhaldar007 Jun 8, 2026
9beacfd
fix: clamped the value-score to 0-1, removed null as value, update po…
priyanshuhaldar007 Jul 10, 2026
a4f196a
fix: update the since tag to x.x.x awaiting release version
priyanshuhaldar007 Jul 10, 2026
f09061b
fix: add early return if not post
priyanshuhaldar007 Jul 10, 2026
8bb84d7
fix: add a generic function for column data rendering for each commen…
priyanshuhaldar007 Jul 10, 2026
06b75af
fix: add XML-like tags instead of raw string interpolation
priyanshuhaldar007 Jul 10, 2026
b9456f2
fix: resolve phpcs issues
priyanshuhaldar007 Jul 10, 2026
08df14b
fix: update the post_id from string to int)
priyanshuhaldar007 Jul 10, 2026
dc0fb7f
fix: updated code to use the global instance of WP_Post(added missing…
priyanshuhaldar007 Jul 10, 2026
41d40bb
feat: added tests for the new implementation
priyanshuhaldar007 Jul 10, 2026
d9b946b
fix: resolve phpcs issues
priyanshuhaldar007 Jul 10, 2026
a10fcd5
fix: resolve merge conflict
priyanshuhaldar007 Jul 17, 2026
2bda535
fix: resolve lint errors, drop null value score, add value score filter
priyanshuhaldar007 Aug 9, 2026
425db68
Merge branch 'develop' into feat-514/add-comment-value-score
priyanshuhaldar007 Aug 9, 2026
1112f5f
Merge branch 'feat-514/add-comment-value-score' of https://github.com…
priyanshuhaldar007 Aug 9, 2026
8a7560e
Merge branch 'develop' into feat-514/add-comment-value-score
dkotter Sep 3, 2026
226ae13
Make the post ID optional
dkotter Sep 3, 2026
04652e1
Fix invalid meta key
dkotter Sep 3, 2026
a474d2f
Update user facing text to mention value score
dkotter Sep 3, 2026
c7a6113
Ensure we only pull context from public posts; ensure we properly esc…
dkotter Sep 3, 2026
459456f
Extract some duplicate code out so it can be reused. Ensure we don't …
dkotter Sep 3, 2026
f612234
Ensure we don't require all three badges when finding pending comment…
dkotter Sep 3, 2026
147f312
Update docs and tests
dkotter Sep 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ While the Classic Editor plugin remains widely used, the AI plugin is focused on
* **[Abilities Explorer](docs/experiments/abilities-explorer.md)** – Discover, inspect, test, and document all abilities registered via the WordPress Abilities API.
* **[AI Request Logging](docs/experiments/ai-request-logging.md)** – Logs AI requests for observability and debugging.
* **[Alt Text Generation](docs/experiments/alt-text-generation.md)** - Generates descriptive alt text for images using AI vision models.
* **[Comment Moderation](docs/experiments/comment-moderation.md)** - Automatically moderate comments based on toxicity detection and sentiment analysis.
* **[Comment Moderation](docs/experiments/comment-moderation.md)** - Automatically moderate comments based on toxicity detection and sentiment analysis, and give each comment a value score.
* **[Connector Approvals](docs/experiments/connector-approval.md)** - Require explicit administrator approval before plugins or themes can use AI connectors configured on this site.
* **[Content Classification](docs/experiments/content-classification.md)** – Suggests relevant tags and categories to organize content.
* **[Content Resizing](docs/experiments/content-resizing.md)** - Shorten, expand, or rephrase selected block content.
Expand Down
38 changes: 31 additions & 7 deletions docs/experiments/comment-moderation.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@

## Summary

The Comment Moderation experiment adds sentiment and toxicity analysis to the classic Comments admin screen (`edit-comments.php`). It also performs automatic moderation when new comments are created: comments with **high toxicity** and **negative sentiment** are moved to moderation. The experiment exposes one WordPress Ability (`ai/comment-analysis`) that can be used from the UI or via REST API.
The Comment Moderation experiment adds sentiment, toxicity, and value analysis to the classic Comments admin screen (`edit-comments.php`). It also performs automatic moderation when new comments are created: comments with **high toxicity** and **negative sentiment** are moved to moderation. The experiment exposes one WordPress Ability (`ai/comment-analysis`) that can be used from the UI or via REST API.

## Overview

When enabled, the Comments list table gets two additional columns: **Sentiment** and **Toxicity**. Each comment can show a badge with the current analysis state or result.
When enabled, the Comments list table gets three additional columns: **Sentiment**, **Toxicity**, and **Value**. Each comment can show a badge with the current analysis state or result.

The **Value** score rates how relevant and substantive a comment is to the post it was left on, so moderators can separate genuine contributions from spam, engagement bait, and generic filler. Scoring it needs the post for context, which the ability reads from the post excerpt, then the AI-generated summary (`wpai_generated_summary`), then the post content, in that order. Context is only drawn from publicly readable posts — password-protected posts and non-public statuses (drafts, private posts) are skipped so gated editorial content is never sent to the provider.

**Key Features:**

- Adds sentiment and toxicity badges to the Comments admin list table
- Adds a bulk action (**Analyze Sentiment and Toxicity**) to queue selected comments for analysis
- Adds sentiment, toxicity, and value badges to the Comments admin list table
- Adds a bulk action (**Analyze Sentiment, Toxicity, and Value**) to queue selected comments for analysis
- Processes queued comments in the browser, sequentially, to avoid server overload
- Automatically moderates newly created comments when analysis indicates high risk
- Uses one shared ability (`ai/comment-analysis`) for both automated and manual workflows
Expand Down Expand Up @@ -56,10 +58,17 @@ array(
'type' => 'string',
'enum' => array( 'positive', 'negative', 'neutral' ),
),
'value_score' => array(
'type' => 'number',
'minimum' => 0,
'maximum' => 1,
),
),
)
```

`value_score` runs from 0 (spam, engagement bait, or completely off-topic) to 1 (on-topic and substantive).

### Permissions

- `ai/comment-analysis` requires `current_user_can( 'moderate_comments' )`
Expand Down Expand Up @@ -101,7 +110,8 @@ curl -X POST "https://yoursite.com/wp-json/wp-abilities/v1/abilities/ai/comment-
{
"comment_id": 123,
"toxicity_score": 0.81,
"sentiment": "negative"
"sentiment": "negative",
"value_score": 0.24
}
```

Expand Down Expand Up @@ -130,9 +140,22 @@ add_filter( 'wpai_comment_moderation_should_moderate', function( $should_moderat
}, 10, 3 );
```

### Controlling which posts supply value-score context

By default a post only supplies context when it is publicly readable and not password-protected, so gated editorial content is never sent to the provider. Use `wpai_comment_analysis_post_context_shareable` to widen or narrow that:

```php
add_filter( 'wpai_comment_analysis_post_context_shareable', function ( bool $shareable, WP_Post $post ): bool {
// Never send context from a specific post type.
return 'internal_memo' === $post->post_type ? false : $shareable;
}, 10, 2 );
```

When no context is available the comment is still analyzed — the model scores it on its own merits.

### Adjusting the Bulk Batch Cap

Each comment queued by the **Analyze Sentiment and Toxicity** bulk action becomes one billed model call once it is analyzed, so `handle_bulk_action()` caps how many comments a single request will queue. The default is 100; comments beyond the cap are not queued, and the surplus is reported to the user in an admin notice.
Each comment queued by the **Analyze Sentiment, Toxicity, and Value** bulk action becomes one billed model call once it is analyzed, so `handle_bulk_action()` caps how many comments a single request will queue. The default is 100; comments beyond the cap are not queued, and the surplus is reported to the user in an admin notice.

```php
add_filter( 'wpai_bulk_action_max_items', function ( int $max_items, string $feature_id ): int {
Expand All @@ -153,7 +176,7 @@ Values below 1 are clamped to 1. The same filter governs the alt text and summar

2. **List table badges and bulk analysis:**
- Go to `Comments -> All Comments`
- Select multiple comments and run **Analyze Sentiment and Toxicity**
- Select multiple comments and run **Analyze Sentiment, Toxicity, and Value**
- Confirm a success notice reports queued count
- Verify pending badges transition to analyzed badges (or failed state) as processing runs
- Confirm `wpai_analysis_queued` is removed from the URL after processing, and refresh does not re-show the queue notice
Expand Down Expand Up @@ -186,3 +209,4 @@ Values below 1 are clamped to 1. The same filter governs the alt text and summar
- Works only on the classic comments list table (no block-based comments UI integration here)
- Analysis is not batched server-side; one ability invocation per comment
- Current retry behavior for failed badges is best-effort and may repeat on reload until resolved
- Comments analyzed before the **Value** column existed have no value score stored. They show a `—` in that column rather than a fabricated score, and are excluded from the value score filters until they are re-analyzed.
147 changes: 129 additions & 18 deletions includes/Abilities/Comment_Moderation/Comment_Analysis.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
/**
* Comment Analysis WordPress Ability.
*
* Analyzes comments for toxicity and sentiment.
* Analyzes comments for toxicity, sentiment, and value.
*
* @since 0.9.0
*/
Expand Down Expand Up @@ -66,6 +66,12 @@ protected function output_schema(): array {
'enum' => array_keys( Comment_Moderation::get_sentiment_config() ),
'description' => esc_html__( 'The sentiment of the comment.', 'ai' ),
),
'value_score' => array(
'type' => 'number',
'minimum' => 0,
'maximum' => 1,
'description' => esc_html__( 'Value score from 0 (low value) to 1 (high value).', 'ai' ),
),
),
);
}
Expand All @@ -75,7 +81,7 @@ protected function output_schema(): array {
*
* @since 0.9.0
*
* @return array{comment_id: int, toxicity_score: float, sentiment: string}|\WP_Error The result of the ability execution.
* @return array{comment_id: int, toxicity_score: float, sentiment: string, value_score: float}|\WP_Error The result of the ability execution.
*/
protected function execute_callback( $input ) {
return $this->analyze_comment_by_id( absint( $input['comment_id'] ?? 0 ) );
Expand All @@ -90,7 +96,7 @@ protected function execute_callback( $input ) {
* @since 0.9.0
*
* @param int $comment_id Comment ID.
* @return array{comment_id: int, toxicity_score: float, sentiment: string}|\WP_Error The result of the analysis.
* @return array{comment_id: int, toxicity_score: float, sentiment: string, value_score: float}|\WP_Error The result of the analysis.
*/
public function analyze_comment_by_id( int $comment_id ) {
$comment_id = absint( $comment_id );
Expand Down Expand Up @@ -129,7 +135,7 @@ public function analyze_comment_by_id( int $comment_id ) {
update_comment_meta( $comment_id, Comment_Moderation::META_ANALYSIS_STATUS, Comment_Moderation::STATUS_PROCESSING );

// Analyze the comment.
$result = $this->analyze_comment( $comment->comment_content, $comment->comment_author );
$result = $this->analyze_comment( $comment->comment_content, $comment->comment_author, absint( $comment->comment_post_ID ) );

if ( is_wp_error( $result ) ) {
// Mark as failed.
Expand All @@ -140,13 +146,15 @@ public function analyze_comment_by_id( int $comment_id ) {
// Store the results.
update_comment_meta( $comment_id, Comment_Moderation::META_TOXICITY_SCORE, $result['toxicity_score'] );
update_comment_meta( $comment_id, Comment_Moderation::META_SENTIMENT, $result['sentiment'] );
update_comment_meta( $comment_id, Comment_Moderation::META_VALUE_SCORE, $result['value_score'] );
update_comment_meta( $comment_id, Comment_Moderation::META_ANALYSIS_STATUS, Comment_Moderation::STATUS_COMPLETE );
update_comment_meta( $comment_id, Comment_Moderation::META_ANALYZED_AT, time() );

return array(
'comment_id' => $comment_id,
'toxicity_score' => $result['toxicity_score'],
'sentiment' => $result['sentiment'],
'value_score' => $result['value_score'],
);
}

Expand Down Expand Up @@ -190,8 +198,9 @@ private function response_schema(): array {
'properties' => array(
'toxicity_score' => array( 'type' => 'number' ),
'sentiment' => array( 'type' => 'string' ),
'value_score' => array( 'type' => 'number' ),
),
'required' => array( 'toxicity_score', 'sentiment' ),
'required' => array( 'toxicity_score', 'sentiment', 'value_score' ),
'additionalProperties' => false,
);

Expand All @@ -206,39 +215,136 @@ private function response_schema(): array {
}

/**
* Analyzes a comment for toxicity and sentiment.
* Returns context from the post for comment analysis.
*
* @since x.x.x
*
* @param int $post_id The ID of the post.
* @return string|null The content of the post, or null if no context is available.
*/
private function get_post_context( int $post_id ): ?string {
if ( $post_id <= 0 ) {
return null;
}

$post = get_post( $post_id );
Comment thread
dkotter marked this conversation as resolved.
Resolved

if ( ! $post instanceof \WP_Post ) {
return null;
}

if ( ! $this->is_post_context_shareable( $post ) ) {
return null;
}

// 1. Use excerpt if available (human-written, most reliable)
$excerpt = trim( $post->post_excerpt );
Comment thread
dkotter marked this conversation as resolved.
Resolved
if ( ! empty( $excerpt ) ) {
return $excerpt;
}

// 2. Fall back to AI-generated summary if available
$ai_summary = trim( (string) get_post_meta( $post_id, 'wpai_generated_summary', true ) );
if ( ! empty( $ai_summary ) ) {
return $ai_summary;
}

// 3. Fall back to trimmed post content (strip tags, normalize whitespace)
$content = wp_strip_all_tags( $post->post_content );
$content = trim( (string) preg_replace( '/\s+/', ' ', $content ) );

if ( empty( $content ) ) {
return null;
}

return mb_substr( $content, 0, 650 );
Comment thread
dkotter marked this conversation as resolved.
Resolved
}

/**
* Checks whether a post's content may be sent as context.
*
* @since x.x.x
*
* @param \WP_Post $post The post the comment was left on.
* @return bool Whether the post's content is safe to share as context.
*/
private function is_post_context_shareable( \WP_Post $post ): bool {
if ( '' !== (string) $post->post_password ) {
return false;
}

$status = get_post_status_object( $post->post_status );

$shareable = $status instanceof \stdClass && ! empty( $status->public );

/**
* Filters whether a post's content may be sent as comment analysis context.
*
* Defaults to true only for publicly readable, non-password-protected posts.
*
* @since x.x.x
*
* @param bool $shareable Whether the post's content is safe to share as context.
* @param \WP_Post $post The post the comment was left on.
*/
return (bool) apply_filters( 'wpai_comment_analysis_post_context_shareable', $shareable, $post );
}

/**
* Escapes untrusted text before it is embedded in the pseudo-XML prompt.
*
* @since x.x.x
*
* @param string $text The untrusted text.
* @return string The text with markup delimiters neutralized.
*/
private function escape_prompt_value( string $text ): string {
return str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), $text );
}

/**
* Analyzes a comment for toxicity, sentiment and value.
*
* @since 0.9.0
*
* @param string $content The comment content.
* @param string $author The comment author name.
* @return array{toxicity_score: float, sentiment: string}|\WP_Error The analysis result.
* @param string $content The comment content.
* @param string $author The comment author name.
* @param int|null $post_id The ID of the post the comment was left on, if known.
* @return array{toxicity_score: float, sentiment: string, value_score: float}|\WP_Error The analysis result.
*/
private function analyze_comment( string $content, string $author ) {
private function analyze_comment( string $content, string $author, ?int $post_id = null ) {
/**
* Filters the comment analysis result before calling the AI provider.
*
* Returning an array short-circuits the provider call. This is primarily useful for tests
* and integrations that provide their own comment analysis implementation.
*
* @since 0.9.0
* @since x.x.x Added the `$post_id` parameter.
*
* @param array{toxicity_score: float, sentiment: string}|null $result Precomputed analysis result.
* @param string $content Comment content.
* @param string $author Comment author name.
* @param array{toxicity_score: float, sentiment: string, value_score: float}|null $result Precomputed analysis result.
* @param string $content Comment content.
* @param string $author Comment author name.
* @param int|null $post_id The ID of the post.
*/
$pre_result = apply_filters( 'wpai_comment_analysis_result', null, $content, $author );
$pre_result = apply_filters( 'wpai_comment_analysis_result', null, $content, $author, $post_id );

if ( is_array( $pre_result ) ) {
return $this->sanitize_analysis_result( $pre_result );
}

$prompt = sprintf(
"Comment by %s:\n\"\"\"%s\"\"\"",
$author,
$content
"<comment>\n<author>%s</author>\n<content>%s</content>\n</comment>",
$this->escape_prompt_value( $author ),
$this->escape_prompt_value( $content )
);

$post_context = $post_id ? $this->get_post_context( $post_id ) : null;

if ( null !== $post_context ) {
$prompt .= sprintf( "\n<post_context>%s</post_context>", $this->escape_prompt_value( $post_context ) );
}

$prompt = $this->filter_prompt( $prompt, $content, $author );
$prompt_builder = $this->get_prompt_builder( $prompt );

Expand Down Expand Up @@ -292,7 +398,7 @@ private function get_prompt_builder( string $prompt ) {
* @since 0.9.0
*
* @param array<string, mixed> $result Raw analysis result.
* @return array{toxicity_score: float, sentiment: string} Sanitized analysis result.
* @return array{toxicity_score: float, sentiment: string, value_score: float} Sanitized analysis result.
*/
private function sanitize_analysis_result( array $result ): array {
// Validate and sanitize the response.
Expand All @@ -305,9 +411,14 @@ private function sanitize_analysis_result( array $result ): array {
? $result['sentiment']
: Comment_Moderation::SENTIMENT_NEUTRAL;

$value_score = isset( $result['value_score'] )
? max( 0.0, min( 1.0, (float) $result['value_score'] ) )
: 0.0;

return array(
'toxicity_score' => $toxicity_score,
'sentiment' => $sentiment,
'value_score' => $value_score,
);
}
}
16 changes: 14 additions & 2 deletions includes/Abilities/Comment_Moderation/system-instruction.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

return <<<'INSTRUCTION'
You are a comment moderation assistant. Analyze the provided comment and return the following:
You are a comment moderation assistant. You will be given an article and a comment left on that article. Analyze the comment and return the following:

1. "toxicity_score": A number between 0 and 1 indicating how toxic/harmful the comment is:
- 0.0-0.3: Low toxicity (constructive, polite, or neutral)
Expand All @@ -18,5 +18,17 @@
- "negative": The comment expresses criticism, disagreement, frustration, or disappointment
- "neutral": The comment is factual, asks a question, or doesn't express clear emotion

Respond only with those two fields. No explanation, no markdown, no additional text.
3. "value_score": A number between 0 and 1 indicating how relevant and valuable the comment is to the article's discussion:
- 0.0-0.3: Low value (spam, engagement bait, generic acknowledgment such as "+1" or "thanks", or completely off-topic)
- 0.4-0.6: Moderate value (loosely related, adds minor context, or is brief but not noise)
- 0.7-1.0: High value (on-topic, substantive, adds new information, asks a meaningful question, or meaningfully advances the discussion)

When scoring, consider:
- Relevance to the article's subject matter
- Whether the comment adds new information or perspective
- Whether it could stand alone as a meaningful contribution vs. filler

If the article content is unavailable or too short to assess relevance, score the comment on its own merits alone.

Respond only with those three fields as a JSON object. No explanation, no markdown, no additional text.
INSTRUCTION;
Loading
Loading