Skip to content

feat(insights): compare changes on the same prompts by default - #1036

Merged
gkhngyk merged 6 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-same-prompts
Oct 15, 2026
Merged

gkhngyk merged 6 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-same-prompts

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Stacked on #1035 (VIS-001). Until #1035 merges, this PR also shows its commit. The VIS-002 change is the last commit, 6371efa.

Summary

Adding prompts inflated every change on the Insights page. On the live page, tracked prompts went from 200 to 709 in a period, and Mentions showed +203%. The breakdown panel also counted each new prompt as a gain from 0 ("0 → 69.9"). This is VIS-002 in the Visibility spec v2 and matches the "Compare: Same prompts" control in the v2 mockup.

What changes:

  • "Compare: Same prompts" switch in the filter bar, on by default. It is kept in the URL as ?compare=all when off, next to the other filters (feat(insights,citations): keep filters in the URL #917).

  • With the switch on, every change is measured only on the prompts answered in both periods:

    • the Visibility change on the trend card;
    • every leaderboard row's change, for the brand and each competitor;
    • Mentions, Citations and Sentiment;
    • the breakdown panel's total and every prompt, platform and topic row.

    The numbers themselves (78.8, 377, …) still cover every prompt. VIS-001's parity holds: the card, the panel and the leaderboard show the same change.

  • The trend card says what was compared: "vs Aug 16 – Sep 14 · 6 new prompts excluded", or "includes 6 new prompts" with the switch off. The panel shows "Same N prompts: prev → cur" and a one-line note on the new prompts it left out.

  • Competitors added during the period get no change, as on all prompts, instead of a gain from 0.

Data

Scoring each competitor per prompt from prompt_results on every load is what the daily rollups exist to avoid (00098: 16 s for the competitor jsonb over 30 days). So migration 00130:

  • adds the score components (mention_answers, citation_answers, sum_inv_position, position_count, totals, sentiment) to insights_prompt_daily and insights_competitor_prompt_daily, as nullable columns;
  • writes them in refresh_insights_daily. This is the 00098 body with the new columns; the counting rules are unchanged;
  • adds insights_same_prompt_compare_daily (rollups, whole-day windows) and insights_same_prompt_compare (raw rows, for the 24h and topic views). Both are security invoker and share one output shape.

Deploy step: after the migration, run the existing backfill once so past days get the new columns:

cd server && node src/scripts/backfill-insights-daily.js

Until a day is refreshed, its new columns are NULL. The RPC then reports complete: false and the page compares all prompts, as today, so a half-backfilled history never shows a wrong change. The daily sweep keeps the last 3 days current.

Review

I ran a code review before opening this. It found 8 things and 5 are fixed:

  • competitors added mid-period showed a gain from 0;
  • "Same 0 prompts: — → 0" in the panel;
  • a wrong root-cause line when the shared prompts had 0 previous mentions;
  • a stale doc on VisibilityRateTrendSummary.change;
  • the new-prompts note was hidden when there was no change.

Left as notes:

  • Topic views: these take the raw path, which adds one more competitor-jsonb scan per load. The card already reads topics raw. A timeout only drops the comparison, it doesn't fail the page.
  • Switch off: the comparison RPC still runs, to show how many new prompts the change includes.
  • No SQL tests: the repo has no SQL test harness. I checked the rollup and raw variants against each other on a dev database, and they matched.

Related issue

None. Product spec: Visibility spec v2, task VIS-002. Depends on #1035.

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 00129 (from fix(insights): show the same visibility on the card, breakdown and leaderboard #1035) and 00130, then refill the rollups: run backfill-insights-daily.js, or select refresh_insights_daily(id, <first day>, current_date) per brand.
  2. Open Insights with 30d on a brand that added prompts this period. "Compare: Same prompts" is on; the trend card shows "· N new prompts excluded".
  3. Compare the Visibility change on the trend card, your Leaderboard row and the Visibility breakdown panel ("Same N prompts: a → b"). All three match.
  4. Open the Mentions breakdown. Its change matches the Mentions card.
  5. Turn the switch off: the URL gets ?compare=all, the changes go back to all prompts, and the trend card says "includes N new prompts".
  6. Before the backfill (or on a day not yet refreshed), the page shows today's all-prompt changes and no "same prompts" note.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): 0 errors; the 7 warnings are in code this PR doesn't 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: 554/554. New tests are insights-same-prompts.test.ts, the same-prompt cases in insights-breakdown.test.ts, and the "Same prompts parity (VIS-002)" block in tracking-visibility-parity.test.ts. The parity block checks that card, panel and leaderboard agree, that the switch off and the not-backfilled state fall back to all prompts, and that adding prompts leaves earlier prompts' rows unchanged.
  • yarn build: passed.
  • bash supabase/build-schema.sh: schema.sql is up to date.
  • The migration is applied and the rollups are refilled on a dev database. I checked in the browser at 30d with the switch on and off, the panel, light and dark mode, and 1024px.

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 14, 2026 17:08
…aderboard

The Visibility card, the "View breakdown" panel and the leaderboard's own
row could show different numbers for the same filters (VIS-001):

- the panel fetched raw answers, capped at 1,000 per window in no fixed
  order, so it scored an arbitrary sample (24.1 in the panel against 17.4
  on the card for the same 30 days);
- the panel built its previous window from timestamps, the card from
  whole UTC days;
- on All time the leaderboard compared all time with the last 7 days, and
  the panel quietly showed the last 7 days.

All three now take their windows from one place (insights-windows.ts),
and the totals come from the card's own aggregates. The panel's prompt,
platform and topic slices are grouped in Postgres by a new RPC,
insights_breakdown_groups (00129), so no row cap applies. All time shows
no change anywhere. The "vs" label names the days actually compared, and
whole-day presets count their days instead of rounding elapsed time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk this is ready for review. It's VIS-002 from the Visibility spec v2, stacked on #1035. Until that merges, the VIS-002 change is the last commit.

It adds the mockup's "Compare: Same prompts" switch, on by default. Every change on the page (Visibility, leaderboard, Mentions, Citations, Sentiment, breakdown) is then measured only on prompts answered in both periods, so adding 509 prompts no longer reads as +203%.

Things to look at:

  • Migration 00130 adds per-prompt score components to the two prompt-grain rollup tables, writes them in refresh_insights_daily, and adds two security-invoker RPCs.
  • Deploy step: run node src/scripts/backfill-insights-daily.js once after the migration. Until then the page falls back to the current all-prompt comparison, so nothing shows a wrong number in between.
  • Topic views use the raw path and add one competitor-jsonb scan per load, like the card's own topic reads. A timeout there only drops the comparison.

Code review, yarn test (554/554), lint, typecheck and build pass. I checked it on a dev database with backfilled rollups, in the browser in light and dark mode at 1024px.

@gkhngyk

gkhngyk commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Minor.

  • getSamePromptComparison returns null on an RPC error, even when loadWindowedInsights runs with strict: true.
  • On 24h, that degraded result is then stored by cachedAnchoredInsights. After one transient failure, the view shows all-prompt changes, with no new-prompts note, until the next tracking run.
  • Let it throw and wrap it in lenient(...) like the other sections, so strict mode keeps a degraded result out of the cache.

@gkhngyk

gkhngyk commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Blocker: insights_same_prompt_compare_daily times out on the largest brand.

00129–00135 are applied to the hosted database, and the rollups are backfilled. I timed this RPC on the largest brand (~219k answers), 30d against the previous 30d:

  • As the owner (no RLS): 4.5 s.
  • As authenticated, for a real org member: more than 30 s. The role's statement_timeout is 8 s.
  • With work_mem = 64MB and plan_cache_mode = force_custom_plan (the settings competitor_aggregates_daily uses): still over the limit.

Same Prompts is on by default, so every Insights open for this brand waits out the 8 s timeout. getSamePromptComparison then returns null, and the page quietly falls back to comparing all prompts. Smaller brands are fine (~0.4 s on the second largest).

Even 4.5 s as the owner is close to the limit, so the query itself needs work as well as the RLS path. 00119 is one pattern to follow: security definer with an explicit org-membership check.

Please re-time it as authenticated on the largest brand before the next review.

@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.

The logic reads well, and the fallback keeps the page up. One blocker, measured on production (00129–00135 are applied there) as a signed-in member of the largest brand:

insights_same_prompt_compare_daily is far over the 8 s limit. 30 days ran past 50 s and 90 days took 17.8 s, while the same query with literal values takes 0.9 s. Inside the SQL function the windows are parameters, so the planner expects one row per scan and joins the competitor rows with a nested loop that re-runs the 230k-row competitor scan for every window and competitor. The call sits in loadWindowedInsights's Promise.all, so every Insights load on a big brand would wait for the timeout before falling back. 00113 hit the same thing on competitor_aggregates_daily; plpgsql with plan_cache_mode = force_custom_plan and work_mem fixed it there. Aggregating the competitor rows per window and competitor before the left join would help too.

The raw insights_same_prompt_compare runs past 25 s on the largest topic over 30 days, so topic views wait the same way (24h is fine at 1.2 s).

00131 is already applied in production, so the fix needs a new migration after the stack. insights_change_drivers_daily (00135, #1042) also runs past 15 s for 30 days, probably for the same reason.

cihan-gyk and others added 2 commits October 15, 2026 23:43
…bers

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cihan-gyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 15, 2026
00147 (ansvisor#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

cihan-gyk commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks @gkhngyk! Both points are fixed.

Update: this also answers your 19:40 review, which reached me after I wrote the rest. In short:

  • Both RPCs are plpgsql with force_custom_plan and work_mem set on the function, as in 00113. plan_cache_mode only reaches plpgsql plans, which is why it didn't help the SQL function.
  • The competitor rows are summed per window and competitor before the left join (comp_sums in 00147).
  • The new migrations come after the stack: 00147 here, 00148 on feat(insights): explain the visibility change beside the platform table #1042, and 00149 on feat(insights): show the KPI cards in two rows, as in the v2 mockup #1037, so production keeps 00131's output.
  • The raw variant is in the same migration. On the dev database, the largest topic over 30 days went from 9.0 s to 1.4 s (median). Cold reads on this small instance are slow for both versions, so your hosted timing will tell.

Blocker: insights_same_prompt_compare_daily timing out. A new migration, 00147, rewrites both same-prompt RPCs (00130 is untouched):

  • plpgsql with force_custom_plan. On PostgreSQL 17, a SQL-language function is planned without its argument values, so plan_cache_mode never reached it. A generic PREPARE of the old body expects ~150 rows for the day ranges and gets ~207k. Each call is now planned with its real arguments.
  • Security definer with an explicit org-membership check, as in 00119. RLS no longer runs inside the scan. The service role still reads, because the cached 24h view (cachedAnchoredInsights) calls the raw variant with it after checking the caller's access. Non-members get null, and anon loses execute.
  • A cheaper query. The rollup rows are folded to one row per prompt and window before anything joins them. The raw variant keeps one copy of its rows instead of three.

The output is unchanged. On the test brand below, both RPCs return identical JSON before and after for 30d, 7d, 90d, a model filter, 24h and a topic view, as a member and as the service role.

Local timings. I can't time the hosted database. I used our dev database (Supabase, PostgreSQL 17.11) with a synthetic brand shaped like the largest one: 210,416 answers over 62 days, 709 prompts (509 new this period), 8 engines, rollups filled by refresh_insights_daily. These are medians of 5 runs as authenticated, with a real org member's JWT claims:

Window Before After
30d vs previous 30d 981 ms 185 ms
7d 428 ms 141 ms
90d 464 ms 153 ms
30d, one model 205 ms 70 ms
24h (raw) 2,216 ms 171 ms
Topic, 30d (raw)* 8,995 ms 1,407 ms

* Very noisy on this instance (1.6–31 s before, 1.2–18 s after): it reads the topic's answers prompt by prompt from disk.

  • As the owner, the old function took 4.8 s on its first call and ~1 s after that, close to your 4.5 s.
  • The dev database doesn't reproduce the 30 s member time, because its RLS subquery reads a one-row profiles table. With the definer, the membership check runs once per call, so member and service-role times now match.
  • On this small instance, the first call after other queries takes 2–4 s on both versions, because it reads from disk.

Re-timing on the hosted database is yours to run. Two notes:

Minor: strict mode. getSamePromptComparison now throws on an RPC error, and loadWindowedInsights wraps it in lenient(...) like the other sections. In strict mode, a failure now fails the cached 24h read, which falls back to the live read and caches nothing. The breakdown panel catches the error and compares all prompts, as before.

  • New test tracking-insights-cache.test.ts: a failed comparison leaves the cache empty, and the next open shows the comparison. It fails on the old code.
  • The parity tests gained the panel case.

yarn test (601/601), lint (0 errors; the 7 warnings are in files this PR doesn't touch), typecheck and build pass. build-schema.sh regenerated schema.sql.

gkhngyk
gkhngyk previously approved these changes Oct 15, 2026

@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.

Thanks, the blocker is fixed. I timed the 00147 bodies on production, planned per call as force_custom_plan does, on the largest brand:

  • insights_same_prompt_compare_daily: 30 days 2.6 s cold, 90 days 0.6 s (before: past 50 s and 17.8 s).
  • insights_same_prompt_compare, 24h: 1.1 s.
  • insights_same_prompt_compare, largest topic over 30 days: 2.4 s warm. A cold first read still takes 9–20 s from disk, and now falls back through lenient as intended. 00149's body, which unpacks the competitor entries once, took 2.8 s.

The definer's membership check and the anon revoke look right.

On deploy, 00147 can't go to production alone, since it would drop 00131's fields there. It needs 00149 (#1037) in the same step, and 00148 (#1042) next to them.

@cihan-gyk
cihan-gyk dismissed gkhngyk’s stale review October 15, 2026 21:18

The merge-base changed after approval.

gkhngyk
gkhngyk previously approved these changes Oct 15, 2026

@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.

Re-approving: the earlier approval was dismissed when the merge-base moved. Same head; the merge with main is clean and 00147–00149 are applied to production.

@cihan-gyk
cihan-gyk dismissed gkhngyk’s stale review October 15, 2026 21:36

The merge-base changed after approval.

@gkhngyk
gkhngyk merged commit 2249d2a into ansvisor:main Oct 15, 2026
5 checks passed
gkhngyk pushed a commit that referenced this pull request Oct 16, 2026
…1037)

* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk pushed a commit that referenced this pull request Oct 16, 2026
* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 16, 2026
…form table (#1039)

* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk pushed a commit that referenced this pull request Oct 16, 2026
… the gap to the next (#1041)

* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* feat(insights): show the brands around yours on the leaderboard, with the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk pushed a commit that referenced this pull request Oct 16, 2026
…le (#1042)

* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* feat(insights): show the brands around yours on the leaderboard, with the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

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

* feat(insights): explain the visibility change beside the platform table

The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): make "Why it changed" fast for signed-in members

insights_change_drivers_daily took 0.58 s as the owner but over 20 s for
an org member: a SQL function is planned without its argument values on
PostgreSQL 17, and RLS was planned into that guess.

00148 makes both change-driver RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rows are folded per
prompt, engine and window first. Output is unchanged.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 16, 2026
…e trend (#1043)

* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* feat(insights): show the brands around yours on the leaderboard, with the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

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

* feat(insights): explain the visibility change beside the platform table

The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): pin competitors and mark prompt and action days on the trend

The v2 mockup's visibility trend (VIS-007):
- Insights opens on 30 days; 24h stays one click away.
- "Pin" keeps up to five competitors on the chart whatever the range, saved
  on the brand so the team sees the same lines (admins and managers change
  them, like other brand settings). Without pins the strongest four show,
  as before. Chips above the chart name the lines and highlight them.
- Markers: the days the most prompts were added (+) and the latest days
  people sent Action Center actions (A), three of each, listed under the
  chart; days after the last point are listed but not drawn. With a topic
  selected, only that topic's prompts count.
- The active AI visibility KPI's target shows as a dashed goal line, and
  the axis grows to keep it in view.

Migration 00136 adds brands.insights_pinned_competitors (uuid[], at most
five) and insights_trend_markers: prompts created and actions sent per UTC
day, security invoker.

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 16, 2026
* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* feat(insights): show the brands around yours on the leaderboard, with the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

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

* feat(insights): explain the visibility change beside the platform table

The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): pin competitors and mark prompt and action days on the trend

The v2 mockup's visibility trend (VIS-007):
- Insights opens on 30 days; 24h stays one click away.
- "Pin" keeps up to five competitors on the chart whatever the range, saved
  on the brand so the team sees the same lines (admins and managers change
  them, like other brand settings). Without pins the strongest four show,
  as before. Chips above the chart name the lines and highlight them.
- Markers: the days the most prompts were added (+) and the latest days
  people sent Action Center actions (A), three of each, listed under the
  chart; days after the last point are listed but not drawn. With a topic
  selected, only that topic's prompts count.
- The active AI visibility KPI's target shows as a dashed goal line, and
  the axis grows to keep it in view.

Migration 00136 adds brands.insights_pinned_competitors (uuid[], at most
five) and insights_trend_markers: prompts created and actions sent per UTC
day, security invoker.

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

* feat(insights): add the topics vs competitors heat map

The v2 mockup's heat map (VIS-010): a row per active topic, a column for
you and each competitor on the trend (pinned, or the strongest four), each
cell the Visibility score in that topic shaded light to dark, and the gap
to the topic's leader ("Lead", or e.g. "−26.5"). Scores use the card's
formula with your answers in the topic as the denominator, as the
leaderboard does. Topics you lead come first, then the biggest gaps, then
topics with fewer than 20 answers (faded, no gap). The topic name opens the
topic; six rows show until "Show all". Hidden on the 24h view and with a
topic selected.

Migration 00137 adds insights_topic_competitors_daily: per active topic,
the brand's and each live competitor's Visibility components from the
prompt-grain rollups, security invoker.

"Send biggest gap to Actions" follows in its own PR.

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

* fix(insights): spread the heat map's tones over the scores shown

The heat map shaded cells at fixed steps (15/25/35/45), so a brand whose
scores are all above 45 saw every cell in the same dark grey. Tones now
spread between the lowest and highest non-zero score in the table, so the
cells read in steps whatever the level, and a 0 stays the lightest. The
shades are softer too, with the text color kept on every one, so a full
table doesn't turn into dark blocks.

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

* perf(insights): plan the topics vs competitors read with its arguments

As reviewed: insights_topic_competitors_daily took 13.5 s for a signed-in
member of the largest brand over 30 days (8 s limit), 1.3 s planned with
its real arguments. 00152 redefines it as 00147/00148 do: plpgsql with
force_custom_plan and work_mem, security definer with the organization
check made explicit (null for a non-member, which hides the map). Each
topic's competitors are folded once by topic and competitor instead of
rescanned per topic. The output is unchanged. A new migration rather than an
edit of 00137, per the repo's migration rule.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 16, 2026
* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* feat(insights): show the brands around yours on the leaderboard, with the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

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

* feat(insights): explain the visibility change beside the platform table

The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): pin competitors and mark prompt and action days on the trend

The v2 mockup's visibility trend (VIS-007):
- Insights opens on 30 days; 24h stays one click away.
- "Pin" keeps up to five competitors on the chart whatever the range, saved
  on the brand so the team sees the same lines (admins and managers change
  them, like other brand settings). Without pins the strongest four show,
  as before. Chips above the chart name the lines and highlight them.
- Markers: the days the most prompts were added (+) and the latest days
  people sent Action Center actions (A), three of each, listed under the
  chart; days after the last point are listed but not drawn. With a topic
  selected, only that topic's prompts count.
- The active AI visibility KPI's target shows as a dashed goal line, and
  the axis grows to keep it in view.

Migration 00136 adds brands.insights_pinned_competitors (uuid[], at most
five) and insights_trend_markers: prompts created and actions sent per UTC
day, security invoker.

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

* feat(insights): add the topics vs competitors heat map

The v2 mockup's heat map (VIS-010): a row per active topic, a column for
you and each competitor on the trend (pinned, or the strongest four), each
cell the Visibility score in that topic shaded light to dark, and the gap
to the topic's leader ("Lead", or e.g. "−26.5"). Scores use the card's
formula with your answers in the topic as the denominator, as the
leaderboard does. Topics you lead come first, then the biggest gaps, then
topics with fewer than 20 answers (faded, no gap). The topic name opens the
topic; six rows show until "Show all". Hidden on the 24h view and with a
topic selected.

Migration 00137 adds insights_topic_competitors_daily: per active topic,
the brand's and each live competitor's Visibility components from the
prompt-grain rollups, security invoker.

"Send biggest gap to Actions" follows in its own PR.

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

* fix(insights): spread the heat map's tones over the scores shown

The heat map shaded cells at fixed steps (15/25/35/45), so a brand whose
scores are all above 45 saw every cell in the same dark grey. Tones now
spread between the lowest and highest non-zero score in the table, so the
cells read in steps whatever the level, and a 0 stays the lightest. The
shades are softer too, with the text color kept on every one, so a full
table doesn't turn into dark blocks.

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

* feat(insights): send the biggest topic gap to the Action Center

The v2 mockup's "Send biggest gap to Actions" (VIS-010, part 2): the heat
map's button opens a Compete action for the topic you trail by the most,
against the competitor leading it. The server measures the gap again from
the rollups (00137) rather than trusting the page, refuses a topic it
doesn't see a gap in or with fewer than 20 answers, and keeps one open gap
action per topic. The action carries C04's (close_topic_coverage_gap) task
plan and a person's "created" event, and is measured on the topic's
prompts once completed, like an opportunity sent from Content.

- server: POST /api/topics/:id/gap-action and from-topic-gap.js, with
  route and action tests; validate.js measures the new kind on its basket.
- Action Center: the person-sent kind topic_competitor_gap, titled "Close
  the 26.5-pt gap with Peec AI in AI Rank Tracker", without a "0 signals"
  chip, and a drawer section with the topic and the scores when sent.
- Insights: the button, disabled with a reason when no competitor leads,
  a toast with the AC number and a link, and a plain message when the gap
  has closed since the page loaded.

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

* perf(insights): plan the topics vs competitors read with its arguments

As reviewed: insights_topic_competitors_daily took 13.5 s for a signed-in
member of the largest brand over 30 days (8 s limit), 1.3 s planned with
its real arguments. 00152 redefines it as 00147/00148 do: plpgsql with
force_custom_plan and work_mem, security definer with the organization
check made explicit (null for a non-member, which hides the map). Each
topic's competitors are folded once by topic and competitor instead of
rescanned per topic. The output is unchanged. A new migration rather than an
edit of 00137, per the repo's migration rule.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 16, 2026
…1046)

* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* feat(insights): show the brands around yours on the leaderboard, with the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

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

* feat(insights): explain the visibility change beside the platform table

The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): pin competitors and mark prompt and action days on the trend

The v2 mockup's visibility trend (VIS-007):
- Insights opens on 30 days; 24h stays one click away.
- "Pin" keeps up to five competitors on the chart whatever the range, saved
  on the brand so the team sees the same lines (admins and managers change
  them, like other brand settings). Without pins the strongest four show,
  as before. Chips above the chart name the lines and highlight them.
- Markers: the days the most prompts were added (+) and the latest days
  people sent Action Center actions (A), three of each, listed under the
  chart; days after the last point are listed but not drawn. With a topic
  selected, only that topic's prompts count.
- The active AI visibility KPI's target shows as a dashed goal line, and
  the axis grows to keep it in view.

Migration 00136 adds brands.insights_pinned_competitors (uuid[], at most
five) and insights_trend_markers: prompts created and actions sent per UTC
day, security invoker.

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

* feat(insights): add the topics vs competitors heat map

The v2 mockup's heat map (VIS-010): a row per active topic, a column for
you and each competitor on the trend (pinned, or the strongest four), each
cell the Visibility score in that topic shaded light to dark, and the gap
to the topic's leader ("Lead", or e.g. "−26.5"). Scores use the card's
formula with your answers in the topic as the denominator, as the
leaderboard does. Topics you lead come first, then the biggest gaps, then
topics with fewer than 20 answers (faded, no gap). The topic name opens the
topic; six rows show until "Show all". Hidden on the 24h view and with a
topic selected.

Migration 00137 adds insights_topic_competitors_daily: per active topic,
the brand's and each live competitor's Visibility components from the
prompt-grain rollups, security invoker.

"Send biggest gap to Actions" follows in its own PR.

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

* fix(insights): spread the heat map's tones over the scores shown

The heat map shaded cells at fixed steps (15/25/35/45), so a brand whose
scores are all above 45 saw every cell in the same dark grey. Tones now
spread between the lowest and highest non-zero score in the table, so the
cells read in steps whatever the level, and a 0 stays the lightest. The
shades are softer too, with the text color kept on every one, so a full
table doesn't turn into dark blocks.

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

* feat(insights): send the biggest topic gap to the Action Center

The v2 mockup's "Send biggest gap to Actions" (VIS-010, part 2): the heat
map's button opens a Compete action for the topic you trail by the most,
against the competitor leading it. The server measures the gap again from
the rollups (00137) rather than trusting the page, refuses a topic it
doesn't see a gap in or with fewer than 20 answers, and keeps one open gap
action per topic. The action carries C04's (close_topic_coverage_gap) task
plan and a person's "created" event, and is measured on the topic's
prompts once completed, like an opportunity sent from Content.

- server: POST /api/topics/:id/gap-action and from-topic-gap.js, with
  route and action tests; validate.js measures the new kind on its basket.
- Action Center: the person-sent kind topic_competitor_gap, titled "Close
  the 26.5-pt gap with Peec AI in AI Rank Tracker", without a "0 signals"
  chip, and a drawer section with the topic and the scores when sent.
- Insights: the button, disabled with a reason when no competitor leads,
  a toast with the AC number and a link, and a plain message when the gap
  has closed since the page loaded.

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

* feat(insights): add the Opportunities card with relevance and Track

Insights' Recommendations row becomes the v2 mockup's Opportunities card,
under the topic heat map: stored prompt suggestions grouped by topic,
ranked by relevance x demand x gap, those under 0.6 relevance hidden, with
Track (one prompt) and Track N (a topic's prompts) within the plan's prompt
locations.

The suggestion refresh rates each suggestion's relevance in the same model
call. What that adds is capped at 0.1% of the plan price a month, reserved
atomically per organization before a refresh rates (migration 00138).

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

* perf(insights): plan the topics vs competitors read with its arguments

As reviewed: insights_topic_competitors_daily took 13.5 s for a signed-in
member of the largest brand over 30 days (8 s limit), 1.3 s planned with
its real arguments. 00152 redefines it as 00147/00148 do: plpgsql with
force_custom_plan and work_mem, security definer with the organization
check made explicit (null for a non-member, which hides the map). Each
topic's competitors are folded once by topic and competitor instead of
rescanned per topic. The output is unchanged. A new migration rather than an
edit of 00137, per the repo's migration rule.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 16, 2026
…ontent (#1047)

* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* feat(insights): show the brands around yours on the leaderboard, with the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

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

* feat(insights): explain the visibility change beside the platform table

The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): pin competitors and mark prompt and action days on the trend

The v2 mockup's visibility trend (VIS-007):
- Insights opens on 30 days; 24h stays one click away.
- "Pin" keeps up to five competitors on the chart whatever the range, saved
  on the brand so the team sees the same lines (admins and managers change
  them, like other brand settings). Without pins the strongest four show,
  as before. Chips above the chart name the lines and highlight them.
- Markers: the days the most prompts were added (+) and the latest days
  people sent Action Center actions (A), three of each, listed under the
  chart; days after the last point are listed but not drawn. With a topic
  selected, only that topic's prompts count.
- The active AI visibility KPI's target shows as a dashed goal line, and
  the axis grows to keep it in view.

Migration 00136 adds brands.insights_pinned_competitors (uuid[], at most
five) and insights_trend_markers: prompts created and actions sent per UTC
day, security invoker.

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

* feat(insights): add the topics vs competitors heat map

The v2 mockup's heat map (VIS-010): a row per active topic, a column for
you and each competitor on the trend (pinned, or the strongest four), each
cell the Visibility score in that topic shaded light to dark, and the gap
to the topic's leader ("Lead", or e.g. "−26.5"). Scores use the card's
formula with your answers in the topic as the denominator, as the
leaderboard does. Topics you lead come first, then the biggest gaps, then
topics with fewer than 20 answers (faded, no gap). The topic name opens the
topic; six rows show until "Show all". Hidden on the 24h view and with a
topic selected.

Migration 00137 adds insights_topic_competitors_daily: per active topic,
the brand's and each live competitor's Visibility components from the
prompt-grain rollups, security invoker.

"Send biggest gap to Actions" follows in its own PR.

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

* fix(insights): spread the heat map's tones over the scores shown

The heat map shaded cells at fixed steps (15/25/35/45), so a brand whose
scores are all above 45 saw every cell in the same dark grey. Tones now
spread between the lowest and highest non-zero score in the table, so the
cells read in steps whatever the level, and a 0 stays the lightest. The
shades are softer too, with the text color kept on every one, so a full
table doesn't turn into dark blocks.

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

* feat(insights): send the biggest topic gap to the Action Center

The v2 mockup's "Send biggest gap to Actions" (VIS-010, part 2): the heat
map's button opens a Compete action for the topic you trail by the most,
against the competitor leading it. The server measures the gap again from
the rollups (00137) rather than trusting the page, refuses a topic it
doesn't see a gap in or with fewer than 20 answers, and keeps one open gap
action per topic. The action carries C04's (close_topic_coverage_gap) task
plan and a person's "created" event, and is measured on the topic's
prompts once completed, like an opportunity sent from Content.

- server: POST /api/topics/:id/gap-action and from-topic-gap.js, with
  route and action tests; validate.js measures the new kind on its basket.
- Action Center: the person-sent kind topic_competitor_gap, titled "Close
  the 26.5-pt gap with Peec AI in AI Rank Tracker", without a "0 signals"
  chip, and a drawer section with the topic and the scores when sent.
- Insights: the button, disabled with a reason when no competitor leads,
  a toast with the AC number and a link, and a plain message when the gap
  has closed since the page loaded.

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

* feat(insights): add the Opportunities card with relevance and Track

Insights' Recommendations row becomes the v2 mockup's Opportunities card,
under the topic heat map: stored prompt suggestions grouped by topic,
ranked by relevance x demand x gap, those under 0.6 relevance hidden, with
Track (one prompt) and Track N (a topic's prompts) within the plan's prompt
locations.

The suggestion refresh rates each suggestion's relevance in the same model
call. What that adds is capped at 0.1% of the plan price a month, reserved
atomically per organization before a refresh rates (migration 00138).

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

* feat(insights): send opportunities to the Action Center and suggest content

The Opportunities card's second buttons, as in the v2 mockup. A topic
item's Send action opens a Growth action for its suggested prompts and
their demand, on the library's G16 plan when none of the brand's prompts
track the topic and G05 when some do; one open action per topic, measured
on the topic's prompts. A prompt item's Suggest content runs "+ New" for
its topic, steered by the prompt, under the Content quota; it's disabled
for an untracked topic or a spent quota.

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

* perf(insights): plan the topics vs competitors read with its arguments

As reviewed: insights_topic_competitors_daily took 13.5 s for a signed-in
member of the largest brand over 30 days (8 s limit), 1.3 s planned with
its real arguments. 00152 redefines it as 00147/00148 do: plpgsql with
force_custom_plan and work_mem, security definer with the organization
check made explicit (null for a non-member, which hides the map). Each
topic's competitors are folded once by topic and competitor instead of
rescanned per topic. The output is unchanged. A new migration rather than an
edit of 00137, per the repo's migration rule.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk added a commit that referenced this pull request Oct 16, 2026
* feat(insights): compare changes on the same prompts by default

Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

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

* feat(insights): show the KPI cards in two rows, as in the v2 mockup

The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

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

* feat(insights): add the one-line summary above the KPI cards

The v2 mockup opens Insights with one line of facts (VIS-006): the
Visibility score and change, the brand's rank and the gap to its
neighbour (or the lead over the runner-up, or a tie), the platforms whose
Visibility rose and fell most, and what the change compares ("vs <days> ·
N new prompts excluded", moved here from the trend card). A copy button
puts the same line on the clipboard as text. It's a fixed template over
numbers the page already shows; no AI call.

Platform movers follow "Compare: Same prompts". Migration 00132 adds
insights_platform_compare[_daily]: the Visibility components per (model,
platform) in both windows, over the shared prompts when asked, from the
prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): replace the share of voice charts with the by AI platform table

The v2 mockup shows one "By AI platform" table where the Share of Voice
donut and trend were (VIS-008): per platform, Visibility, its change,
Coverage, Share of voice and Avg. position. A platform with fewer than 20
answers shows "Low sample · N runs" and one answered only last period
shows "No runs this period", never 0%. The biggest drop is tinted.

Changes follow "Compare: Same prompts", and a change over fewer than 20
answers in either window is left out, so the summary line's movers and
the table always agree. All time shows the table without changes.

Migration 00133 extends insights_platform_compare[_daily] with the
position sum and, for the current window, the prompt ids answered and
visible per engine, so Coverage counts a prompt once per platform even
when several models answer it. Window bounds now default to open, and no
previous window reads the current one alone.

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

* feat(insights): show the brands around yours on the leaderboard, with the gap to the next

The v2 mockup's leaderboard (VIS-004): ranks 1 and 2, "n more", the brand
directly ahead, yours and the one directly behind, then "Show all N";
boards of five or fewer stay whole. Each row shows the score, its change
("↑ 4.1", following Same prompts) and "Coverage · SoV" under the name.

Under your row, a callout gives the gap to the brand ahead (the summary
line's number) and the lever: the platform where that brand appears in
the largest share of prompts more than yours, among platforms with enough
answers for the By AI platform table. The header link reads
"Head-to-Head", and the board's text moves into en.json.

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

* feat(insights): explain the visibility change beside the platform table

The v2 mockup's "Why it changed" box (VIS-009): the platforms, topics and
prompts that moved Visibility most, as Gains and Drops, each with its own
score before → after and its effect on the overall score, and a line for
the prompts new this period ("6 new prompts · Oct 12 · own baseline, not
counted"). A row opens the breakdown panel on its tab; "Full breakdown"
opens the panel. It sits beside By AI platform and wraps below it on
narrow screens; All time, with nothing to compare, hides it.

A slice's effect is how much higher the overall score is than it would be
had the slice kept last period's rates at this period's volume, so large
slices weigh more and a handful of answers can't top the list. It follows
"Compare: Same prompts"; with fewer than 20 compared answers in a window
the box says so instead of naming drivers.

Migration 00135 adds insights_change_drivers[_daily]: the Visibility
components per prompt and per (model, platform) in both windows, with the
prompts' text and topic and the new prompts' count and added dates, from
the prompt-grain rollups (raw rows for the 24h and topic views).

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

* feat(insights): pin competitors and mark prompt and action days on the trend

The v2 mockup's visibility trend (VIS-007):
- Insights opens on 30 days; 24h stays one click away.
- "Pin" keeps up to five competitors on the chart whatever the range, saved
  on the brand so the team sees the same lines (admins and managers change
  them, like other brand settings). Without pins the strongest four show,
  as before. Chips above the chart name the lines and highlight them.
- Markers: the days the most prompts were added (+) and the latest days
  people sent Action Center actions (A), three of each, listed under the
  chart; days after the last point are listed but not drawn. With a topic
  selected, only that topic's prompts count.
- The active AI visibility KPI's target shows as a dashed goal line, and
  the axis grows to keep it in view.

Migration 00136 adds brands.insights_pinned_competitors (uuid[], at most
five) and insights_trend_markers: prompts created and actions sent per UTC
day, security invoker.

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

* feat(insights): add the topics vs competitors heat map

The v2 mockup's heat map (VIS-010): a row per active topic, a column for
you and each competitor on the trend (pinned, or the strongest four), each
cell the Visibility score in that topic shaded light to dark, and the gap
to the topic's leader ("Lead", or e.g. "−26.5"). Scores use the card's
formula with your answers in the topic as the denominator, as the
leaderboard does. Topics you lead come first, then the biggest gaps, then
topics with fewer than 20 answers (faded, no gap). The topic name opens the
topic; six rows show until "Show all". Hidden on the 24h view and with a
topic selected.

Migration 00137 adds insights_topic_competitors_daily: per active topic,
the brand's and each live competitor's Visibility components from the
prompt-grain rollups, security invoker.

"Send biggest gap to Actions" follows in its own PR.

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

* fix(insights): spread the heat map's tones over the scores shown

The heat map shaded cells at fixed steps (15/25/35/45), so a brand whose
scores are all above 45 saw every cell in the same dark grey. Tones now
spread between the lowest and highest non-zero score in the table, so the
cells read in steps whatever the level, and a 0 stays the lightest. The
shades are softer too, with the text color kept on every one, so a full
table doesn't turn into dark blocks.

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

* feat(insights): send the biggest topic gap to the Action Center

The v2 mockup's "Send biggest gap to Actions" (VIS-010, part 2): the heat
map's button opens a Compete action for the topic you trail by the most,
against the competitor leading it. The server measures the gap again from
the rollups (00137) rather than trusting the page, refuses a topic it
doesn't see a gap in or with fewer than 20 answers, and keeps one open gap
action per topic. The action carries C04's (close_topic_coverage_gap) task
plan and a person's "created" event, and is measured on the topic's
prompts once completed, like an opportunity sent from Content.

- server: POST /api/topics/:id/gap-action and from-topic-gap.js, with
  route and action tests; validate.js measures the new kind on its basket.
- Action Center: the person-sent kind topic_competitor_gap, titled "Close
  the 26.5-pt gap with Peec AI in AI Rank Tracker", without a "0 signals"
  chip, and a drawer section with the topic and the scores when sent.
- Insights: the button, disabled with a reason when no competitor leads,
  a toast with the AC number and a link, and a plain message when the gap
  has closed since the page loaded.

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

* feat(insights): add the Opportunities card with relevance and Track

Insights' Recommendations row becomes the v2 mockup's Opportunities card,
under the topic heat map: stored prompt suggestions grouped by topic,
ranked by relevance x demand x gap, those under 0.6 relevance hidden, with
Track (one prompt) and Track N (a topic's prompts) within the plan's prompt
locations.

The suggestion refresh rates each suggestion's relevance in the same model
call. What that adds is capped at 0.1% of the plan price a month, reserved
atomically per organization before a refresh rates (migration 00138).

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

* feat(insights): send opportunities to the Action Center and suggest content

The Opportunities card's second buttons, as in the v2 mockup. A topic
item's Send action opens a Growth action for its suggested prompts and
their demand, on the library's G16 plan when none of the brand's prompts
track the topic and G05 when some do; one open action per topic, measured
on the topic's prompts. A prompt item's Suggest content runs "+ New" for
its topic, steered by the prompt, under the Content quota; it's disabled
for an untracked topic or a spent quota.

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

* feat(insights): show the last and next run in the header

The v2 mockup's "Acme Coffee · Last run 11h ago · next run in 13h". The
last run is the brand's latest completed full run from the tracking-run
ledger, no longer the newest answer in the filtered range. The next run is
the last scheduled run plus the schedule's period (a day, or a shorter gap
on a self-hosted install), and is left out once it's due.

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

* fix(insights): make the same-prompt comparison fast for signed-in members

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

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

* fix(insights): keep a failed same-prompt comparison out of the 24h cache

getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

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

* fix(insights): keep the KPI cards' fields in the fast same-prompt RPCs

00147 (#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

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

* perf(insights): plan the topics vs competitors read with its arguments

As reviewed: insights_topic_competitors_daily took 13.5 s for a signed-in
member of the largest brand over 30 days (8 s limit), 1.3 s planned with
its real arguments. 00152 redefines it as 00147/00148 do: plpgsql with
force_custom_plan and work_mem, security definer with the organization
check made explicit (null for a non-member, which hides the map). Each
topic's competitors are folded once by topic and competitor instead of
rescanned per topic. The output is unchanged. A new migration rather than an
edit of 00137, per the repo's migration rule.

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

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
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