Skip to content

feat(mentions): correct an answer's sentiment from the response drawer - #1121

Merged
gkhngyk merged 27 commits into
ansvisor:mainfrom
cihan-gyk:feature/mentions-sentiment-override
Oct 17, 2026
Merged

gkhngyk merged 27 commits into
ansvisor:mainfrom
cihan-gyk:feature/mentions-sentiment-override

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

"Sentiment is wrong" for Mentions & Sentiment (MS-08): admins and managers correct an answer's tone toward the brand from the response drawer, with an optional note. The spec asks that "a sentiment override changes the metrics within one refresh and is logged". This does both, everywhere the sentiment counts.

Stacked on #1118 → #1117 → #1116 → #1115 (#1114 is merged). The diff includes their commits until they merge.

Migration 00160_mention_sentiment_override.sql

  • sentiment_overrides: the corrections' append-only history.
    • Each row has the answer, the tone replaced and the new one, an optional note (≤500 characters), who made it and when.
    • The person's name is kept as written, since profiles are readable only by their owner and a name should outlive their membership.
    • Members of the brand's organization read it, and clients can't write to it.
    • It is also what a future classifier can learn from.
  • override_mention_sentiment(result_id, sentiment, note?) (security definer):
    1. It checks that the caller is an admin or manager of the answer's organization (42501 otherwise), the same rule as editing prompts, and that the answer names the brand (sentiment is only classified then).
    2. It changes prompt_results.sentiment, so every reader agrees: Insights' Net and Positive sentiment, the Mentions tabs, the Positions panel, reports written from now on, and the MCP tools. Reports already written keep their snapshot.
    3. It moves visibility_score by tracking's sentiment bonus (computeVisibilityScore: +15 positive, +7 neutral when named, 0 negative). The score's parts add up to at most 100, so swapping the bonus is exact.
    4. It records the correction.
    5. It refreshes the answer's UTC day in the Insights (refresh_insights_daily) and Mentions (refresh_mentions_daily) rollups, so the change shows at once instead of after the nightly sweep.
    • Same tone: choosing the tone the answer already has changes nothing.

Web

  • Correction (_sentiment-correction.tsx):
    • History: the drawer shows the last correction, "Corrected by Demo User on Oct 17, 2026 · was Negative", with its note.
    • Form: admins and managers (useUserRole().canManage) get "Sentiment is wrong?". It opens Positive / Neutral / Negative, an optional note and Save. Save stays off until the tone differs.
    • After saving: the drawer and its table row show the new tone at once. A table filtered by sentiment reads its page again, so the corrected row leaves a filter it no longer matches.
  • lib/actions/mentions.ts:
    • overrideMentionSentiment: errors come back as forbidden, invalid, missing or unknown.
    • getMentionResponse: it also reads the latest correction (none on a build before 00160).
  • Types: types/supabase.ts gets the table and the function.

Related issue

None.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00160 (after 00157 and 00158).
  2. As an admin or manager, open Mentions → Mentions, filter Sentiment → Negative and open an answer.
  3. Click Sentiment is wrong?, choose Positive, add a note and click Save correction.
    • The pill turns Positive.
    • "Corrected by … · was Negative" appears with the note.
    • The table reads again and the row leaves the Negative filter.
  4. Open Overview: Net sentiment has moved (on the demo brand, +21 → +22 over 30 days). Insights' sentiment cards move with it.
  5. As an analyst, the drawer shows the history but no Sentiment is wrong?.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): no errors; the 7 warnings are in files this PR does not touch
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • yarn test (947) and yarn build pass.
    • lib/actions/mentions.test.ts:
      • the correction call, with the note trimmed and a blank note not sent;
      • each error code;
      • the latest correction read, with none, or no table yet.
    • mentions/_mentions-tab.test.tsx:
      • the history shown;
      • a manager's correction updating the drawer and the row;
      • a sentiment-filtered page read again;
      • no form for analysts.
  • Server npm test (1309) passes. The server is unchanged here.
  • bash supabase/build-schema.sh: regenerated schema.sql.
  • Dev database:
    • Rolled-back dry run, then applied.
      • The answer changed: negative → positive moved its visibility_score 33 → 48.
      • That day's rollups moved: Mentions' negative count 1 → 0, Insights' positive count 0 → 1.
      • The note was trimmed and the name stored.
      • The same tone again: no change.
      • An invalid tone was refused (22023).
      • An analyst and a stranger were refused (42501).
      • A stranger reads no history, and a client insert was refused by RLS.
    • In the browser (admin):
      • the correction showed at once;
      • the Overview's Net sentiment moved +21 → +22;
      • the drawer checked in light and dark.
      • The test correction was reverted afterwards (sentiment, score and rollups restored, history row removed).

🤖 Generated with Claude Code

cihan-gyk and others added 10 commits October 17, 2026 09:13
…iment page shell

Mentions & Sentiment (MS-05) gets its sidebar item, "Mentions" with a New
pill and a speech-bubble icon, directly above Citations, its sibling
concept. Once Topics moves into Prompts, it sits between Prompts and
Citations.

/dashboard/mentions has the page's title and description, its V1 tabs
(Overview, Mentions, Perception; Sentiment and Fact-check stay hidden until
built) and the filter bar every tab shares: date range (30 days by default,
as in the mockup), AI platform, country, topic and a search over prompts,
brands and phrases. Tab and filters live in the URL, so a refresh or a
shared link restores the view. The tabs' figures and charts arrive with the
next PRs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The data layer for Mentions & Sentiment (MS-03/04), built from what
tracking already stores on each answer: mention_count, mention_position,
competitor_mentions and the answer's sentiment toward the brand. Opening
the page or changing a filter never calls an LLM.

Migration 00157 adds two daily rollups:
- mentions_prompt_daily (day x prompt x platform x region): answers, the
  answers naming the brand, occurrences, positive and negative mentions,
  and the brand's positions;
- mentions_competitor_daily: answers naming each competitor, and those
  naming the brand too.
refresh_mentions_daily rebuilds them (service role only), and
mentions_overview reads a window and the one before it, filtered by
platform, region, topic and a prompt search: under two days from the
answers, longer windows from whole UTC days. It is security definer with
the organization check made explicit.

The server refreshes the rollups with the Insights and Citations ones,
when a run stamps and in the nightly sweep, and
scripts/backfill-mentions-daily.js fills a brand's history. The web gets
getMentionsOverview, the Overview's metrics (mention rate, the sentiment
split with neutral kept, net sentiment, low sample under 20 mentions,
average position) and the filters-to-query helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Overview tab of Mentions & Sentiment (MS-06), as in the mockup:

- a summary line written from the aggregates by a fixed template (net
  sentiment and its change, the platform behind most of it, the
  competitors named beside you), never an LLM;
- KPI cards: Total mentions, Mention rate, Prompts with mentions and Net
  sentiment with its split and n; under 20 responses a rate is a low
  sample and shows no change;
- a daily trend with a Mentions / Mention rate / Net sentiment toggle;
- a by-platform table with the sentiment split, net and its change, and
  a note when platforms disagree;
- competitor framing: mentions, rate and same-answer counts, with
  sentiment for your brand only.

MetricCard is exported from the Insights cards and takes a footer in
place of its sparkline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Mentions tab of Mentions & Sentiment (MS-07/MS-08, read-only V1):

- migration 00158 adds mentions_list: the answers naming the brand in
  mentions_overview's window, a page of 100 at a time, filtered by
  sentiment and by a competitor named in the same answer (or none),
  sorted newest, oldest, by co-mentions or most negative, and grouped by
  prompt or platform; security definer with the organization check;
- listMentions cuts each answer to the passage around the brand's first
  mention on the server (lib/mention-match.ts matches names as tracking
  does), and getMentionResponse reads one answer for the drawer;
- the table pins its header and Prompt column, marks your brand in
  violet and competitors in grey, and keeps its controls in the URL;
- the drawer shows the prompt, platform and model, country, date,
  sentiment, position and topic, the excerpt, the competitors named,
  the full stored answer with the names marked, and its citations typed
  as on the Citations page, with Copy and View prompt.

The search box now says it searches prompts, as both tabs do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The response drawer's actions and the Mentions table's multi-select
(MS-08):

- Send to Action Center: one or more answers naming the brand become one
  mention_review action. The server reads the answers again (only the
  brand's own mentions count), files them as Protect when any is negative
  (Growth otherwise) with impact from the negative share, plans F08's
  review tasks, quotes the answers as evidence, keeps the selection's
  sentiment as the baseline, and measures the action on the answers'
  prompts once done. The same answers sent again return the open action.
  POST /api/mentions/action, lib/action-center/from-mentions.js.
- The Action Center knows the kind: its title names the prompt (or the
  number of prompts), and the drawer shows the answers quoted when sent.
- Suggest content runs the Prompts page's flow for the answer's prompt,
  with its quota and existing-suggestion checks.
- The table ticks answers on the page and sends them together.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
"Sentiment is wrong" (MS-08): admins and managers correct the tone of an
answer toward the brand, with an optional note.

- Migration 00160 adds sentiment_overrides, the corrections' append-only
  history (previous and new tone, who, when, note; members read it), and
  override_mention_sentiment, which checks the caller is an admin or
  manager of the answer's organization, changes the answer's sentiment
  and its visibility_score by tracking's sentiment bonus, records the
  correction, and refreshes that UTC day's Insights and Mentions rollups,
  so every figure counts the new tone at once.
- The drawer shows the last correction ("Corrected by … · was …") and,
  for admins and managers, a form to correct it; the row updates at once
  and a sentiment-filtered table reads its page again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk "Sentiment is wrong" for Mentions: admins and managers correct an answer's sentiment; it changes everywhere the sentiment counts (Insights included) and is logged in sentiment_overrides. Migration 00160 (00159 is reserved for something I'll send you separately). Stacked on #1118 → #1117 → #1116 → #1115; please merge in that order.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 17, 2026
mentions_list joined the answers to the brand's prompts first, and the
planner walked each prompt's whole history: 8.8 s for 30 days of the
largest brand, past the 8 s timeout, so the table failed on its default
range. It now reads the window's mentions first, through a partial index
on mention_count > 0, then joins the prompts: 1.8 s for 30 days, 2.9 s
for 90.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
…ts_daily

Its inserts picked the answers by (created_at at time zone 'utc')::date,
which no index serves, so refreshing one day read every answer the brand
has: about 1 s warm and 12 s cold for the largest brand. A sentiment
correction (00160) runs it inside the person's 8 s request, where it
timed out. The same answers are now found by created_at range: 0.66 s for
that day, with the same rows, and the correction takes about 1 s.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed. Migration 00160 is applied to production; the visibility bonus swap matches computeVisibilityScore exactly (null sentiment scores 0 there too). Tested end to end as an admin of the largest brand under the 8 s timeout, in a rolled-back transaction: the correction first timed out inside refresh_insights_daily, whose inserts picked the day by (created_at at time zone 'utc')::date and so read all 222k of the brand's answers. Added 00162 (applied): the same answers found by created_at range, 0.66 s for a day with the same totals; the correction now takes about 1 s. A user of another organization gets 42501.

@gkhngyk
gkhngyk merged commit 66178c8 into ansvisor:main Oct 17, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants