Skip to content

feat(chat): add the counts Why did it move reads (00423 chat_why_cells) - #1871

Merged
gkhngyk merged 9 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w2-db-why-cells
Oct 31, 2026
Merged

gkhngyk merged 9 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w2-db-why-cells

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

One read-only database function for Chat's "Why did it move" (explain_change, CHAT-22 §1, W2-18). Stacked on #1853 (Wave 2's tables); behind CHAT_AGENTIC. Nothing calls it yet; W2-18 does.

Why a function: the analysis compares a metric between two periods cell by cell (prompt × engine × location). For a brand with 500 prompts on 6 engines over 14 days, that's about 42,000 day rows. Supabase returns at most 1,000 rows per query (max_rows), so reading them from the web would take 40+ requests. chat_why_cells sums them in the database in one call.

00423 chat_why_cells(brand, a_from, a_to, b_from, b_to, series_from, models?, region?, topic?) → jsonb

  • cells: one entry per prompt, platform, model, location and period (a or b), with:
    • runs (tracked days) and visible_runs (days the brand was named or cited);
    • answers, mention_answers, citation_answers;
    • sum_position and position_count;
    • brand_mentions (total_mentions) and competitor_mentions (the competitors' mention_count), so share of voice counts mentions as the Insights cards do (insights-kpis.ts);
    • last_at.
  • daily: the same sums per day, from series_from to b_to, for the change point, plus visible_prompts and active_prompts (distinct prompts named or cited, and tracked), so visibility follows the app's visible-prompts definition.
  • complete: false when a row in the range still has NULL mention_answers or negative_count (not yet rewritten by refresh_insights_daily), as insights_kpi_series flags it.
  • Sources:
    • Reads insights_prompt_daily and insights_competitor_prompt_daily on their (brand_id, day) index.
    • The competitors' sums are grouped on their own before they meet the brand's, so no join repeats a row.
    • Empty result: {"cells": [], "daily": [], "complete": true}.
  • Guards (errcode 22023):
    • every argument but the filters is required;
    • a period can't end before it starts;
    • period a ends before period b starts;
    • the series starts no later than b's end;
    • each period, and the series, is at most 92 days.
  • Server only:
    • security invoker, stable, search_path = '';
    • revoke all … from public, anon, authenticated and grant execute … to service_role, as chat_agent_usage_shares in 00419;
    • the web checks that the brand is in the caller's workspace before calling it, as the MCP data functions do (in W2-18).
  • plpgsql rather than sql, only for the guards; it reads and writes nothing else.

supabase/schema.sql was rebuilt with build-schema.sh. schema.test.ts covers:

  • 00423 in Wave 2's list, and chat_why_cells among the server-only functions;
  • invoker rights with a fixed search_path, and no writes;
  • the 92-day and a-before-b guards;
  • the competitor CTE, and an empty result as [].

Related issue

None. Chat Wave 2 (W2-18, CHAT-22).

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 00423 in one transaction (psql -1 -f supabase/migrations/00423_chat_why_cells.sql).
  2. As the service role, call select public.chat_why_cells('<brand>', current_date-14, current_date-8, current_date-7, current_date-1, current_date-30);. It should return cells and daily, with numbers as numbers.
  3. Pass a topic id: fewer cells.
  4. A 93-day period, or a_to >= b_from, raises 22023.
  5. has_function_privilege('anon' | 'authenticated', …, 'execute') is false.
  6. Run yarn vitest run src/lib/chat/schema.test.ts (46 tests).

Applied on the dev database and called with the demo brand, using a = 3–9 Oct, b = 10–16 Oct and the series from 17 Sep:

  • 47 cells and 30 days;
  • 32 cells with a topic;
  • an empty range returns {"cells": [], "daily": [], "complete": true};
  • complete is true, and the new mention and prompt counts come back as numbers;
  • the 92-day guard raises;
  • anon and authenticated can't execute it.

Calling it found one bug that the static tests couldn't see, now fixed in the second commit. = any ((select …)) failed with uuid = uuid[], so the topic filter is now an in subquery. The third commit makes share of voice and visibility match the Insights cards (found in W2-18's review) and adds complete.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): eslint clean on the changed test file
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change): no user-visible change

For production (@gkhngyk): apply 00423 after 00417–00422 (#1853), in one transaction. No bucket, cron or env.

Note on old days:

  • mention_answers in both rollups can be NULL on days written before 00130, until refresh_insights_daily rewrites them.
  • The function counts NULL as 0, like the other Insights functions, and says so with complete: false.

🤖 Generated with Claude Code

cihan-gyk and others added 5 commits October 30, 2026 01:12
…iles, Help and add-on packs

Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types and the
demo's coverage only; the code that uses them comes in the Wave 1 PRs.

- 00407: chat_conversations gets shared_at (Share with team: every member
  of the workspace reads it), last_read_at (unread results), deleted_at
  (Delete with Undo; deleted chats are hidden from every member) and a
  title search column; chat_messages gets context_json (what a person's
  message was scoped to) and a text search column. 'simple' text search,
  so a chat in any language is found. The author policy now leaves deleted
  chats out, and a shared policy reads shared ones.
- 00408: chat_user_prefs gets the rest of Settings › General and the
  one-time notices: rail_open, panel_size, default_mode, answer_language,
  notify_via, show_thought, panel_on_pages, focus_prompted_at,
  usage_notice_period, legacy_imported_at.
- 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file,
  the composer's 11 types, 5 a message (a trigger backs the server's
  check), kept 90 days.
- 00410: chat_tool_cache (a chat's read results by tool and scope, server
  only) and each step's and model call's measure: latency, cache hit,
  truncation, result tokens on chat_run_steps (never granted to members),
  prompt cache read/write tokens and latency on the ledger.
- 00411: chat_files (filed deliverables and saved answers, the
  workspace's, kept a year, searchable by title, summary and tags),
  chat_file_task_links, chat_storage_usage kept by a trigger, and the
  private bucket chat-files.
- 00412: help_answer_cache and help_gaps (server only, no workspace or
  person ids).
- 00413: add_on_products seeded with the owner's packs (AI credits $10,
  $50, $250, $1,000 at half their price in budget, 12 months; storage
  +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked),
  add_on_purchases (Admins read), ai_credit_grants and storage_grants
  (server only), and prompt_improve_usage.grant_id.

Members only ever read; every write is the server's. Tool names, tool
results and dollars stay server only. web/src/types/supabase.ts carries
the new tables and columns; schema.test.ts checks the policies, the
server-only tables, the limits and the seeded packs from the SQL;
steps.test.ts keeps the step measure out of the member columns. The demo
coverage skips chat_files and chat_tool_cache (a person's own Chat work).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pact and suggestions (00417–00422)

Chat's Wave 2 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types, tests
and the demo's coverage only; the code that uses them comes in the Wave 2
PRs. Every new table has row level security on; members only ever read,
and every write is the server's.

- 00417: chat_asks (a run's question cards, at most 4 a run, 2–4 options
  with exactly one Recommended, checked by chat_ask_options_valid; the
  answer once) and chat_next_moves (2–4 ranked moves, prompts up to 80
  characters, each with its action class and a ghost_ok mark); both
  readable where their run is. chat_messages.shortcut_id on a person's
  message only (CHAT-08).
- 00418: chat_task_state, the task strip: Chat's own status per Action
  Center task (queued, writing, ready_for_review, done), the run and the
  deliverable. action_tasks is not changed.
- 00419: chat_agents (status, pause reason, owner, private or workspace
  visibility, current version, caps per run and month as shares of the
  AI limit), chat_agent_versions (immutable: skills, instructions, mode,
  connections, model, scope), chat_agent_triggers (schedule, Signal, KPI,
  watch rule; at most 5) and chat_agent_runs (queue, statuses, trigger
  evidence, acting person, brand, action, outcome, cap and use as shares).
  One run at a time per agent and brand; chat_start_next_agent_run()
  starts the next queued one under the workspace's limit, Run now and Run
  agent first. An agent run's chat (chat_conversations.agent_run_id,
  origin agent) is readable with the run. Agent ids on the Activity log,
  and the agent settings in chat_settings. CHAT-27: subtasks as child runs
  (chat_runs.parent_run_id, subtask_title; no message of their own; one
  level, at most 10), agent_id / agent_run_id / parent_run_id on the
  ledger, reserve_chat_ai_usage taking the agent run and its cap (old
  calls still match), and chat_agent_usage_shares() returning shares only
  (server only, since the budget is its argument).
- 00420: chat_why_analyses (the explain_change result per analysis,
  readable where its chat is) and chat_user_prefs.home_seen_at for
  "Since you left".
- 00421: the impact ledger: ship_events, impact_measurements (one per ship
  event; the one outcome vocabulary; d7/d14/d30/d90 checkpoints) and
  impact_control_sets (per checkpoint). Every member reads them.
- 00422: chat_suggestion_feeds and chat_suggestions (CHAT-26): one a day
  per person and brand, own rows only.

web/src/types/supabase.ts carries the new tables, columns and functions;
schema.test.ts checks the Wave 2 policies, limits, vocabularies and the
server-only functions from the SQL. The demo coverage skips the five new
brand-scoped tables (a demo brand runs no agent, ships nothing and gets
no suggestions).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…runs' places

Review fixes for Wave 2's tables, before they ship:

- reserve_chat_ai_usage reads the agent run from the chat
  (chat_conversations.agent_run_id), so a subtask's step counts toward its
  parent's run; a p_agent_run_id that isn't the chat's is refused, and
  p_run_cap is always the whole run's cap. search_path is now ''.
- chat_start_next_agent_run needs a workspace limit, never starts a run of
  an archived agent or a deleted brand, and starts a triggered run only
  while its agent is active (Run now and Run agent also on a paused or
  draft one).
- A run paused at its AI cap keeps its agent and brand place, so an
  Admin's Continue can't collide with the next run.
- ship_events.agent_run_id, for an agent run's Outcome (CHAT-21 §I 43).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
explain_change (CHAT-22 §1) compares a metric prompt × engine by prompt ×
engine between two periods. chat_why_cells sums the Insights rollups for it
in one call: per prompt, platform, model, location and period, the tracked
day rows and those where the brand was named or cited, answers, mentions,
citations, positions and the answers naming a tracked competitor; and the
same sums per day for the change point. The competitors' counts are grouped
on their own before they meet the brand's, so no join repeats a row.

Server only (service role; revoked from public, anon and authenticated),
stable, security invoker, search_path ''. Each period and the series is 92
days at most, a before b, so one call stays small. The web checks the
brand is the caller's workspace's before it calls. schema.sql rebuilt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`prompt_id = any ((select ids …))` reads the subquery as rows of uuid[]
and fails with "operator does not exist: uuid = uuid[]" when the
function runs (plpgsql checks it only then). Found by calling it on the
dev database; a topic now narrows the demo brand's 47 cells to 32.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 30, 2026
cihan-gyk and others added 3 commits October 30, 2026 22:33
chat_why_cells now sums the brand's total_mentions and the competitors'
mention_count (share of voice as the Insights card counts it), gives each
day its prompts named or cited and those tracked (visibility as Insights
counts it), and says complete: false while a row read predates 00130/00131's
columns, as insights_kpi_series does. schema.sql rebuilt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts: web/src/lib/chat/schema.test.ts (kept the PR's 00423 additions on main's file), supabase/schema.sql (rebuilt with build-schema.sh).
…y_cells

Insights' Visibility card is the AI visibility score, whose position
factor is the sum of 1/position over the positions. chat_why_cells
returned only the sum of positions, so Why could not compute the same
Visibility as Insights. Return sum_inv_position per cell and per day.

Also read each rollup on one day range of its (brand_id, day) index;
the periods still narrow it.

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

Looks good with c3a4ba8: current main merged in and one fix commit, described below. Migration 00423 is applied on production before the merge.

Fix (on this branch)

chat_why_cells now returns the Visibility score's position factor. On Insights, the Visibility card is the AI visibility score: 0.6 × mention rate + 0.25 × citation rate + 0.15 × position factor. The position factor is sum_inv_position / position_count (ai_visibility_aggregates_daily, computeAiVisibilityScore). The function returned sum_position but not sum_inv_position. Without it, Why could compute coverage (visible prompts ÷ tracked prompts), but not the number the Visibility card shows.

  • Each cell and each day now also returns sum_inv_position. Nothing else in the payload changes.
  • Both rollup reads also get one day range, day between least(p_a_from, p_series_from) and p_b_to, ahead of the three-period or. Now the (brand_id, day) index takes the range as its index condition. Before, it read every day the brand has and filtered them. Results don't change.
  • Two new schema.test.ts cases cover these. Both fail without the change.

What we checked

  • Number: 00423 is in the Chat block (00400–00449). Neither main nor any open PR uses it.
  • Who can call it:
    • The function is security invoker, stable, with search_path = '' and schema-qualified names.
    • Execute is revoked from public, anon and authenticated and granted to service_role only. That's the same pattern as chat_agent_usage_shares.
    • It reads only. There's no new table, view or policy.
  • The counts match Insights. Called next to the Insights functions on real data (7 days against the 7 before, the whole brand and with one topic), all of these were equal:
    • brand and competitor mentions (share_of_voice_aggregates_daily)
    • visible and tracked prompts (visible_prompt_stats_daily, tracked_prompt_count_daily)
    • answers, answers naming the brand, answers citing it, and the position factor (ai_visibility_aggregates_daily, with the fix)
    • position sum and count (insights_aggregates_daily)
    • every day of daily against insights_kpi_series.
  • The competitor join: no competitor mentions fall outside a brand cell, so the left join drops nothing.
  • The guards (92 days, a before b, required arguments) each raise 22023.
  • Embeds: none. This PR has no web code.

Follow-ups (not blocking)

  1. Size and time on a large brand. For the largest brand we track:
    • 7 days against 7, with a 30-day series: about 0.5 s and 1.1 MB of JSON (about 2,700 cells).
    • The 92-day maximum: about 2.2 s and 2.8 MB (about 7,400 cells).
    • Building the JSON takes most of that time. A larger work_mem didn't help.
    • It's fine for W2-18 as written. If explain_change only needs the cells that moved, W2-18 could narrow the call by engine or topic, or compact the payload (for example, leaving out last_at per cell).
  2. The citations metric. chat_why_analyses allows a citations metric. The function returns citation_answers (for citation rate), not total_citations. If Why's "citations" should match the Citations count on Insights rather than Citation rate, it needs total_citations too.
  3. The header comment says "from scheduled tracking only". The rollups include manual runs, as Insights does. The comment could say "as Insights counts it" instead.

Base and tests

this branch = this PR's head abb976f6e + a merge of current main 703a68600, then the fix.

  • schema.test.ts conflicted, because #1853 landed on main as a squash. I kept the PR's 00423 additions.
  • schema.sql was rebuilt with build-schema.sh, and a second run leaves it unchanged.
  • this branch merges clean on current main.

Tests run on this branch:

  • lib/chat/schema.test.ts: 48 pass, including the 2 new ones, which fail without the fix.
  • lib/guards/plan-row.test.ts: passes.
  • tsc --noEmit, plus eslint and prettier on the changed test file: clean.

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

Merging in order with the other approved PRs. This head merges current main; its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build.

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants